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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  13. this.xmpp = require("./modules/xmpp/xmpp");
  14. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  15. this.translation = require("./modules/translation/translation");
  16. this.settings = require("./modules/settings/Settings");
  17. this.DTMF = require("./modules/DTMF/DTMF");
  18. this.members = require("./modules/members/MemberList");
  19. }
  20. };
  21. function init() {
  22. APP.desktopsharing.init();
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. APP.keyboardshortcut.init();
  28. APP.members.start();
  29. }
  30. $(document).ready(function () {
  31. var URLProcessor = require("./modules/URLProcessor/URLProcessor");
  32. URLProcessor.setConfigParametersFromUrl();
  33. APP.init();
  34. APP.translation.init();
  35. if(APP.API.isEnabled())
  36. APP.API.init();
  37. APP.UI.start(init);
  38. });
  39. $(window).bind('beforeunload', function () {
  40. if(APP.API.isEnabled())
  41. APP.API.dispose();
  42. });
  43. module.exports = APP;
  44. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":11,"./modules/URLProcessor/URLProcessor":42,"./modules/connectionquality/connectionquality":43,"./modules/desktopsharing/desktopsharing":44,"./modules/keyboardshortcut/keyboardshortcut":45,"./modules/members/MemberList":46,"./modules/settings/Settings":47,"./modules/statistics/statistics":51,"./modules/translation/translation":52,"./modules/xmpp/xmpp":66}],2:[function(require,module,exports){
  45. /* global APP */
  46. /**
  47. * Implements API class that communicates with external api class
  48. * and provides interface to access Jitsi Meet features by external
  49. * applications that embed Jitsi Meet
  50. */
  51. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  52. /**
  53. * List of the available commands.
  54. * @type {{
  55. * displayName: inputDisplayNameHandler,
  56. * muteAudio: toggleAudio,
  57. * muteVideo: toggleVideo,
  58. * toggleFilmStrip: toggleFilmStrip,
  59. * toggleChat: toggleChat,
  60. * toggleContactList: toggleContactList
  61. * }}
  62. */
  63. var commands = {};
  64. function initCommands() {
  65. commands = {
  66. displayName: APP.UI.inputDisplayNameHandler,
  67. muteAudio: APP.UI.toggleAudio,
  68. muteVideo: APP.UI.toggleVideo,
  69. toggleFilmStrip: APP.UI.toggleFilmStrip,
  70. toggleChat: APP.UI.toggleChat,
  71. toggleContactList: APP.UI.toggleContactList
  72. };
  73. }
  74. /**
  75. * Maps the supported events and their status
  76. * (true it the event is enabled and false if it is disabled)
  77. * @type {{
  78. * incomingMessage: boolean,
  79. * outgoingMessage: boolean,
  80. * displayNameChange: boolean,
  81. * participantJoined: boolean,
  82. * participantLeft: boolean
  83. * }}
  84. */
  85. var events = {
  86. incomingMessage: false,
  87. outgoingMessage:false,
  88. displayNameChange: false,
  89. participantJoined: false,
  90. participantLeft: false
  91. };
  92. var displayName = {};
  93. /**
  94. * Processes commands from external application.
  95. * @param message the object with the command
  96. */
  97. function processCommand(message) {
  98. if (message.action != "execute") {
  99. console.error("Unknown action of the message");
  100. return;
  101. }
  102. for (var key in message) {
  103. if(commands[key])
  104. commands[key].apply(null, message[key]);
  105. }
  106. }
  107. /**
  108. * Processes events objects from external applications
  109. * @param event the event
  110. */
  111. function processEvent(event) {
  112. if (!event.action) {
  113. console.error("Event with no action is received.");
  114. return;
  115. }
  116. var i = 0;
  117. switch(event.action) {
  118. case "add":
  119. for (; i < event.events.length; i++) {
  120. events[event.events[i]] = true;
  121. }
  122. break;
  123. case "remove":
  124. for (; i < event.events.length; i++) {
  125. events[event.events[i]] = false;
  126. }
  127. break;
  128. default:
  129. console.error("Unknown action for event.");
  130. }
  131. }
  132. /**
  133. * Sends message to the external application.
  134. * @param object
  135. */
  136. function sendMessage(object) {
  137. window.parent.postMessage(JSON.stringify(object), "*");
  138. }
  139. /**
  140. * Processes a message event from the external application
  141. * @param event the message event
  142. */
  143. function processMessage(event) {
  144. var message;
  145. try {
  146. message = JSON.parse(event.data);
  147. } catch (e) {}
  148. if(!message.type)
  149. return;
  150. switch (message.type) {
  151. case "command":
  152. processCommand(message);
  153. break;
  154. case "event":
  155. processEvent(message);
  156. break;
  157. default:
  158. console.error("Unknown type of the message");
  159. return;
  160. }
  161. }
  162. function setupListeners() {
  163. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  164. API.triggerEvent("participantJoined", {jid: from});
  165. });
  166. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  167. if (from != myjid)
  168. API.triggerEvent("incomingMessage",
  169. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  170. });
  171. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  172. API.triggerEvent("participantLeft", {jid: jid});
  173. });
  174. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  175. var name = displayName[jid];
  176. if(!name || name != newDisplayName) {
  177. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  178. displayName[jid] = newDisplayName;
  179. }
  180. });
  181. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  182. APP.API.triggerEvent("outgoingMessage", {"message": body});
  183. });
  184. }
  185. var API = {
  186. /**
  187. * Check whether the API should be enabled or not.
  188. * @returns {boolean}
  189. */
  190. isEnabled: function () {
  191. var hash = location.hash;
  192. if (hash && hash.indexOf("external") > -1 && window.postMessage)
  193. return true;
  194. return false;
  195. },
  196. /**
  197. * Initializes the APIConnector. Setups message event listeners that will
  198. * receive information from external applications that embed Jitsi Meet.
  199. * It also sends a message to the external application that APIConnector
  200. * is initialized.
  201. */
  202. init: function () {
  203. initCommands();
  204. if (window.addEventListener) {
  205. window.addEventListener('message',
  206. processMessage, false);
  207. }
  208. else {
  209. window.attachEvent('onmessage', processMessage);
  210. }
  211. sendMessage({type: "system", loaded: true});
  212. setupListeners();
  213. },
  214. /**
  215. * Checks whether the event is enabled ot not.
  216. * @param name the name of the event.
  217. * @returns {*}
  218. */
  219. isEventEnabled: function (name) {
  220. return events[name];
  221. },
  222. /**
  223. * Sends event object to the external application that has been subscribed
  224. * for that event.
  225. * @param name the name event
  226. * @param object data associated with the event
  227. */
  228. triggerEvent: function (name, object) {
  229. if(this.isEnabled() && this.isEventEnabled(name))
  230. sendMessage({
  231. type: "event", action: "result", event: name, result: object});
  232. },
  233. /**
  234. * Removes the listeners.
  235. */
  236. dispose: function () {
  237. if(window.removeEventListener) {
  238. window.removeEventListener("message",
  239. processMessage, false);
  240. }
  241. else {
  242. window.detachEvent('onmessage', processMessage);
  243. }
  244. }
  245. };
  246. module.exports = API;
  247. },{"../../service/xmpp/XMPPEvents":116}],3:[function(require,module,exports){
  248. /* global APP */
  249. /**
  250. * A module for sending DTMF tones.
  251. */
  252. var DTMFSender;
  253. var initDtmfSender = function() {
  254. // TODO: This needs to reset this if the peerconnection changes
  255. // (e.g. the call is re-made)
  256. if (DTMFSender)
  257. return;
  258. var localAudio = APP.RTC.localAudio;
  259. if (localAudio && localAudio.getTracks().length > 0)
  260. {
  261. var peerconnection
  262. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  263. if (peerconnection) {
  264. DTMFSender =
  265. peerconnection.peerconnection
  266. .createDTMFSender(localAudio.getTracks()[0]);
  267. console.log("Initialized DTMFSender");
  268. }
  269. else {
  270. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  271. }
  272. }
  273. else {
  274. console.log("Failed to initialize DTMFSender: no audio track.");
  275. }
  276. };
  277. var DTMF = {
  278. sendTones: function (tones, duration, pause) {
  279. if (!DTMFSender)
  280. initDtmfSender();
  281. if (DTMFSender){
  282. DTMFSender.insertDTMF(tones,
  283. (duration || 200),
  284. (pause || 200));
  285. }
  286. }
  287. };
  288. module.exports = DTMF;
  289. },{}],4:[function(require,module,exports){
  290. /* global config, APP, Strophe */
  291. // cache datachannels to avoid garbage collection
  292. // https://code.google.com/p/chromium/issues/detail?id=405545
  293. var RTCEvents = require("../../service/RTC/RTCEvents");
  294. var _dataChannels = [];
  295. var eventEmitter = null;
  296. var DataChannels = {
  297. /**
  298. * Callback triggered by PeerConnection when new data channel is opened
  299. * on the bridge.
  300. * @param event the event info object.
  301. */
  302. onDataChannel: function (event) {
  303. var dataChannel = event.channel;
  304. dataChannel.onopen = function () {
  305. console.info("Data channel opened by the Videobridge!", dataChannel);
  306. // Code sample for sending string and/or binary data
  307. // Sends String message to the bridge
  308. //dataChannel.send("Hello bridge!");
  309. // Sends 12 bytes binary message to the bridge
  310. //dataChannel.send(new ArrayBuffer(12));
  311. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  312. };
  313. dataChannel.onerror = function (error) {
  314. console.error("Data Channel Error:", error, dataChannel);
  315. };
  316. dataChannel.onmessage = function (event) {
  317. var data = event.data;
  318. // JSON
  319. var obj;
  320. try {
  321. obj = JSON.parse(data);
  322. }
  323. catch (e) {
  324. console.error(
  325. "Failed to parse data channel message as JSON: ",
  326. data,
  327. dataChannel);
  328. }
  329. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  330. var colibriClass = obj.colibriClass;
  331. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  332. // Endpoint ID from the Videobridge.
  333. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  334. console.info(
  335. "Data channel new dominant speaker event: ",
  336. dominantSpeakerEndpoint);
  337. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  338. }
  339. else if ("InLastNChangeEvent" === colibriClass) {
  340. var oldValue = obj.oldValue;
  341. var newValue = obj.newValue;
  342. // Make sure that oldValue and newValue are of type boolean.
  343. var type;
  344. if ((type = typeof oldValue) !== 'boolean') {
  345. if (type === 'string') {
  346. oldValue = (oldValue == "true");
  347. } else {
  348. oldValue = new Boolean(oldValue).valueOf();
  349. }
  350. }
  351. if ((type = typeof newValue) !== 'boolean') {
  352. if (type === 'string') {
  353. newValue = (newValue == "true");
  354. } else {
  355. newValue = new Boolean(newValue).valueOf();
  356. }
  357. }
  358. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  359. }
  360. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  361. // The new/latest list of last-n endpoint IDs.
  362. var lastNEndpoints = obj.lastNEndpoints;
  363. // The list of endpoint IDs which are entering the list of
  364. // last-n at this time i.e. were not in the old list of last-n
  365. // endpoint IDs.
  366. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  367. console.log(
  368. "Data channel new last-n event: ",
  369. lastNEndpoints, endpointsEnteringLastN, obj);
  370. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  371. lastNEndpoints, endpointsEnteringLastN, obj);
  372. }
  373. else {
  374. console.debug("Data channel JSON-formatted message: ", obj);
  375. }
  376. }
  377. };
  378. dataChannel.onclose = function () {
  379. console.info("The Data Channel closed", dataChannel);
  380. var idx = _dataChannels.indexOf(dataChannel);
  381. if (idx > -1)
  382. _dataChannels = _dataChannels.splice(idx, 1);
  383. };
  384. _dataChannels.push(dataChannel);
  385. },
  386. /**
  387. * Binds "ondatachannel" event listener to given PeerConnection instance.
  388. * @param peerConnection WebRTC peer connection instance.
  389. */
  390. init: function (peerConnection, emitter) {
  391. if(!config.openSctp)
  392. return;
  393. peerConnection.ondatachannel = this.onDataChannel;
  394. eventEmitter = emitter;
  395. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  396. // Although it's not a requirement to open separate channels from both bridge
  397. // and peer as single channel can be used for sending and receiving data.
  398. // So either channel opened by the bridge or the one opened here is enough
  399. // for communication with the bridge.
  400. /*var dataChannelOptions =
  401. {
  402. reliable: true
  403. };
  404. var dataChannel
  405. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  406. // Can be used only when is in open state
  407. dataChannel.onopen = function ()
  408. {
  409. dataChannel.send("My channel !!!");
  410. };
  411. dataChannel.onmessage = function (event)
  412. {
  413. var msgData = event.data;
  414. console.info("Got My Data Channel Message:", msgData, dataChannel);
  415. };*/
  416. },
  417. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  418. handlePinnedEndpointEvent: onPinnedEndpointChanged
  419. };
  420. function onSelectedEndpointChanged(userResource) {
  421. console.log('selected endpoint changed: ', userResource);
  422. if (_dataChannels && _dataChannels.length != 0) {
  423. _dataChannels.some(function (dataChannel) {
  424. if (dataChannel.readyState == 'open') {
  425. console.log('sending selected endpoint changed ' +
  426. 'notification to the bridge: ', userResource);
  427. dataChannel.send(JSON.stringify({
  428. 'colibriClass': 'SelectedEndpointChangedEvent',
  429. 'selectedEndpoint':
  430. (!userResource || userResource === null)?
  431. null : userResource
  432. }));
  433. return true;
  434. }
  435. });
  436. }
  437. }
  438. function onPinnedEndpointChanged(userResource) {
  439. console.log('pinned endpoint changed: ', userResource);
  440. if (_dataChannels && _dataChannels.length != 0) {
  441. _dataChannels.some(function (dataChannel) {
  442. if (dataChannel.readyState == 'open') {
  443. dataChannel.send(JSON.stringify({
  444. 'colibriClass': 'PinnedEndpointChangedEvent',
  445. 'pinnedEndpoint':
  446. (!userResource || userResource == null)?
  447. null : userResource
  448. }));
  449. return true;
  450. }
  451. });
  452. }
  453. }
  454. module.exports = DataChannels;
  455. },{"../../service/RTC/RTCEvents":107}],5:[function(require,module,exports){
  456. /* global APP */
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. var RTCEvents = require("../../service/RTC/RTCEvents");
  459. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  460. this.stream = stream;
  461. this.eventEmitter = eventEmitter;
  462. this.type = type;
  463. this.videoType = videoType;
  464. this.isGUMStream = true;
  465. if(isGUMStream === false)
  466. this.isGUMStream = isGUMStream;
  467. var self = this;
  468. if(type == "audio") {
  469. this.getTracks = function () {
  470. return self.stream.getAudioTracks();
  471. };
  472. } else {
  473. this.getTracks = function () {
  474. return self.stream.getVideoTracks();
  475. };
  476. }
  477. this.stream.onended = function() {
  478. self.streamEnded();
  479. };
  480. }
  481. LocalStream.prototype.streamEnded = function () {
  482. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  483. };
  484. LocalStream.prototype.getOriginalStream = function()
  485. {
  486. return this.stream;
  487. };
  488. LocalStream.prototype.isAudioStream = function () {
  489. return this.type === "audio";
  490. };
  491. LocalStream.prototype.setMute = function (mute)
  492. {
  493. var isAudio = this.isAudioStream();
  494. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  495. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  496. (isAudio && this.isGUMStream) || this.videoType === "screen") {
  497. var tracks = this.getTracks();
  498. for (var idx = 0; idx < tracks.length; idx++) {
  499. tracks[idx].enabled = !mute;
  500. }
  501. this.eventEmitter.emit(eventType, mute);
  502. } else {
  503. if (mute) {
  504. APP.xmpp.removeStream(this.stream);
  505. this.stream.stop();
  506. this.eventEmitter.emit(eventType, true);
  507. } else {
  508. var self = this;
  509. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  510. (this.isAudioStream() ? ["audio"] : ["video"]),
  511. function (stream) {
  512. if (isAudio) {
  513. APP.RTC.changeLocalAudio(stream,
  514. function () {
  515. self.eventEmitter.emit(eventType, false);
  516. });
  517. } else {
  518. APP.RTC.changeLocalVideo(stream, false,
  519. function () {
  520. self.eventEmitter.emit(eventType, false);
  521. });
  522. }
  523. });
  524. }
  525. }
  526. };
  527. LocalStream.prototype.isMuted = function () {
  528. var tracks = [];
  529. if (this.isAudioStream()) {
  530. tracks = this.stream.getAudioTracks();
  531. } else {
  532. if (this.stream.ended)
  533. return true;
  534. tracks = this.stream.getVideoTracks();
  535. }
  536. for (var idx = 0; idx < tracks.length; idx++) {
  537. if(tracks[idx].enabled)
  538. return false;
  539. }
  540. return true;
  541. };
  542. LocalStream.prototype.getId = function () {
  543. return this.stream.getTracks()[0].id;
  544. };
  545. module.exports = LocalStream;
  546. },{"../../service/RTC/RTCEvents":107,"../../service/RTC/StreamEventTypes.js":109}],6:[function(require,module,exports){
  547. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  548. /**
  549. * Creates a MediaStream object for the given data, session id and ssrc.
  550. * It is a wrapper class for the MediaStream.
  551. *
  552. * @param data the data object from which we obtain the stream,
  553. * the peerjid, etc.
  554. * @param sid the session id
  555. * @param ssrc the ssrc corresponding to this MediaStream
  556. *
  557. * @constructor
  558. */
  559. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  560. // XXX(gp) to minimize headaches in the future, we should build our
  561. // abstractions around tracks and not streams. ORTC is track based API.
  562. // Mozilla expects m-lines to represent media tracks.
  563. //
  564. // Practically, what I'm saying is that we should have a MediaTrack class
  565. // and not a MediaStream class.
  566. //
  567. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  568. // a track might have an associated RTX and FEC sources.
  569. this.sid = sid;
  570. this.stream = data.stream;
  571. this.peerjid = data.peerjid;
  572. this.videoType = data.videoType;
  573. this.ssrc = ssrc;
  574. this.type = (this.stream.getVideoTracks().length > 0)?
  575. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  576. this.muted = false;
  577. this.eventEmitter = eventEmitter;
  578. }
  579. MediaStream.prototype.getOriginalStream = function() {
  580. return this.stream;
  581. };
  582. MediaStream.prototype.setMute = function (value) {
  583. this.stream.muted = value;
  584. this.muted = value;
  585. };
  586. module.exports = MediaStream;
  587. },{"../../service/RTC/MediaStreamTypes":106}],7:[function(require,module,exports){
  588. /* global APP */
  589. var EventEmitter = require("events");
  590. var RTCBrowserType = require("./RTCBrowserType");
  591. var RTCUtils = require("./RTCUtils.js");
  592. var LocalStream = require("./LocalStream.js");
  593. var DataChannels = require("./DataChannels");
  594. var MediaStream = require("./MediaStream.js");
  595. var DesktopSharingEventTypes
  596. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  597. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  598. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  599. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  600. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  601. var UIEvents = require("../../service/UI/UIEvents");
  602. var eventEmitter = new EventEmitter();
  603. function getMediaStreamUsage()
  604. {
  605. var result = {
  606. audio: true,
  607. video: true
  608. };
  609. /** There are some issues with the desktop sharing
  610. * when this property is enabled.
  611. * WARNING: We must change the implementation to start video/audio if we
  612. * receive from the focus that the peer is not muted.
  613. var isSecureConnection = window.location.protocol == "https:";
  614. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  615. {
  616. result = {
  617. audio: false,
  618. video: false
  619. };
  620. }
  621. **/
  622. return result;
  623. }
  624. var RTC = {
  625. rtcUtils: null,
  626. devices: {
  627. audio: true,
  628. video: true
  629. },
  630. localStreams: [],
  631. remoteStreams: {},
  632. localAudio: null,
  633. localVideo: null,
  634. addStreamListener: function (listener, eventType) {
  635. eventEmitter.on(eventType, listener);
  636. },
  637. addListener: function (type, listener) {
  638. eventEmitter.on(type, listener);
  639. },
  640. removeStreamListener: function (listener, eventType) {
  641. if(!(eventType instanceof StreamEventTypes))
  642. throw "Illegal argument";
  643. eventEmitter.removeListener(eventType, listener);
  644. },
  645. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  646. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  647. //in firefox we have only one stream object
  648. if(this.localStreams.length == 0 ||
  649. this.localStreams[0].getOriginalStream() != stream)
  650. this.localStreams.push(localStream);
  651. if(isMuted === true)
  652. localStream.setMute(true);
  653. if(type == "audio") {
  654. this.localAudio = localStream;
  655. } else {
  656. this.localVideo = localStream;
  657. }
  658. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  659. if(change)
  660. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  661. eventEmitter.emit(eventType, localStream, isMuted);
  662. return localStream;
  663. },
  664. removeLocalStream: function (stream) {
  665. for(var i = 0; i < this.localStreams.length; i++) {
  666. if(this.localStreams[i].getOriginalStream() === stream) {
  667. delete this.localStreams[i];
  668. return;
  669. }
  670. }
  671. },
  672. createRemoteStream: function (data, sid, thessrc) {
  673. var remoteStream = new MediaStream(data, sid, thessrc,
  674. RTCBrowserType.getBrowserType(), eventEmitter);
  675. var jid = data.peerjid || APP.xmpp.myJid();
  676. if(!this.remoteStreams[jid]) {
  677. this.remoteStreams[jid] = {};
  678. }
  679. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  680. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  681. return remoteStream;
  682. },
  683. getPCConstraints: function () {
  684. return this.rtcUtils.pc_constraints;
  685. },
  686. getUserMediaWithConstraints:function(um, success_callback,
  687. failure_callback, resolution,
  688. bandwidth, fps, desktopStream)
  689. {
  690. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  691. failure_callback, resolution, bandwidth, fps, desktopStream);
  692. },
  693. attachMediaStream: function (elSelector, stream) {
  694. this.rtcUtils.attachMediaStream(elSelector, stream);
  695. },
  696. getStreamID: function (stream) {
  697. return this.rtcUtils.getStreamID(stream);
  698. },
  699. getVideoSrc: function (element) {
  700. return this.rtcUtils.getVideoSrc(element);
  701. },
  702. setVideoSrc: function (element, src) {
  703. this.rtcUtils.setVideoSrc(element, src);
  704. },
  705. getVideoElementName: function () {
  706. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  707. },
  708. dispose: function() {
  709. if (this.rtcUtils) {
  710. this.rtcUtils = null;
  711. }
  712. },
  713. stop: function () {
  714. this.dispose();
  715. },
  716. start: function () {
  717. var self = this;
  718. APP.desktopsharing.addListener(
  719. function (stream, isUsingScreenStream, callback) {
  720. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  721. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  722. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  723. DataChannels.init(event.peerconnection, eventEmitter);
  724. });
  725. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  726. DataChannels.handleSelectedEndpointEvent);
  727. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  728. DataChannels.handlePinnedEndpointEvent);
  729. // In case of IE we continue from 'onReady' callback
  730. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  731. // once it is initialized.
  732. var onReady = function () {
  733. eventEmitter.emit(RTCEvents.RTC_READY, true);
  734. self.rtcUtils.obtainAudioAndVideoPermissions(
  735. null, null, getMediaStreamUsage());
  736. };
  737. this.rtcUtils = new RTCUtils(this, onReady);
  738. // Call onReady() if Temasys plugin is not used
  739. if (!RTCBrowserType.isTemasysPluginUsed()) {
  740. onReady();
  741. }
  742. },
  743. muteRemoteVideoStream: function (jid, value) {
  744. var stream;
  745. if(this.remoteStreams[jid] &&
  746. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  747. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  748. }
  749. if(!stream)
  750. return true;
  751. if (value != stream.muted) {
  752. stream.setMute(value);
  753. return true;
  754. }
  755. return false;
  756. },
  757. switchVideoStreams: function (new_stream) {
  758. this.localVideo.stream = new_stream;
  759. this.localStreams = [];
  760. //in firefox we have only one stream object
  761. if (this.localAudio.getOriginalStream() != new_stream)
  762. this.localStreams.push(this.localAudio);
  763. this.localStreams.push(this.localVideo);
  764. },
  765. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  766. var oldStream = this.localVideo.getOriginalStream();
  767. var type = (isUsingScreenStream? "screen" : "video");
  768. var localCallback = callback;
  769. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  770. localCallback = function() {
  771. APP.xmpp.setVideoMute(false, function(mute) {
  772. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  773. });
  774. callback();
  775. };
  776. }
  777. // FIXME: Workaround for FF/IE/Safari
  778. if (stream && stream.videoStream) {
  779. stream = stream.videoStream;
  780. }
  781. var videoStream = this.rtcUtils.createStream(stream, true);
  782. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  783. // Stop the stream to trigger onended event for old stream
  784. oldStream.stop();
  785. this.switchVideoStreams(videoStream, oldStream);
  786. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  787. },
  788. changeLocalAudio: function (stream, callback) {
  789. var oldStream = this.localAudio.getOriginalStream();
  790. var newStream = this.rtcUtils.createStream(stream);
  791. this.localAudio = this.createLocalStream(newStream, "audio", true);
  792. // Stop the stream to trigger onended event for old stream
  793. oldStream.stop();
  794. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  795. },
  796. isVideoMuted: function (jid) {
  797. if (jid === APP.xmpp.myJid()) {
  798. var localVideo = APP.RTC.localVideo;
  799. return (!localVideo || localVideo.isMuted());
  800. } else {
  801. if (!APP.RTC.remoteStreams[jid] ||
  802. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  803. return null;
  804. }
  805. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  806. }
  807. },
  808. /**
  809. * Checks if video identified by given src is desktop stream.
  810. * @param videoSrc eg.
  811. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  812. * @returns {boolean}
  813. */
  814. isVideoSrcDesktop: function (jid) {
  815. if(!jid)
  816. return false;
  817. var isDesktop = false;
  818. var stream = null;
  819. if (APP.xmpp.myJid() === jid) {
  820. // local video
  821. stream = this.localVideo;
  822. } else {
  823. var peerStreams = this.remoteStreams[jid];
  824. if(!peerStreams)
  825. return false;
  826. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  827. }
  828. if(stream)
  829. isDesktop = (stream.videoType === "screen");
  830. return isDesktop;
  831. },
  832. setVideoMute: function (mute, callback, options) {
  833. if (!this.localVideo)
  834. return;
  835. if (mute == APP.RTC.localVideo.isMuted())
  836. {
  837. APP.xmpp.sendVideoInfoPresence(mute);
  838. if (callback)
  839. callback(mute);
  840. }
  841. else
  842. {
  843. APP.RTC.localVideo.setMute(mute);
  844. APP.xmpp.setVideoMute(
  845. mute,
  846. callback,
  847. options);
  848. }
  849. },
  850. setDeviceAvailability: function (devices) {
  851. if(!devices)
  852. return;
  853. if(devices.audio === true || devices.audio === false)
  854. this.devices.audio = devices.audio;
  855. if(devices.video === true || devices.video === false)
  856. this.devices.video = devices.video;
  857. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  858. }
  859. };
  860. module.exports = RTC;
  861. },{"../../service/RTC/MediaStreamTypes":106,"../../service/RTC/RTCEvents.js":107,"../../service/RTC/StreamEventTypes.js":109,"../../service/UI/UIEvents":110,"../../service/desktopsharing/DesktopSharingEventTypes":113,"../../service/xmpp/XMPPEvents":116,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":117}],8:[function(require,module,exports){
  862. var currentBrowser;
  863. var browserVersion;
  864. var RTCBrowserType = {
  865. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  866. RTC_BROWSER_OPERA: "rtc_browser.opera",
  867. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  868. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  869. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  870. getBrowserType: function () {
  871. return currentBrowser;
  872. },
  873. isChrome: function () {
  874. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  875. },
  876. isOpera: function () {
  877. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  878. },
  879. isFirefox: function () {
  880. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  881. },
  882. isIExplorer: function () {
  883. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  884. },
  885. isSafari: function () {
  886. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  887. },
  888. isTemasysPluginUsed: function () {
  889. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  890. },
  891. getFirefoxVersion: function () {
  892. return RTCBrowserType.isFirefox() ? browserVersion : null;
  893. },
  894. getChromeVersion: function () {
  895. return RTCBrowserType.isChrome() ? browserVersion : null;
  896. },
  897. usesPlanB: function() {
  898. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  899. RTCBrowserType.isTemasysPluginUsed();
  900. },
  901. usesUnifiedPlan: function() {
  902. return RTCBrowserType.isFirefox();
  903. }
  904. // Add version getters for other browsers when needed
  905. };
  906. // detectOpera() must be called before detectChrome() !!!
  907. // otherwise Opera wil be detected as Chrome
  908. function detectChrome() {
  909. if (navigator.webkitGetUserMedia) {
  910. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  911. var userAgent = navigator.userAgent.toLowerCase();
  912. // We can assume that user agent is chrome, because it's
  913. // enforced when 'ext' streaming method is set
  914. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  915. console.log("This appears to be Chrome, ver: " + ver);
  916. return ver;
  917. }
  918. return null;
  919. }
  920. function detectOpera() {
  921. var userAgent = navigator.userAgent;
  922. if (userAgent.match(/Opera|OPR/)) {
  923. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  924. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  925. console.info("This appears to be Opera, ver: " + version);
  926. return version;
  927. }
  928. return null;
  929. }
  930. function detectFirefox() {
  931. if (navigator.mozGetUserMedia) {
  932. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  933. var version = parseInt(
  934. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  935. console.log('This appears to be Firefox, ver: ' + version);
  936. return version;
  937. }
  938. return null;
  939. }
  940. function detectSafari() {
  941. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  942. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  943. console.info("This appears to be Safari");
  944. // FIXME detect Safari version when needed
  945. return 1;
  946. }
  947. return null;
  948. }
  949. function detectIE() {
  950. var version;
  951. var ua = window.navigator.userAgent;
  952. var msie = ua.indexOf('MSIE ');
  953. if (msie > 0) {
  954. // IE 10 or older => return version number
  955. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  956. }
  957. var trident = ua.indexOf('Trident/');
  958. if (!version && trident > 0) {
  959. // IE 11 => return version number
  960. var rv = ua.indexOf('rv:');
  961. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  962. }
  963. var edge = ua.indexOf('Edge/');
  964. if (!version && edge > 0) {
  965. // IE 12 => return version number
  966. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  967. }
  968. if (version) {
  969. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  970. console.info("This appears to be IExplorer, ver: " + version);
  971. }
  972. return version;
  973. }
  974. function detectBrowser() {
  975. var version;
  976. var detectors = [
  977. detectOpera,
  978. detectChrome,
  979. detectFirefox,
  980. detectIE,
  981. detectSafari
  982. ];
  983. // Try all browser detectors
  984. for (var i = 0; i < detectors.length; i++) {
  985. version = detectors[i]();
  986. if (version)
  987. return version;
  988. }
  989. console.error("Failed to detect browser type");
  990. return undefined;
  991. }
  992. browserVersion = detectBrowser();
  993. module.exports = RTCBrowserType;
  994. },{}],9:[function(require,module,exports){
  995. /* global config, require, attachMediaStream, getUserMedia */
  996. var RTCBrowserType = require("./RTCBrowserType");
  997. var Resolutions = require("../../service/RTC/Resolutions");
  998. var AdapterJS = require("./adapter.screenshare");
  999. var SDPUtil = require("../xmpp/SDPUtil");
  1000. var currentResolution = null;
  1001. function getPreviousResolution(resolution) {
  1002. if(!Resolutions[resolution])
  1003. return null;
  1004. var order = Resolutions[resolution].order;
  1005. var res = null;
  1006. var resName = null;
  1007. for(var i in Resolutions) {
  1008. var tmp = Resolutions[i];
  1009. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1010. resName = i;
  1011. res = tmp;
  1012. }
  1013. }
  1014. return resName;
  1015. }
  1016. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1017. if (resolution && !constraints.video || isAndroid) {
  1018. // same behaviour as true
  1019. constraints.video = { mandatory: {}, optional: [] };
  1020. }
  1021. if(Resolutions[resolution]) {
  1022. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1023. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1024. }
  1025. else {
  1026. if (isAndroid) {
  1027. constraints.video.mandatory.minWidth = 320;
  1028. constraints.video.mandatory.minHeight = 240;
  1029. constraints.video.mandatory.maxFrameRate = 15;
  1030. }
  1031. }
  1032. if (constraints.video.mandatory.minWidth)
  1033. constraints.video.mandatory.maxWidth =
  1034. constraints.video.mandatory.minWidth;
  1035. if (constraints.video.mandatory.minHeight)
  1036. constraints.video.mandatory.maxHeight =
  1037. constraints.video.mandatory.minHeight;
  1038. }
  1039. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1040. {
  1041. var constraints = {audio: false, video: false};
  1042. if (um.indexOf('video') >= 0) {
  1043. // same behaviour as true
  1044. constraints.video = { mandatory: {}, optional: [] };
  1045. }
  1046. if (um.indexOf('audio') >= 0) {
  1047. // same behaviour as true
  1048. constraints.audio = { mandatory: {}, optional: []};
  1049. }
  1050. if (um.indexOf('screen') >= 0) {
  1051. if (RTCBrowserType.isChrome()) {
  1052. constraints.video = {
  1053. mandatory: {
  1054. chromeMediaSource: "screen",
  1055. googLeakyBucket: true,
  1056. maxWidth: window.screen.width,
  1057. maxHeight: window.screen.height,
  1058. maxFrameRate: 3
  1059. },
  1060. optional: []
  1061. };
  1062. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1063. constraints.video = {
  1064. optional: [
  1065. {
  1066. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1067. }
  1068. ]
  1069. };
  1070. } else {
  1071. console.error(
  1072. "'screen' WebRTC media source is supported only in Chrome" +
  1073. " and with Temasys plugin");
  1074. }
  1075. }
  1076. if (um.indexOf('desktop') >= 0) {
  1077. constraints.video = {
  1078. mandatory: {
  1079. chromeMediaSource: "desktop",
  1080. chromeMediaSourceId: desktopStream,
  1081. googLeakyBucket: true,
  1082. maxWidth: window.screen.width,
  1083. maxHeight: window.screen.height,
  1084. maxFrameRate: 3
  1085. },
  1086. optional: []
  1087. };
  1088. }
  1089. if (constraints.audio) {
  1090. // if it is good enough for hangouts...
  1091. constraints.audio.optional.push(
  1092. {googEchoCancellation: true},
  1093. {googAutoGainControl: true},
  1094. {googNoiseSupression: true},
  1095. {googHighpassFilter: true},
  1096. {googNoisesuppression2: true},
  1097. {googEchoCancellation2: true},
  1098. {googAutoGainControl2: true}
  1099. );
  1100. }
  1101. if (constraints.video) {
  1102. constraints.video.optional.push(
  1103. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1104. );
  1105. if (um.indexOf('video') >= 0) {
  1106. constraints.video.optional.push(
  1107. {googLeakyBucket: true}
  1108. );
  1109. }
  1110. }
  1111. if (um.indexOf('video') >= 0) {
  1112. setResolutionConstraints(constraints, resolution, isAndroid);
  1113. }
  1114. if (bandwidth) {
  1115. if (!constraints.video) {
  1116. //same behaviour as true
  1117. constraints.video = {mandatory: {}, optional: []};
  1118. }
  1119. constraints.video.optional.push({bandwidth: bandwidth});
  1120. }
  1121. if (fps) {
  1122. // for some cameras it might be necessary to request 30fps
  1123. // so they choose 30fps mjpg over 10fps yuy2
  1124. if (!constraints.video) {
  1125. // same behaviour as true;
  1126. constraints.video = {mandatory: {}, optional: []};
  1127. }
  1128. constraints.video.mandatory.minFrameRate = fps;
  1129. }
  1130. return constraints;
  1131. }
  1132. function RTCUtils(RTCService, onTemasysPluginReady)
  1133. {
  1134. var self = this;
  1135. this.service = RTCService;
  1136. if (RTCBrowserType.isFirefox()) {
  1137. var FFversion = RTCBrowserType.getFirefoxVersion();
  1138. if (FFversion >= 40 && config.useBundle && config.useRtcpMux) {
  1139. this.peerconnection = mozRTCPeerConnection;
  1140. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1141. this.pc_constraints = {};
  1142. this.attachMediaStream = function (element, stream) {
  1143. // srcObject is being standardized and FF will eventually
  1144. // support that unprefixed. FF also supports the
  1145. // "element.src = URL.createObjectURL(...)" combo, but that
  1146. // will be deprecated in favour of srcObject.
  1147. //
  1148. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1149. // https://github.com/webrtc/samples/issues/302
  1150. if(!element[0])
  1151. return;
  1152. element[0].mozSrcObject = stream;
  1153. element[0].play();
  1154. };
  1155. this.getStreamID = function (stream) {
  1156. var id = stream.id;
  1157. if (!id) {
  1158. var tracks = stream.getVideoTracks();
  1159. if (!tracks || tracks.length === 0) {
  1160. tracks = stream.getAudioTracks();
  1161. }
  1162. id = tracks[0].id;
  1163. }
  1164. return SDPUtil.filter_special_chars(id);
  1165. };
  1166. this.getVideoSrc = function (element) {
  1167. if(!element)
  1168. return null;
  1169. return element.mozSrcObject;
  1170. };
  1171. this.setVideoSrc = function (element, src) {
  1172. if(element)
  1173. element.mozSrcObject = src;
  1174. };
  1175. RTCSessionDescription = mozRTCSessionDescription;
  1176. RTCIceCandidate = mozRTCIceCandidate;
  1177. } else {
  1178. console.error(
  1179. "Firefox requirements not met, ver: " + FFversion +
  1180. ", bundle: " + config.useBundle +
  1181. ", rtcp-mux: " + config.useRtcpMux);
  1182. window.location.href = 'unsupported_browser.html';
  1183. return;
  1184. }
  1185. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1186. this.peerconnection = webkitRTCPeerConnection;
  1187. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1188. this.attachMediaStream = function (element, stream) {
  1189. element.attr('src', webkitURL.createObjectURL(stream));
  1190. };
  1191. this.getStreamID = function (stream) {
  1192. // streams from FF endpoints have the characters '{' and '}'
  1193. // that make jQuery choke.
  1194. return SDPUtil.filter_special_chars(stream.id);
  1195. };
  1196. this.getVideoSrc = function (element) {
  1197. if(!element)
  1198. return null;
  1199. return element.getAttribute("src");
  1200. };
  1201. this.setVideoSrc = function (element, src) {
  1202. if(element)
  1203. element.setAttribute("src", src);
  1204. };
  1205. // DTLS should now be enabled by default but..
  1206. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1207. if (navigator.userAgent.indexOf('Android') != -1) {
  1208. this.pc_constraints = {}; // disable DTLS on Android
  1209. }
  1210. if (!webkitMediaStream.prototype.getVideoTracks) {
  1211. webkitMediaStream.prototype.getVideoTracks = function () {
  1212. return this.videoTracks;
  1213. };
  1214. }
  1215. if (!webkitMediaStream.prototype.getAudioTracks) {
  1216. webkitMediaStream.prototype.getAudioTracks = function () {
  1217. return this.audioTracks;
  1218. };
  1219. }
  1220. }
  1221. // Detect IE/Safari
  1222. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1223. //AdapterJS.WebRTCPlugin.setLogLevel(
  1224. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1225. AdapterJS.webRTCReady(function (isPlugin) {
  1226. self.peerconnection = RTCPeerConnection;
  1227. self.getUserMedia = getUserMedia;
  1228. self.attachMediaStream = function (elSel, stream) {
  1229. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1230. return;
  1231. }
  1232. attachMediaStream(elSel[0], stream);
  1233. };
  1234. self.getStreamID = function (stream) {
  1235. var id = SDPUtil.filter_special_chars(stream.label);
  1236. return id;
  1237. };
  1238. self.getVideoSrc = function (element) {
  1239. if (!element) {
  1240. console.warn("Attempt to get video SRC of null element");
  1241. return null;
  1242. }
  1243. var children = element.children;
  1244. for (var i = 0; i !== children.length; ++i) {
  1245. if (children[i].name === 'streamId') {
  1246. return children[i].value;
  1247. }
  1248. }
  1249. //console.info(element.id + " SRC: " + src);
  1250. return null;
  1251. };
  1252. self.setVideoSrc = function (element, src) {
  1253. //console.info("Set video src: ", element, src);
  1254. if (!src) {
  1255. console.warn("Not attaching video stream, 'src' is null");
  1256. return;
  1257. }
  1258. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1259. var stream = AdapterJS.WebRTCPlugin.plugin
  1260. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1261. attachMediaStream(element, stream);
  1262. };
  1263. onTemasysPluginReady(isPlugin);
  1264. });
  1265. } else {
  1266. try {
  1267. console.log('Browser does not appear to be WebRTC-capable');
  1268. } catch (e) { }
  1269. window.location.href = 'unsupported_browser.html';
  1270. }
  1271. }
  1272. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1273. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1274. desktopStream) {
  1275. currentResolution = resolution;
  1276. // Check if we are running on Android device
  1277. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1278. var constraints = getConstraints(
  1279. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1280. console.info("Get media constraints", constraints);
  1281. var self = this;
  1282. try {
  1283. this.getUserMedia(constraints,
  1284. function (stream) {
  1285. console.log('onUserMediaSuccess');
  1286. self.setAvailableDevices(um, true);
  1287. success_callback(stream);
  1288. },
  1289. function (error) {
  1290. self.setAvailableDevices(um, false);
  1291. console.warn('Failed to get access to local media. Error ',
  1292. error, constraints);
  1293. if (failure_callback) {
  1294. failure_callback(error);
  1295. }
  1296. });
  1297. } catch (e) {
  1298. console.error('GUM failed: ', e);
  1299. if(failure_callback) {
  1300. failure_callback(e);
  1301. }
  1302. }
  1303. };
  1304. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1305. var devices = {};
  1306. if(um.indexOf("video") != -1) {
  1307. devices.video = available;
  1308. }
  1309. if(um.indexOf("audio") != -1) {
  1310. devices.audio = available;
  1311. }
  1312. this.service.setDeviceAvailability(devices);
  1313. };
  1314. /**
  1315. * We ask for audio and video combined stream in order to get permissions and
  1316. * not to ask twice.
  1317. */
  1318. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1319. function(devices, callback, usageOptions)
  1320. {
  1321. var self = this;
  1322. // Get AV
  1323. var successCallback = function (stream) {
  1324. if(callback)
  1325. callback(stream, usageOptions);
  1326. else
  1327. self.successCallback(stream, usageOptions);
  1328. };
  1329. if(!devices)
  1330. devices = ['audio', 'video'];
  1331. var newDevices = [];
  1332. if(usageOptions)
  1333. for(var i = 0; i < devices.length; i++) {
  1334. var device = devices[i];
  1335. if(usageOptions[device] === true)
  1336. newDevices.push(device);
  1337. }
  1338. else
  1339. newDevices = devices;
  1340. if(newDevices.length === 0) {
  1341. successCallback();
  1342. return;
  1343. }
  1344. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1345. // With FF/IE we can't split the stream into audio and video because FF
  1346. // doesn't support media stream constructors. So, we need to get the
  1347. // audio stream separately from the video stream using two distinct GUM
  1348. // calls. Not very user friendly :-( but we don't have many other
  1349. // options neither.
  1350. //
  1351. // Note that we pack those 2 streams in a single object and pass it to
  1352. // the successCallback method.
  1353. var obtainVideo = function (audioStream) {
  1354. self.getUserMediaWithConstraints(
  1355. ['video'],
  1356. function (videoStream) {
  1357. return successCallback({
  1358. audioStream: audioStream,
  1359. videoStream: videoStream
  1360. });
  1361. },
  1362. function (error) {
  1363. console.error(
  1364. 'failed to obtain video stream - stop', error);
  1365. self.errorCallback(error);
  1366. },
  1367. config.resolution || '360');
  1368. };
  1369. var obtainAudio = function () {
  1370. self.getUserMediaWithConstraints(
  1371. ['audio'],
  1372. function (audioStream) {
  1373. if (newDevices.indexOf('video') !== -1)
  1374. obtainVideo(audioStream);
  1375. },
  1376. function (error) {
  1377. console.error(
  1378. 'failed to obtain audio stream - stop', error);
  1379. self.errorCallback(error);
  1380. }
  1381. );
  1382. };
  1383. if (newDevices.indexOf('audio') !== -1) {
  1384. obtainAudio();
  1385. } else {
  1386. obtainVideo(null);
  1387. }
  1388. } else {
  1389. this.getUserMediaWithConstraints(
  1390. newDevices,
  1391. function (stream) {
  1392. successCallback(stream);
  1393. },
  1394. function (error) {
  1395. self.errorCallback(error);
  1396. },
  1397. config.resolution || '360');
  1398. }
  1399. };
  1400. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1401. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1402. // it's an object with two properties: audioStream, videoStream.
  1403. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1404. console.log('got', stream, stream.getAudioTracks().length,
  1405. stream.getVideoTracks().length);
  1406. this.handleLocalStream(stream, usageOptions);
  1407. };
  1408. RTCUtils.prototype.errorCallback = function (error) {
  1409. var self = this;
  1410. console.error('failed to obtain audio/video stream - trying audio only', error);
  1411. var resolution = getPreviousResolution(currentResolution);
  1412. if(typeof error == "object" && error.constraintName && error.name
  1413. && (error.name == "ConstraintNotSatisfiedError" ||
  1414. error.name == "OverconstrainedError") &&
  1415. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1416. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1417. && resolution != null)
  1418. {
  1419. self.getUserMediaWithConstraints(['audio', 'video'],
  1420. function (stream) {
  1421. return self.successCallback(stream);
  1422. }, function (error) {
  1423. return self.errorCallback(error);
  1424. }, resolution);
  1425. }
  1426. else {
  1427. self.getUserMediaWithConstraints(
  1428. ['audio'],
  1429. function (stream) {
  1430. return self.successCallback(stream);
  1431. },
  1432. function (error) {
  1433. console.error('failed to obtain audio/video stream - stop',
  1434. error);
  1435. return self.successCallback(null);
  1436. }
  1437. );
  1438. }
  1439. };
  1440. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1441. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1442. // an object with two properties: audioStream, videoStream.
  1443. var audioStream, videoStream;
  1444. if(window.webkitMediaStream)
  1445. {
  1446. audioStream = new webkitMediaStream();
  1447. videoStream = new webkitMediaStream();
  1448. if(stream) {
  1449. var audioTracks = stream.getAudioTracks();
  1450. for (var i = 0; i < audioTracks.length; i++) {
  1451. audioStream.addTrack(audioTracks[i]);
  1452. }
  1453. var videoTracks = stream.getVideoTracks();
  1454. for (i = 0; i < videoTracks.length; i++) {
  1455. videoStream.addTrack(videoTracks[i]);
  1456. }
  1457. }
  1458. }
  1459. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1460. { // Firefox and Temasys plugin
  1461. if (stream && stream.audioStream)
  1462. audioStream = stream.audioStream;
  1463. else
  1464. audioStream = new DummyMediaStream("dummyAudio");
  1465. if (stream && stream.videoStream)
  1466. videoStream = stream.videoStream;
  1467. else
  1468. videoStream = new DummyMediaStream("dummyVideo");
  1469. }
  1470. var audioMuted = (usageOptions && usageOptions.audio === false),
  1471. videoMuted = (usageOptions && usageOptions.video === false);
  1472. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1473. videoGUM = (!usageOptions || usageOptions.video !== false);
  1474. this.service.createLocalStream(audioStream, "audio", null, null,
  1475. audioMuted, audioGUM);
  1476. this.service.createLocalStream(videoStream, "video", null, null,
  1477. videoMuted, videoGUM);
  1478. };
  1479. function DummyMediaStream(id) {
  1480. this.id = id;
  1481. this.label = id;
  1482. this.stop = function() { };
  1483. this.getAudioTracks = function() { return []; };
  1484. this.getVideoTracks = function() { return []; };
  1485. }
  1486. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1487. var newStream = null;
  1488. if (window.webkitMediaStream) {
  1489. newStream = new webkitMediaStream();
  1490. if (newStream) {
  1491. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1492. for (var i = 0; i < tracks.length; i++) {
  1493. newStream.addTrack(tracks[i]);
  1494. }
  1495. }
  1496. }
  1497. else {
  1498. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1499. if (stream) {
  1500. newStream = stream;
  1501. } else {
  1502. newStream =
  1503. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1504. }
  1505. }
  1506. return newStream;
  1507. };
  1508. module.exports = RTCUtils;
  1509. },{"../../service/RTC/Resolutions":108,"../xmpp/SDPUtil":56,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1510. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1511. // Adapter's interface.
  1512. var AdapterJS = AdapterJS || {};
  1513. // Browserify compatibility
  1514. if(typeof exports !== 'undefined') {
  1515. module.exports = AdapterJS;
  1516. }
  1517. AdapterJS.options = AdapterJS.options || {};
  1518. // uncomment to get virtual webcams
  1519. // AdapterJS.options.getAllCams = true;
  1520. // uncomment to prevent the install prompt when the plugin in not yet installed
  1521. // AdapterJS.options.hidePluginInstallPrompt = true;
  1522. // AdapterJS version
  1523. AdapterJS.VERSION = '0.11.0';
  1524. // This function will be called when the WebRTC API is ready to be used
  1525. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1526. // the plugin
  1527. // You may Override this function to synchronise the start of your application
  1528. // with the WebRTC API being ready.
  1529. // If you decide not to override use this synchronisation, it may result in
  1530. // an extensive CPU usage on the plugin start (once per tab loaded)
  1531. // Params:
  1532. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1533. //
  1534. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1535. // The WebRTC API is ready.
  1536. // Override me and do whatever you want here
  1537. };
  1538. // Sets a callback function to be called when the WebRTC interface is ready.
  1539. // The first argument is the function to callback.\
  1540. // Throws an error if the first argument is not a function
  1541. AdapterJS.webRTCReady = function (callback) {
  1542. if (typeof callback !== 'function') {
  1543. throw new Error('Callback provided is not a function');
  1544. }
  1545. if (true === AdapterJS.onwebrtcreadyDone) {
  1546. // All WebRTC interfaces are ready, just call the callback
  1547. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1548. } else {
  1549. // will be triggered automatically when your browser/plugin is ready.
  1550. AdapterJS.onwebrtcready = callback;
  1551. }
  1552. };
  1553. // Plugin namespace
  1554. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1555. // The object to store plugin information
  1556. AdapterJS.WebRTCPlugin.pluginInfo = {
  1557. prefix : 'Tem',
  1558. plugName : 'TemWebRTCPlugin',
  1559. pluginId : 'plugin0',
  1560. type : 'application/x-temwebrtcplugin',
  1561. onload : '__TemWebRTCReady0',
  1562. portalLink : 'http://skylink.io/plugin/',
  1563. downloadLink : null, //set below
  1564. companyName: 'Temasys'
  1565. };
  1566. if(!!navigator.platform.match(/^Mac/i)) {
  1567. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1568. }
  1569. else if(!!navigator.platform.match(/^Win/i)) {
  1570. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1571. }
  1572. // Unique identifier of each opened page
  1573. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1574. // Use this whenever you want to call the plugin.
  1575. AdapterJS.WebRTCPlugin.plugin = null;
  1576. // Set log level for the plugin once it is ready.
  1577. // The different values are
  1578. // This is an asynchronous function that will run when the plugin is ready
  1579. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1580. // Defines webrtc's JS interface according to the plugin's implementation.
  1581. // Define plugin Browsers as WebRTC Interface.
  1582. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1583. // This function detects whether or not a plugin is installed.
  1584. // Checks if Not IE (firefox, for example), else if it's IE,
  1585. // we're running IE and do something. If not it is not supported.
  1586. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1587. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1588. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1589. // Inject the HTML DOM object element into the page.
  1590. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1591. // States of readiness that the plugin goes through when
  1592. // being injected and stated
  1593. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1594. NONE : 0, // no plugin use
  1595. INITIALIZING : 1, // Detected need for plugin
  1596. INJECTING : 2, // Injecting plugin
  1597. INJECTED: 3, // Plugin element injected but not usable yet
  1598. READY: 4 // Plugin ready to be used
  1599. };
  1600. // Current state of the plugin. You cannot use the plugin before this is
  1601. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1602. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1603. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1604. // Used to make sure AdapterJS.onwebrtcready is only called once
  1605. AdapterJS.onwebrtcreadyDone = false;
  1606. // Log levels for the plugin.
  1607. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1608. /*
  1609. Log outputs are prefixed in some cases.
  1610. INFO: Information reported by the plugin.
  1611. ERROR: Errors originating from within the plugin.
  1612. WEBRTC: Error originating from within the libWebRTC library
  1613. */
  1614. // From the least verbose to the most verbose
  1615. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1616. NONE : 'NONE',
  1617. ERROR : 'ERROR',
  1618. WARNING : 'WARNING',
  1619. INFO: 'INFO',
  1620. VERBOSE: 'VERBOSE',
  1621. SENSITIVE: 'SENSITIVE'
  1622. };
  1623. // Does a waiting check before proceeding to load the plugin.
  1624. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1625. // This methid will use an interval to wait for the plugin to be ready.
  1626. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1627. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1628. // This function will be called when plugin is ready. It sends necessary
  1629. // details to the plugin.
  1630. // The function will wait for the document to be ready and the set the
  1631. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1632. // indicating that it can start being requested.
  1633. // This function is not in the IE/Safari condition brackets so that
  1634. // TemPluginLoaded function might be called on Chrome/Firefox.
  1635. // This function is the only private function that is not encapsulated to
  1636. // allow the plugin method to be called.
  1637. __TemWebRTCReady0 = function () {
  1638. if (document.readyState === 'complete') {
  1639. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1640. AdapterJS.maybeThroughWebRTCReady();
  1641. } else {
  1642. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1643. if (document.readyState === 'complete') {
  1644. // TODO: update comments, we wait for the document to be ready
  1645. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1646. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1647. AdapterJS.maybeThroughWebRTCReady();
  1648. }
  1649. }, 100);
  1650. }
  1651. };
  1652. AdapterJS.maybeThroughWebRTCReady = function() {
  1653. if (!AdapterJS.onwebrtcreadyDone) {
  1654. AdapterJS.onwebrtcreadyDone = true;
  1655. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1656. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1657. }
  1658. }
  1659. };
  1660. // Text namespace
  1661. AdapterJS.TEXT = {
  1662. PLUGIN: {
  1663. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1664. 'to work on this browser.',
  1665. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1666. BUTTON: 'Install Now'
  1667. },
  1668. REFRESH: {
  1669. REQUIRE_REFRESH: 'Please refresh page',
  1670. BUTTON: 'Refresh Page'
  1671. }
  1672. };
  1673. // The result of ice connection states.
  1674. // - starting: Ice connection is starting.
  1675. // - checking: Ice connection is checking.
  1676. // - connected Ice connection is connected.
  1677. // - completed Ice connection is connected.
  1678. // - done Ice connection has been completed.
  1679. // - disconnected Ice connection has been disconnected.
  1680. // - failed Ice connection has failed.
  1681. // - closed Ice connection is closed.
  1682. AdapterJS._iceConnectionStates = {
  1683. starting : 'starting',
  1684. checking : 'checking',
  1685. connected : 'connected',
  1686. completed : 'connected',
  1687. done : 'completed',
  1688. disconnected : 'disconnected',
  1689. failed : 'failed',
  1690. closed : 'closed'
  1691. };
  1692. //The IceConnection states that has been fired for each peer.
  1693. AdapterJS._iceConnectionFiredStates = [];
  1694. // Check if WebRTC Interface is defined.
  1695. AdapterJS.isDefined = null;
  1696. // This function helps to retrieve the webrtc detected browser information.
  1697. // This sets:
  1698. // - webrtcDetectedBrowser: The browser agent name.
  1699. // - webrtcDetectedVersion: The browser version.
  1700. // - webrtcDetectedType: The types of webRTC support.
  1701. // - 'moz': Mozilla implementation of webRTC.
  1702. // - 'webkit': WebKit implementation of webRTC.
  1703. // - 'plugin': Using the plugin implementation.
  1704. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1705. var hasMatch, checkMatch = navigator.userAgent.match(
  1706. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1707. if (/trident/i.test(checkMatch[1])) {
  1708. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1709. webrtcDetectedBrowser = 'IE';
  1710. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1711. } else if (checkMatch[1] === 'Chrome') {
  1712. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1713. if (hasMatch !== null) {
  1714. webrtcDetectedBrowser = 'opera';
  1715. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1716. }
  1717. }
  1718. if (navigator.userAgent.indexOf('Safari')) {
  1719. if (typeof InstallTrigger !== 'undefined') {
  1720. webrtcDetectedBrowser = 'firefox';
  1721. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1722. webrtcDetectedBrowser = 'IE';
  1723. } else if (
  1724. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1725. webrtcDetectedBrowser = 'safari';
  1726. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1727. webrtcDetectedBrowser = 'opera';
  1728. } else if (!!window.chrome) {
  1729. webrtcDetectedBrowser = 'chrome';
  1730. }
  1731. }
  1732. if (!webrtcDetectedBrowser) {
  1733. webrtcDetectedVersion = checkMatch[1];
  1734. }
  1735. if (!webrtcDetectedVersion) {
  1736. try {
  1737. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1738. [navigator.appName, navigator.appVersion, '-?'];
  1739. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1740. checkMatch.splice(1, 1, hasMatch[1]);
  1741. }
  1742. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1743. } catch (error) { }
  1744. }
  1745. };
  1746. // To fix configuration as some browsers does not support
  1747. // the 'urls' attribute.
  1748. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1749. if (pcConfig === null) {
  1750. return;
  1751. }
  1752. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1753. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1754. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1755. delete pcConfig.iceServers[i].urls;
  1756. }
  1757. }
  1758. };
  1759. AdapterJS.addEvent = function(elem, evnt, func) {
  1760. if (elem.addEventListener) { // W3C DOM
  1761. elem.addEventListener(evnt, func, false);
  1762. } else if (elem.attachEvent) {// OLD IE DOM
  1763. elem.attachEvent('on'+evnt, func);
  1764. } else { // No much to do
  1765. elem[evnt] = func;
  1766. }
  1767. };
  1768. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1769. // only inject once the page is ready
  1770. if (document.readyState !== 'complete') {
  1771. return;
  1772. }
  1773. var w = window;
  1774. var i = document.createElement('iframe');
  1775. i.style.position = 'fixed';
  1776. i.style.top = '-41px';
  1777. i.style.left = 0;
  1778. i.style.right = 0;
  1779. i.style.width = '100%';
  1780. i.style.height = '40px';
  1781. i.style.backgroundColor = '#ffffe1';
  1782. i.style.border = 'none';
  1783. i.style.borderBottom = '1px solid #888888';
  1784. i.style.zIndex = '9999999';
  1785. if(typeof i.style.webkitTransition === 'string') {
  1786. i.style.webkitTransition = 'all .5s ease-out';
  1787. } else if(typeof i.style.transition === 'string') {
  1788. i.style.transition = 'all .5s ease-out';
  1789. }
  1790. document.body.appendChild(i);
  1791. c = (i.contentWindow) ? i.contentWindow :
  1792. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1793. c.document.open();
  1794. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1795. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1796. 'middle; cursor: default;">' + text + '</span>');
  1797. if(buttonText && buttonLink) {
  1798. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1799. c.document.close();
  1800. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1801. if (!!displayRefreshBar) {
  1802. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1803. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1804. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1805. }
  1806. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1807. e.preventDefault();
  1808. try {
  1809. event.cancelBubble = true;
  1810. } catch(error) { }
  1811. });
  1812. }
  1813. else {
  1814. c.document.close();
  1815. }
  1816. AdapterJS.addEvent(c.document, 'click', function() {
  1817. w.document.body.removeChild(i);
  1818. });
  1819. setTimeout(function() {
  1820. if(typeof i.style.webkitTransform === 'string') {
  1821. i.style.webkitTransform = 'translateY(40px)';
  1822. } else if(typeof i.style.transform === 'string') {
  1823. i.style.transform = 'translateY(40px)';
  1824. } else {
  1825. i.style.top = '0px';
  1826. }
  1827. }, 300);
  1828. };
  1829. // -----------------------------------------------------------
  1830. // Detected webrtc implementation. Types are:
  1831. // - 'moz': Mozilla implementation of webRTC.
  1832. // - 'webkit': WebKit implementation of webRTC.
  1833. // - 'plugin': Using the plugin implementation.
  1834. webrtcDetectedType = null;
  1835. // Detected webrtc datachannel support. Types are:
  1836. // - 'SCTP': SCTP datachannel support.
  1837. // - 'RTP': RTP datachannel support.
  1838. webrtcDetectedDCSupport = null;
  1839. // Set the settings for creating DataChannels, MediaStream for
  1840. // Cross-browser compability.
  1841. // - This is only for SCTP based support browsers.
  1842. // the 'urls' attribute.
  1843. checkMediaDataChannelSettings =
  1844. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1845. if (typeof callback !== 'function') {
  1846. return;
  1847. }
  1848. var beOfferer = true;
  1849. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1850. // Nightly version does not require MozDontOfferDataChannel for interop
  1851. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1852. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1853. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1854. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1855. // Resends an updated version of constraints for MozDataChannel to work
  1856. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1857. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1858. try {
  1859. delete constraints.mandatory.MozDontOfferDataChannel;
  1860. } catch (error) {
  1861. console.error('Failed deleting MozDontOfferDataChannel');
  1862. console.error(error);
  1863. }
  1864. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1865. constraints.mandatory.MozDontOfferDataChannel = true;
  1866. }
  1867. if (!isLocalFirefox) {
  1868. // temporary measure to remove Moz* constraints in non Firefox browsers
  1869. for (var prop in constraints.mandatory) {
  1870. if (constraints.mandatory.hasOwnProperty(prop)) {
  1871. if (prop.indexOf('Moz') !== -1) {
  1872. delete constraints.mandatory[prop];
  1873. }
  1874. }
  1875. }
  1876. }
  1877. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1878. // interopability of the media stream
  1879. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1880. beOfferer = false;
  1881. }
  1882. callback(beOfferer, constraints);
  1883. };
  1884. // Handles the differences for all browsers ice connection state output.
  1885. // - Tested outcomes are:
  1886. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1887. // - Chrome (answerer) : 'checking' > 'connected'
  1888. // - Firefox (offerer) : 'checking' > 'connected'
  1889. // - Firefox (answerer): 'checking' > 'connected'
  1890. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1891. if (typeof callback !== 'function') {
  1892. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1893. return;
  1894. }
  1895. peerId = (peerId) ? peerId : 'peer';
  1896. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1897. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1898. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1899. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1900. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1901. }
  1902. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1903. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1904. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1905. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1906. setTimeout(function () {
  1907. AdapterJS._iceConnectionFiredStates[peerId]
  1908. .push(AdapterJS._iceConnectionStates.done);
  1909. callback(AdapterJS._iceConnectionStates.done);
  1910. }, 1000);
  1911. }
  1912. callback(iceConnectionState);
  1913. }
  1914. return;
  1915. };
  1916. // Firefox:
  1917. // - Creates iceServer from the url for Firefox.
  1918. // - Create iceServer with stun url.
  1919. // - Create iceServer with turn url.
  1920. // - Ignore the transport parameter from TURN url for FF version <=27.
  1921. // - Return null for createIceServer if transport=tcp.
  1922. // - FF 27 and above supports transport parameters in TURN url,
  1923. // - So passing in the full url to create iceServer.
  1924. // Chrome:
  1925. // - Creates iceServer from the url for Chrome M33 and earlier.
  1926. // - Create iceServer with stun url.
  1927. // - Chrome M28 & above uses below TURN format.
  1928. // Plugin:
  1929. // - Creates Ice Server for Plugin Browsers
  1930. // - If Stun - Create iceServer with stun url.
  1931. // - Else - Create iceServer with turn url
  1932. // - This is a WebRTC Function
  1933. createIceServer = null;
  1934. // Firefox:
  1935. // - Creates IceServers for Firefox
  1936. // - Use .url for FireFox.
  1937. // - Multiple Urls support
  1938. // Chrome:
  1939. // - Creates iceServers from the urls for Chrome M34 and above.
  1940. // - .urls is supported since Chrome M34.
  1941. // - Multiple Urls support
  1942. // Plugin:
  1943. // - Creates Ice Servers for Plugin Browsers
  1944. // - Multiple Urls support
  1945. // - This is a WebRTC Function
  1946. createIceServers = null;
  1947. //------------------------------------------------------------
  1948. //The RTCPeerConnection object.
  1949. RTCPeerConnection = null;
  1950. // Creates RTCSessionDescription object for Plugin Browsers
  1951. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  1952. RTCSessionDescription : null;
  1953. // Creates RTCIceCandidate object for Plugin Browsers
  1954. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  1955. RTCIceCandidate : null;
  1956. // Get UserMedia (only difference is the prefix).
  1957. // Code from Adam Barth.
  1958. getUserMedia = null;
  1959. // Attach a media stream to an element.
  1960. attachMediaStream = null;
  1961. // Re-attach a media stream to an element.
  1962. reattachMediaStream = null;
  1963. // Detected browser agent name. Types are:
  1964. // - 'firefox': Firefox browser.
  1965. // - 'chrome': Chrome browser.
  1966. // - 'opera': Opera browser.
  1967. // - 'safari': Safari browser.
  1968. // - 'IE' - Internet Explorer browser.
  1969. webrtcDetectedBrowser = null;
  1970. // Detected browser version.
  1971. webrtcDetectedVersion = null;
  1972. // Check for browser types and react accordingly
  1973. if (navigator.mozGetUserMedia) {
  1974. webrtcDetectedBrowser = 'firefox';
  1975. webrtcDetectedVersion = parseInt(navigator
  1976. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1977. webrtcDetectedType = 'moz';
  1978. webrtcDetectedDCSupport = 'SCTP';
  1979. RTCPeerConnection = function (pcConfig, pcConstraints) {
  1980. AdapterJS.maybeFixConfiguration(pcConfig);
  1981. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  1982. };
  1983. // The RTCSessionDescription object.
  1984. RTCSessionDescription = mozRTCSessionDescription;
  1985. window.RTCSessionDescription = RTCSessionDescription;
  1986. // The RTCIceCandidate object.
  1987. RTCIceCandidate = mozRTCIceCandidate;
  1988. window.RTCIceCandidate = RTCIceCandidate;
  1989. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1990. navigator.getUserMedia = window.getUserMedia;
  1991. // Shim for MediaStreamTrack.getSources.
  1992. MediaStreamTrack.getSources = function(successCb) {
  1993. setTimeout(function() {
  1994. var infos = [
  1995. { kind: 'audio', id: 'default', label:'', facing:'' },
  1996. { kind: 'video', id: 'default', label:'', facing:'' }
  1997. ];
  1998. successCb(infos);
  1999. }, 0);
  2000. };
  2001. createIceServer = function (url, username, password) {
  2002. var iceServer = null;
  2003. var url_parts = url.split(':');
  2004. if (url_parts[0].indexOf('stun') === 0) {
  2005. iceServer = { url : url };
  2006. } else if (url_parts[0].indexOf('turn') === 0) {
  2007. if (webrtcDetectedVersion < 27) {
  2008. var turn_url_parts = url.split('?');
  2009. if (turn_url_parts.length === 1 ||
  2010. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2011. iceServer = {
  2012. url : turn_url_parts[0],
  2013. credential : password,
  2014. username : username
  2015. };
  2016. }
  2017. } else {
  2018. iceServer = {
  2019. url : url,
  2020. credential : password,
  2021. username : username
  2022. };
  2023. }
  2024. }
  2025. return iceServer;
  2026. };
  2027. createIceServers = function (urls, username, password) {
  2028. var iceServers = [];
  2029. for (i = 0; i < urls.length; i++) {
  2030. var iceServer = createIceServer(urls[i], username, password);
  2031. if (iceServer !== null) {
  2032. iceServers.push(iceServer);
  2033. }
  2034. }
  2035. return iceServers;
  2036. };
  2037. attachMediaStream = function (element, stream) {
  2038. element.mozSrcObject = stream;
  2039. if (stream !== null)
  2040. element.play();
  2041. return element;
  2042. };
  2043. reattachMediaStream = function (to, from) {
  2044. to.mozSrcObject = from.mozSrcObject;
  2045. to.play();
  2046. return to;
  2047. };
  2048. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2049. if (!callback) {
  2050. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2051. ': 1 argument required, but only 0 present.');
  2052. }
  2053. return callback([]);
  2054. };
  2055. // Fake get{Video,Audio}Tracks
  2056. if (!MediaStream.prototype.getVideoTracks) {
  2057. MediaStream.prototype.getVideoTracks = function () {
  2058. return [];
  2059. };
  2060. }
  2061. if (!MediaStream.prototype.getAudioTracks) {
  2062. MediaStream.prototype.getAudioTracks = function () {
  2063. return [];
  2064. };
  2065. }
  2066. AdapterJS.maybeThroughWebRTCReady();
  2067. } else if (navigator.webkitGetUserMedia) {
  2068. webrtcDetectedBrowser = 'chrome';
  2069. webrtcDetectedType = 'webkit';
  2070. webrtcDetectedVersion = parseInt(navigator
  2071. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2072. // check if browser is opera 20+
  2073. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2074. if (checkIfOpera !== null) {
  2075. webrtcDetectedBrowser = 'opera';
  2076. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2077. }
  2078. // check browser datachannel support
  2079. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2080. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2081. webrtcDetectedDCSupport = 'SCTP';
  2082. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2083. webrtcDetectedVersion > 24) {
  2084. webrtcDetectedDCSupport = 'RTP';
  2085. } else {
  2086. webrtcDetectedDCSupport = '';
  2087. }
  2088. createIceServer = function (url, username, password) {
  2089. var iceServer = null;
  2090. var url_parts = url.split(':');
  2091. if (url_parts[0].indexOf('stun') === 0) {
  2092. iceServer = { 'url' : url };
  2093. } else if (url_parts[0].indexOf('turn') === 0) {
  2094. iceServer = {
  2095. 'url' : url,
  2096. 'credential' : password,
  2097. 'username' : username
  2098. };
  2099. }
  2100. return iceServer;
  2101. };
  2102. createIceServers = function (urls, username, password) {
  2103. var iceServers = [];
  2104. if (webrtcDetectedVersion >= 34) {
  2105. iceServers = {
  2106. 'urls' : urls,
  2107. 'credential' : password,
  2108. 'username' : username
  2109. };
  2110. } else {
  2111. for (i = 0; i < urls.length; i++) {
  2112. var iceServer = createIceServer(urls[i], username, password);
  2113. if (iceServer !== null) {
  2114. iceServers.push(iceServer);
  2115. }
  2116. }
  2117. }
  2118. return iceServers;
  2119. };
  2120. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2121. if (webrtcDetectedVersion < 34) {
  2122. AdapterJS.maybeFixConfiguration(pcConfig);
  2123. }
  2124. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2125. };
  2126. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2127. navigator.getUserMedia = window.getUserMedia;
  2128. attachMediaStream = function (element, stream) {
  2129. if (typeof element.srcObject !== 'undefined') {
  2130. element.srcObject = stream;
  2131. } else if (typeof element.mozSrcObject !== 'undefined') {
  2132. element.mozSrcObject = stream;
  2133. } else if (typeof element.src !== 'undefined') {
  2134. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2135. } else {
  2136. console.log('Error attaching stream to element.');
  2137. }
  2138. return element;
  2139. };
  2140. reattachMediaStream = function (to, from) {
  2141. to.src = from.src;
  2142. return to;
  2143. };
  2144. AdapterJS.maybeThroughWebRTCReady();
  2145. } else { // TRY TO USE PLUGIN
  2146. // IE 9 is not offering an implementation of console.log until you open a console
  2147. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2148. /* jshint -W020 */
  2149. console = {} || console;
  2150. // Implemented based on console specs from MDN
  2151. // You may override these functions
  2152. console.log = function (arg) {};
  2153. console.info = function (arg) {};
  2154. console.error = function (arg) {};
  2155. console.dir = function (arg) {};
  2156. console.exception = function (arg) {};
  2157. console.trace = function (arg) {};
  2158. console.warn = function (arg) {};
  2159. console.count = function (arg) {};
  2160. console.debug = function (arg) {};
  2161. console.count = function (arg) {};
  2162. console.time = function (arg) {};
  2163. console.timeEnd = function (arg) {};
  2164. console.group = function (arg) {};
  2165. console.groupCollapsed = function (arg) {};
  2166. console.groupEnd = function (arg) {};
  2167. /* jshint +W020 */
  2168. }
  2169. webrtcDetectedType = 'plugin';
  2170. webrtcDetectedDCSupport = 'plugin';
  2171. AdapterJS.parseWebrtcDetectedBrowser();
  2172. isIE = webrtcDetectedBrowser === 'IE';
  2173. /* jshint -W035 */
  2174. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2175. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2176. /* empty because it needs to prevent the function from running. */
  2177. }
  2178. };
  2179. /* jshint +W035 */
  2180. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2181. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2182. // Call immediately if possible
  2183. // Once the plugin is set, the code will always take this path
  2184. callback();
  2185. } else {
  2186. // otherwise start a 100ms interval
  2187. var checkPluginReadyState = setInterval(function () {
  2188. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2189. clearInterval(checkPluginReadyState);
  2190. callback();
  2191. }
  2192. }, 100);
  2193. }
  2194. };
  2195. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2196. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2197. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2198. });
  2199. };
  2200. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2201. // only inject once the page is ready
  2202. if (document.readyState !== 'complete') {
  2203. return;
  2204. }
  2205. // Prevent multiple injections
  2206. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2207. return;
  2208. }
  2209. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2210. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2211. var frag = document.createDocumentFragment();
  2212. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2213. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2214. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2215. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2216. '<param name="pluginId" value="' +
  2217. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2218. '<param name="windowless" value="false" /> ' +
  2219. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2220. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2221. '" />' +
  2222. // uncomment to be able to use virtual cams
  2223. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2224. '</object>';
  2225. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2226. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2227. }
  2228. document.body.appendChild(frag);
  2229. // Need to re-fetch the plugin
  2230. AdapterJS.WebRTCPlugin.plugin =
  2231. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2232. } else {
  2233. // Load Plugin
  2234. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2235. AdapterJS.WebRTCPlugin.plugin.id =
  2236. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2237. // IE will only start the plugin if it's ACTUALLY visible
  2238. if (isIE) {
  2239. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2240. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2241. } else { // The size of the plugin on Safari should be 0x0px
  2242. // so that the autorisation prompt is at the top
  2243. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2244. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2245. }
  2246. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2247. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2248. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2249. '<param name="pluginId" value="' +
  2250. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2251. '<param name="windowless" value="false" /> ' +
  2252. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2253. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2254. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2255. }
  2256. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2257. };
  2258. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2259. function (comName, plugName, installedCb, notInstalledCb) {
  2260. if (!isIE) {
  2261. var pluginArray = navigator.plugins;
  2262. for (var i = 0; i < pluginArray.length; i++) {
  2263. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2264. installedCb();
  2265. return;
  2266. }
  2267. }
  2268. notInstalledCb();
  2269. } else {
  2270. try {
  2271. var axo = new ActiveXObject(comName + '.' + plugName);
  2272. } catch (e) {
  2273. notInstalledCb();
  2274. return;
  2275. }
  2276. installedCb();
  2277. }
  2278. };
  2279. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2280. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2281. AdapterJS.isDefined = function (variable) {
  2282. return variable !== null && variable !== undefined;
  2283. };
  2284. createIceServer = function (url, username, password) {
  2285. var iceServer = null;
  2286. var url_parts = url.split(':');
  2287. if (url_parts[0].indexOf('stun') === 0) {
  2288. iceServer = {
  2289. 'url' : url,
  2290. 'hasCredentials' : false
  2291. };
  2292. } else if (url_parts[0].indexOf('turn') === 0) {
  2293. iceServer = {
  2294. 'url' : url,
  2295. 'hasCredentials' : true,
  2296. 'credential' : password,
  2297. 'username' : username
  2298. };
  2299. }
  2300. return iceServer;
  2301. };
  2302. createIceServers = function (urls, username, password) {
  2303. var iceServers = [];
  2304. for (var i = 0; i < urls.length; ++i) {
  2305. iceServers.push(createIceServer(urls[i], username, password));
  2306. }
  2307. return iceServers;
  2308. };
  2309. RTCSessionDescription = function (info) {
  2310. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2311. return AdapterJS.WebRTCPlugin.plugin.
  2312. ConstructSessionDescription(info.type, info.sdp);
  2313. };
  2314. RTCPeerConnection = function (servers, constraints) {
  2315. var iceServers = null;
  2316. if (servers) {
  2317. iceServers = servers.iceServers;
  2318. for (var i = 0; i < iceServers.length; i++) {
  2319. if (iceServers[i].urls && !iceServers[i].url) {
  2320. iceServers[i].url = iceServers[i].urls;
  2321. }
  2322. iceServers[i].hasCredentials = AdapterJS.
  2323. isDefined(iceServers[i].username) &&
  2324. AdapterJS.isDefined(iceServers[i].credential);
  2325. }
  2326. }
  2327. var mandatory = (constraints && constraints.mandatory) ?
  2328. constraints.mandatory : null;
  2329. var optional = (constraints && constraints.optional) ?
  2330. constraints.optional : null;
  2331. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2332. return AdapterJS.WebRTCPlugin.plugin.
  2333. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2334. iceServers, mandatory, optional);
  2335. };
  2336. MediaStreamTrack = {};
  2337. MediaStreamTrack.getSources = function (callback) {
  2338. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2339. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2340. });
  2341. };
  2342. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2343. constraints.audio = constraints.audio || false;
  2344. constraints.video = constraints.video || false;
  2345. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2346. AdapterJS.WebRTCPlugin.plugin.
  2347. getUserMedia(constraints, successCallback, failureCallback);
  2348. });
  2349. };
  2350. window.navigator.getUserMedia = window.getUserMedia;
  2351. attachMediaStream = function (element, stream) {
  2352. if (!element || !element.parentNode) {
  2353. return;
  2354. }
  2355. var streamId
  2356. if (stream === null) {
  2357. streamId = '';
  2358. }
  2359. else {
  2360. stream.enableSoundTracks(true);
  2361. streamId = stream.id;
  2362. }
  2363. if (element.nodeName.toLowerCase() !== 'audio') {
  2364. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2365. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2366. var frag = document.createDocumentFragment();
  2367. var temp = document.createElement('div');
  2368. var classHTML = '';
  2369. if (element.className) {
  2370. classHTML = 'class="' + element.className + '" ';
  2371. } else if (element.attributes && element.attributes['class']) {
  2372. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2373. }
  2374. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2375. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2376. '<param name="pluginId" value="' + elementId + '" /> ' +
  2377. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2378. '<param name="windowless" value="true" /> ' +
  2379. '<param name="streamId" value="' + streamId + '" /> ' +
  2380. '</object>';
  2381. while (temp.firstChild) {
  2382. frag.appendChild(temp.firstChild);
  2383. }
  2384. var height = '';
  2385. var width = '';
  2386. if (element.getBoundingClientRect) {
  2387. var rectObject = element.getBoundingClientRect();
  2388. width = rectObject.width + 'px';
  2389. height = rectObject.height + 'px';
  2390. }
  2391. else if (element.width) {
  2392. width = element.width;
  2393. height = element.height;
  2394. } else {
  2395. // TODO: What scenario could bring us here?
  2396. }
  2397. element.parentNode.insertBefore(frag, element);
  2398. frag = document.getElementById(elementId);
  2399. frag.width = width;
  2400. frag.height = height;
  2401. element.parentNode.removeChild(element);
  2402. } else {
  2403. var children = element.children;
  2404. for (var i = 0; i !== children.length; ++i) {
  2405. if (children[i].name === 'streamId') {
  2406. children[i].value = streamId;
  2407. break;
  2408. }
  2409. }
  2410. element.setStreamId(streamId);
  2411. }
  2412. var newElement = document.getElementById(elementId);
  2413. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2414. if (isIE) { // on IE the event needs to be plugged manually
  2415. newElement.attachEvent('onplaying', newElement.onplaying);
  2416. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2417. newElement._TemOnClick = function (id) {
  2418. var arg = {
  2419. srcElement : document.getElementById(id)
  2420. };
  2421. newElement.onclick(arg);
  2422. };
  2423. }
  2424. return newElement;
  2425. } else {
  2426. return element;
  2427. }
  2428. };
  2429. reattachMediaStream = function (to, from) {
  2430. var stream = null;
  2431. var children = from.children;
  2432. for (var i = 0; i !== children.length; ++i) {
  2433. if (children[i].name === 'streamId') {
  2434. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2435. stream = AdapterJS.WebRTCPlugin.plugin
  2436. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2437. break;
  2438. }
  2439. }
  2440. if (stream !== null) {
  2441. return attachMediaStream(to, stream);
  2442. } else {
  2443. console.log('Could not find the stream associated with this element');
  2444. }
  2445. };
  2446. RTCIceCandidate = function (candidate) {
  2447. if (!candidate.sdpMid) {
  2448. candidate.sdpMid = '';
  2449. }
  2450. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2451. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2452. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2453. );
  2454. };
  2455. // inject plugin
  2456. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2457. AdapterJS.WebRTCPlugin.injectPlugin();
  2458. };
  2459. // This function will be called if the plugin is needed (browser different
  2460. // from Chrome or Firefox), but the plugin is not installed.
  2461. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2462. function() {
  2463. AdapterJS.addEvent(document,
  2464. 'readystatechange',
  2465. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2466. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2467. };
  2468. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2469. if (AdapterJS.options.hidePluginInstallPrompt) {
  2470. return;
  2471. }
  2472. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2473. if(downloadLink) { // if download link
  2474. var popupString;
  2475. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2476. popupString = 'This website requires you to install the ' +
  2477. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2478. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2479. ' WebRTC Plugin</a>' +
  2480. ' to work on this browser.';
  2481. } else { // no portal link, just print a generic explanation
  2482. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2483. }
  2484. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2485. } else { // no download link, just print a generic explanation
  2486. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2487. }
  2488. };
  2489. // Try to detect the plugin and act accordingly
  2490. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2491. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2492. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2493. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2494. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2495. }
  2496. (function () {
  2497. 'use strict';
  2498. var baseGetUserMedia = null;
  2499. AdapterJS.TEXT.EXTENSION = {
  2500. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2501. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2502. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2503. BUTTON_FF: 'Install Now',
  2504. BUTTON_CHROME: 'Go to Chrome Web Store'
  2505. };
  2506. var clone = function(obj) {
  2507. if (null == obj || "object" != typeof obj) return obj;
  2508. var copy = obj.constructor();
  2509. for (var attr in obj) {
  2510. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2511. }
  2512. return copy;
  2513. };
  2514. if (window.navigator.mozGetUserMedia) {
  2515. baseGetUserMedia = window.navigator.getUserMedia;
  2516. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2517. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2518. // intercepting screensharing requests
  2519. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2520. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2521. }
  2522. var updatedConstraints = clone(constraints);
  2523. //constraints.video.mediaSource = constraints.video.mediaSource;
  2524. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2525. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2526. // strange but this works anyway
  2527. var checkIfReady = setInterval(function () {
  2528. if (document.readyState === 'complete') {
  2529. clearInterval(checkIfReady);
  2530. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2531. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2532. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2533. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2534. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2535. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2536. } else {
  2537. failureCb(error);
  2538. }
  2539. });
  2540. }
  2541. }, 1);
  2542. } else { // regular GetUserMediaRequest
  2543. baseGetUserMedia(constraints, successCb, failureCb);
  2544. }
  2545. };
  2546. getUserMedia = navigator.getUserMedia;
  2547. } else if (window.navigator.webkitGetUserMedia) {
  2548. baseGetUserMedia = window.navigator.getUserMedia;
  2549. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2550. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2551. if (window.webrtcDetectedBrowser !== 'chrome') {
  2552. throw new Error('Current browser does not support screensharing');
  2553. }
  2554. // would be fine since no methods
  2555. var updatedConstraints = clone(constraints);
  2556. var chromeCallback = function(error, sourceId) {
  2557. if(!error) {
  2558. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2559. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2560. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2561. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2562. if (sourceId) {
  2563. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2564. }
  2565. delete updatedConstraints.video.mediaSource;
  2566. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2567. } else {
  2568. if (error === 'permission-denied') {
  2569. throw new Error('Permission denied for screen retrieval');
  2570. } else {
  2571. throw new Error('Failed retrieving selected screen');
  2572. }
  2573. }
  2574. };
  2575. var onIFrameCallback = function (event) {
  2576. if (!event.data) {
  2577. return;
  2578. }
  2579. if (event.data.chromeMediaSourceId) {
  2580. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2581. chromeCallback('permission-denied');
  2582. } else {
  2583. chromeCallback(null, event.data.chromeMediaSourceId);
  2584. }
  2585. }
  2586. if (event.data.chromeExtensionStatus) {
  2587. if (event.data.chromeExtensionStatus === 'not-installed') {
  2588. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2589. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2590. event.data.data, true, true);
  2591. } else {
  2592. chromeCallback(event.data.chromeExtensionStatus, null);
  2593. }
  2594. }
  2595. // this event listener is no more needed
  2596. window.removeEventListener('message', onIFrameCallback);
  2597. };
  2598. window.addEventListener('message', onIFrameCallback);
  2599. postFrameMessage({
  2600. captureSourceId: true
  2601. });
  2602. } else {
  2603. baseGetUserMedia(constraints, successCb, failureCb);
  2604. }
  2605. };
  2606. getUserMedia = navigator.getUserMedia;
  2607. } else {
  2608. baseGetUserMedia = window.navigator.getUserMedia;
  2609. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2610. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2611. // would be fine since no methods
  2612. var updatedConstraints = clone(constraints);
  2613. // wait for plugin to be ready
  2614. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2615. // check if screensharing feature is available
  2616. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2617. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2618. // set the constraints
  2619. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2620. updatedConstraints.video.optional.push({
  2621. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2622. });
  2623. delete updatedConstraints.video.mediaSource;
  2624. } else {
  2625. throw new Error('Your WebRTC plugin does not support screensharing');
  2626. }
  2627. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2628. });
  2629. } else {
  2630. baseGetUserMedia(constraints, successCb, failureCb);
  2631. }
  2632. };
  2633. getUserMedia = window.navigator.getUserMedia;
  2634. }
  2635. if (window.webrtcDetectedBrowser === 'chrome') {
  2636. var iframe = document.createElement('iframe');
  2637. iframe.onload = function() {
  2638. iframe.isLoaded = true;
  2639. };
  2640. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2641. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2642. iframe.style.display = 'none';
  2643. (document.body || document.documentElement).appendChild(iframe);
  2644. var postFrameMessage = function (object) {
  2645. object = object || {};
  2646. if (!iframe.isLoaded) {
  2647. setTimeout(function () {
  2648. iframe.contentWindow.postMessage(object, '*');
  2649. }, 100);
  2650. return;
  2651. }
  2652. iframe.contentWindow.postMessage(object, '*');
  2653. };
  2654. }
  2655. })();
  2656. },{}],11:[function(require,module,exports){
  2657. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2658. var UI = {};
  2659. var VideoLayout = require("./videolayout/VideoLayout.js");
  2660. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2661. var Prezi = require("./prezi/Prezi.js");
  2662. var Etherpad = require("./etherpad/Etherpad.js");
  2663. var Chat = require("./side_pannels/chat/Chat.js");
  2664. var Toolbar = require("./toolbars/Toolbar");
  2665. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2666. var BottomToolbar = require("./toolbars/BottomToolbar");
  2667. var ContactList = require("./side_pannels/contactlist/ContactList");
  2668. var Avatar = require("./avatar/Avatar");
  2669. var EventEmitter = require("events");
  2670. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2671. var Settings = require("./../settings/Settings");
  2672. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2673. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2674. UI.messageHandler = require("./util/MessageHandler");
  2675. var messageHandler = UI.messageHandler;
  2676. var Authentication = require("./authentication/Authentication");
  2677. var UIUtil = require("./util/UIUtil");
  2678. var NicknameHandler = require("./util/NicknameHandler");
  2679. var CQEvents = require("../../service/connectionquality/CQEvents");
  2680. var DesktopSharingEventTypes
  2681. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2682. var RTCEvents = require("../../service/RTC/RTCEvents");
  2683. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2684. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2685. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2686. var UIEvents = require("../../service/UI/UIEvents");
  2687. var MemberEvents = require("../../service/members/Events");
  2688. var eventEmitter = new EventEmitter();
  2689. var roomName = null;
  2690. function promptDisplayName() {
  2691. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2692. message += APP.translation.translateString(
  2693. "dialog.displayNameRequired");
  2694. message += '</h2>' +
  2695. '<input name="displayName" type="text" data-i18n=' +
  2696. '"[placeholder]defaultNickname" placeholder="' +
  2697. APP.translation.translateString(
  2698. "defaultNickname", {name: "Jane Pink"}) +
  2699. '" autofocus>';
  2700. var buttonTxt
  2701. = APP.translation.generateTranslationHTML("dialog.Ok");
  2702. var buttons = [];
  2703. buttons.push({title: buttonTxt, value: "ok"});
  2704. messageHandler.openDialog(null, message,
  2705. true,
  2706. buttons,
  2707. function (e, v, m, f) {
  2708. if (v == "ok") {
  2709. var displayName = f.displayName;
  2710. if (displayName) {
  2711. VideoLayout.inputDisplayNameHandler(displayName);
  2712. return true;
  2713. }
  2714. }
  2715. e.preventDefault();
  2716. },
  2717. function () {
  2718. var form = $.prompt.getPrompt();
  2719. var input = form.find("input[name='displayName']");
  2720. input.focus();
  2721. var button = form.find("button");
  2722. button.attr("disabled", "disabled");
  2723. input.keyup(function () {
  2724. if(!input.val())
  2725. button.attr("disabled", "disabled");
  2726. else
  2727. button.removeAttr("disabled");
  2728. });
  2729. }
  2730. );
  2731. }
  2732. function notifyForInitialMute() {
  2733. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2734. "notify.muted", null, {timeOut: 120000});
  2735. }
  2736. function setupPrezi() {
  2737. $("#reloadPresentationLink").click(function() {
  2738. Prezi.reloadPresentation();
  2739. });
  2740. }
  2741. function setupChat() {
  2742. Chat.init();
  2743. $("#toggle_smileys").click(function() {
  2744. Chat.toggleSmileys();
  2745. });
  2746. }
  2747. function setupToolbars() {
  2748. Toolbar.init(UI);
  2749. Toolbar.setupButtonsFromConfig();
  2750. BottomToolbar.init();
  2751. }
  2752. function streamHandler(stream, isMuted) {
  2753. switch (stream.type) {
  2754. case "audio":
  2755. VideoLayout.changeLocalAudio(stream, isMuted);
  2756. break;
  2757. case "video":
  2758. VideoLayout.changeLocalVideo(stream, isMuted);
  2759. break;
  2760. case "stream":
  2761. VideoLayout.changeLocalStream(stream, isMuted);
  2762. break;
  2763. }
  2764. }
  2765. function onXmppConnectionFailed(stropheErrorMsg) {
  2766. var title = APP.translation.generateTranslationHTML(
  2767. "dialog.error");
  2768. var message;
  2769. if (stropheErrorMsg) {
  2770. message = APP.translation.generateTranslationHTML(
  2771. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2772. } else {
  2773. message = APP.translation.generateTranslationHTML(
  2774. "dialog.connectError");
  2775. }
  2776. messageHandler.openDialog(
  2777. title, message, true, {}, function (e, v, m, f) { return false; });
  2778. }
  2779. function onDisposeConference(unload) {
  2780. Toolbar.showAuthenticateButton(false);
  2781. }
  2782. function onDisplayNameChanged(jid, displayName) {
  2783. ContactList.onDisplayNameChange(jid, displayName);
  2784. SettingsMenu.onDisplayNameChange(jid, displayName);
  2785. VideoLayout.onDisplayNameChanged(jid, displayName);
  2786. }
  2787. function registerListeners() {
  2788. APP.RTC.addStreamListener(streamHandler,
  2789. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2790. APP.RTC.addStreamListener(streamHandler,
  2791. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2792. APP.RTC.addStreamListener(function (stream) {
  2793. VideoLayout.onRemoteStreamAdded(stream);
  2794. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2795. APP.RTC.addStreamListener(function (jid) {
  2796. VideoLayout.onVideoTypeChanged(jid);
  2797. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  2798. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2799. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  2800. function (resourceJid) {
  2801. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2802. });
  2803. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2804. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2805. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2806. endpointsEnteringLastN, stream);
  2807. });
  2808. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2809. function (devices) {
  2810. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2811. });
  2812. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  2813. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function() {
  2814. // when the data channel becomes available, tell the bridge about video
  2815. // selections so that it can do adaptive simulcast,
  2816. // we want the notification to trigger even if userJid is undefined,
  2817. // or null.
  2818. var userJid = APP.UI.getLargeVideoJid();
  2819. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userJid);
  2820. });
  2821. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  2822. var resourceJid;
  2823. if(jid === APP.statistics.LOCAL_JID) {
  2824. resourceJid = AudioLevels.LOCAL_LEVEL;
  2825. if(APP.RTC.localAudio.isMuted()) {
  2826. audioLevel = 0;
  2827. }
  2828. } else {
  2829. resourceJid = Strophe.getResourceFromJid(jid);
  2830. }
  2831. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2832. UI.getLargeVideoJid());
  2833. });
  2834. APP.desktopsharing.addListener(function () {
  2835. ToolbarToggler.showDesktopSharingButton();
  2836. }, DesktopSharingEventTypes.INIT);
  2837. APP.desktopsharing.addListener(
  2838. Toolbar.changeDesktopSharingButtonState,
  2839. DesktopSharingEventTypes.SWITCHING_DONE);
  2840. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2841. VideoLayout.updateLocalConnectionStats);
  2842. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2843. VideoLayout.updateConnectionStats);
  2844. APP.connectionquality.addListener(CQEvents.STOP,
  2845. VideoLayout.onStatsStop);
  2846. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2847. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2848. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2849. messageHandler.openMessageDialog(
  2850. 'dialog.serviceUnavailable',
  2851. 'dialog.gracefulShutdown'
  2852. );
  2853. });
  2854. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2855. var title = APP.translation.generateTranslationHTML(
  2856. "dialog.reservationError");
  2857. var message = APP.translation.generateTranslationHTML(
  2858. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2859. messageHandler.openDialog(
  2860. title,
  2861. message,
  2862. true, {},
  2863. function (event, value, message, formVals) {
  2864. return false;
  2865. }
  2866. );
  2867. });
  2868. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2869. messageHandler.openMessageDialog("dialog.sessTerminated",
  2870. "dialog.kickMessage");
  2871. });
  2872. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2873. //FIXME: use Session Terminated from translation, but
  2874. // 'reason' text comes from XMPP packet and is not translated
  2875. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2876. messageHandler.openDialog(
  2877. title, reason, true, {},
  2878. function (event, value, message, formVals) {
  2879. return false;
  2880. }
  2881. );
  2882. });
  2883. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2884. messageHandler.showError("dialog.error",
  2885. "dialog.bridgeUnavailable");
  2886. });
  2887. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2888. Avatar.setUserAvatar(from, id);
  2889. });
  2890. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2891. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2892. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2893. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2894. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2895. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2896. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2897. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2898. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2899. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2900. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2901. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2902. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2903. onAuthenticationRequired);
  2904. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2905. function (resource, devices) {
  2906. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2907. });
  2908. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  2909. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  2910. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function(doMuteAudio) {
  2911. UI.setAudioMuted(doMuteAudio);
  2912. });
  2913. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2914. onDtmfSupportChanged);
  2915. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  2916. SettingsMenu.setStartMuted(audio, video);
  2917. });
  2918. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  2919. UI.setInitialMuteFromFocus(audio, video);
  2920. });
  2921. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  2922. UI.messageHandler.showError("dialog.sorry",
  2923. "dialog.internalError");
  2924. });
  2925. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function() {
  2926. messageHandler.showError("dialog.error",
  2927. "dialog.SLDFailure");
  2928. });
  2929. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function() {
  2930. messageHandler.showError("dialog.error",
  2931. "dialog.SRDFailure");
  2932. });
  2933. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function() {
  2934. messageHandler.showError();
  2935. });
  2936. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function() {
  2937. // FIXME: re-use LoginDialog which supports retries
  2938. UI.showLoginPopup(connect);
  2939. });
  2940. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function(focusComponent, retrySec) {
  2941. UI.messageHandler.notify(
  2942. null, "notify.focus",
  2943. 'disconnected', "notify.focusFail",
  2944. {component: focusComponent, ms: retrySec});
  2945. });
  2946. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function(pres) {
  2947. UI.messageHandler.openReportDialog(null,
  2948. "dialog.joinError", pres);
  2949. });
  2950. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function(pres) {
  2951. UI.messageHandler.openReportDialog(null,
  2952. "dialog.connectError", pres);
  2953. });
  2954. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function() {
  2955. var roomName = UI.generateRoomName();
  2956. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  2957. });
  2958. //NicknameHandler emits this event
  2959. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  2960. APP.xmpp.addToPresence("displayName", nickname);
  2961. });
  2962. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  2963. AudioLevels.init();
  2964. });
  2965. // Listens for video interruption events.
  2966. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  2967. // Listens for video restores events.
  2968. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  2969. }
  2970. /**
  2971. * Mutes/unmutes the local video.
  2972. *
  2973. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2974. * @param options an object which specifies optional arguments such as the
  2975. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2976. * specifies whether the method was initiated in response to a user command (in
  2977. * contrast to an automatic decision taken by the application logic)
  2978. */
  2979. function setVideoMute(mute, options) {
  2980. APP.RTC.setVideoMute(mute,
  2981. UI.setVideoMuteButtonsState,
  2982. options);
  2983. }
  2984. function onResize() {
  2985. Chat.resizeChat();
  2986. VideoLayout.resizeLargeVideoContainer();
  2987. }
  2988. function bindEvents() {
  2989. /**
  2990. * Resizes and repositions videos in full screen mode.
  2991. */
  2992. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  2993. onResize);
  2994. $(window).resize(onResize);
  2995. }
  2996. UI.start = function (init) {
  2997. document.title = interfaceConfig.APP_NAME;
  2998. var setupWelcomePage = null;
  2999. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3000. (!window.localStorage.welcomePageDisabled ||
  3001. window.localStorage.welcomePageDisabled == "false")) {
  3002. $("#videoconference_page").hide();
  3003. if (!setupWelcomePage)
  3004. setupWelcomePage = require("./welcome_page/WelcomePage");
  3005. setupWelcomePage();
  3006. return;
  3007. }
  3008. $("#welcome_page").hide();
  3009. $("#videospace").mousemove(function () {
  3010. return ToolbarToggler.showToolbar();
  3011. });
  3012. // Set the defaults for prompt dialogs.
  3013. $.prompt.setDefaults({persistent: false});
  3014. registerListeners();
  3015. VideoLayout.init(eventEmitter);
  3016. NicknameHandler.init(eventEmitter);
  3017. bindEvents();
  3018. setupPrezi();
  3019. setupToolbars();
  3020. setupChat();
  3021. document.title = interfaceConfig.APP_NAME;
  3022. $("#downloadlog").click(function (event) {
  3023. dump(event.target);
  3024. });
  3025. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3026. (!window.localStorage.welcomePageDisabled ||
  3027. window.localStorage.welcomePageDisabled == "false")) {
  3028. $("#videoconference_page").hide();
  3029. if (!setupWelcomePage)
  3030. setupWelcomePage = require("./welcome_page/WelcomePage");
  3031. setupWelcomePage();
  3032. return;
  3033. }
  3034. $("#welcome_page").hide();
  3035. // Display notice message at the top of the toolbar
  3036. if (config.noticeMessage) {
  3037. $('#noticeText').text(config.noticeMessage);
  3038. $('#notice').css({display: 'block'});
  3039. }
  3040. if(config.requireDisplayName) {
  3041. var currentSettings = Settings.getSettings();
  3042. if (!currentSettings.displayName) {
  3043. promptDisplayName();
  3044. }
  3045. }
  3046. init();
  3047. toastr.options = {
  3048. "closeButton": true,
  3049. "debug": false,
  3050. "positionClass": "notification-bottom-right",
  3051. "onclick": null,
  3052. "showDuration": "300",
  3053. "hideDuration": "1000",
  3054. "timeOut": "2000",
  3055. "extendedTimeOut": "1000",
  3056. "showEasing": "swing",
  3057. "hideEasing": "linear",
  3058. "showMethod": "fadeIn",
  3059. "hideMethod": "fadeOut",
  3060. "reposition": function() {
  3061. if(PanelToggler.isVisible()) {
  3062. $("#toast-container").addClass("notification-bottom-right-center");
  3063. } else {
  3064. $("#toast-container").removeClass("notification-bottom-right-center");
  3065. }
  3066. },
  3067. "newestOnTop": false
  3068. };
  3069. SettingsMenu.init();
  3070. };
  3071. function chatAddError(errorMessage, originalText) {
  3072. return Chat.chatAddError(errorMessage, originalText);
  3073. }
  3074. function chatSetSubject(text) {
  3075. return Chat.chatSetSubject(text);
  3076. }
  3077. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3078. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3079. }
  3080. function onMucJoined(jid, info) {
  3081. Toolbar.updateRoomUrl(window.location.href);
  3082. var meHTML = APP.translation.generateTranslationHTML("me");
  3083. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3084. var settings = Settings.getSettings();
  3085. // Make sure we configure our avatar id, before creating avatar for us
  3086. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3087. // Add myself to the contact list.
  3088. ContactList.addContact(jid);
  3089. // Once we've joined the muc show the toolbar
  3090. ToolbarToggler.showToolbar();
  3091. var displayName =
  3092. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3093. if (displayName)
  3094. onDisplayNameChanged('localVideoContainer', displayName);
  3095. VideoLayout.mucJoined();
  3096. }
  3097. function initEtherpad(name) {
  3098. Etherpad.init(name);
  3099. }
  3100. function onMucMemberLeft(jid) {
  3101. console.log('left.muc', jid);
  3102. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3103. '>.displayname').html();
  3104. messageHandler.notify(displayName,'notify.somebody',
  3105. 'disconnected',
  3106. 'notify.disconnected');
  3107. if (!config.startAudioMuted ||
  3108. config.startAudioMuted > APP.members.size()) {
  3109. UIUtil.playSoundNotification('userLeft');
  3110. }
  3111. ContactList.removeContact(jid);
  3112. VideoLayout.participantLeft(jid);
  3113. }
  3114. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3115. console.info("My role changed, new role: " + info.role);
  3116. onModeratorStatusChanged(isModerator);
  3117. VideoLayout.showModeratorIndicator();
  3118. SettingsMenu.onRoleChanged();
  3119. if (isModerator) {
  3120. Authentication.closeAuthenticationWindow();
  3121. messageHandler.notify(null, "notify.me",
  3122. 'connected', "notify.moderator");
  3123. }
  3124. }
  3125. function onModeratorStatusChanged(isModerator) {
  3126. Toolbar.showSipCallButton(isModerator);
  3127. Toolbar.showRecordingButton(
  3128. isModerator); //&&
  3129. // FIXME:
  3130. // Recording visible if
  3131. // there are at least 2(+ 1 focus) participants
  3132. //Object.keys(connection.emuc.members).length >= 3);
  3133. }
  3134. function onPasswordRequired(callback) {
  3135. // password is required
  3136. Toolbar.lockLockButton();
  3137. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3138. message += APP.translation.translateString(
  3139. "dialog.passwordRequired");
  3140. message += '</h2>' +
  3141. '<input name="lockKey" type="text" data-i18n=' +
  3142. '"[placeholder]dialog.password" placeholder="' +
  3143. APP.translation.translateString("dialog.password") +
  3144. '" autofocus>';
  3145. messageHandler.openTwoButtonDialog(null, null, null, message,
  3146. true,
  3147. "dialog.Ok",
  3148. function (e, v, m, f) {},
  3149. null,
  3150. function (e, v, m, f) {
  3151. if (v) {
  3152. var lockKey = f.lockKey;
  3153. if (lockKey) {
  3154. Toolbar.setSharedKey(lockKey);
  3155. callback(lockKey);
  3156. }
  3157. }
  3158. },
  3159. ':input:first'
  3160. );
  3161. }
  3162. /**
  3163. * The dialpad button is shown iff there is at least one member that supports
  3164. * DTMF (e.g. jigasi).
  3165. */
  3166. function onDtmfSupportChanged(dtmfSupport) {
  3167. //TODO: enable when the UI is ready
  3168. //Toolbar.showDialPadButton(dtmfSupport);
  3169. }
  3170. function onMucMemberJoined(jid, id, displayName) {
  3171. messageHandler.notify(displayName,'notify.somebody',
  3172. 'connected',
  3173. 'notify.connected');
  3174. if (!config.startAudioMuted ||
  3175. config.startAudioMuted > APP.members.size())
  3176. UIUtil.playSoundNotification('userJoined');
  3177. // Configure avatar
  3178. Avatar.setUserAvatar(jid, id);
  3179. // Add Peer's container
  3180. VideoLayout.ensurePeerContainerExists(jid);
  3181. }
  3182. function onMucPresenceStatus(jid, info) {
  3183. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3184. }
  3185. function onMucRoleChanged(role, displayName) {
  3186. VideoLayout.showModeratorIndicator();
  3187. if (role === 'moderator') {
  3188. var messageKey, messageOptions = {};
  3189. if (!displayName) {
  3190. messageKey = "notify.grantedToUnknown";
  3191. }
  3192. else {
  3193. messageKey = "notify.grantedTo";
  3194. messageOptions = {to: displayName};
  3195. }
  3196. messageHandler.notify(
  3197. displayName,'notify.somebody',
  3198. 'connected', messageKey,
  3199. messageOptions);
  3200. }
  3201. }
  3202. function onAuthenticationRequired(intervalCallback) {
  3203. Authentication.openAuthenticationDialog(
  3204. roomName, intervalCallback, function () {
  3205. Toolbar.authenticateClicked();
  3206. });
  3207. }
  3208. function onLastNChanged(oldValue, newValue) {
  3209. if (config.muteLocalVideoIfNotInLastN) {
  3210. setVideoMute(!newValue, { 'byUser': false });
  3211. }
  3212. }
  3213. UI.toggleSmileys = function () {
  3214. Chat.toggleSmileys();
  3215. };
  3216. UI.getSettings = function () {
  3217. return Settings.getSettings();
  3218. };
  3219. UI.toggleFilmStrip = function () {
  3220. return BottomToolbar.toggleFilmStrip();
  3221. };
  3222. UI.toggleChat = function () {
  3223. return BottomToolbar.toggleChat();
  3224. };
  3225. UI.toggleContactList = function () {
  3226. return BottomToolbar.toggleContactList();
  3227. };
  3228. UI.inputDisplayNameHandler = function (value) {
  3229. VideoLayout.inputDisplayNameHandler(value);
  3230. };
  3231. UI.getLargeVideoJid = function() {
  3232. return VideoLayout.getLargeVideoJid();
  3233. };
  3234. UI.generateRoomName = function() {
  3235. if(roomName)
  3236. return roomName;
  3237. var roomnode = null;
  3238. var path = window.location.pathname;
  3239. // determinde the room node from the url
  3240. // TODO: just the roomnode or the whole bare jid?
  3241. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3242. // custom function might be responsible for doing the pushstate
  3243. roomnode = config.getroomnode(path);
  3244. } else {
  3245. /* fall back to default strategy
  3246. * this is making assumptions about how the URL->room mapping happens.
  3247. * It currently assumes deployment at root, with a rewrite like the
  3248. * following one (for nginx):
  3249. location ~ ^/([a-zA-Z0-9]+)$ {
  3250. rewrite ^/(.*)$ / break;
  3251. }
  3252. */
  3253. if (path.length > 1) {
  3254. roomnode = path.substr(1).toLowerCase();
  3255. } else {
  3256. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3257. roomnode = word.toLowerCase();
  3258. window.history.pushState('VideoChat',
  3259. 'Room: ' + word, window.location.pathname + word);
  3260. }
  3261. }
  3262. roomName = roomnode + '@' + config.hosts.muc;
  3263. return roomName;
  3264. };
  3265. UI.connectionIndicatorShowMore = function(jid) {
  3266. return VideoLayout.showMore(jid);
  3267. };
  3268. UI.showLoginPopup = function(callback) {
  3269. console.log('password is required');
  3270. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3271. message += APP.translation.translateString(
  3272. "dialog.passwordRequired");
  3273. message += '</h2>' +
  3274. '<input name="username" type="text" ' +
  3275. 'placeholder="user@domain.net" autofocus>' +
  3276. '<input name="password" ' +
  3277. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3278. ' placeholder="user password">';
  3279. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3280. true,
  3281. "dialog.Ok",
  3282. function (e, v, m, f) {
  3283. if (v) {
  3284. if (f.username !== null && f.password != null) {
  3285. callback(f.username, f.password);
  3286. }
  3287. }
  3288. },
  3289. null, null, ':input:first'
  3290. );
  3291. };
  3292. UI.checkForNicknameAndJoin = function () {
  3293. Authentication.closeAuthenticationDialog();
  3294. Authentication.stopInterval();
  3295. var nick = null;
  3296. if (config.useNicks) {
  3297. nick = window.prompt('Your nickname (optional)');
  3298. }
  3299. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3300. };
  3301. function dump(elem, filename) {
  3302. elem = elem.parentNode;
  3303. elem.download = filename || 'meetlog.json';
  3304. elem.href = 'data:application/json;charset=utf-8,\n';
  3305. var data = APP.xmpp.getJingleLog();
  3306. var metadata = {};
  3307. metadata.time = new Date();
  3308. metadata.url = window.location.href;
  3309. metadata.ua = navigator.userAgent;
  3310. var log = APP.xmpp.getXmppLog();
  3311. if (log) {
  3312. metadata.xmpp = log;
  3313. }
  3314. data.metadata = metadata;
  3315. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3316. return false;
  3317. }
  3318. UI.getRoomName = function () {
  3319. return roomName;
  3320. };
  3321. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3322. if (muteAudio || muteVideo)
  3323. notifyForInitialMute();
  3324. if (muteAudio)
  3325. UI.setAudioMuted(true);
  3326. if (muteVideo)
  3327. UI.setVideoMute(true);
  3328. };
  3329. /**
  3330. * Mutes/unmutes the local video.
  3331. */
  3332. UI.toggleVideo = function () {
  3333. setVideoMute(!APP.RTC.localVideo.isMuted());
  3334. };
  3335. /**
  3336. * Mutes / unmutes audio for the local participant.
  3337. */
  3338. UI.toggleAudio = function() {
  3339. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3340. };
  3341. /**
  3342. * Sets muted audio state for the local participant.
  3343. */
  3344. UI.setAudioMuted = function (mute, earlyMute) {
  3345. var audioMute = null;
  3346. if (earlyMute)
  3347. audioMute = function (mute, cb) {
  3348. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3349. };
  3350. else
  3351. audioMute = function (mute, cb) {
  3352. return APP.xmpp.setAudioMute(mute, cb);
  3353. };
  3354. if (!audioMute(mute, function () {
  3355. VideoLayout.showLocalAudioIndicator(mute);
  3356. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3357. })) {
  3358. // We still click the button.
  3359. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3360. return;
  3361. }
  3362. };
  3363. UI.addListener = function (type, listener) {
  3364. eventEmitter.on(type, listener);
  3365. };
  3366. UI.clickOnVideo = function (videoNumber) {
  3367. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3368. if (remoteVideos.length > videoNumber) {
  3369. remoteVideos[videoNumber].click();
  3370. }
  3371. };
  3372. //Used by torture
  3373. UI.showToolbar = function () {
  3374. return ToolbarToggler.showToolbar();
  3375. };
  3376. //Used by torture
  3377. UI.dockToolbar = function (isDock) {
  3378. return ToolbarToggler.dockToolbar(isDock);
  3379. };
  3380. UI.setVideoMuteButtonsState = function (mute) {
  3381. var video = $('#video');
  3382. var communicativeClass = "icon-camera";
  3383. var muteClass = "icon-camera icon-camera-disabled";
  3384. if (mute) {
  3385. video.removeClass(communicativeClass);
  3386. video.addClass(muteClass);
  3387. } else {
  3388. video.removeClass(muteClass);
  3389. video.addClass(communicativeClass);
  3390. }
  3391. };
  3392. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3393. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3394. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3395. if(resourceJid === APP.xmpp.myResource())
  3396. SettingsMenu.changeAvatar(thumbUrl);
  3397. };
  3398. UI.setVideoMute = setVideoMute;
  3399. module.exports = UI;
  3400. },{"../../service/RTC/RTCEvents":107,"../../service/RTC/StreamEventTypes":109,"../../service/UI/UIEvents":110,"../../service/connectionquality/CQEvents":112,"../../service/desktopsharing/DesktopSharingEventTypes":113,"../../service/members/Events":114,"../../service/xmpp/XMPPEvents":116,"../RTC/RTCBrowserType":8,"./../settings/Settings":47,"./audio_levels/AudioLevels.js":12,"./authentication/Authentication":14,"./avatar/Avatar":16,"./etherpad/Etherpad.js":17,"./prezi/Prezi.js":18,"./side_pannels/SidePanelToggler":20,"./side_pannels/chat/Chat.js":21,"./side_pannels/contactlist/ContactList":25,"./side_pannels/settings/SettingsMenu":26,"./toolbars/BottomToolbar":27,"./toolbars/Toolbar":28,"./toolbars/ToolbarToggler":29,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":117}],12:[function(require,module,exports){
  3401. /* global APP, interfaceConfig, $, Strophe */
  3402. var CanvasUtil = require("./CanvasUtils");
  3403. var ASDrawContext = null;
  3404. function initActiveSpeakerAudioLevels() {
  3405. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3406. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3407. // Draw a circle.
  3408. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3409. // Add a shadow around the circle
  3410. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3411. ASDrawContext.shadowOffsetX = 0;
  3412. ASDrawContext.shadowOffsetY = 0;
  3413. }
  3414. /**
  3415. * The audio Levels plugin.
  3416. */
  3417. var AudioLevels = (function(my) {
  3418. var audioLevelCanvasCache = {};
  3419. my.LOCAL_LEVEL = 'local';
  3420. my.init = function () {
  3421. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3422. initActiveSpeakerAudioLevels();
  3423. };
  3424. /**
  3425. * Updates the audio level canvas for the given peerJid. If the canvas
  3426. * didn't exist we create it.
  3427. */
  3428. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3429. var resourceJid = null;
  3430. var videoSpanId = null;
  3431. if (!peerJid)
  3432. videoSpanId = 'localVideoContainer';
  3433. else {
  3434. resourceJid = Strophe.getResourceFromJid(peerJid);
  3435. videoSpanId = 'participant_' + resourceJid;
  3436. }
  3437. var videoSpan = document.getElementById(videoSpanId);
  3438. if (!videoSpan) {
  3439. if (resourceJid)
  3440. console.error("No video element for jid", resourceJid);
  3441. else
  3442. console.error("No video element for local video.");
  3443. return;
  3444. }
  3445. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3446. var videoSpaceWidth = $('#remoteVideos').width();
  3447. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3448. var thumbnailWidth = thumbnailSize[0];
  3449. var thumbnailHeight = thumbnailSize[1];
  3450. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3451. audioLevelCanvas = document.createElement('canvas');
  3452. audioLevelCanvas.className = "audiolevel";
  3453. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3454. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3455. resizeAudioLevelCanvas( audioLevelCanvas,
  3456. thumbnailWidth,
  3457. thumbnailHeight);
  3458. videoSpan.appendChild(audioLevelCanvas);
  3459. } else {
  3460. audioLevelCanvas = audioLevelCanvas.get(0);
  3461. resizeAudioLevelCanvas( audioLevelCanvas,
  3462. thumbnailWidth,
  3463. thumbnailHeight);
  3464. }
  3465. };
  3466. /**
  3467. * Updates the audio level UI for the given resourceJid.
  3468. *
  3469. * @param resourceJid the resource jid indicating the video element for
  3470. * which we draw the audio level
  3471. * @param audioLevel the newAudio level to render
  3472. */
  3473. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3474. drawAudioLevelCanvas(resourceJid, audioLevel);
  3475. var videoSpanId = getVideoSpanId(resourceJid);
  3476. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3477. if (!audioLevelCanvas)
  3478. return;
  3479. var drawContext = audioLevelCanvas.getContext('2d');
  3480. var canvasCache = audioLevelCanvasCache[resourceJid];
  3481. drawContext.clearRect (0, 0,
  3482. audioLevelCanvas.width, audioLevelCanvas.height);
  3483. drawContext.drawImage(canvasCache, 0, 0);
  3484. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3485. if(!APP.xmpp.myJid()) {
  3486. return;
  3487. }
  3488. resourceJid = APP.xmpp.myResource();
  3489. }
  3490. if(resourceJid === largeVideoResourceJid) {
  3491. window.requestAnimationFrame(function () {
  3492. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3493. });
  3494. }
  3495. };
  3496. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3497. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3498. return;
  3499. ASDrawContext.clearRect(0, 0, 300, 300);
  3500. if(audioLevel == 0)
  3501. return;
  3502. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3503. // Fill the shape.
  3504. ASDrawContext.fill();
  3505. };
  3506. /**
  3507. * Resizes the given audio level canvas to match the given thumbnail size.
  3508. */
  3509. function resizeAudioLevelCanvas(audioLevelCanvas,
  3510. thumbnailWidth,
  3511. thumbnailHeight) {
  3512. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3513. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3514. }
  3515. /**
  3516. * Draws the audio level canvas into the cached canvas object.
  3517. *
  3518. * @param resourceJid the resource jid indicating the video element for
  3519. * which we draw the audio level
  3520. * @param audioLevel the newAudio level to render
  3521. */
  3522. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3523. if (!audioLevelCanvasCache[resourceJid]) {
  3524. var videoSpanId = getVideoSpanId(resourceJid);
  3525. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3526. /*
  3527. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3528. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3529. * error. Since audio levels are frequently updated, the errors have
  3530. * been observed to pile into the console, strain the CPU.
  3531. */
  3532. if (audioLevelCanvasOrig) {
  3533. audioLevelCanvasCache[resourceJid] =
  3534. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3535. }
  3536. }
  3537. var canvas = audioLevelCanvasCache[resourceJid];
  3538. if (!canvas)
  3539. return;
  3540. var drawContext = canvas.getContext('2d');
  3541. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3542. var shadowLevel = getShadowLevel(audioLevel);
  3543. if (shadowLevel > 0) {
  3544. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3545. CanvasUtil.drawRoundRectGlow(drawContext,
  3546. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3547. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3548. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3549. interfaceConfig.CANVAS_RADIUS,
  3550. interfaceConfig.SHADOW_COLOR,
  3551. shadowLevel);
  3552. }
  3553. }
  3554. /**
  3555. * Returns the shadow/glow level for the given audio level.
  3556. *
  3557. * @param audioLevel the audio level from which we determine the shadow
  3558. * level
  3559. */
  3560. function getShadowLevel (audioLevel) {
  3561. var shadowLevel = 0;
  3562. if (audioLevel <= 0.3) {
  3563. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3564. }
  3565. else if (audioLevel <= 0.6) {
  3566. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3567. }
  3568. else {
  3569. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3570. }
  3571. return shadowLevel;
  3572. }
  3573. /**
  3574. * Returns the video span id corresponding to the given resourceJid or local
  3575. * user.
  3576. */
  3577. function getVideoSpanId(resourceJid) {
  3578. var videoSpanId = null;
  3579. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3580. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3581. videoSpanId = 'localVideoContainer';
  3582. else
  3583. videoSpanId = 'participant_' + resourceJid;
  3584. return videoSpanId;
  3585. }
  3586. /**
  3587. * Indicates that the remote video has been resized.
  3588. */
  3589. $(document).bind('remotevideo.resized', function (event, width, height) {
  3590. var resized = false;
  3591. $('#remoteVideos>span>canvas').each(function() {
  3592. var canvas = $(this).get(0);
  3593. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3594. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3595. resized = true;
  3596. }
  3597. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3598. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3599. resized = true;
  3600. }
  3601. });
  3602. if (resized)
  3603. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3604. audioLevelCanvasCache[resourceJid].width =
  3605. width + interfaceConfig.CANVAS_EXTRA;
  3606. audioLevelCanvasCache[resourceJid].height =
  3607. height + interfaceConfig.CANVAS_EXTRA;
  3608. });
  3609. });
  3610. return my;
  3611. })(AudioLevels || {});
  3612. module.exports = AudioLevels;
  3613. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3614. /**
  3615. * Utility class for drawing canvas shapes.
  3616. */
  3617. var CanvasUtil = (function(my) {
  3618. /**
  3619. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3620. * of the glow.
  3621. *
  3622. * @param drawContext the context of the canvas to draw to
  3623. * @param x the x coordinate of the round rectangle
  3624. * @param y the y coordinate of the round rectangle
  3625. * @param w the width of the round rectangle
  3626. * @param h the height of the round rectangle
  3627. * @param glowColor the color of the glow
  3628. * @param glowWidth the width of the glow
  3629. */
  3630. my.drawRoundRectGlow
  3631. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3632. // Save the previous state of the context.
  3633. drawContext.save();
  3634. if (w < 2 * r) r = w / 2;
  3635. if (h < 2 * r) r = h / 2;
  3636. // Draw a round rectangle.
  3637. drawContext.beginPath();
  3638. drawContext.moveTo(x+r, y);
  3639. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3640. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3641. drawContext.arcTo(x, y+h, x, y, r);
  3642. drawContext.arcTo(x, y, x+w, y, r);
  3643. drawContext.closePath();
  3644. // Add a shadow around the rectangle
  3645. drawContext.shadowColor = glowColor;
  3646. drawContext.shadowBlur = glowWidth;
  3647. drawContext.shadowOffsetX = 0;
  3648. drawContext.shadowOffsetY = 0;
  3649. // Fill the shape.
  3650. drawContext.fill();
  3651. drawContext.save();
  3652. drawContext.restore();
  3653. // 1) Uncomment this line to use Composite Operation, which is doing the
  3654. // same as the clip function below and is also antialiasing the round
  3655. // border, but is said to be less fast performance wise.
  3656. // drawContext.globalCompositeOperation='destination-out';
  3657. drawContext.beginPath();
  3658. drawContext.moveTo(x+r, y);
  3659. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3660. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3661. drawContext.arcTo(x, y+h, x, y, r);
  3662. drawContext.arcTo(x, y, x+w, y, r);
  3663. drawContext.closePath();
  3664. // 2) Uncomment this line to use Composite Operation, which is doing the
  3665. // same as the clip function below and is also antialiasing the round
  3666. // border, but is said to be less fast performance wise.
  3667. // drawContext.fill();
  3668. // Comment these two lines if choosing to do the same with composite
  3669. // operation above 1 and 2.
  3670. drawContext.clip();
  3671. drawContext.clearRect(0, 0, 277, 200);
  3672. // Restore the previous context state.
  3673. drawContext.restore();
  3674. };
  3675. /**
  3676. * Clones the given canvas.
  3677. *
  3678. * @return the new cloned canvas.
  3679. */
  3680. my.cloneCanvas = function (oldCanvas) {
  3681. /*
  3682. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3683. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3684. * levels are frequently updated, the errors have been observed to pile
  3685. * into the console, strain the CPU.
  3686. */
  3687. if (!oldCanvas)
  3688. return oldCanvas;
  3689. //create a new canvas
  3690. var newCanvas = document.createElement('canvas');
  3691. var context = newCanvas.getContext('2d');
  3692. //set dimensions
  3693. newCanvas.width = oldCanvas.width;
  3694. newCanvas.height = oldCanvas.height;
  3695. //apply the old canvas to the new one
  3696. context.drawImage(oldCanvas, 0, 0);
  3697. //return the new canvas
  3698. return newCanvas;
  3699. };
  3700. return my;
  3701. })(CanvasUtil || {});
  3702. module.exports = CanvasUtil;
  3703. },{}],14:[function(require,module,exports){
  3704. /* global $, APP*/
  3705. var LoginDialog = require('./LoginDialog');
  3706. var Moderator = require('../../xmpp/moderator');
  3707. /* Initial "authentication required" dialog */
  3708. var authDialog = null;
  3709. /* Loop retry ID that wits for other user to create the room */
  3710. var authRetryId = null;
  3711. var authenticationWindow = null;
  3712. var Authentication = {
  3713. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3714. // This is the loop that will wait for the room to be created by
  3715. // someone else. 'auth_required.moderator' will bring us back here.
  3716. authRetryId = window.setTimeout(intervalCallback, 5000);
  3717. // Show prompt only if it's not open
  3718. if (authDialog !== null) {
  3719. return;
  3720. }
  3721. // extract room name from 'room@muc.server.net'
  3722. var room = roomName.substr(0, roomName.indexOf('@'));
  3723. var title
  3724. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3725. var msg
  3726. = APP.translation.generateTranslationHTML(
  3727. "dialog.WaitForHostMsg", {room: room});
  3728. var buttonTxt
  3729. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3730. var buttons = [];
  3731. buttons.push({title: buttonTxt, value: "authNow"});
  3732. authDialog = APP.UI.messageHandler.openDialog(
  3733. title,
  3734. msg,
  3735. true,
  3736. buttons,
  3737. function (onSubmitEvent, submitValue) {
  3738. // Do not close the dialog yet
  3739. onSubmitEvent.preventDefault();
  3740. // Open login popup
  3741. if (submitValue === 'authNow') {
  3742. callback();
  3743. }
  3744. }
  3745. );
  3746. },
  3747. closeAuthenticationWindow: function () {
  3748. if (authenticationWindow) {
  3749. authenticationWindow.close();
  3750. authenticationWindow = null;
  3751. }
  3752. },
  3753. xmppAuthenticate: function () {
  3754. var loginDialog = LoginDialog.show(
  3755. function (connection, state) {
  3756. if (!state) {
  3757. // User cancelled
  3758. loginDialog.close();
  3759. return;
  3760. } else if (state == APP.xmpp.Status.CONNECTED) {
  3761. loginDialog.close();
  3762. Authentication.stopInterval();
  3763. Authentication.closeAuthenticationDialog();
  3764. // Close the connection as anonymous one will be used
  3765. // to create the conference. Session-id will authorize
  3766. // the request.
  3767. connection.disconnect();
  3768. var roomName = APP.UI.generateRoomName();
  3769. Moderator.allocateConferenceFocus(roomName, function () {
  3770. // If it's not "on the fly" authentication now join
  3771. // the conference room
  3772. if (!APP.xmpp.isMUCJoined()) {
  3773. APP.UI.checkForNicknameAndJoin();
  3774. }
  3775. });
  3776. }
  3777. }, true);
  3778. },
  3779. focusAuthenticationWindow: function () {
  3780. // If auth window exists just bring it to the front
  3781. if (authenticationWindow) {
  3782. authenticationWindow.focus();
  3783. return;
  3784. }
  3785. },
  3786. closeAuthenticationDialog: function () {
  3787. // Close authentication dialog if opened
  3788. if (authDialog) {
  3789. authDialog.close();
  3790. authDialog = null;
  3791. }
  3792. },
  3793. createAuthenticationWindow: function (callback, url) {
  3794. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3795. url, 910, 660,
  3796. // On closed
  3797. function () {
  3798. // Close authentication dialog if opened
  3799. Authentication.closeAuthenticationDialog();
  3800. callback();
  3801. authenticationWindow = null;
  3802. });
  3803. return authenticationWindow;
  3804. },
  3805. stopInterval: function () {
  3806. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3807. if (authRetryId) {
  3808. window.clearTimeout(authRetryId);
  3809. authRetryId = null;
  3810. }
  3811. }
  3812. };
  3813. module.exports = Authentication;
  3814. },{"../../xmpp/moderator":58,"./LoginDialog":15}],15:[function(require,module,exports){
  3815. /* global $, APP, config*/
  3816. var XMPP = require('../../xmpp/xmpp');
  3817. var Moderator = require('../../xmpp/moderator');
  3818. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3819. // anonymous domain is not enabled
  3820. /**
  3821. * Creates new <tt>Dialog</tt> instance.
  3822. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3823. * when we either fail to connect or succeed(check Strophe.Status).
  3824. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3825. * in order to create session-id after the connection is established.
  3826. * @constructor
  3827. */
  3828. function Dialog(callback, obtainSession) {
  3829. var self = this;
  3830. var stop = false;
  3831. var connection = APP.xmpp.createConnection();
  3832. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3833. message += APP.translation.translateString("dialog.passwordRequired");
  3834. message += '</h2>' +
  3835. '<input name="username" type="text" ' +
  3836. 'placeholder="user@domain.net" autofocus>' +
  3837. '<input name="password" ' +
  3838. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3839. ' placeholder="user password">';
  3840. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3841. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3842. var states = {
  3843. login: {
  3844. html: message,
  3845. buttons: [
  3846. { title: okButton, value: true},
  3847. { title: cancelButton, value: false}
  3848. ],
  3849. focus: ':input:first',
  3850. submit: function (e, v, m, f) {
  3851. e.preventDefault();
  3852. if (v) {
  3853. var jid = f.username;
  3854. var password = f.password;
  3855. if (jid && password) {
  3856. stop = false;
  3857. connection.reset();
  3858. connDialog.goToState('connecting');
  3859. connection.connect(jid, password, stateHandler);
  3860. }
  3861. } else {
  3862. // User cancelled
  3863. stop = true;
  3864. callback();
  3865. }
  3866. }
  3867. },
  3868. connecting: {
  3869. title: APP.translation.translateString('dialog.connecting'),
  3870. html: '<div id="connectionStatus"></div>',
  3871. buttons: [],
  3872. defaultButton: 0
  3873. },
  3874. finished: {
  3875. title: APP.translation.translateString('dialog.error'),
  3876. html: '<div id="errorMessage"></div>',
  3877. buttons: [
  3878. {
  3879. title: APP.translation.translateString('dialog.retry'),
  3880. value: 'retry'
  3881. },
  3882. {
  3883. title: APP.translation.translateString('dialog.Cancel'),
  3884. value: 'cancel'
  3885. },
  3886. ],
  3887. defaultButton: 0,
  3888. submit: function (e, v, m, f) {
  3889. e.preventDefault();
  3890. if (v === 'retry')
  3891. connDialog.goToState('login');
  3892. else
  3893. callback();
  3894. }
  3895. }
  3896. };
  3897. var connDialog
  3898. = APP.UI.messageHandler.openDialogWithStates(states,
  3899. { persistent: true, closeText: '' }, null);
  3900. var stateHandler = function (status, message) {
  3901. if (stop) {
  3902. return;
  3903. }
  3904. var translateKey = "connection." + XMPP.getStatusString(status);
  3905. var statusStr = APP.translation.translateString(translateKey);
  3906. // Display current state
  3907. var connectionStatus =
  3908. connDialog.getState('connecting').find('#connectionStatus');
  3909. connectionStatus.text(statusStr);
  3910. switch (status) {
  3911. case XMPP.Status.CONNECTED:
  3912. stop = true;
  3913. if (!obtainSession) {
  3914. callback(connection, status);
  3915. return;
  3916. }
  3917. // Obtaining session-id status
  3918. connectionStatus.text(
  3919. APP.translation.translateString(
  3920. 'connection.FETCH_SESSION_ID'));
  3921. // Authenticate with Jicofo and obtain session-id
  3922. var roomName = APP.UI.generateRoomName();
  3923. // Jicofo will return new session-id when connected
  3924. // from authenticated domain
  3925. connection.sendIQ(
  3926. Moderator.createConferenceIq(roomName),
  3927. function (result) {
  3928. connectionStatus.text(
  3929. APP.translation.translateString(
  3930. 'connection.GOT_SESSION_ID'));
  3931. stop = true;
  3932. // Parse session-id
  3933. Moderator.parseSessionId(result);
  3934. callback(connection, status);
  3935. },
  3936. function (error) {
  3937. console.error("Auth on the fly failed", error);
  3938. stop = true;
  3939. var errorMsg =
  3940. APP.translation.translateString(
  3941. 'connection.GET_SESSION_ID_ERROR') +
  3942. $(error).find('>error').attr('code');
  3943. self.displayError(errorMsg);
  3944. connection.disconnect();
  3945. });
  3946. break;
  3947. case XMPP.Status.AUTHFAIL:
  3948. case XMPP.Status.CONNFAIL:
  3949. case XMPP.Status.DISCONNECTED:
  3950. stop = true;
  3951. callback(connection, status);
  3952. var errorMessage = statusStr;
  3953. if (message)
  3954. {
  3955. errorMessage += ': ' + message;
  3956. }
  3957. self.displayError(errorMessage);
  3958. break;
  3959. default:
  3960. break;
  3961. }
  3962. };
  3963. /**
  3964. * Displays error message in 'finished' state which allows either to cancel
  3965. * or retry.
  3966. * @param message the final message to be displayed.
  3967. */
  3968. this.displayError = function (message) {
  3969. var finishedState = connDialog.getState('finished');
  3970. var errorMessageElem = finishedState.find('#errorMessage');
  3971. errorMessageElem.text(message);
  3972. connDialog.goToState('finished');
  3973. };
  3974. /**
  3975. * Closes LoginDialog.
  3976. */
  3977. this.close = function () {
  3978. stop = true;
  3979. connDialog.close();
  3980. };
  3981. }
  3982. var LoginDialog = {
  3983. /**
  3984. * Displays login prompt used to establish new XMPP connection. Given
  3985. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  3986. * called when we connect successfully(status === CONNECTED) or when we fail
  3987. * to do so. On connection failure program can call Dialog.close() method in
  3988. * order to cancel or do nothing to let the user retry.
  3989. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  3990. * called when we either fail to connect or succeed(check
  3991. * Strophe.Status).
  3992. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  3993. * Jicofo in order to create session-id after the connection is
  3994. * established.
  3995. * @returns {Dialog}
  3996. */
  3997. show: function (callback, obtainSession) {
  3998. return new Dialog(callback, obtainSession);
  3999. }
  4000. };
  4001. module.exports = LoginDialog;
  4002. },{"../../xmpp/moderator":58,"../../xmpp/xmpp":66}],16:[function(require,module,exports){
  4003. var Settings = require("../../settings/Settings");
  4004. var users = {};
  4005. var Avatar = {
  4006. /**
  4007. * Sets the user's avatar in the settings menu(if local user), contact list
  4008. * and thumbnail
  4009. * @param jid jid of the user
  4010. * @param id email or userID to be used as a hash
  4011. */
  4012. setUserAvatar: function (jid, id) {
  4013. if (id) {
  4014. if (users[jid] === id) {
  4015. return;
  4016. }
  4017. users[jid] = id;
  4018. }
  4019. var thumbUrl = this.getThumbUrl(jid);
  4020. var contactListUrl = this.getContactListUrl(jid);
  4021. var resourceJid = Strophe.getResourceFromJid(jid);
  4022. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4023. },
  4024. /**
  4025. * Returns image URL for the avatar to be displayed on large video area
  4026. * where current active speaker is presented.
  4027. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4028. */
  4029. getActiveSpeakerUrl: function (jid) {
  4030. return this.getGravatarUrl(jid, 100);
  4031. },
  4032. /**
  4033. * Returns image URL for the avatar to be displayed on small video thumbnail
  4034. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4035. */
  4036. getThumbUrl: function (jid) {
  4037. return this.getGravatarUrl(jid, 100);
  4038. },
  4039. /**
  4040. * Returns the URL for the avatar to be displayed as contactlist item
  4041. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4042. */
  4043. getContactListUrl: function (jid) {
  4044. return this.getGravatarUrl(jid, 30);
  4045. },
  4046. getGravatarUrl: function (jid, size) {
  4047. if (!jid) {
  4048. console.error("Get gravatar - jid is undefined");
  4049. return null;
  4050. }
  4051. var id = users[jid];
  4052. if (!id) {
  4053. console.warn(
  4054. "No avatar stored yet for " + jid + " - using JID as ID");
  4055. id = jid;
  4056. }
  4057. return 'https://www.gravatar.com/avatar/' +
  4058. MD5.hexdigest(id.trim().toLowerCase()) +
  4059. "?d=wavatar&size=" + (size || "30");
  4060. }
  4061. };
  4062. module.exports = Avatar;
  4063. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4064. /* global $, config,
  4065. setLargeVideoVisible, Util */
  4066. var VideoLayout = require("../videolayout/VideoLayout");
  4067. var Prezi = require("../prezi/Prezi");
  4068. var UIUtil = require("../util/UIUtil");
  4069. var etherpadName = null;
  4070. var etherpadIFrame = null;
  4071. var domain = null;
  4072. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4073. /**
  4074. * Resizes the etherpad.
  4075. */
  4076. function resize() {
  4077. if ($('#etherpad>iframe').length) {
  4078. var remoteVideos = $('#remoteVideos');
  4079. var availableHeight
  4080. = window.innerHeight - remoteVideos.outerHeight();
  4081. var availableWidth = UIUtil.getAvailableVideoWidth();
  4082. $('#etherpad>iframe').width(availableWidth);
  4083. $('#etherpad>iframe').height(availableHeight);
  4084. }
  4085. }
  4086. /**
  4087. * Creates the Etherpad button and adds it to the toolbar.
  4088. */
  4089. function enableEtherpadButton() {
  4090. if (!$('#etherpadButton').is(":visible"))
  4091. $('#etherpadButton').css({display: 'inline-block'});
  4092. }
  4093. /**
  4094. * Creates the IFrame for the etherpad.
  4095. */
  4096. function createIFrame() {
  4097. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4098. domain + etherpadName + options, function() {
  4099. document.domain = document.domain;
  4100. bubbleIframeMouseMove(etherpadIFrame);
  4101. setTimeout(function() {
  4102. // the iframes inside of the etherpad are
  4103. // not yet loaded when the etherpad iframe is loaded
  4104. var outer = etherpadIFrame.
  4105. contentDocument.getElementsByName("ace_outer")[0];
  4106. bubbleIframeMouseMove(outer);
  4107. var inner = outer.
  4108. contentDocument.getElementsByName("ace_inner")[0];
  4109. bubbleIframeMouseMove(inner);
  4110. }, 2000);
  4111. });
  4112. }
  4113. function bubbleIframeMouseMove(iframe){
  4114. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4115. iframe.contentWindow.onmousemove = function(e){
  4116. if(existingOnMouseMove) existingOnMouseMove(e);
  4117. var evt = document.createEvent("MouseEvents");
  4118. var boundingClientRect = iframe.getBoundingClientRect();
  4119. evt.initMouseEvent(
  4120. "mousemove",
  4121. true, // bubbles
  4122. false, // not cancelable
  4123. window,
  4124. e.detail,
  4125. e.screenX,
  4126. e.screenY,
  4127. e.clientX + boundingClientRect.left,
  4128. e.clientY + boundingClientRect.top,
  4129. e.ctrlKey,
  4130. e.altKey,
  4131. e.shiftKey,
  4132. e.metaKey,
  4133. e.button,
  4134. null // no related element
  4135. );
  4136. iframe.dispatchEvent(evt);
  4137. };
  4138. }
  4139. var Etherpad = {
  4140. /**
  4141. * Initializes the etherpad.
  4142. */
  4143. init: function (name) {
  4144. if (config.etherpad_base && !etherpadName && name) {
  4145. domain = config.etherpad_base;
  4146. etherpadName = name;
  4147. enableEtherpadButton();
  4148. /**
  4149. * Resizes the etherpad, when the window is resized.
  4150. */
  4151. $(window).resize(function () {
  4152. resize();
  4153. });
  4154. }
  4155. },
  4156. /**
  4157. * Opens/hides the Etherpad.
  4158. */
  4159. toggleEtherpad: function (isPresentation) {
  4160. if (!etherpadIFrame)
  4161. createIFrame();
  4162. if(VideoLayout.getLargeVideoState() === "etherpad")
  4163. {
  4164. VideoLayout.setLargeVideoState("video");
  4165. }
  4166. else
  4167. {
  4168. VideoLayout.setLargeVideoState("etherpad");
  4169. }
  4170. resize();
  4171. }
  4172. };
  4173. module.exports = Etherpad;
  4174. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4175. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4176. var UIUtil = require("../util/UIUtil");
  4177. var VideoLayout = require("../videolayout/VideoLayout");
  4178. var messageHandler = require("../util/MessageHandler");
  4179. var PreziPlayer = require("./PreziPlayer");
  4180. var preziPlayer = null;
  4181. /**
  4182. * Shows/hides a presentation.
  4183. */
  4184. function setPresentationVisible(visible) {
  4185. if (visible) {
  4186. VideoLayout.setLargeVideoState("prezi");
  4187. }
  4188. else {
  4189. VideoLayout.setLargeVideoState("video");
  4190. }
  4191. }
  4192. var Prezi = {
  4193. /**
  4194. * Reloads the current presentation.
  4195. */
  4196. reloadPresentation: function() {
  4197. var iframe = document.getElementById(preziPlayer.options.preziId);
  4198. iframe.src = iframe.src;
  4199. },
  4200. /**
  4201. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4202. * otherwise.
  4203. */
  4204. isPresentationVisible: function () {
  4205. return ($('#presentation>iframe') != null
  4206. && $('#presentation>iframe').css('opacity') == 1);
  4207. },
  4208. /**
  4209. * Opens the Prezi dialog, from which the user could choose a presentation
  4210. * to load.
  4211. */
  4212. openPreziDialog: function() {
  4213. var myprezi = APP.xmpp.getPrezi();
  4214. if (myprezi) {
  4215. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4216. null,
  4217. "dialog.removePreziMsg",
  4218. null,
  4219. false,
  4220. "dialog.Remove",
  4221. function(e,v,m,f) {
  4222. if(v) {
  4223. APP.xmpp.removePreziFromPresence();
  4224. }
  4225. }
  4226. );
  4227. }
  4228. else if (preziPlayer != null) {
  4229. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4230. null, "dialog.sharePreziMsg",
  4231. null,
  4232. false,
  4233. "dialog.Ok",
  4234. function(e,v,m,f) {
  4235. $.prompt.close();
  4236. }
  4237. );
  4238. }
  4239. else {
  4240. var html = APP.translation.generateTranslationHTML(
  4241. "dialog.sharePreziTitle");
  4242. var cancelButton = APP.translation.generateTranslationHTML(
  4243. "dialog.Cancel");
  4244. var shareButton = APP.translation.generateTranslationHTML(
  4245. "dialog.Share");
  4246. var backButton = APP.translation.generateTranslationHTML(
  4247. "dialog.Back");
  4248. var buttons = [];
  4249. var buttons1 = [];
  4250. // Cancel button to both states
  4251. buttons.push({title: cancelButton, value: false});
  4252. buttons1.push({title: cancelButton, value: false});
  4253. // Share button
  4254. buttons.push({title: shareButton, value: true});
  4255. // Back button
  4256. buttons1.push({title: backButton, value: true});
  4257. var linkError = APP.translation.generateTranslationHTML(
  4258. "dialog.preziLinkError");
  4259. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4260. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4261. var openPreziState = {
  4262. state0: {
  4263. html: '<h2>' + html + '</h2>' +
  4264. '<input name="preziUrl" type="text" ' +
  4265. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4266. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4267. '\' placeholder="' + defaultUrl + '" autofocus>',
  4268. persistent: false,
  4269. buttons: buttons,
  4270. focus: ':input:first',
  4271. defaultButton: 0,
  4272. submit: function (e, v, m, f) {
  4273. e.preventDefault();
  4274. if(v)
  4275. {
  4276. var preziUrl = f.preziUrl;
  4277. if (preziUrl)
  4278. {
  4279. var urlValue
  4280. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4281. if (urlValue.indexOf('http://prezi.com/') != 0
  4282. && urlValue.indexOf('https://prezi.com/') != 0)
  4283. {
  4284. $.prompt.goToState('state1');
  4285. return false;
  4286. }
  4287. else {
  4288. var presIdTmp = urlValue.substring(
  4289. urlValue.indexOf("prezi.com/") + 10);
  4290. if (!isAlphanumeric(presIdTmp)
  4291. || presIdTmp.indexOf('/') < 2) {
  4292. $.prompt.goToState('state1');
  4293. return false;
  4294. }
  4295. else {
  4296. APP.xmpp.addToPresence("prezi", urlValue);
  4297. $.prompt.close();
  4298. }
  4299. }
  4300. }
  4301. }
  4302. else
  4303. $.prompt.close();
  4304. }
  4305. },
  4306. state1: {
  4307. html: '<h2>' + html + '</h2>' +
  4308. linkError,
  4309. persistent: false,
  4310. buttons: buttons1,
  4311. focus: ':input:first',
  4312. defaultButton: 1,
  4313. submit: function (e, v, m, f) {
  4314. e.preventDefault();
  4315. if (v === 0)
  4316. $.prompt.close();
  4317. else
  4318. $.prompt.goToState('state0');
  4319. }
  4320. }
  4321. };
  4322. messageHandler.openDialogWithStates(openPreziState);
  4323. }
  4324. }
  4325. };
  4326. /**
  4327. * A new presentation has been added.
  4328. *
  4329. * @param event the event indicating the add of a presentation
  4330. * @param jid the jid from which the presentation was added
  4331. * @param presUrl url of the presentation
  4332. * @param currentSlide the current slide to which we should move
  4333. */
  4334. function presentationAdded(event, jid, presUrl, currentSlide) {
  4335. console.log("presentation added", presUrl);
  4336. var presId = getPresentationId(presUrl);
  4337. var elementId = 'participant_'
  4338. + Strophe.getResourceFromJid(jid)
  4339. + '_' + presId;
  4340. VideoLayout.addPreziContainer(elementId);
  4341. var controlsEnabled = false;
  4342. if (jid === APP.xmpp.myJid())
  4343. controlsEnabled = true;
  4344. setPresentationVisible(true);
  4345. VideoLayout.setLargeVideoHover(
  4346. function (event) {
  4347. if (Prezi.isPresentationVisible()) {
  4348. var reloadButtonRight = window.innerWidth
  4349. - $('#presentation>iframe').offset().left
  4350. - $('#presentation>iframe').width();
  4351. $('#reloadPresentation').css({ right: reloadButtonRight,
  4352. display:'inline-block'});
  4353. }
  4354. },
  4355. function (event) {
  4356. if (!Prezi.isPresentationVisible())
  4357. $('#reloadPresentation').css({display:'none'});
  4358. else {
  4359. var e = event.toElement || event.relatedTarget;
  4360. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4361. $('#reloadPresentation').css({display:'none'});
  4362. }
  4363. });
  4364. preziPlayer = new PreziPlayer(
  4365. 'presentation',
  4366. {preziId: presId,
  4367. width: getPresentationWidth(),
  4368. height: getPresentationHeihgt(),
  4369. controls: controlsEnabled,
  4370. debug: true
  4371. });
  4372. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4373. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4374. console.log("prezi status", event.value);
  4375. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4376. if (jid != APP.xmpp.myJid())
  4377. preziPlayer.flyToStep(currentSlide);
  4378. }
  4379. });
  4380. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4381. console.log("event value", event.value);
  4382. APP.xmpp.addToPresence("preziSlide", event.value);
  4383. });
  4384. $("#" + elementId).css( 'background-image',
  4385. 'url(../images/avatarprezi.png)');
  4386. $("#" + elementId).click(
  4387. function () {
  4388. setPresentationVisible(true);
  4389. }
  4390. );
  4391. };
  4392. /**
  4393. * A presentation has been removed.
  4394. *
  4395. * @param event the event indicating the remove of a presentation
  4396. * @param jid the jid for which the presentation was removed
  4397. * @param the url of the presentation
  4398. */
  4399. function presentationRemoved(event, jid, presUrl) {
  4400. console.log('presentation removed', presUrl);
  4401. var presId = getPresentationId(presUrl);
  4402. setPresentationVisible(false);
  4403. $('#participant_'
  4404. + Strophe.getResourceFromJid(jid)
  4405. + '_' + presId).remove();
  4406. $('#presentation>iframe').remove();
  4407. if (preziPlayer != null) {
  4408. preziPlayer.destroy();
  4409. preziPlayer = null;
  4410. }
  4411. };
  4412. /**
  4413. * Indicates if the given string is an alphanumeric string.
  4414. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4415. * purpose of checking URIs.
  4416. */
  4417. function isAlphanumeric(unsafeText) {
  4418. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4419. return regex.test(unsafeText);
  4420. }
  4421. /**
  4422. * Returns the presentation id from the given url.
  4423. */
  4424. function getPresentationId (presUrl) {
  4425. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4426. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4427. }
  4428. /**
  4429. * Returns the presentation width.
  4430. */
  4431. function getPresentationWidth() {
  4432. var availableWidth = UIUtil.getAvailableVideoWidth();
  4433. var availableHeight = getPresentationHeihgt();
  4434. var aspectRatio = 16.0 / 9.0;
  4435. if (availableHeight < availableWidth / aspectRatio) {
  4436. availableWidth = Math.floor(availableHeight * aspectRatio);
  4437. }
  4438. return availableWidth;
  4439. }
  4440. /**
  4441. * Returns the presentation height.
  4442. */
  4443. function getPresentationHeihgt() {
  4444. var remoteVideos = $('#remoteVideos');
  4445. return window.innerHeight - remoteVideos.outerHeight();
  4446. }
  4447. /**
  4448. * Resizes the presentation iframe.
  4449. */
  4450. function resize() {
  4451. if ($('#presentation>iframe')) {
  4452. $('#presentation>iframe').width(getPresentationWidth());
  4453. $('#presentation>iframe').height(getPresentationHeihgt());
  4454. }
  4455. }
  4456. /**
  4457. * Presentation has been removed.
  4458. */
  4459. $(document).bind('presentationremoved.muc', presentationRemoved);
  4460. /**
  4461. * Presentation has been added.
  4462. */
  4463. $(document).bind('presentationadded.muc', presentationAdded);
  4464. /*
  4465. * Indicates presentation slide change.
  4466. */
  4467. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4468. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4469. preziPlayer.flyToStep(current);
  4470. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4471. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4472. preziPlayer.flyToStep(current, i);
  4473. }
  4474. }
  4475. });
  4476. $(window).resize(function () {
  4477. resize();
  4478. });
  4479. module.exports = Prezi;
  4480. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4481. (function() {
  4482. "use strict";
  4483. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4484. window.PreziPlayer = (function() {
  4485. PreziPlayer.API_VERSION = 1;
  4486. PreziPlayer.CURRENT_STEP = 'currentStep';
  4487. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4488. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4489. PreziPlayer.STATUS_LOADING = 'loading';
  4490. PreziPlayer.STATUS_READY = 'ready';
  4491. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4492. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4493. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4494. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4495. PreziPlayer.EVENT_STATUS = "statusChange";
  4496. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4497. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4498. PreziPlayer.domain = "https://prezi.com";
  4499. PreziPlayer.path = "/player/";
  4500. PreziPlayer.players = {};
  4501. PreziPlayer.binded_methods = ['changesHandler'];
  4502. PreziPlayer.createMultiplePlayers = function(optionArray){
  4503. for(var i=0; i<optionArray.length; i++) {
  4504. var optionSet = optionArray[i];
  4505. new PreziPlayer(optionSet.id, optionSet);
  4506. };
  4507. };
  4508. PreziPlayer.messageReceived = function(event){
  4509. var message, item, player;
  4510. try {
  4511. message = JSON.parse(event.data);
  4512. if (message.id && (player = PreziPlayer.players[message.id])) {
  4513. if (player.options.debug === true) {
  4514. if (console && console.log)
  4515. console.log('received', message);
  4516. }
  4517. if (message.type === "changes") {
  4518. player.changesHandler(message);
  4519. }
  4520. for (var i = 0; i < player.callbacks.length; i++) {
  4521. item = player.callbacks[i];
  4522. if (item && message.type === item.event) {
  4523. item.callback(message);
  4524. }
  4525. }
  4526. }
  4527. } catch (e) { }
  4528. };
  4529. function PreziPlayer(id, options) {
  4530. var params, paramString = "", _this = this;
  4531. if (PreziPlayer.players[id]){
  4532. PreziPlayer.players[id].destroy();
  4533. }
  4534. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4535. var method_name = PreziPlayer.binded_methods[i];
  4536. _this[method_name] = __bind(_this[method_name], _this);
  4537. };
  4538. options = options || {};
  4539. this.options = options;
  4540. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4541. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4542. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4543. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4544. this.callbacks = [];
  4545. this.id = id;
  4546. this.embedTo = document.getElementById(id);
  4547. if (!this.embedTo) {
  4548. throw "The element id is not available.";
  4549. }
  4550. this.iframe = document.createElement('iframe');
  4551. params = [
  4552. { name: 'oid', value: options.preziId },
  4553. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4554. { name: 'controls', value: options.controls ? 1 : 0 }
  4555. ];
  4556. for(var i=0; i<params.length; i++) {
  4557. var param = params[i];
  4558. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4559. };
  4560. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4561. this.iframe.frameBorder = 0;
  4562. this.iframe.scrolling = "no";
  4563. this.iframe.width = options.width || 640;
  4564. this.iframe.height = options.height || 480;
  4565. this.embedTo.innerHTML = '';
  4566. // JITSI: IN CASE SOMETHING GOES WRONG.
  4567. try {
  4568. this.embedTo.appendChild(this.iframe);
  4569. }
  4570. catch (err) {
  4571. console.log("CATCH ERROR");
  4572. }
  4573. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4574. // crashes for us.
  4575. this.initPollInterval = setInterval(function(){
  4576. _this.sendMessage({'action': 'init'});
  4577. }, 500);
  4578. PreziPlayer.players[id] = this;
  4579. }
  4580. PreziPlayer.prototype.changesHandler = function(message) {
  4581. var key, value, j, item;
  4582. if (this.initPollInterval) {
  4583. clearInterval(this.initPollInterval);
  4584. this.initPollInterval = false;
  4585. }
  4586. for (key in message.data) {
  4587. if (message.data.hasOwnProperty(key)){
  4588. value = message.data[key];
  4589. this.values[key] = value;
  4590. for (j=0; j<this.callbacks.length; j++) {
  4591. item = this.callbacks[j];
  4592. if (item && item.event === key + "Change"){
  4593. item.callback({type: item.event, value: value});
  4594. }
  4595. }
  4596. }
  4597. }
  4598. };
  4599. PreziPlayer.prototype.destroy = function() {
  4600. if (this.initPollInterval) {
  4601. clearInterval(this.initPollInterval);
  4602. this.initPollInterval = false;
  4603. }
  4604. this.embedTo.innerHTML = '';
  4605. };
  4606. PreziPlayer.prototype.sendMessage = function(message) {
  4607. if (this.options.debug === true) {
  4608. if (console && console.log) console.log('sent', message);
  4609. }
  4610. message.version = PreziPlayer.API_VERSION;
  4611. message.id = this.id;
  4612. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4613. };
  4614. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4615. PreziPlayer.prototype.flyToNextStep = function() {
  4616. return this.sendMessage({
  4617. 'action': 'present',
  4618. 'data': ['moveToNextStep']
  4619. });
  4620. };
  4621. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4622. PreziPlayer.prototype.flyToPreviousStep = function() {
  4623. return this.sendMessage({
  4624. 'action': 'present',
  4625. 'data': ['moveToPrevStep']
  4626. });
  4627. };
  4628. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4629. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4630. var obj = this;
  4631. // check animation_step
  4632. if (animation_step > 0 &&
  4633. obj.values.animationCountOnSteps &&
  4634. obj.values.animationCountOnSteps[step] <= animation_step) {
  4635. animation_step = obj.values.animationCountOnSteps[step];
  4636. }
  4637. // jump to animation steps by calling flyToNextStep()
  4638. function doAnimationSteps() {
  4639. if (obj.values.isMoving == true) {
  4640. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4641. return;
  4642. }
  4643. while (animation_step-- > 0) {
  4644. obj.flyToNextStep(); // do the animation steps
  4645. }
  4646. }
  4647. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4648. // jump to the step
  4649. return this.sendMessage({
  4650. 'action': 'present',
  4651. 'data': ['moveToStep', step]
  4652. });
  4653. };
  4654. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4655. PreziPlayer.prototype.flyToObject = function(objectId) {
  4656. return this.sendMessage({
  4657. 'action': 'present',
  4658. 'data': ['moveToObject', objectId]
  4659. });
  4660. };
  4661. PreziPlayer.prototype.play = function(defaultDelay) {
  4662. return this.sendMessage({
  4663. 'action': 'present',
  4664. 'data': ['startAutoPlay', defaultDelay]
  4665. });
  4666. };
  4667. PreziPlayer.prototype.stop = function() {
  4668. return this.sendMessage({
  4669. 'action': 'present',
  4670. 'data': ['stopAutoPlay']
  4671. });
  4672. };
  4673. PreziPlayer.prototype.pause = function(defaultDelay) {
  4674. return this.sendMessage({
  4675. 'action': 'present',
  4676. 'data': ['pauseAutoPlay', defaultDelay]
  4677. });
  4678. };
  4679. PreziPlayer.prototype.getCurrentStep = function() {
  4680. return this.values.currentStep;
  4681. };
  4682. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4683. return this.values.currentAnimationStep;
  4684. };
  4685. PreziPlayer.prototype.getCurrentObject = function() {
  4686. return this.values.currentObject;
  4687. };
  4688. PreziPlayer.prototype.getStatus = function() {
  4689. return this.values.status;
  4690. };
  4691. PreziPlayer.prototype.isPlaying = function() {
  4692. return this.values.isAutoPlaying;
  4693. };
  4694. PreziPlayer.prototype.getStepCount = function() {
  4695. return this.values.stepCount;
  4696. };
  4697. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4698. return this.values.animationCountOnSteps;
  4699. };
  4700. PreziPlayer.prototype.getTitle = function() {
  4701. return this.values.title;
  4702. };
  4703. PreziPlayer.prototype.setDimensions = function(dims) {
  4704. for (var parameter in dims) {
  4705. this.iframe[parameter] = dims[parameter];
  4706. }
  4707. }
  4708. PreziPlayer.prototype.getDimensions = function() {
  4709. return {
  4710. width: parseInt(this.iframe.width, 10),
  4711. height: parseInt(this.iframe.height, 10)
  4712. }
  4713. }
  4714. PreziPlayer.prototype.on = function(event, callback) {
  4715. this.callbacks.push({
  4716. event: event,
  4717. callback: callback
  4718. });
  4719. };
  4720. PreziPlayer.prototype.off = function(event, callback) {
  4721. var j, item;
  4722. if (event === undefined) {
  4723. this.callbacks = [];
  4724. }
  4725. j = this.callbacks.length;
  4726. while (j--) {
  4727. item = this.callbacks[j];
  4728. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4729. this.callbacks.splice(j, 1);
  4730. }
  4731. }
  4732. };
  4733. if (window.addEventListener) {
  4734. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4735. } else {
  4736. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4737. }
  4738. return PreziPlayer;
  4739. })();
  4740. })();
  4741. module.exports = PreziPlayer;
  4742. },{}],20:[function(require,module,exports){
  4743. /* global require, $ */
  4744. var Chat = require("./chat/Chat");
  4745. var ContactList = require("./contactlist/ContactList");
  4746. var Settings = require("./../../settings/Settings");
  4747. var SettingsMenu = require("./settings/SettingsMenu");
  4748. var VideoLayout = require("../videolayout/VideoLayout");
  4749. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4750. var UIUtil = require("../util/UIUtil");
  4751. var LargeVideo = require("../videolayout/LargeVideo");
  4752. /**
  4753. * Toggler for the chat, contact list, settings menu, etc..
  4754. */
  4755. var PanelToggler = (function(my) {
  4756. var currentlyOpen = null;
  4757. var buttons = {
  4758. '#chatspace': '#chatBottomButton',
  4759. '#contactlist': '#contactListButton',
  4760. '#settingsmenu': '#settingsButton'
  4761. };
  4762. /**
  4763. * Toggles the windows in the side panel
  4764. * @param object the window that should be shown
  4765. * @param selector the selector for the element containing the panel
  4766. * @param onOpenComplete function to be called when the panel is opened
  4767. * @param onOpen function to be called if the window is going to be opened
  4768. * @param onClose function to be called if the window is going to be closed
  4769. */
  4770. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4771. UIUtil.buttonClick(buttons[selector], "active");
  4772. if (object.isVisible()) {
  4773. $("#toast-container").animate({
  4774. right: '5px'
  4775. },
  4776. {
  4777. queue: false,
  4778. duration: 500
  4779. });
  4780. $(selector).hide("slide", {
  4781. direction: "right",
  4782. queue: false,
  4783. duration: 500
  4784. });
  4785. if(typeof onClose === "function") {
  4786. onClose();
  4787. }
  4788. currentlyOpen = null;
  4789. }
  4790. else {
  4791. // Undock the toolbar when the chat is shown and if we're in a
  4792. // video mode.
  4793. if (LargeVideo.isLargeVideoVisible()) {
  4794. ToolbarToggler.dockToolbar(false);
  4795. }
  4796. if(currentlyOpen) {
  4797. var current = $(currentlyOpen);
  4798. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4799. current.css('z-index', 4);
  4800. setTimeout(function () {
  4801. current.css('display', 'none');
  4802. current.css('z-index', 5);
  4803. }, 500);
  4804. }
  4805. $("#toast-container").animate({
  4806. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4807. },
  4808. {
  4809. queue: false,
  4810. duration: 500
  4811. });
  4812. $(selector).show("slide", {
  4813. direction: "right",
  4814. queue: false,
  4815. duration: 500,
  4816. complete: onOpenComplete
  4817. });
  4818. if(typeof onOpen === "function") {
  4819. onOpen();
  4820. }
  4821. currentlyOpen = selector;
  4822. }
  4823. };
  4824. /**
  4825. * Opens / closes the chat area.
  4826. */
  4827. my.toggleChat = function() {
  4828. var chatCompleteFunction = Chat.isVisible() ?
  4829. function() {} : function () {
  4830. Chat.scrollChatToBottom();
  4831. $('#chatspace').trigger('shown');
  4832. };
  4833. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4834. toggle(Chat,
  4835. '#chatspace',
  4836. function () {
  4837. // Request the focus in the nickname field or the chat input field.
  4838. if ($('#nickname').css('visibility') === 'visible') {
  4839. $('#nickinput').focus();
  4840. } else {
  4841. $('#usermsg').focus();
  4842. }
  4843. },
  4844. null,
  4845. Chat.resizeChat,
  4846. null);
  4847. };
  4848. /**
  4849. * Opens / closes the contact list area.
  4850. */
  4851. my.toggleContactList = function () {
  4852. var completeFunction = ContactList.isVisible() ?
  4853. function() {} : function () { $('#contactlist').trigger('shown');};
  4854. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4855. toggle(ContactList,
  4856. '#contactlist',
  4857. null,
  4858. function() {
  4859. ContactList.setVisualNotification(false);
  4860. },
  4861. null);
  4862. };
  4863. /**
  4864. * Opens / closes the settings menu
  4865. */
  4866. my.toggleSettingsMenu = function() {
  4867. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4868. toggle(SettingsMenu,
  4869. '#settingsmenu',
  4870. null,
  4871. function() {
  4872. var settings = Settings.getSettings();
  4873. $('#setDisplayName').get(0).value = settings.displayName;
  4874. $('#setEmail').get(0).value = settings.email;
  4875. },
  4876. null);
  4877. };
  4878. /**
  4879. * Returns the size of the side panel.
  4880. */
  4881. my.getPanelSize = function () {
  4882. var availableHeight = window.innerHeight;
  4883. var availableWidth = window.innerWidth;
  4884. var panelWidth = 200;
  4885. if (availableWidth * 0.2 < 200) {
  4886. panelWidth = availableWidth * 0.2;
  4887. }
  4888. return [panelWidth, availableHeight];
  4889. };
  4890. my.isVisible = function() {
  4891. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4892. };
  4893. return my;
  4894. }(PanelToggler || {}));
  4895. module.exports = PanelToggler;
  4896. },{"../toolbars/ToolbarToggler":29,"../util/UIUtil":33,"../videolayout/LargeVideo":35,"../videolayout/VideoLayout":39,"./../../settings/Settings":47,"./chat/Chat":21,"./contactlist/ContactList":25,"./settings/SettingsMenu":26}],21:[function(require,module,exports){
  4897. /* global APP, $, Util, nickname:true */
  4898. var Replacement = require("./Replacement");
  4899. var CommandsProcessor = require("./Commands");
  4900. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4901. var smileys = require("./smileys.json").smileys;
  4902. var NicknameHandler = require("../../util/NicknameHandler");
  4903. var UIUtil = require("../../util/UIUtil");
  4904. var UIEvents = require("../../../../service/UI/UIEvents");
  4905. var notificationInterval = false;
  4906. var unreadMessages = 0;
  4907. /**
  4908. * Shows/hides a visual notification, indicating that a message has arrived.
  4909. */
  4910. function setVisualNotification(show) {
  4911. var unreadMsgElement = document.getElementById('unreadMessages');
  4912. var unreadMsgBottomElement
  4913. = document.getElementById('bottomUnreadMessages');
  4914. var glower = $('#chatButton');
  4915. var bottomGlower = $('#chatBottomButton');
  4916. if (unreadMessages) {
  4917. unreadMsgElement.innerHTML = unreadMessages.toString();
  4918. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4919. ToolbarToggler.dockToolbar(true);
  4920. var chatButtonElement
  4921. = document.getElementById('chatButton').parentNode;
  4922. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4923. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4924. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4925. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4926. unreadMsgElement.setAttribute(
  4927. 'style',
  4928. 'top:' + topIndent +
  4929. '; left:' + leftIndent + ';');
  4930. var chatBottomButtonElement
  4931. = document.getElementById('chatBottomButton').parentNode;
  4932. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4933. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4934. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4935. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  4936. unreadMsgBottomElement.setAttribute(
  4937. 'style',
  4938. 'top:' + bottomTopIndent +
  4939. '; left:' + bottomLeftIndent + ';');
  4940. if (!glower.hasClass('icon-chat-simple')) {
  4941. glower.removeClass('icon-chat');
  4942. glower.addClass('icon-chat-simple');
  4943. }
  4944. }
  4945. else {
  4946. unreadMsgElement.innerHTML = '';
  4947. unreadMsgBottomElement.innerHTML = '';
  4948. glower.removeClass('icon-chat-simple');
  4949. glower.addClass('icon-chat');
  4950. }
  4951. if (show && !notificationInterval) {
  4952. notificationInterval = window.setInterval(function () {
  4953. glower.toggleClass('active');
  4954. bottomGlower.toggleClass('active glowing');
  4955. }, 800);
  4956. }
  4957. else if (!show && notificationInterval) {
  4958. window.clearInterval(notificationInterval);
  4959. notificationInterval = false;
  4960. glower.removeClass('active');
  4961. bottomGlower.removeClass('glowing');
  4962. bottomGlower.addClass('active');
  4963. }
  4964. }
  4965. /**
  4966. * Returns the current time in the format it is shown to the user
  4967. * @returns {string}
  4968. */
  4969. function getCurrentTime(stamp) {
  4970. var now = (stamp? new Date(stamp): new Date());
  4971. var hour = now.getHours();
  4972. var minute = now.getMinutes();
  4973. var second = now.getSeconds();
  4974. if(hour.toString().length === 1) {
  4975. hour = '0'+hour;
  4976. }
  4977. if(minute.toString().length === 1) {
  4978. minute = '0'+minute;
  4979. }
  4980. if(second.toString().length === 1) {
  4981. second = '0'+second;
  4982. }
  4983. return hour+':'+minute+':'+second;
  4984. }
  4985. function toggleSmileys() {
  4986. var smileys = $('#smileysContainer');
  4987. if(!smileys.is(':visible')) {
  4988. smileys.show("slide", { direction: "down", duration: 300});
  4989. } else {
  4990. smileys.hide("slide", { direction: "down", duration: 300});
  4991. }
  4992. $('#usermsg').focus();
  4993. }
  4994. function addClickFunction(smiley, number) {
  4995. smiley.onclick = function addSmileyToMessage() {
  4996. var usermsg = $('#usermsg');
  4997. var message = usermsg.val();
  4998. message += smileys['smiley' + number];
  4999. usermsg.val(message);
  5000. usermsg.get(0).setSelectionRange(message.length, message.length);
  5001. toggleSmileys();
  5002. usermsg.focus();
  5003. };
  5004. }
  5005. /**
  5006. * Adds the smileys container to the chat
  5007. */
  5008. function addSmileys() {
  5009. var smileysContainer = document.createElement('div');
  5010. smileysContainer.id = 'smileysContainer';
  5011. for(var i = 1; i <= 21; i++) {
  5012. var smileyContainer = document.createElement('div');
  5013. smileyContainer.id = 'smiley' + i;
  5014. smileyContainer.className = 'smileyContainer';
  5015. var smiley = document.createElement('img');
  5016. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5017. smiley.className = 'smiley';
  5018. addClickFunction(smiley, i);
  5019. smileyContainer.appendChild(smiley);
  5020. smileysContainer.appendChild(smileyContainer);
  5021. }
  5022. $("#chatspace").append(smileysContainer);
  5023. }
  5024. /**
  5025. * Resizes the chat conversation.
  5026. */
  5027. function resizeChatConversation() {
  5028. var msgareaHeight = $('#usermsg').outerHeight();
  5029. var chatspace = $('#chatspace');
  5030. var width = chatspace.width();
  5031. var chat = $('#chatconversation');
  5032. var smileys = $('#smileysarea');
  5033. smileys.height(msgareaHeight);
  5034. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5035. $('#smileysContainer').css('bottom', msgareaHeight);
  5036. chat.width(width - 10);
  5037. chat.height(window.innerHeight - 15 - msgareaHeight);
  5038. }
  5039. /**
  5040. * Chat related user interface.
  5041. */
  5042. var Chat = (function (my) {
  5043. /**
  5044. * Initializes chat related interface.
  5045. */
  5046. my.init = function () {
  5047. if(NicknameHandler.getNickname())
  5048. Chat.setChatConversationMode(true);
  5049. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5050. function (nickname) {
  5051. Chat.setChatConversationMode(true);
  5052. });
  5053. $('#nickinput').keydown(function (event) {
  5054. if (event.keyCode === 13) {
  5055. event.preventDefault();
  5056. var val = UIUtil.escapeHtml(this.value);
  5057. this.value = '';
  5058. if (!NicknameHandler.getNickname()) {
  5059. NicknameHandler.setNickname(val);
  5060. return;
  5061. }
  5062. }
  5063. });
  5064. var usermsg = $('#usermsg');
  5065. usermsg.keydown(function (event) {
  5066. if (event.keyCode === 13) {
  5067. event.preventDefault();
  5068. var value = this.value;
  5069. usermsg.val('').trigger('autosize.resize');
  5070. this.focus();
  5071. var command = new CommandsProcessor(value);
  5072. if(command.isCommand()) {
  5073. command.processCommand();
  5074. }
  5075. else {
  5076. var message = UIUtil.escapeHtml(value);
  5077. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5078. }
  5079. }
  5080. });
  5081. var onTextAreaResize = function () {
  5082. resizeChatConversation();
  5083. Chat.scrollChatToBottom();
  5084. };
  5085. usermsg.autosize({callback: onTextAreaResize});
  5086. $("#chatspace").bind("shown",
  5087. function () {
  5088. unreadMessages = 0;
  5089. setVisualNotification(false);
  5090. });
  5091. addSmileys();
  5092. };
  5093. /**
  5094. * Appends the given message to the chat conversation.
  5095. */
  5096. my.updateChatConversation =
  5097. function (from, displayName, message, myjid, stamp) {
  5098. var divClassName = '';
  5099. if (APP.xmpp.myJid() === from) {
  5100. divClassName = "localuser";
  5101. }
  5102. else {
  5103. divClassName = "remoteuser";
  5104. if (!Chat.isVisible()) {
  5105. unreadMessages++;
  5106. UIUtil.playSoundNotification('chatNotification');
  5107. setVisualNotification(true);
  5108. }
  5109. }
  5110. // replace links and smileys
  5111. // Strophe already escapes special symbols on sending,
  5112. // so we escape here only tags to avoid double &amp;
  5113. var escMessage = message.replace(/</g, '&lt;').
  5114. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5115. var escDisplayName = UIUtil.escapeHtml(displayName);
  5116. message = Replacement.processReplacements(escMessage);
  5117. var messageContainer =
  5118. '<div class="chatmessage">'+
  5119. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5120. '<div class="username ' + divClassName +'">' + escDisplayName +
  5121. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5122. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5123. '</div>';
  5124. $('#chatconversation').append(messageContainer);
  5125. $('#chatconversation').animate(
  5126. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5127. };
  5128. /**
  5129. * Appends error message to the conversation
  5130. * @param errorMessage the received error message.
  5131. * @param originalText the original message.
  5132. */
  5133. my.chatAddError = function(errorMessage, originalText) {
  5134. errorMessage = UIUtil.escapeHtml(errorMessage);
  5135. originalText = UIUtil.escapeHtml(originalText);
  5136. $('#chatconversation').append(
  5137. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5138. (originalText? (' \"'+ originalText + '\"') : "") +
  5139. ' was not sent.' +
  5140. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5141. $('#chatconversation').animate(
  5142. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5143. };
  5144. /**
  5145. * Sets the subject to the UI
  5146. * @param subject the subject
  5147. */
  5148. my.chatSetSubject = function(subject) {
  5149. if (subject)
  5150. subject = subject.trim();
  5151. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5152. if(subject === "") {
  5153. $("#subject").css({display: "none"});
  5154. }
  5155. else {
  5156. $("#subject").css({display: "block"});
  5157. }
  5158. };
  5159. /**
  5160. * Sets the chat conversation mode.
  5161. */
  5162. my.setChatConversationMode = function (isConversationMode) {
  5163. if (isConversationMode) {
  5164. $('#nickname').css({visibility: 'hidden'});
  5165. $('#chatconversation').css({visibility: 'visible'});
  5166. $('#usermsg').css({visibility: 'visible'});
  5167. $('#smileysarea').css({visibility: 'visible'});
  5168. $('#usermsg').focus();
  5169. }
  5170. };
  5171. /**
  5172. * Resizes the chat area.
  5173. */
  5174. my.resizeChat = function () {
  5175. var chatSize = require("../SidePanelToggler").getPanelSize();
  5176. $('#chatspace').width(chatSize[0]);
  5177. $('#chatspace').height(chatSize[1]);
  5178. resizeChatConversation();
  5179. };
  5180. /**
  5181. * Indicates if the chat is currently visible.
  5182. */
  5183. my.isVisible = function () {
  5184. return $('#chatspace').is(":visible");
  5185. };
  5186. /**
  5187. * Shows and hides the window with the smileys
  5188. */
  5189. my.toggleSmileys = toggleSmileys;
  5190. /**
  5191. * Scrolls chat to the bottom.
  5192. */
  5193. my.scrollChatToBottom = function() {
  5194. setTimeout(function () {
  5195. $('#chatconversation').scrollTop(
  5196. $('#chatconversation')[0].scrollHeight);
  5197. }, 5);
  5198. };
  5199. return my;
  5200. }(Chat || {}));
  5201. module.exports = Chat;
  5202. },{"../../../../service/UI/UIEvents":110,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5203. /* global APP, require */
  5204. var UIUtil = require("../../util/UIUtil");
  5205. /**
  5206. * List with supported commands. The keys are the names of the commands and
  5207. * the value is the function that processes the message.
  5208. * @type {{String: function}}
  5209. */
  5210. var commands = {
  5211. "topic" : processTopic
  5212. };
  5213. /**
  5214. * Extracts the command from the message.
  5215. * @param message the received message
  5216. * @returns {string} the command
  5217. */
  5218. function getCommand(message) {
  5219. if(message) {
  5220. for(var command in commands) {
  5221. if(message.indexOf("/" + command) == 0)
  5222. return command;
  5223. }
  5224. }
  5225. return "";
  5226. }
  5227. /**
  5228. * Processes the data for topic command.
  5229. * @param commandArguments the arguments of the topic command.
  5230. */
  5231. function processTopic(commandArguments) {
  5232. var topic = UIUtil.escapeHtml(commandArguments);
  5233. APP.xmpp.setSubject(topic);
  5234. }
  5235. /**
  5236. * Constructs a new CommandProccessor instance from a message that
  5237. * handles commands received via chat messages.
  5238. * @param message the message
  5239. * @constructor
  5240. */
  5241. function CommandsProcessor(message) {
  5242. var command = getCommand(message);
  5243. /**
  5244. * Returns the name of the command.
  5245. * @returns {String} the command
  5246. */
  5247. this.getCommand = function() {
  5248. return command;
  5249. };
  5250. var messageArgument = message.substr(command.length + 2);
  5251. /**
  5252. * Returns the arguments of the command.
  5253. * @returns {string}
  5254. */
  5255. this.getArgument = function() {
  5256. return messageArgument;
  5257. };
  5258. }
  5259. /**
  5260. * Checks whether this instance is valid command or not.
  5261. * @returns {boolean}
  5262. */
  5263. CommandsProcessor.prototype.isCommand = function() {
  5264. if (this.getCommand())
  5265. return true;
  5266. return false;
  5267. };
  5268. /**
  5269. * Processes the command.
  5270. */
  5271. CommandsProcessor.prototype.processCommand = function() {
  5272. if(!this.isCommand())
  5273. return;
  5274. commands[this.getCommand()](this.getArgument());
  5275. };
  5276. module.exports = CommandsProcessor;
  5277. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5278. var Smileys = require("./smileys.json");
  5279. /**
  5280. * Processes links and smileys in "body"
  5281. */
  5282. function processReplacements(body)
  5283. {
  5284. //make links clickable
  5285. body = linkify(body);
  5286. //add smileys
  5287. body = smilify(body);
  5288. return body;
  5289. }
  5290. /**
  5291. * Finds and replaces all links in the links in "body"
  5292. * with their <a href=""></a>
  5293. */
  5294. function linkify(inputText)
  5295. {
  5296. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5297. //URLs starting with http://, https://, or ftp://
  5298. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5299. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5300. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5301. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5302. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5303. //Change email addresses to mailto:: links.
  5304. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5305. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5306. return replacedText;
  5307. }
  5308. /**
  5309. * Replaces common smiley strings with images
  5310. */
  5311. function smilify(body)
  5312. {
  5313. if(!body) {
  5314. return body;
  5315. }
  5316. var regexs = Smileys["regexs"];
  5317. for(var smiley in regexs) {
  5318. if(regexs.hasOwnProperty(smiley)) {
  5319. body = body.replace(regexs[smiley],
  5320. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5321. }
  5322. }
  5323. return body;
  5324. }
  5325. module.exports = {
  5326. processReplacements: processReplacements,
  5327. linkify: linkify
  5328. };
  5329. },{"./smileys.json":24}],24:[function(require,module,exports){
  5330. module.exports={
  5331. "smileys": {
  5332. "smiley1": ":)",
  5333. "smiley2": ":(",
  5334. "smiley3": ":D",
  5335. "smiley4": "(y)",
  5336. "smiley5": " :P",
  5337. "smiley6": "(wave)",
  5338. "smiley7": "(blush)",
  5339. "smiley8": "(chuckle)",
  5340. "smiley9": "(shocked)",
  5341. "smiley10": ":*",
  5342. "smiley11": "(n)",
  5343. "smiley12": "(search)",
  5344. "smiley13": " <3",
  5345. "smiley14": "(oops)",
  5346. "smiley15": "(angry)",
  5347. "smiley16": "(angel)",
  5348. "smiley17": "(sick)",
  5349. "smiley18": ";(",
  5350. "smiley19": "(bomb)",
  5351. "smiley20": "(clap)",
  5352. "smiley21": " ;)"
  5353. },
  5354. "regexs": {
  5355. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5356. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5357. "smiley1": /(:-\)|:\))/gi,
  5358. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5359. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5360. "smiley6": /(\(wave\))/gi,
  5361. "smiley7": /(\(blush\))/gi,
  5362. "smiley8": /(\(chuckle\))/gi,
  5363. "smiley9": /(:-0|\(shocked\))/gi,
  5364. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5365. "smiley11": /(\(n\))/gi,
  5366. "smiley12": /(\(search\))/g,
  5367. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5368. "smiley14": /(\(oops\))/gi,
  5369. "smiley15": /(\(angry\))/gi,
  5370. "smiley16": /(\(angel\))/gi,
  5371. "smiley17": /(\(sick\))/gi,
  5372. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5373. "smiley19": /(\(bomb\))/gi,
  5374. "smiley20": /(\(clap\))/gi,
  5375. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5376. }
  5377. }
  5378. },{}],25:[function(require,module,exports){
  5379. /* global $, APP, Strophe */
  5380. var Avatar = require('../../avatar/Avatar');
  5381. var numberOfContacts = 0;
  5382. var notificationInterval;
  5383. /**
  5384. * Updates the number of participants in the contact list button and sets
  5385. * the glow
  5386. * @param delta indicates whether a new user has joined (1) or someone has
  5387. * left(-1)
  5388. */
  5389. function updateNumberOfParticipants(delta) {
  5390. numberOfContacts += delta;
  5391. if (numberOfContacts === 1) {
  5392. // when the user is alone we don't show the number of participants
  5393. $("#numberOfParticipants").text('');
  5394. ContactList.setVisualNotification(false);
  5395. } else if (numberOfContacts > 1) {
  5396. ContactList.setVisualNotification(!ContactList.isVisible());
  5397. $("#numberOfParticipants").text(numberOfContacts);
  5398. } else {
  5399. console.error("Invalid number of participants: " + numberOfContacts);
  5400. }
  5401. }
  5402. /**
  5403. * Creates the avatar element.
  5404. *
  5405. * @return {object} the newly created avatar element
  5406. */
  5407. function createAvatar(jid) {
  5408. var avatar = document.createElement('img');
  5409. avatar.className = "icon-avatar avatar";
  5410. avatar.src = Avatar.getContactListUrl(jid);
  5411. return avatar;
  5412. }
  5413. /**
  5414. * Creates the display name paragraph.
  5415. *
  5416. * @param displayName the display name to set
  5417. */
  5418. function createDisplayNameParagraph(key, displayName) {
  5419. var p = document.createElement('p');
  5420. if(displayName)
  5421. p.innerText = displayName;
  5422. else if(key) {
  5423. p.setAttribute("data-i18n",key);
  5424. p.innerText = APP.translation.translateString(key);
  5425. }
  5426. return p;
  5427. }
  5428. function stopGlowing(glower) {
  5429. window.clearInterval(notificationInterval);
  5430. notificationInterval = false;
  5431. glower.removeClass('glowing');
  5432. if (!ContactList.isVisible()) {
  5433. glower.removeClass('active');
  5434. }
  5435. }
  5436. /**
  5437. * Contact list.
  5438. */
  5439. var ContactList = {
  5440. /**
  5441. * Indicates if the chat is currently visible.
  5442. *
  5443. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5444. * otherwise
  5445. */
  5446. isVisible: function () {
  5447. return $('#contactlist').is(":visible");
  5448. },
  5449. /**
  5450. * Adds a contact for the given peerJid if such doesn't yet exist.
  5451. *
  5452. * @param peerJid the peerJid corresponding to the contact
  5453. */
  5454. ensureAddContact: function (peerJid) {
  5455. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5456. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5457. if (!contact || contact.length <= 0)
  5458. ContactList.addContact(peerJid);
  5459. },
  5460. /**
  5461. * Adds a contact for the given peer jid.
  5462. *
  5463. * @param peerJid the jid of the contact to add
  5464. */
  5465. addContact: function (peerJid) {
  5466. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5467. var contactlist = $('#contacts');
  5468. var newContact = document.createElement('li');
  5469. newContact.id = resourceJid;
  5470. newContact.className = "clickable";
  5471. newContact.onclick = function (event) {
  5472. if (event.currentTarget.className === "clickable") {
  5473. $(ContactList).trigger('contactclicked', [peerJid]);
  5474. }
  5475. };
  5476. newContact.appendChild(createAvatar(peerJid));
  5477. newContact.appendChild(createDisplayNameParagraph("participant"));
  5478. if (resourceJid === APP.xmpp.myResource()) {
  5479. contactlist.prepend(newContact);
  5480. }
  5481. else {
  5482. contactlist.append(newContact);
  5483. }
  5484. updateNumberOfParticipants(1);
  5485. },
  5486. /**
  5487. * Removes a contact for the given peer jid.
  5488. *
  5489. * @param peerJid the peerJid corresponding to the contact to remove
  5490. */
  5491. removeContact: function (peerJid) {
  5492. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5493. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5494. if (contact && contact.length > 0) {
  5495. var contactlist = $('#contactlist>ul');
  5496. contactlist.get(0).removeChild(contact.get(0));
  5497. updateNumberOfParticipants(-1);
  5498. }
  5499. },
  5500. setVisualNotification: function (show, stopGlowingIn) {
  5501. var glower = $('#contactListButton');
  5502. if (show && !notificationInterval) {
  5503. notificationInterval = window.setInterval(function () {
  5504. glower.toggleClass('active glowing');
  5505. }, 800);
  5506. }
  5507. else if (!show && notificationInterval) {
  5508. stopGlowing(glower);
  5509. }
  5510. if (stopGlowingIn) {
  5511. setTimeout(function () {
  5512. stopGlowing(glower);
  5513. }, stopGlowingIn);
  5514. }
  5515. },
  5516. setClickable: function (resourceJid, isClickable) {
  5517. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5518. if (isClickable) {
  5519. contact.addClass('clickable');
  5520. } else {
  5521. contact.removeClass('clickable');
  5522. }
  5523. },
  5524. onDisplayNameChange: function (peerJid, displayName) {
  5525. if (peerJid === 'localVideoContainer')
  5526. peerJid = APP.xmpp.myJid();
  5527. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5528. var contactName = $('#contacts #' + resourceJid + '>p');
  5529. if (contactName && displayName && displayName.length > 0)
  5530. contactName.html(displayName);
  5531. },
  5532. userAvatarChanged: function (resourceJid, contactListUrl) {
  5533. // set the avatar in the contact list
  5534. var contact = $('#' + resourceJid + '>img');
  5535. if (contact && contact.length > 0) {
  5536. contact.get(0).src = contactListUrl;
  5537. }
  5538. }
  5539. };
  5540. module.exports = ContactList;
  5541. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5542. /* global APP, $ */
  5543. var Avatar = require("../../avatar/Avatar");
  5544. var Settings = require("./../../../settings/Settings");
  5545. var UIUtil = require("../../util/UIUtil");
  5546. var languages = require("../../../../service/translation/languages");
  5547. function generateLanguagesSelectBox() {
  5548. var currentLang = APP.translation.getCurrentLanguage();
  5549. var html = "<select id=\"languages_selectbox\">";
  5550. var langArray = languages.getLanguages();
  5551. for(var i = 0; i < langArray.length; i++) {
  5552. var lang = langArray[i];
  5553. html += "<option ";
  5554. if(lang === currentLang)
  5555. html += "selected ";
  5556. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5557. html += "</option>";
  5558. }
  5559. return html + "</select>";
  5560. }
  5561. var SettingsMenu = {
  5562. init: function () {
  5563. var startMutedSelector = $("#startMutedOptions");
  5564. startMutedSelector.before(generateLanguagesSelectBox());
  5565. APP.translation.translateElement($("#languages_selectbox"));
  5566. $('#settingsmenu>input').keyup(function(event){
  5567. if(event.keyCode === 13) {//enter
  5568. SettingsMenu.update();
  5569. }
  5570. });
  5571. if (APP.xmpp.isModerator()) {
  5572. startMutedSelector.css("display", "block");
  5573. }
  5574. else {
  5575. startMutedSelector.css("display", "none");
  5576. }
  5577. $("#updateSettings").click(function () {
  5578. SettingsMenu.update();
  5579. });
  5580. },
  5581. onRoleChanged: function () {
  5582. if(APP.xmpp.isModerator()) {
  5583. $("#startMutedOptions").css("display", "block");
  5584. }
  5585. else {
  5586. $("#startMutedOptions").css("display", "none");
  5587. }
  5588. },
  5589. setStartMuted: function (audio, video) {
  5590. $("#startAudioMuted").attr("checked", audio);
  5591. $("#startVideoMuted").attr("checked", video);
  5592. },
  5593. update: function() {
  5594. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5595. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5596. if(newDisplayName) {
  5597. var displayName = Settings.setDisplayName(newDisplayName);
  5598. APP.xmpp.addToPresence("displayName", displayName, true);
  5599. }
  5600. var language = $("#languages_selectbox").val();
  5601. APP.translation.setLanguage(language);
  5602. Settings.setLanguage(language);
  5603. APP.xmpp.addToPresence("email", newEmail);
  5604. var email = Settings.setEmail(newEmail);
  5605. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5606. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5607. APP.xmpp.addToPresence("startMuted",
  5608. [startAudioMuted, startVideoMuted]);
  5609. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5610. },
  5611. isVisible: function() {
  5612. return $('#settingsmenu').is(':visible');
  5613. },
  5614. setDisplayName: function(newDisplayName) {
  5615. var displayName = Settings.setDisplayName(newDisplayName);
  5616. $('#setDisplayName').get(0).value = displayName;
  5617. },
  5618. onDisplayNameChange: function(peerJid, newDisplayName) {
  5619. if(peerJid === 'localVideoContainer' ||
  5620. peerJid === APP.xmpp.myJid()) {
  5621. this.setDisplayName(newDisplayName);
  5622. }
  5623. },
  5624. changeAvatar: function (thumbUrl) {
  5625. $('#avatar').get(0).src = thumbUrl;
  5626. }
  5627. };
  5628. module.exports = SettingsMenu;
  5629. },{"../../../../service/translation/languages":115,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5630. /* global $ */
  5631. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5632. var buttonHandlers = {
  5633. "bottom_toolbar_contact_list": function () {
  5634. BottomToolbar.toggleContactList();
  5635. },
  5636. "bottom_toolbar_film_strip": function () {
  5637. BottomToolbar.toggleFilmStrip();
  5638. },
  5639. "bottom_toolbar_chat": function () {
  5640. BottomToolbar.toggleChat();
  5641. }
  5642. };
  5643. var BottomToolbar = (function (my) {
  5644. my.init = function () {
  5645. for(var k in buttonHandlers)
  5646. $("#" + k).click(buttonHandlers[k]);
  5647. };
  5648. my.toggleChat = function() {
  5649. PanelToggler.toggleChat();
  5650. };
  5651. my.toggleContactList = function() {
  5652. PanelToggler.toggleContactList();
  5653. };
  5654. my.toggleFilmStrip = function() {
  5655. var filmstrip = $("#remoteVideos");
  5656. filmstrip.toggleClass("hidden");
  5657. };
  5658. $(document).bind("remotevideo.resized", function (event, width, height) {
  5659. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5660. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5661. });
  5662. return my;
  5663. }(BottomToolbar || {}));
  5664. module.exports = BottomToolbar;
  5665. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5666. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5667. Util */
  5668. var messageHandler = require("../util/MessageHandler");
  5669. var BottomToolbar = require("./BottomToolbar");
  5670. var Prezi = require("../prezi/Prezi");
  5671. var Etherpad = require("../etherpad/Etherpad");
  5672. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5673. var Authentication = require("../authentication/Authentication");
  5674. var UIUtil = require("../util/UIUtil");
  5675. var AuthenticationEvents
  5676. = require("../../../service/authentication/AuthenticationEvents");
  5677. var roomUrl = null;
  5678. var sharedKey = '';
  5679. var UI = null;
  5680. var buttonHandlers = {
  5681. "toolbar_button_mute": function () {
  5682. return APP.UI.toggleAudio();
  5683. },
  5684. "toolbar_button_camera": function () {
  5685. return APP.UI.toggleVideo();
  5686. },
  5687. /*"toolbar_button_authentication": function () {
  5688. return Toolbar.authenticateClicked();
  5689. },*/
  5690. "toolbar_button_record": function () {
  5691. return toggleRecording();
  5692. },
  5693. "toolbar_button_security": function () {
  5694. return Toolbar.openLockDialog();
  5695. },
  5696. "toolbar_button_link": function () {
  5697. return Toolbar.openLinkDialog();
  5698. },
  5699. "toolbar_button_chat": function () {
  5700. return BottomToolbar.toggleChat();
  5701. },
  5702. "toolbar_button_prezi": function () {
  5703. return Prezi.openPreziDialog();
  5704. },
  5705. "toolbar_button_etherpad": function () {
  5706. return Etherpad.toggleEtherpad(0);
  5707. },
  5708. "toolbar_button_desktopsharing": function () {
  5709. return APP.desktopsharing.toggleScreenSharing();
  5710. },
  5711. "toolbar_button_fullScreen": function() {
  5712. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  5713. return Toolbar.toggleFullScreen();
  5714. },
  5715. "toolbar_button_sip": function () {
  5716. return callSipButtonClicked();
  5717. },
  5718. "toolbar_button_dialpad": function () {
  5719. return dialpadButtonClicked();
  5720. },
  5721. "toolbar_button_settings": function () {
  5722. PanelToggler.toggleSettingsMenu();
  5723. },
  5724. "toolbar_button_hangup": function () {
  5725. return hangup();
  5726. },
  5727. "toolbar_button_login": function () {
  5728. Toolbar.authenticateClicked();
  5729. },
  5730. "toolbar_button_logout": function () {
  5731. // Ask for confirmation
  5732. messageHandler.openTwoButtonDialog(
  5733. "dialog.logoutTitle",
  5734. null,
  5735. "dialog.logoutQuestion",
  5736. null,
  5737. false,
  5738. "dialog.Yes",
  5739. function (evt, yes) {
  5740. if (yes) {
  5741. APP.xmpp.logout(function (url) {
  5742. if (url) {
  5743. window.location.href = url;
  5744. } else {
  5745. hangup();
  5746. }
  5747. });
  5748. }
  5749. });
  5750. }
  5751. };
  5752. function hangup() {
  5753. APP.xmpp.disposeConference();
  5754. if(config.enableWelcomePage) {
  5755. setTimeout(function() {
  5756. window.localStorage.welcomePageDisabled = false;
  5757. window.location.pathname = "/";
  5758. }, 10000);
  5759. }
  5760. var title = APP.translation.generateTranslationHTML(
  5761. "dialog.sessTerminated");
  5762. var msg = APP.translation.generateTranslationHTML(
  5763. "dialog.hungUp");
  5764. var button = APP.translation.generateTranslationHTML(
  5765. "dialog.joinAgain");
  5766. var buttons = [];
  5767. buttons.push({title: button, value: true});
  5768. UI.messageHandler.openDialog(
  5769. title,
  5770. msg,
  5771. true,
  5772. buttons,
  5773. function(event, value, message, formVals) {
  5774. window.location.reload();
  5775. return false;
  5776. }
  5777. );
  5778. }
  5779. /**
  5780. * Starts or stops the recording for the conference.
  5781. */
  5782. function toggleRecording() {
  5783. APP.xmpp.toggleRecording(function (callback) {
  5784. var msg = APP.translation.generateTranslationHTML(
  5785. "dialog.recordingToken");
  5786. var token = APP.translation.translateString("dialog.token");
  5787. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5788. '<h2>' + msg + '</h2>' +
  5789. '<input name="recordingToken" type="text" ' +
  5790. ' data-i18n="[placeholder]dialog.token" ' +
  5791. 'placeholder="' + token + '" autofocus>',
  5792. false,
  5793. "dialog.Save",
  5794. function (e, v, m, f) {
  5795. if (v) {
  5796. var token = f.recordingToken;
  5797. if (token) {
  5798. callback(UIUtil.escapeHtml(token));
  5799. }
  5800. }
  5801. },
  5802. null,
  5803. function () { },
  5804. ':input:first'
  5805. );
  5806. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  5807. }
  5808. /**
  5809. * Locks / unlocks the room.
  5810. */
  5811. function lockRoom(lock) {
  5812. var currentSharedKey = '';
  5813. if (lock)
  5814. currentSharedKey = sharedKey;
  5815. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5816. // password is required
  5817. if (sharedKey) {
  5818. console.log('set room password');
  5819. Toolbar.lockLockButton();
  5820. }
  5821. else {
  5822. console.log('removed room password');
  5823. Toolbar.unlockLockButton();
  5824. }
  5825. }, function (err) {
  5826. console.warn('setting password failed', err);
  5827. messageHandler.showError("dialog.lockTitle",
  5828. "dialog.lockMessage");
  5829. Toolbar.setSharedKey('');
  5830. }, function () {
  5831. console.warn('room passwords not supported');
  5832. messageHandler.showError("dialog.warning",
  5833. "dialog.passwordNotSupported");
  5834. Toolbar.setSharedKey('');
  5835. });
  5836. }
  5837. /**
  5838. * Invite participants to conference.
  5839. */
  5840. function inviteParticipants() {
  5841. if (roomUrl === null)
  5842. return;
  5843. var sharedKeyText = "";
  5844. if (sharedKey && sharedKey.length > 0) {
  5845. sharedKeyText =
  5846. APP.translation.translateString("email.sharedKey",
  5847. {sharedKey: sharedKey});
  5848. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5849. }
  5850. var supportedBrowsers = "Chromium, Google Chrome " +
  5851. APP.translation.translateString("email.and") + " Opera";
  5852. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5853. var subject = APP.translation.translateString("email.subject",
  5854. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5855. var body = APP.translation.translateString("email.body",
  5856. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5857. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5858. body = body.replace(/\n/g, "%0D%0A");
  5859. if (window.localStorage.displayname) {
  5860. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5861. }
  5862. if (interfaceConfig.INVITATION_POWERED_BY) {
  5863. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5864. }
  5865. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5866. }
  5867. function dialpadButtonClicked() {
  5868. //TODO show the dialpad box
  5869. }
  5870. function callSipButtonClicked() {
  5871. var defaultNumber
  5872. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5873. var sipMsg = APP.translation.generateTranslationHTML(
  5874. "dialog.sipMsg");
  5875. messageHandler.openTwoButtonDialog(null, null, null,
  5876. '<h2>' + sipMsg + '</h2>' +
  5877. '<input name="sipNumber" type="text"' +
  5878. ' value="' + defaultNumber + '" autofocus>',
  5879. false,
  5880. "dialog.Dial",
  5881. function (e, v, m, f) {
  5882. if (v) {
  5883. var numberInput = f.sipNumber;
  5884. if (numberInput) {
  5885. APP.xmpp.dial(
  5886. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5887. }
  5888. }
  5889. },
  5890. null, null, ':input:first'
  5891. );
  5892. }
  5893. var Toolbar = (function (my) {
  5894. my.init = function (ui) {
  5895. for(var k in buttonHandlers)
  5896. $("#" + k).click(buttonHandlers[k]);
  5897. UI = ui;
  5898. // Update login info
  5899. APP.xmpp.addListener(
  5900. AuthenticationEvents.IDENTITY_UPDATED,
  5901. function (authenticationEnabled, userIdentity) {
  5902. var loggedIn = false;
  5903. if (userIdentity) {
  5904. loggedIn = true;
  5905. }
  5906. Toolbar.showAuthenticateButton(authenticationEnabled);
  5907. if (authenticationEnabled) {
  5908. Toolbar.setAuthenticatedIdentity(userIdentity);
  5909. Toolbar.showLoginButton(!loggedIn);
  5910. Toolbar.showLogoutButton(loggedIn);
  5911. }
  5912. }
  5913. );
  5914. };
  5915. /**
  5916. * Sets shared key
  5917. * @param sKey the shared key
  5918. */
  5919. my.setSharedKey = function (sKey) {
  5920. sharedKey = sKey;
  5921. };
  5922. my.authenticateClicked = function () {
  5923. Authentication.focusAuthenticationWindow();
  5924. if (!APP.xmpp.isExternalAuthEnabled()) {
  5925. Authentication.xmppAuthenticate();
  5926. return;
  5927. }
  5928. // Get authentication URL
  5929. if (!APP.xmpp.isMUCJoined()) {
  5930. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  5931. // If conference has not been started yet - redirect to login page
  5932. window.location.href = url;
  5933. });
  5934. } else {
  5935. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  5936. // Otherwise - open popup with authentication URL
  5937. var authenticationWindow = Authentication.createAuthenticationWindow(
  5938. function () {
  5939. // On popup closed - retry room allocation
  5940. APP.xmpp.allocateConferenceFocus(
  5941. APP.UI.getRoomName(),
  5942. function () { console.info("AUTH DONE"); }
  5943. );
  5944. }, url);
  5945. if (!authenticationWindow) {
  5946. messageHandler.openMessageDialog(
  5947. null, "dialog.popupError");
  5948. }
  5949. });
  5950. }
  5951. };
  5952. /**
  5953. * Updates the room invite url.
  5954. */
  5955. my.updateRoomUrl = function (newRoomUrl) {
  5956. roomUrl = newRoomUrl;
  5957. // If the invite dialog has been already opened we update the information.
  5958. var inviteLink = document.getElementById('inviteLinkRef');
  5959. if (inviteLink) {
  5960. inviteLink.value = roomUrl;
  5961. inviteLink.select();
  5962. $('#inviteLinkRef').parent()
  5963. .find('button[value=true]').prop('disabled', false);
  5964. }
  5965. };
  5966. /**
  5967. * Disables and enables some of the buttons.
  5968. */
  5969. my.setupButtonsFromConfig = function () {
  5970. if (config.disablePrezi) {
  5971. $("#prezi_button").css({display: "none"});
  5972. }
  5973. };
  5974. /**
  5975. * Opens the lock room dialog.
  5976. */
  5977. my.openLockDialog = function () {
  5978. // Only the focus is able to set a shared key.
  5979. if (!APP.xmpp.isModerator()) {
  5980. if (sharedKey) {
  5981. messageHandler.openMessageDialog(null,
  5982. "dialog.passwordError");
  5983. } else {
  5984. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  5985. }
  5986. } else {
  5987. if (sharedKey) {
  5988. messageHandler.openTwoButtonDialog(null, null,
  5989. "dialog.passwordCheck",
  5990. null,
  5991. false,
  5992. "dialog.Remove",
  5993. function (e, v) {
  5994. if (v) {
  5995. Toolbar.setSharedKey('');
  5996. lockRoom(false);
  5997. }
  5998. });
  5999. } else {
  6000. var msg = APP.translation.generateTranslationHTML(
  6001. "dialog.passwordMsg");
  6002. var yourPassword = APP.translation.translateString(
  6003. "dialog.yourPassword");
  6004. messageHandler.openTwoButtonDialog(null, null, null,
  6005. '<h2>' + msg + '</h2>' +
  6006. '<input name="lockKey" type="text"' +
  6007. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6008. 'placeholder="' + yourPassword + '" autofocus>',
  6009. false,
  6010. "dialog.Save",
  6011. function (e, v, m, f) {
  6012. if (v) {
  6013. var lockKey = f.lockKey;
  6014. if (lockKey) {
  6015. Toolbar.setSharedKey(
  6016. UIUtil.escapeHtml(lockKey));
  6017. lockRoom(true);
  6018. }
  6019. }
  6020. },
  6021. null, null, 'input:first'
  6022. );
  6023. }
  6024. }
  6025. };
  6026. /**
  6027. * Opens the invite link dialog.
  6028. */
  6029. my.openLinkDialog = function () {
  6030. var inviteAttreibutes;
  6031. if (roomUrl === null) {
  6032. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6033. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6034. } else {
  6035. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6036. }
  6037. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6038. null, null,
  6039. '<input id="inviteLinkRef" type="text" ' +
  6040. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6041. false,
  6042. "dialog.Invite",
  6043. function (e, v) {
  6044. if (v) {
  6045. if (roomUrl) {
  6046. inviteParticipants();
  6047. }
  6048. }
  6049. },
  6050. function (event) {
  6051. if (roomUrl) {
  6052. document.getElementById('inviteLinkRef').select();
  6053. } else {
  6054. if (event && event.target)
  6055. $(event.target)
  6056. .find('button[value=true]').prop('disabled', true);
  6057. }
  6058. }
  6059. );
  6060. };
  6061. /**
  6062. * Opens the settings dialog.
  6063. * FIXME: not used ?
  6064. */
  6065. my.openSettingsDialog = function () {
  6066. var settings1 = APP.translation.generateTranslationHTML(
  6067. "dialog.settings1");
  6068. var settings2 = APP.translation.generateTranslationHTML(
  6069. "dialog.settings2");
  6070. var settings3 = APP.translation.generateTranslationHTML(
  6071. "dialog.settings3");
  6072. var yourPassword = APP.translation.translateString(
  6073. "dialog.yourPassword");
  6074. messageHandler.openTwoButtonDialog(null,
  6075. '<h2>' + settings1 + '</h2>' +
  6076. '<input type="checkbox" id="initMuted">' +
  6077. settings2 + '<br/>' +
  6078. '<input type="checkbox" id="requireNicknames">' +
  6079. settings3 +
  6080. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6081. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6082. null,
  6083. null,
  6084. false,
  6085. "dialog.Save",
  6086. function () {
  6087. document.getElementById('lockKey').focus();
  6088. },
  6089. function (e, v) {
  6090. if (v) {
  6091. if ($('#initMuted').is(":checked")) {
  6092. // it is checked
  6093. }
  6094. if ($('#requireNicknames').is(":checked")) {
  6095. // it is checked
  6096. }
  6097. /*
  6098. var lockKey = document.getElementById('lockKey');
  6099. if (lockKey.value) {
  6100. setSharedKey(lockKey.value);
  6101. lockRoom(true);
  6102. }
  6103. */
  6104. }
  6105. }
  6106. );
  6107. };
  6108. /**
  6109. * Toggles the application in and out of full screen mode
  6110. * (a.k.a. presentation mode in Chrome).
  6111. */
  6112. my.toggleFullScreen = function () {
  6113. var fsElement = document.documentElement;
  6114. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6115. //Enter Full Screen
  6116. if (fsElement.mozRequestFullScreen) {
  6117. fsElement.mozRequestFullScreen();
  6118. }
  6119. else {
  6120. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6121. }
  6122. } else {
  6123. //Exit Full Screen
  6124. if (document.mozCancelFullScreen) {
  6125. document.mozCancelFullScreen();
  6126. } else {
  6127. document.webkitCancelFullScreen();
  6128. }
  6129. }
  6130. };
  6131. /**
  6132. * Unlocks the lock button state.
  6133. */
  6134. my.unlockLockButton = function () {
  6135. if ($("#lockIcon").hasClass("icon-security-locked"))
  6136. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6137. };
  6138. /**
  6139. * Updates the lock button state to locked.
  6140. */
  6141. my.lockLockButton = function () {
  6142. if ($("#lockIcon").hasClass("icon-security"))
  6143. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6144. };
  6145. /**
  6146. * Shows or hides authentication button
  6147. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6148. */
  6149. my.showAuthenticateButton = function (show) {
  6150. if (show) {
  6151. $('#authentication').css({display: "inline"});
  6152. }
  6153. else {
  6154. $('#authentication').css({display: "none"});
  6155. }
  6156. };
  6157. // Shows or hides the 'recording' button.
  6158. my.showRecordingButton = function (show) {
  6159. if (!config.enableRecording) {
  6160. return;
  6161. }
  6162. if (show) {
  6163. $('#recording').css({display: "inline"});
  6164. }
  6165. else {
  6166. $('#recording').css({display: "none"});
  6167. }
  6168. };
  6169. // Sets the state of the recording button
  6170. my.setRecordingButtonState = function (isRecording) {
  6171. var selector = $('#recordButton');
  6172. if (isRecording) {
  6173. selector.removeClass("icon-recEnable");
  6174. selector.addClass("icon-recEnable active");
  6175. } else {
  6176. selector.removeClass("icon-recEnable active");
  6177. selector.addClass("icon-recEnable");
  6178. }
  6179. };
  6180. // Shows or hides SIP calls button
  6181. my.showSipCallButton = function (show) {
  6182. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6183. $('#sipCallButton').css({display: "inline-block"});
  6184. } else {
  6185. $('#sipCallButton').css({display: "none"});
  6186. }
  6187. };
  6188. // Shows or hides the dialpad button
  6189. my.showDialPadButton = function (show) {
  6190. if (show) {
  6191. $('#dialPadButton').css({display: "inline-block"});
  6192. } else {
  6193. $('#dialPadButton').css({display: "none"});
  6194. }
  6195. };
  6196. /**
  6197. * Displays user authenticated identity name(login).
  6198. * @param authIdentity identity name to be displayed.
  6199. */
  6200. my.setAuthenticatedIdentity = function (authIdentity) {
  6201. if (authIdentity) {
  6202. var selector = $('#toolbar_auth_identity');
  6203. selector.css({display: "list-item"});
  6204. selector.text(authIdentity);
  6205. } else {
  6206. $('#toolbar_auth_identity').css({display: "none"});
  6207. }
  6208. };
  6209. /**
  6210. * Shows/hides login button.
  6211. * @param show <tt>true</tt> to show
  6212. */
  6213. my.showLoginButton = function (show) {
  6214. if (show) {
  6215. $('#toolbar_button_login').css({display: "list-item"});
  6216. } else {
  6217. $('#toolbar_button_login').css({display: "none"});
  6218. }
  6219. };
  6220. /**
  6221. * Shows/hides logout button.
  6222. * @param show <tt>true</tt> to show
  6223. */
  6224. my.showLogoutButton = function (show) {
  6225. if (show) {
  6226. $('#toolbar_button_logout').css({display: "list-item"});
  6227. } else {
  6228. $('#toolbar_button_logout').css({display: "none"});
  6229. }
  6230. };
  6231. /**
  6232. * Sets the state of the button. The button has blue glow if desktop
  6233. * streaming is active.
  6234. * @param active the state of the desktop streaming.
  6235. */
  6236. my.changeDesktopSharingButtonState = function (active) {
  6237. var button = $("#desktopsharing > a");
  6238. if (active) {
  6239. button.addClass("glow");
  6240. } else {
  6241. button.removeClass("glow");
  6242. }
  6243. };
  6244. return my;
  6245. }(Toolbar || {}));
  6246. module.exports = Toolbar;
  6247. },{"../../../service/authentication/AuthenticationEvents":111,"../authentication/Authentication":14,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../side_pannels/SidePanelToggler":20,"../util/MessageHandler":31,"../util/UIUtil":33,"./BottomToolbar":27}],29:[function(require,module,exports){
  6248. /* global APP, config, $, interfaceConfig, Moderator,
  6249. DesktopStreaming.showDesktopSharingButton */
  6250. var toolbarTimeoutObject,
  6251. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6252. function showDesktopSharingButton() {
  6253. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6254. $('#desktopsharing').css({display: "inline"});
  6255. } else {
  6256. $('#desktopsharing').css({display: "none"});
  6257. }
  6258. }
  6259. /**
  6260. * Hides the toolbar.
  6261. */
  6262. function hideToolbar() {
  6263. if(config.alwaysVisibleToolbar)
  6264. return;
  6265. var header = $("#header"),
  6266. bottomToolbar = $("#bottomToolbar");
  6267. var isToolbarHover = false;
  6268. header.find('*').each(function () {
  6269. var id = $(this).attr('id');
  6270. if ($("#" + id + ":hover").length > 0) {
  6271. isToolbarHover = true;
  6272. }
  6273. });
  6274. if ($("#bottomToolbar:hover").length > 0) {
  6275. isToolbarHover = true;
  6276. }
  6277. clearTimeout(toolbarTimeoutObject);
  6278. toolbarTimeoutObject = null;
  6279. if (!isToolbarHover) {
  6280. header.hide("slide", { direction: "up", duration: 300});
  6281. $('#subject').animate({top: "-=40"}, 300);
  6282. if ($("#remoteVideos").hasClass("hidden")) {
  6283. bottomToolbar.hide(
  6284. "slide", {direction: "right", duration: 300});
  6285. }
  6286. }
  6287. else {
  6288. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6289. }
  6290. }
  6291. var ToolbarToggler = {
  6292. /**
  6293. * Shows the main toolbar.
  6294. */
  6295. showToolbar: function () {
  6296. var header = $("#header"),
  6297. bottomToolbar = $("#bottomToolbar");
  6298. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6299. header.show("slide", { direction: "up", duration: 300});
  6300. $('#subject').animate({top: "+=40"}, 300);
  6301. if (!bottomToolbar.is(":visible")) {
  6302. bottomToolbar.show(
  6303. "slide", {direction: "right", duration: 300});
  6304. }
  6305. if (toolbarTimeoutObject) {
  6306. clearTimeout(toolbarTimeoutObject);
  6307. toolbarTimeoutObject = null;
  6308. }
  6309. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6310. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6311. }
  6312. if (APP.xmpp.isModerator())
  6313. {
  6314. // TODO: Enable settings functionality.
  6315. // Need to uncomment the settings button in index.html.
  6316. // $('#settingsButton').css({visibility:"visible"});
  6317. }
  6318. // Show/hide desktop sharing button
  6319. showDesktopSharingButton();
  6320. },
  6321. /**
  6322. * Docks/undocks the toolbar.
  6323. *
  6324. * @param isDock indicates what operation to perform
  6325. */
  6326. dockToolbar: function (isDock) {
  6327. if (isDock) {
  6328. // First make sure the toolbar is shown.
  6329. if (!$('#header').is(':visible')) {
  6330. this.showToolbar();
  6331. }
  6332. // Then clear the time out, to dock the toolbar.
  6333. if (toolbarTimeoutObject) {
  6334. clearTimeout(toolbarTimeoutObject);
  6335. toolbarTimeoutObject = null;
  6336. }
  6337. }
  6338. else {
  6339. if (!$('#header').is(':visible')) {
  6340. this.showToolbar();
  6341. }
  6342. else {
  6343. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6344. }
  6345. }
  6346. },
  6347. showDesktopSharingButton: showDesktopSharingButton
  6348. };
  6349. module.exports = ToolbarToggler;
  6350. },{}],30:[function(require,module,exports){
  6351. /* global $ */
  6352. var JitsiPopover = (function () {
  6353. /**
  6354. * Constructs new JitsiPopover and attaches it to the element
  6355. * @param element jquery selector
  6356. * @param options the options for the popover.
  6357. * @constructor
  6358. */
  6359. function JitsiPopover(element, options)
  6360. {
  6361. this.options = {
  6362. skin: "white",
  6363. content: ""
  6364. };
  6365. if(options)
  6366. {
  6367. if(options.skin)
  6368. this.options.skin = options.skin;
  6369. if(options.content)
  6370. this.options.content = options.content;
  6371. }
  6372. this.elementIsHovered = false;
  6373. this.popoverIsHovered = false;
  6374. this.popoverShown = false;
  6375. element.data("jitsi_popover", this);
  6376. this.element = element;
  6377. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6378. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6379. '<div class="jitsiPopupmenuPadding"></div></div>';
  6380. var self = this;
  6381. this.element.on("mouseenter", function () {
  6382. self.elementIsHovered = true;
  6383. self.show();
  6384. }).on("mouseleave", function () {
  6385. self.elementIsHovered = false;
  6386. setTimeout(function () {
  6387. self.hide();
  6388. }, 10);
  6389. });
  6390. }
  6391. /**
  6392. * Shows the popover
  6393. */
  6394. JitsiPopover.prototype.show = function () {
  6395. this.createPopover();
  6396. this.popoverShown = true;
  6397. };
  6398. /**
  6399. * Hides the popover
  6400. */
  6401. JitsiPopover.prototype.hide = function () {
  6402. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6403. this.popoverShown) {
  6404. this.forceHide();
  6405. }
  6406. };
  6407. /**
  6408. * Hides the popover.
  6409. */
  6410. JitsiPopover.prototype.forceHide = function () {
  6411. $(".jitsipopover").remove();
  6412. this.popoverShown = false;
  6413. };
  6414. /**
  6415. * Creates the popover html.
  6416. */
  6417. JitsiPopover.prototype.createPopover = function () {
  6418. $("body").append(this.template);
  6419. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6420. var self = this;
  6421. $(".jitsipopover").on("mouseenter", function () {
  6422. self.popoverIsHovered = true;
  6423. }).on("mouseleave", function () {
  6424. self.popoverIsHovered = false;
  6425. self.hide();
  6426. });
  6427. this.refreshPosition();
  6428. };
  6429. /**
  6430. * Refreshes the position of the popover.
  6431. */
  6432. JitsiPopover.prototype.refreshPosition = function () {
  6433. $(".jitsipopover").position({
  6434. my: "bottom",
  6435. at: "top",
  6436. collision: "fit",
  6437. of: this.element,
  6438. using: function (position, elements) {
  6439. var calcLeft = elements.target.left - elements.element.left +
  6440. elements.target.width/2;
  6441. $(".jitsipopover").css(
  6442. {top: position.top, left: position.left, display: "table"});
  6443. $(".jitsipopover > .arrow").css({left: calcLeft});
  6444. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6445. {left: calcLeft - 50});
  6446. }
  6447. });
  6448. };
  6449. /**
  6450. * Updates the content of popover.
  6451. * @param content new content
  6452. */
  6453. JitsiPopover.prototype.updateContent = function (content) {
  6454. this.options.content = content;
  6455. if(!this.popoverShown)
  6456. return;
  6457. $(".jitsipopover").remove();
  6458. this.createPopover();
  6459. };
  6460. return JitsiPopover;
  6461. })();
  6462. module.exports = JitsiPopover;
  6463. },{}],31:[function(require,module,exports){
  6464. /* global $, APP, jQuery, toastr */
  6465. var messageHandler = (function(my) {
  6466. /**
  6467. * Shows a message to the user.
  6468. *
  6469. * @param titleKey the title of the message
  6470. * @param messageKey the text of the message
  6471. */
  6472. my.openMessageDialog = function(titleKey, messageKey) {
  6473. var title = null;
  6474. if(titleKey) {
  6475. title = APP.translation.generateTranslationHTML(titleKey);
  6476. }
  6477. var message = APP.translation.generateTranslationHTML(messageKey);
  6478. $.prompt(message,
  6479. {title: title, persistent: false}
  6480. );
  6481. };
  6482. /**
  6483. * Shows a message to the user with two buttons: first is given as a
  6484. * parameter and the second is Cancel.
  6485. *
  6486. * @param titleString the title of the message
  6487. * @param msgString the text of the message
  6488. * @param persistent boolean value which determines whether the message is
  6489. * persistent or not
  6490. * @param leftButton the fist button's text
  6491. * @param submitFunction function to be called on submit
  6492. * @param loadedFunction function to be called after the prompt is fully
  6493. * loaded
  6494. * @param closeFunction function to be called after the prompt is closed
  6495. * @param focus optional focus selector or button index to be focused after
  6496. * the dialog is opened
  6497. * @param defaultButton index of default button which will be activated when
  6498. * the user press 'enter'. Indexed from 0.
  6499. */
  6500. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6501. persistent, leftButtonKey, submitFunction, loadedFunction,
  6502. closeFunction, focus, defaultButton) {
  6503. var buttons = [];
  6504. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6505. buttons.push({ title: leftButton, value: true});
  6506. var cancelButton
  6507. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6508. buttons.push({title: cancelButton, value: false});
  6509. var message = msgString, title = titleString;
  6510. if (titleKey) {
  6511. title = APP.translation.generateTranslationHTML(titleKey);
  6512. }
  6513. if (msgKey) {
  6514. message = APP.translation.generateTranslationHTML(msgKey);
  6515. }
  6516. $.prompt(message, {
  6517. title: title,
  6518. persistent: false,
  6519. buttons: buttons,
  6520. defaultButton: defaultButton,
  6521. focus: focus,
  6522. loaded: loadedFunction,
  6523. submit: submitFunction,
  6524. close: closeFunction
  6525. });
  6526. };
  6527. /**
  6528. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6529. *
  6530. * @param titleString the title of the message
  6531. * @param msgString the text of the message
  6532. * @param persistent boolean value which determines whether the message is
  6533. * persistent or not
  6534. * @param buttons object with the buttons. The keys must be the name of the
  6535. * button and value is the value that will be passed to
  6536. * submitFunction
  6537. * @param submitFunction function to be called on submit
  6538. * @param loadedFunction function to be called after the prompt is fully
  6539. * loaded
  6540. */
  6541. my.openDialog = function (titleString, msgString, persistent, buttons,
  6542. submitFunction, loadedFunction) {
  6543. var args = {
  6544. title: titleString,
  6545. persistent: persistent,
  6546. buttons: buttons,
  6547. defaultButton: 1,
  6548. loaded: loadedFunction,
  6549. submit: submitFunction
  6550. };
  6551. if (persistent) {
  6552. args.closeText = '';
  6553. }
  6554. return new Impromptu(msgString, args);
  6555. };
  6556. /**
  6557. * Closes currently opened dialog.
  6558. */
  6559. my.closeDialog = function () {
  6560. $.prompt.close();
  6561. };
  6562. /**
  6563. * Shows a dialog with different states to the user.
  6564. *
  6565. * @param statesObject object containing all the states of the dialog.
  6566. */
  6567. my.openDialogWithStates = function (statesObject, options) {
  6568. return new Impromptu(statesObject, options);
  6569. };
  6570. /**
  6571. * Opens new popup window for given <tt>url</tt> centered over current
  6572. * window.
  6573. *
  6574. * @param url the URL to be displayed in the popup window
  6575. * @param w the width of the popup window
  6576. * @param h the height of the popup window
  6577. * @param onPopupClosed optional callback function called when popup window
  6578. * has been closed.
  6579. *
  6580. * @returns {object} popup window object if opened successfully or undefined
  6581. * in case we failed to open it(popup blocked)
  6582. */
  6583. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6584. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6585. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6586. var popup = window.open(
  6587. url, '_blank',
  6588. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6589. if (popup && onPopupClosed) {
  6590. var pollTimer = window.setInterval(function () {
  6591. if (popup.closed !== false) {
  6592. window.clearInterval(pollTimer);
  6593. onPopupClosed();
  6594. }
  6595. }, 200);
  6596. }
  6597. return popup;
  6598. };
  6599. /**
  6600. * Shows a dialog prompting the user to send an error report.
  6601. *
  6602. * @param titleKey the title of the message
  6603. * @param msgKey the text of the message
  6604. * @param error the error that is being reported
  6605. */
  6606. my.openReportDialog = function(titleKey, msgKey, error) {
  6607. my.openMessageDialog(titleKey, msgKey);
  6608. console.log(error);
  6609. //FIXME send the error to the server
  6610. };
  6611. /**
  6612. * Shows an error dialog to the user.
  6613. * @param titleKey the title of the message.
  6614. * @param msgKey the text of the message.
  6615. */
  6616. my.showError = function(titleKey, msgKey) {
  6617. if (!titleKey) {
  6618. titleKey = "dialog.oops";
  6619. }
  6620. if (!msgKey) {
  6621. msgKey = "dialog.defaultError";
  6622. }
  6623. messageHandler.openMessageDialog(titleKey, msgKey);
  6624. };
  6625. my.notify = function(displayName, displayNameKey,
  6626. cls, messageKey, messageArguments, options) {
  6627. var displayNameSpan = '<span class="nickname" ';
  6628. if (displayName) {
  6629. displayNameSpan += ">" + displayName;
  6630. } else {
  6631. displayNameSpan += "data-i18n='" + displayNameKey +
  6632. "'>" + APP.translation.translateString(displayNameKey);
  6633. }
  6634. displayNameSpan += "</span>";
  6635. toastr.info(
  6636. displayNameSpan + '<br>' +
  6637. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6638. (messageArguments?
  6639. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6640. : "") + ">" +
  6641. APP.translation.translateString(messageKey,
  6642. messageArguments) +
  6643. '</span>', null, options);
  6644. };
  6645. return my;
  6646. }(messageHandler || {}));
  6647. module.exports = messageHandler;
  6648. },{}],32:[function(require,module,exports){
  6649. var UIEvents = require("../../../service/UI/UIEvents");
  6650. var nickname = null;
  6651. var eventEmitter = null;
  6652. var NicknameHandler = {
  6653. init: function (emitter) {
  6654. eventEmitter = emitter;
  6655. var storedDisplayName = window.localStorage.displayname;
  6656. if (storedDisplayName) {
  6657. nickname = storedDisplayName;
  6658. }
  6659. },
  6660. setNickname: function (newNickname) {
  6661. if (!newNickname || nickname === newNickname)
  6662. return;
  6663. nickname = newNickname;
  6664. window.localStorage.displayname = nickname;
  6665. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6666. },
  6667. getNickname: function () {
  6668. return nickname;
  6669. },
  6670. addListener: function (type, listener) {
  6671. eventEmitter.on(type, listener);
  6672. }
  6673. };
  6674. module.exports = NicknameHandler;
  6675. },{"../../../service/UI/UIEvents":110}],33:[function(require,module,exports){
  6676. /* global $ */
  6677. /**
  6678. * Created by hristo on 12/22/14.
  6679. */
  6680. module.exports = {
  6681. /**
  6682. * Returns the available video width.
  6683. */
  6684. getAvailableVideoWidth: function (isVisible) {
  6685. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6686. if(typeof isVisible === "undefined" || isVisible === null)
  6687. isVisible = PanelToggler.isVisible();
  6688. var rightPanelWidth
  6689. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6690. return window.innerWidth - rightPanelWidth;
  6691. },
  6692. /**
  6693. * Changes the style class of the element given by id.
  6694. */
  6695. buttonClick: function(id, classname) {
  6696. $(id).toggleClass(classname); // add the class to the clicked element
  6697. },
  6698. /**
  6699. * Returns the text width for the given element.
  6700. *
  6701. * @param el the element
  6702. */
  6703. getTextWidth: function (el) {
  6704. return (el.clientWidth + 1);
  6705. },
  6706. /**
  6707. * Returns the text height for the given element.
  6708. *
  6709. * @param el the element
  6710. */
  6711. getTextHeight: function (el) {
  6712. return (el.clientHeight + 1);
  6713. },
  6714. /**
  6715. * Plays the sound given by id.
  6716. *
  6717. * @param id the identifier of the audio element.
  6718. */
  6719. playSoundNotification: function (id) {
  6720. document.getElementById(id).play();
  6721. },
  6722. /**
  6723. * Escapes the given text.
  6724. */
  6725. escapeHtml: function (unsafeText) {
  6726. return $('<div/>').text(unsafeText).html();
  6727. },
  6728. imageToGrayScale: function (canvas) {
  6729. var context = canvas.getContext('2d');
  6730. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6731. var pixels = imgData.data;
  6732. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6733. var grayscale
  6734. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  6735. pixels[i ] = grayscale; // red
  6736. pixels[i+1] = grayscale; // green
  6737. pixels[i+2] = grayscale; // blue
  6738. // pixels[i+3] is alpha
  6739. }
  6740. // redraw the image in black & white
  6741. context.putImageData(imgData, 0, 0);
  6742. },
  6743. setTooltip: function (element, key, position) {
  6744. element.setAttribute("data-i18n", "[data-content]" + key);
  6745. element.setAttribute("data-toggle", "popover");
  6746. element.setAttribute("data-placement", position);
  6747. element.setAttribute("data-html", true);
  6748. element.setAttribute("data-container", "body");
  6749. }
  6750. };
  6751. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6752. /* global APP, $ */
  6753. var JitsiPopover = require("../util/JitsiPopover");
  6754. /**
  6755. * Constructs new connection indicator.
  6756. * @param videoContainer the video container associated with the indicator.
  6757. * @constructor
  6758. */
  6759. function ConnectionIndicator(videoContainer, jid) {
  6760. this.videoContainer = videoContainer;
  6761. this.bandwidth = null;
  6762. this.packetLoss = null;
  6763. this.bitrate = null;
  6764. this.showMoreValue = false;
  6765. this.resolution = null;
  6766. this.transport = [];
  6767. this.popover = null;
  6768. this.jid = jid;
  6769. this.create();
  6770. }
  6771. /**
  6772. * Values for the connection quality
  6773. * @type {{98: string,
  6774. * 81: string,
  6775. * 64: string,
  6776. * 47: string,
  6777. * 30: string,
  6778. * 0: string}}
  6779. */
  6780. ConnectionIndicator.connectionQualityValues = {
  6781. 98: "18px", //full
  6782. 81: "15px",//4 bars
  6783. 64: "11px",//3 bars
  6784. 47: "7px",//2 bars
  6785. 30: "3px",//1 bar
  6786. 0: "0px"//empty
  6787. };
  6788. ConnectionIndicator.getIP = function(value) {
  6789. return value.substring(0, value.lastIndexOf(":"));
  6790. };
  6791. ConnectionIndicator.getPort = function(value) {
  6792. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6793. };
  6794. ConnectionIndicator.getStringFromArray = function (array) {
  6795. var res = "";
  6796. for(var i = 0; i < array.length; i++) {
  6797. res += (i === 0? "" : ", ") + array[i];
  6798. }
  6799. return res;
  6800. };
  6801. /**
  6802. * Generates the html content.
  6803. * @returns {string} the html content.
  6804. */
  6805. ConnectionIndicator.prototype.generateText = function () {
  6806. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6807. var translate = APP.translation.translateString;
  6808. if(this.bitrate === null) {
  6809. downloadBitrate = "N/A";
  6810. uploadBitrate = "N/A";
  6811. }
  6812. else {
  6813. downloadBitrate =
  6814. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6815. uploadBitrate =
  6816. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6817. }
  6818. if(this.packetLoss === null) {
  6819. packetLoss = "N/A";
  6820. } else {
  6821. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6822. (this.packetLoss.download !== null ?
  6823. this.packetLoss.download : "N/A") +
  6824. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6825. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  6826. "%";
  6827. }
  6828. var resolutionValue = null;
  6829. if(this.resolution && this.jid != null) {
  6830. var keys = Object.keys(this.resolution);
  6831. for(var ssrc in this.resolution) {
  6832. resolutionValue = this.resolution[ssrc];
  6833. }
  6834. }
  6835. if(this.jid === null) {
  6836. resolution = "";
  6837. if(this.resolution === null || !Object.keys(this.resolution) ||
  6838. Object.keys(this.resolution).length === 0) {
  6839. resolution = "N/A";
  6840. } else {
  6841. for (i in this.resolution) {
  6842. resolutionValue = this.resolution[i];
  6843. if (resolutionValue) {
  6844. if (resolutionValue.height &&
  6845. resolutionValue.width) {
  6846. resolution += (resolution === "" ? "" : ", ") +
  6847. resolutionValue.width + "x" +
  6848. resolutionValue.height;
  6849. }
  6850. }
  6851. }
  6852. }
  6853. } else if(!resolutionValue ||
  6854. !resolutionValue.height ||
  6855. !resolutionValue.width) {
  6856. resolution = "N/A";
  6857. } else {
  6858. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6859. }
  6860. var result = "<table style='width:100%'>" +
  6861. "<tr>" +
  6862. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6863. translate("connectionindicator.bitrate") + "</span></td>" +
  6864. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6865. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6866. uploadBitrate + "</td>" +
  6867. "</tr><tr>" +
  6868. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6869. translate("connectionindicator.packetloss") + "</span></td>" +
  6870. "<td>" + packetLoss + "</td>" +
  6871. "</tr><tr>" +
  6872. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6873. translate("connectionindicator.resolution") + "</span></td>" +
  6874. "<td>" + resolution + "</td></tr></table>";
  6875. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6876. result += "<div class=\"jitsipopover_showmore\" " +
  6877. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6878. // FIXME: we do not know local jid when this text is generated
  6879. //this.jid + "')\" data-i18n='connectionindicator." +
  6880. "local')\" data-i18n='connectionindicator." +
  6881. (this.showMoreValue ? "less" : "more") + "'>" +
  6882. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6883. "</div><br />";
  6884. }
  6885. if (this.showMoreValue) {
  6886. var downloadBandwidth, uploadBandwidth, transport;
  6887. if (this.bandwidth === null) {
  6888. downloadBandwidth = "N/A";
  6889. uploadBandwidth = "N/A";
  6890. } else {
  6891. downloadBandwidth = this.bandwidth.download?
  6892. this.bandwidth.download + " Kbps" :
  6893. "N/A";
  6894. uploadBandwidth = this.bandwidth.upload?
  6895. this.bandwidth.upload + " Kbps" :
  6896. "N/A";
  6897. }
  6898. if (!this.transport || this.transport.length === 0) {
  6899. transport = "<tr>" +
  6900. "<td><span class='jitsipopover_blue' " +
  6901. "data-i18n='connectionindicator.address'>" +
  6902. translate("connectionindicator.address") + "</span></td>" +
  6903. "<td> N/A</td></tr>";
  6904. } else {
  6905. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  6906. for(i = 0; i < this.transport.length; i++) {
  6907. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  6908. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  6909. var localIP =
  6910. ConnectionIndicator.getIP(this.transport[i].localip);
  6911. var localPort =
  6912. ConnectionIndicator.getPort(this.transport[i].localip);
  6913. if(data.remoteIP.indexOf(ip) == -1) {
  6914. data.remoteIP.push(ip);
  6915. }
  6916. if(data.remotePort.indexOf(port) == -1) {
  6917. data.remotePort.push(port);
  6918. }
  6919. if(data.localIP.indexOf(localIP) == -1) {
  6920. data.localIP.push(localIP);
  6921. }
  6922. if(data.localPort.indexOf(localPort) == -1) {
  6923. data.localPort.push(localPort);
  6924. }
  6925. }
  6926. var local_address_key = "connectionindicator.localaddress";
  6927. var remote_address_key = "connectionindicator.remoteaddress";
  6928. var localTransport =
  6929. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6930. local_address_key +"' data-i18n-options='" +
  6931. JSON.stringify({count: data.localIP.length}) + "'>" +
  6932. translate(local_address_key, {count: data.localIP.length}) +
  6933. "</span></td><td> " +
  6934. ConnectionIndicator.getStringFromArray(data.localIP) +
  6935. "</td></tr>";
  6936. transport =
  6937. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6938. remote_address_key + "' data-i18n-options='" +
  6939. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  6940. translate(remote_address_key,
  6941. {count: data.remoteIP.length}) +
  6942. "</span></td><td> " +
  6943. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  6944. "</td></tr>";
  6945. var key_remote = "connectionindicator.remoteport",
  6946. key_local = "connectionindicator.localport";
  6947. transport += "<tr>" +
  6948. "<td>" +
  6949. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  6950. "' data-i18n-options='" +
  6951. JSON.stringify({count: this.transport.length}) + "'>" +
  6952. translate(key_remote, {count: this.transport.length}) +
  6953. "</span></td><td>";
  6954. localTransport += "<tr>" +
  6955. "<td>" +
  6956. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  6957. "' data-i18n-options='" +
  6958. JSON.stringify({count: this.transport.length}) + "'>" +
  6959. translate(key_local, {count: this.transport.length}) +
  6960. "</span></td><td>";
  6961. transport +=
  6962. ConnectionIndicator.getStringFromArray(data.remotePort);
  6963. localTransport +=
  6964. ConnectionIndicator.getStringFromArray(data.localPort);
  6965. transport += "</td></tr>";
  6966. transport += localTransport + "</td></tr>";
  6967. transport +="<tr>" +
  6968. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  6969. translate("connectionindicator.transport") + "</span></td>" +
  6970. "<td>" + this.transport[0].type + "</td></tr>";
  6971. }
  6972. result += "<table style='width:100%'>" +
  6973. "<tr>" +
  6974. "<td>" +
  6975. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  6976. translate("connectionindicator.bandwidth") + "</span>" +
  6977. "</td><td>" +
  6978. "<span class='jitsipopover_green'>&darr;</span>" +
  6979. downloadBandwidth +
  6980. " <span class='jitsipopover_orange'>&uarr;</span>" +
  6981. uploadBandwidth + "</td></tr>";
  6982. result += transport + "</table>";
  6983. }
  6984. return result;
  6985. };
  6986. /**
  6987. * Shows or hide the additional information.
  6988. */
  6989. ConnectionIndicator.prototype.showMore = function () {
  6990. this.showMoreValue = !this.showMoreValue;
  6991. this.updatePopoverData();
  6992. };
  6993. function createIcon(classes) {
  6994. var icon = document.createElement("span");
  6995. for(var i in classes) {
  6996. icon.classList.add(classes[i]);
  6997. }
  6998. icon.appendChild(
  6999. document.createElement("i")).classList.add("icon-connection");
  7000. return icon;
  7001. }
  7002. /**
  7003. * Creates the indicator
  7004. */
  7005. ConnectionIndicator.prototype.create = function () {
  7006. this.connectionIndicatorContainer = document.createElement("div");
  7007. this.connectionIndicatorContainer.className = "connectionindicator";
  7008. this.connectionIndicatorContainer.style.display = "none";
  7009. this.videoContainer.container.appendChild(
  7010. this.connectionIndicatorContainer);
  7011. this.popover = new JitsiPopover(
  7012. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7013. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7014. APP.translation.translateString("connectionindicator.na") + "</div>",
  7015. skin: "black"});
  7016. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7017. createIcon(["connection", "connection_empty"]));
  7018. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7019. createIcon(["connection", "connection_full"]));
  7020. };
  7021. /**
  7022. * Removes the indicator
  7023. */
  7024. ConnectionIndicator.prototype.remove = function() {
  7025. if (this.connectionIndicatorContainer.parentNode) {
  7026. this.connectionIndicatorContainer.parentNode.removeChild(
  7027. this.connectionIndicatorContainer);
  7028. }
  7029. this.popover.forceHide();
  7030. };
  7031. /**
  7032. * Updates the data of the indicator
  7033. * @param percent the percent of connection quality
  7034. * @param object the statistics data.
  7035. */
  7036. ConnectionIndicator.prototype.updateConnectionQuality =
  7037. function (percent, object) {
  7038. if (percent === null) {
  7039. this.connectionIndicatorContainer.style.display = "none";
  7040. this.popover.forceHide();
  7041. return;
  7042. } else {
  7043. if(this.connectionIndicatorContainer.style.display == "none") {
  7044. this.connectionIndicatorContainer.style.display = "block";
  7045. this.videoContainer.updateIconPositions();
  7046. }
  7047. }
  7048. this.bandwidth = object.bandwidth;
  7049. this.bitrate = object.bitrate;
  7050. this.packetLoss = object.packetLoss;
  7051. this.transport = object.transport;
  7052. if (object.resolution) {
  7053. this.resolution = object.resolution;
  7054. }
  7055. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7056. if (percent >= quality) {
  7057. this.fullIcon.style.width =
  7058. ConnectionIndicator.connectionQualityValues[quality];
  7059. }
  7060. }
  7061. this.updatePopoverData();
  7062. };
  7063. /**
  7064. * Updates the resolution
  7065. * @param resolution the new resolution
  7066. */
  7067. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7068. this.resolution = resolution;
  7069. this.updatePopoverData();
  7070. };
  7071. /**
  7072. * Updates the content of the popover
  7073. */
  7074. ConnectionIndicator.prototype.updatePopoverData = function () {
  7075. this.popover.updateContent(
  7076. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7077. APP.translation.translateElement($(".connection_info"));
  7078. };
  7079. /**
  7080. * Hides the popover
  7081. */
  7082. ConnectionIndicator.prototype.hide = function () {
  7083. this.popover.forceHide();
  7084. };
  7085. /**
  7086. * Hides the indicator
  7087. */
  7088. ConnectionIndicator.prototype.hideIndicator = function () {
  7089. this.connectionIndicatorContainer.style.display = "none";
  7090. if(this.popover)
  7091. this.popover.forceHide();
  7092. };
  7093. module.exports = ConnectionIndicator;
  7094. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7095. /* global $, APP, Strophe, interfaceConfig */
  7096. var Avatar = require("../avatar/Avatar");
  7097. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7098. var UIUtil = require("../util/UIUtil");
  7099. var UIEvents = require("../../../service/UI/UIEvents");
  7100. var xmpp = require("../../xmpp/xmpp");
  7101. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7102. // FIXME: With Temasys we have to re-select everytime
  7103. //var video = $('#largeVideo');
  7104. var currentVideoWidth = null;
  7105. var currentVideoHeight = null;
  7106. // By default we use camera
  7107. var getVideoSize = getCameraVideoSize;
  7108. var getVideoPosition = getCameraVideoPosition;
  7109. /**
  7110. * The small video instance that is displayed in the large video
  7111. * @type {SmallVideo}
  7112. */
  7113. var currentSmallVideo = null;
  7114. /**
  7115. * Indicates whether the large video is enabled.
  7116. * @type {boolean}
  7117. */
  7118. var isEnabled = true;
  7119. /**
  7120. * Current large video state.
  7121. * Possible values - video, prezi or etherpad.
  7122. * @type {string}
  7123. */
  7124. var state = "video";
  7125. /**
  7126. * Returns the html element associated with the passed state of large video
  7127. * @param state the state.
  7128. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7129. */
  7130. function getContainerByState(state)
  7131. {
  7132. var selector = null;
  7133. switch (state)
  7134. {
  7135. case "video":
  7136. selector = "#largeVideo";
  7137. break;
  7138. case "etherpad":
  7139. selector = "#etherpad>iframe";
  7140. break;
  7141. case "prezi":
  7142. selector = "#presentation>iframe";
  7143. break;
  7144. }
  7145. return (selector !== null)? $(selector) : null;
  7146. }
  7147. /**
  7148. * Sets the size and position of the given video element.
  7149. *
  7150. * @param video the video element to position
  7151. * @param width the desired video width
  7152. * @param height the desired video height
  7153. * @param horizontalIndent the left and right indent
  7154. * @param verticalIndent the top and bottom indent
  7155. */
  7156. function positionVideo(video,
  7157. width,
  7158. height,
  7159. horizontalIndent,
  7160. verticalIndent,
  7161. animate) {
  7162. if (animate) {
  7163. video.animate({
  7164. width: width,
  7165. height: height,
  7166. top: verticalIndent,
  7167. bottom: verticalIndent,
  7168. left: horizontalIndent,
  7169. right: horizontalIndent
  7170. },
  7171. {
  7172. queue: false,
  7173. duration: 500
  7174. });
  7175. } else {
  7176. video.width(width);
  7177. video.height(height);
  7178. video.css({ top: verticalIndent + 'px',
  7179. bottom: verticalIndent + 'px',
  7180. left: horizontalIndent + 'px',
  7181. right: horizontalIndent + 'px'});
  7182. }
  7183. }
  7184. /**
  7185. * Returns an array of the video dimensions, so that it keeps it's aspect
  7186. * ratio and fits available area with it's larger dimension. This method
  7187. * ensures that whole video will be visible and can leave empty areas.
  7188. *
  7189. * @return an array with 2 elements, the video width and the video height
  7190. */
  7191. function getDesktopVideoSize(videoWidth,
  7192. videoHeight,
  7193. videoSpaceWidth,
  7194. videoSpaceHeight) {
  7195. if (!videoWidth)
  7196. videoWidth = currentVideoWidth;
  7197. if (!videoHeight)
  7198. videoHeight = currentVideoHeight;
  7199. var aspectRatio = videoWidth / videoHeight;
  7200. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7201. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7202. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7203. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7204. {
  7205. availableHeight = videoSpaceHeight;
  7206. availableWidth = availableHeight * aspectRatio;
  7207. }
  7208. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7209. {
  7210. availableWidth = videoSpaceWidth;
  7211. availableHeight = availableWidth / aspectRatio;
  7212. }
  7213. return [availableWidth, availableHeight];
  7214. }
  7215. /**
  7216. * Returns an array of the video horizontal and vertical indents,
  7217. * so that if fits its parent.
  7218. *
  7219. * @return an array with 2 elements, the horizontal indent and the vertical
  7220. * indent
  7221. */
  7222. function getCameraVideoPosition(videoWidth,
  7223. videoHeight,
  7224. videoSpaceWidth,
  7225. videoSpaceHeight) {
  7226. // Parent height isn't completely calculated when we position the video in
  7227. // full screen mode and this is why we use the screen height in this case.
  7228. // Need to think it further at some point and implement it properly.
  7229. var isFullScreen = document.fullScreen ||
  7230. document.mozFullScreen ||
  7231. document.webkitIsFullScreen;
  7232. if (isFullScreen)
  7233. videoSpaceHeight = window.innerHeight;
  7234. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7235. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7236. return [horizontalIndent, verticalIndent];
  7237. }
  7238. /**
  7239. * Returns an array of the video horizontal and vertical indents.
  7240. * Centers horizontally and top aligns vertically.
  7241. *
  7242. * @return an array with 2 elements, the horizontal indent and the vertical
  7243. * indent
  7244. */
  7245. function getDesktopVideoPosition(videoWidth,
  7246. videoHeight,
  7247. videoSpaceWidth,
  7248. videoSpaceHeight) {
  7249. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7250. var verticalIndent = 0;// Top aligned
  7251. return [horizontalIndent, verticalIndent];
  7252. }
  7253. /**
  7254. * Returns an array of the video dimensions, so that it covers the screen.
  7255. * It leaves no empty areas, but some parts of the video might not be visible.
  7256. *
  7257. * @return an array with 2 elements, the video width and the video height
  7258. */
  7259. function getCameraVideoSize(videoWidth,
  7260. videoHeight,
  7261. videoSpaceWidth,
  7262. videoSpaceHeight) {
  7263. if (!videoWidth)
  7264. videoWidth = currentVideoWidth;
  7265. if (!videoHeight)
  7266. videoHeight = currentVideoHeight;
  7267. var aspectRatio = videoWidth / videoHeight;
  7268. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7269. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7270. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7271. availableHeight = videoSpaceHeight;
  7272. availableWidth = availableHeight * aspectRatio;
  7273. }
  7274. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7275. availableWidth = videoSpaceWidth;
  7276. availableHeight = availableWidth / aspectRatio;
  7277. }
  7278. return [availableWidth, availableHeight];
  7279. }
  7280. /**
  7281. * Updates the src of the active speaker avatar
  7282. * @param jid of the current active speaker
  7283. */
  7284. function updateActiveSpeakerAvatarSrc() {
  7285. var avatar = $("#activeSpeakerAvatar")[0];
  7286. var jid = currentSmallVideo.peerJid;
  7287. var url = Avatar.getActiveSpeakerUrl(jid);
  7288. if (avatar.src === url)
  7289. return;
  7290. if (jid) {
  7291. avatar.src = url;
  7292. currentSmallVideo.showAvatar();
  7293. }
  7294. }
  7295. /**
  7296. * Change the video source of the large video.
  7297. * @param isVisible
  7298. */
  7299. function changeVideo(isVisible) {
  7300. if (!currentSmallVideo) {
  7301. console.error("Unable to change large video - no 'currentSmallVideo'");
  7302. return;
  7303. }
  7304. updateActiveSpeakerAvatarSrc();
  7305. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7306. var videoTransform = document.getElementById('largeVideo')
  7307. .style.webkitTransform;
  7308. var flipX = currentSmallVideo.flipX;
  7309. if (flipX && videoTransform !== 'scaleX(-1)') {
  7310. document.getElementById('largeVideo').style.webkitTransform =
  7311. "scaleX(-1)";
  7312. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7313. document.getElementById('largeVideo').style.webkitTransform =
  7314. "none";
  7315. }
  7316. var isDesktop = APP.RTC.isVideoSrcDesktop(currentSmallVideo.peerJid);
  7317. // Change the way we'll be measuring and positioning large video
  7318. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7319. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7320. getCameraVideoPosition;
  7321. // Only if the large video is currently visible.
  7322. if (isVisible) {
  7323. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7324. $('#largeVideo').fadeIn(300);
  7325. }
  7326. }
  7327. /**
  7328. * Creates the html elements for the large video.
  7329. */
  7330. function createLargeVideoHTML()
  7331. {
  7332. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7333. html += '<div id="presentation"></div>' +
  7334. '<div id="etherpad"></div>' +
  7335. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7336. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7337. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7338. '<span data-i18n="poweredby"></span> jitsi.org' +
  7339. '</a>'+
  7340. '<div id="activeSpeaker">' +
  7341. '<img id="activeSpeakerAvatar" src=""/>' +
  7342. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7343. '</div>' +
  7344. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7345. '<span id="videoConnectionMessage"></span>';
  7346. html += '</div>';
  7347. $(html).prependTo("#videospace");
  7348. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7349. var leftWatermarkDiv
  7350. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7351. leftWatermarkDiv.css({display: 'block'});
  7352. leftWatermarkDiv.parent().get(0).href
  7353. = interfaceConfig.JITSI_WATERMARK_LINK;
  7354. }
  7355. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7356. var rightWatermarkDiv
  7357. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7358. rightWatermarkDiv.css({display: 'block'});
  7359. rightWatermarkDiv.parent().get(0).href
  7360. = interfaceConfig.BRAND_WATERMARK_LINK;
  7361. rightWatermarkDiv.get(0).style.backgroundImage
  7362. = "url(images/rightwatermark.png)";
  7363. }
  7364. if (interfaceConfig.SHOW_POWERED_BY) {
  7365. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7366. }
  7367. if (!RTCBrowserType.isIExplorer()) {
  7368. $('#largeVideo').volume = 0;
  7369. }
  7370. }
  7371. var LargeVideo = {
  7372. init: function (VideoLayout, emitter) {
  7373. if(!isEnabled)
  7374. return;
  7375. createLargeVideoHTML();
  7376. this.VideoLayout = VideoLayout;
  7377. this.eventEmitter = emitter;
  7378. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7379. var self = this;
  7380. // Listen for large video size updates
  7381. var largeVideo = $('#largeVideo')[0];
  7382. var onplaying = function (arg1, arg2, arg3) {
  7383. // re-select
  7384. if (RTCBrowserType.isTemasysPluginUsed())
  7385. largeVideo = $('#largeVideo')[0];
  7386. currentVideoWidth = largeVideo.videoWidth;
  7387. currentVideoHeight = largeVideo.videoHeight;
  7388. self.position(currentVideoWidth, currentVideoHeight);
  7389. };
  7390. largeVideo.onplaying = onplaying;
  7391. },
  7392. /**
  7393. * Indicates if the large video is currently visible.
  7394. *
  7395. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7396. */
  7397. isLargeVideoVisible: function() {
  7398. return $('#largeVideo').is(':visible');
  7399. },
  7400. /**
  7401. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7402. */
  7403. isCurrentlyOnLarge: function (resourceJid) {
  7404. return currentSmallVideo && resourceJid &&
  7405. currentSmallVideo.getResourceJid() === resourceJid;
  7406. },
  7407. /**
  7408. * Updates the large video with the given new video source.
  7409. */
  7410. updateLargeVideo: function (resourceJid, forceUpdate) {
  7411. if(!isEnabled)
  7412. return;
  7413. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7414. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7415. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7416. $('#activeSpeaker').css('visibility', 'hidden');
  7417. var oldSmallVideo = null;
  7418. if (currentSmallVideo) {
  7419. oldSmallVideo = currentSmallVideo;
  7420. }
  7421. currentSmallVideo = newSmallVideo;
  7422. var oldJid = null;
  7423. if (oldSmallVideo)
  7424. oldJid = oldSmallVideo.peerJid;
  7425. if (oldJid !== resourceJid) {
  7426. // we want the notification to trigger even if userJid is undefined,
  7427. // or null.
  7428. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7429. }
  7430. if (RTCBrowserType.isSafari()) {
  7431. // FIXME In Safari fadeOut works only for the first time
  7432. changeVideo(this.isLargeVideoVisible());
  7433. } else {
  7434. $('#largeVideo').fadeOut(300,
  7435. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7436. }
  7437. } else {
  7438. if (currentSmallVideo) {
  7439. currentSmallVideo.showAvatar();
  7440. }
  7441. }
  7442. },
  7443. /**
  7444. * Shows/hides the large video.
  7445. */
  7446. setLargeVideoVisible: function(isVisible) {
  7447. if(!isEnabled)
  7448. return;
  7449. if (isVisible) {
  7450. $('#largeVideo').css({visibility: 'visible'});
  7451. $('.watermark').css({visibility: 'visible'});
  7452. if(currentSmallVideo)
  7453. currentSmallVideo.enableDominantSpeaker(true);
  7454. }
  7455. else {
  7456. $('#largeVideo').css({visibility: 'hidden'});
  7457. $('#activeSpeaker').css('visibility', 'hidden');
  7458. $('.watermark').css({visibility: 'hidden'});
  7459. if(currentSmallVideo)
  7460. currentSmallVideo.enableDominantSpeaker(false);
  7461. }
  7462. },
  7463. onVideoTypeChanged: function (jid) {
  7464. if(!isEnabled)
  7465. return;
  7466. var resourceJid = Strophe.getResourceFromJid(jid);
  7467. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7468. {
  7469. var isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7470. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7471. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7472. : getCameraVideoPosition;
  7473. this.position(null, null);
  7474. }
  7475. },
  7476. /**
  7477. * Positions the large video.
  7478. *
  7479. * @param videoWidth the stream video width
  7480. * @param videoHeight the stream video height
  7481. */
  7482. position: function (videoWidth, videoHeight,
  7483. videoSpaceWidth, videoSpaceHeight, animate) {
  7484. if(!isEnabled)
  7485. return;
  7486. if(!videoSpaceWidth)
  7487. videoSpaceWidth = $('#videospace').width();
  7488. if(!videoSpaceHeight)
  7489. videoSpaceHeight = window.innerHeight;
  7490. var videoSize = getVideoSize(videoWidth,
  7491. videoHeight,
  7492. videoSpaceWidth,
  7493. videoSpaceHeight);
  7494. var largeVideoWidth = videoSize[0];
  7495. var largeVideoHeight = videoSize[1];
  7496. var videoPosition = getVideoPosition(largeVideoWidth,
  7497. largeVideoHeight,
  7498. videoSpaceWidth,
  7499. videoSpaceHeight);
  7500. var horizontalIndent = videoPosition[0];
  7501. var verticalIndent = videoPosition[1];
  7502. positionVideo($('#largeVideo'),
  7503. largeVideoWidth,
  7504. largeVideoHeight,
  7505. horizontalIndent, verticalIndent, animate);
  7506. },
  7507. resize: function (animate, isVisible, completeFunction) {
  7508. if(!isEnabled)
  7509. return;
  7510. var availableHeight = window.innerHeight;
  7511. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7512. if (availableWidth < 0 || availableHeight < 0) return;
  7513. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7514. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7515. $('#activeSpeaker').css('top', top);
  7516. if(animate) {
  7517. $('#videospace').animate({
  7518. right: window.innerWidth - availableWidth,
  7519. width: availableWidth,
  7520. height: availableHeight
  7521. },
  7522. {
  7523. queue: false,
  7524. duration: 500,
  7525. complete: completeFunction
  7526. });
  7527. $('#largeVideoContainer').animate({
  7528. width: availableWidth,
  7529. height: availableHeight
  7530. },
  7531. {
  7532. queue: false,
  7533. duration: 500
  7534. });
  7535. } else {
  7536. $('#videospace').width(availableWidth);
  7537. $('#videospace').height(availableHeight);
  7538. $('#largeVideoContainer').width(availableWidth);
  7539. $('#largeVideoContainer').height(availableHeight);
  7540. }
  7541. return [availableWidth, availableHeight];
  7542. },
  7543. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7544. if(!isEnabled)
  7545. return;
  7546. var size = this.resize(true, isVisible, completeFunction);
  7547. this.position(null, null, size[0], size[1], true);
  7548. },
  7549. getResourceJid: function () {
  7550. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7551. },
  7552. updateAvatar: function (resourceJid) {
  7553. if(!isEnabled)
  7554. return;
  7555. if (resourceJid === this.getResourceJid()) {
  7556. updateActiveSpeakerAvatarSrc();
  7557. }
  7558. },
  7559. showAvatar: function (resourceJid, show) {
  7560. if(!isEnabled)
  7561. return;
  7562. if(this.getResourceJid() === resourceJid && state === "video") {
  7563. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7564. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7565. return true;
  7566. }
  7567. return false;
  7568. },
  7569. /**
  7570. * Disables the large video
  7571. */
  7572. disable: function () {
  7573. isEnabled = false;
  7574. },
  7575. /**
  7576. * Enables the large video
  7577. */
  7578. enable: function () {
  7579. isEnabled = true;
  7580. },
  7581. /**
  7582. * Returns true if the video is enabled.
  7583. */
  7584. isEnabled: function () {
  7585. return isEnabled;
  7586. },
  7587. /**
  7588. * Creates the iframe used by the etherpad
  7589. * @param src the value for src attribute
  7590. * @param onloadHandler handler executed when the iframe loads it content
  7591. * @returns {HTMLElement} the iframe
  7592. */
  7593. createEtherpadIframe: function (src, onloadHandler) {
  7594. if(!isEnabled)
  7595. return;
  7596. var etherpadIFrame = document.createElement('iframe');
  7597. etherpadIFrame.src = src;
  7598. etherpadIFrame.frameBorder = 0;
  7599. etherpadIFrame.scrolling = "no";
  7600. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7601. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7602. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7603. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7604. etherpadIFrame.onload = onloadHandler;
  7605. return etherpadIFrame;
  7606. },
  7607. /**
  7608. * Changes the state of the large video.
  7609. * Possible values - video, prezi, etherpad.
  7610. * @param newState - the new state
  7611. */
  7612. setState: function (newState) {
  7613. if(state === newState)
  7614. return;
  7615. var currentContainer = getContainerByState(state);
  7616. if(!currentContainer)
  7617. return;
  7618. var self = this;
  7619. var oldState = state;
  7620. switch (newState)
  7621. {
  7622. case "etherpad":
  7623. $('#activeSpeaker').css('visibility', 'hidden');
  7624. currentContainer.fadeOut(300, function () {
  7625. if (oldState === "prezi") {
  7626. currentContainer.css({opacity: '0'});
  7627. $('#reloadPresentation').css({display: 'none'});
  7628. }
  7629. else {
  7630. self.setLargeVideoVisible(false);
  7631. }
  7632. });
  7633. $('#etherpad>iframe').fadeIn(300, function () {
  7634. document.body.style.background = '#eeeeee';
  7635. $('#etherpad>iframe').css({visibility: 'visible'});
  7636. $('#etherpad').css({zIndex: 2});
  7637. });
  7638. break;
  7639. case "prezi":
  7640. var prezi = $('#presentation>iframe');
  7641. currentContainer.fadeOut(300, function() {
  7642. document.body.style.background = 'black';
  7643. });
  7644. prezi.fadeIn(300, function() {
  7645. prezi.css({opacity:'1'});
  7646. ToolbarToggler.dockToolbar(true);//fix that
  7647. self.setLargeVideoVisible(false);
  7648. $('#etherpad>iframe').css({visibility: 'hidden'});
  7649. $('#etherpad').css({zIndex: 0});
  7650. });
  7651. $('#activeSpeaker').css('visibility', 'hidden');
  7652. break;
  7653. case "video":
  7654. currentContainer.fadeOut(300, function () {
  7655. $('#presentation>iframe').css({opacity:'0'});
  7656. $('#reloadPresentation').css({display:'none'});
  7657. $('#etherpad>iframe').css({visibility: 'hidden'});
  7658. $('#etherpad').css({zIndex: 0});
  7659. document.body.style.background = 'black';
  7660. ToolbarToggler.dockToolbar(false);//fix that
  7661. });
  7662. $('#largeVideo').fadeIn(300, function () {
  7663. self.setLargeVideoVisible(true);
  7664. });
  7665. break;
  7666. }
  7667. state = newState;
  7668. },
  7669. /**
  7670. * Returns the current state of the large video.
  7671. * @returns {string} the current state - video, prezi or etherpad.
  7672. */
  7673. getState: function () {
  7674. return state;
  7675. },
  7676. /**
  7677. * Sets hover handlers for the large video container div.
  7678. *
  7679. * @param inHandler
  7680. * @param outHandler
  7681. */
  7682. setHover: function(inHandler, outHandler)
  7683. {
  7684. $('#largeVideoContainer').hover(inHandler, outHandler);
  7685. },
  7686. /**
  7687. * Enables/disables the filter indicating a video problem to the user.
  7688. *
  7689. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  7690. */
  7691. enableVideoProblemFilter: function (enable) {
  7692. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  7693. }
  7694. };
  7695. module.exports = LargeVideo;
  7696. },{"../../../service/UI/UIEvents":110,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":66,"../avatar/Avatar":16,"../toolbars/ToolbarToggler":29,"../util/UIUtil":33}],36:[function(require,module,exports){
  7697. /* global $, interfaceConfig, APP */
  7698. var SmallVideo = require("./SmallVideo");
  7699. var ConnectionIndicator = require("./ConnectionIndicator");
  7700. var NicknameHandler = require("../util/NicknameHandler");
  7701. var UIUtil = require("../util/UIUtil");
  7702. var LargeVideo = require("./LargeVideo");
  7703. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7704. function LocalVideo(VideoLayout) {
  7705. this.videoSpanId = "localVideoContainer";
  7706. this.container = $("#localVideoContainer").get(0);
  7707. this.VideoLayout = VideoLayout;
  7708. this.flipX = true;
  7709. this.isLocal = true;
  7710. this.peerJid = null;
  7711. }
  7712. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7713. LocalVideo.prototype.constructor = LocalVideo;
  7714. /**
  7715. * Creates the edit display name button.
  7716. *
  7717. * @returns {object} the edit button
  7718. */
  7719. function createEditDisplayNameButton() {
  7720. var editButton = document.createElement('a');
  7721. editButton.className = 'displayname';
  7722. UIUtil.setTooltip(editButton,
  7723. "videothumbnail.editnickname",
  7724. "top");
  7725. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7726. return editButton;
  7727. }
  7728. /**
  7729. * Sets the display name for the given video span id.
  7730. */
  7731. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7732. if (!this.container) {
  7733. console.warn(
  7734. "Unable to set displayName - " + this.videoSpanId +
  7735. " does not exist");
  7736. return;
  7737. }
  7738. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7739. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7740. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7741. var meHTML;
  7742. // If we already have a display name for this video.
  7743. if (nameSpan.length > 0) {
  7744. if (nameSpan.text() !== displayName) {
  7745. if (displayName && displayName.length > 0) {
  7746. meHTML = APP.translation.generateTranslationHTML("me");
  7747. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7748. } else {
  7749. $('#localDisplayName').html(defaultLocalDisplayName);
  7750. }
  7751. }
  7752. } else {
  7753. var editButton = createEditDisplayNameButton();
  7754. nameSpan = document.createElement('span');
  7755. nameSpan.className = 'displayname';
  7756. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7757. if (displayName && displayName.length > 0) {
  7758. meHTML = APP.translation.generateTranslationHTML("me");
  7759. nameSpan.innerHTML = displayName + meHTML;
  7760. }
  7761. else {
  7762. nameSpan.innerHTML = defaultLocalDisplayName;
  7763. }
  7764. nameSpan.id = 'localDisplayName';
  7765. this.container.appendChild(editButton);
  7766. //translates popover of edit button
  7767. APP.translation.translateElement($("a.displayname"));
  7768. var editableText = document.createElement('input');
  7769. editableText.className = 'displayname';
  7770. editableText.type = 'text';
  7771. editableText.id = 'editDisplayName';
  7772. if (displayName && displayName.length) {
  7773. editableText.value = displayName;
  7774. }
  7775. var defaultNickname = APP.translation.translateString(
  7776. "defaultNickname", {name: "Jane Pink"});
  7777. editableText.setAttribute('style', 'display:none;');
  7778. editableText.setAttribute('data-18n',
  7779. '[placeholder]defaultNickname');
  7780. editableText.setAttribute("data-i18n-options",
  7781. JSON.stringify({name: "Jane Pink"}));
  7782. editableText.setAttribute("placeholder", defaultNickname);
  7783. this.container.appendChild(editableText);
  7784. var self = this;
  7785. $('#localVideoContainer .displayname')
  7786. .bind("click", function (e) {
  7787. var editDisplayName = $('#editDisplayName');
  7788. e.preventDefault();
  7789. e.stopPropagation();
  7790. $('#localDisplayName').hide();
  7791. editDisplayName.show();
  7792. editDisplayName.focus();
  7793. editDisplayName.select();
  7794. editDisplayName.one("focusout", function (e) {
  7795. self.VideoLayout.inputDisplayNameHandler(this.value);
  7796. });
  7797. editDisplayName.on('keydown', function (e) {
  7798. if (e.keyCode === 13) {
  7799. e.preventDefault();
  7800. self.VideoLayout.inputDisplayNameHandler(this.value);
  7801. }
  7802. });
  7803. });
  7804. }
  7805. };
  7806. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7807. NicknameHandler.setNickname(name);
  7808. var localDisplayName = $('#localDisplayName');
  7809. if (!localDisplayName.is(":visible")) {
  7810. if (NicknameHandler.getNickname()) {
  7811. var meHTML = APP.translation.generateTranslationHTML("me");
  7812. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  7813. meHTML + ")");
  7814. } else {
  7815. var defaultHTML = APP.translation.generateTranslationHTML(
  7816. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7817. localDisplayName .html(defaultHTML);
  7818. }
  7819. localDisplayName.show();
  7820. }
  7821. $('#editDisplayName').hide();
  7822. };
  7823. LocalVideo.prototype.createConnectionIndicator = function() {
  7824. if(this.connectionIndicator)
  7825. return;
  7826. this.connectionIndicator = new ConnectionIndicator(this, null);
  7827. };
  7828. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7829. var self = this;
  7830. function localVideoClick(event) {
  7831. // FIXME: with Temasys plugin event arg is not an event, but
  7832. // the clicked object itself, so we have to skip this call
  7833. if (event.stopPropagation) {
  7834. event.stopPropagation();
  7835. }
  7836. self.VideoLayout.handleVideoThumbClicked(
  7837. false,
  7838. APP.xmpp.myResource());
  7839. }
  7840. var localVideoContainerSelector = $('#localVideoContainer');
  7841. localVideoContainerSelector.off('click');
  7842. localVideoContainerSelector.on('click', localVideoClick);
  7843. // Add hover handler
  7844. localVideoContainerSelector.hover(
  7845. function() {
  7846. self.showDisplayName(true);
  7847. },
  7848. function() {
  7849. if (!LargeVideo.isLargeVideoVisible() ||
  7850. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  7851. self.showDisplayName(false);
  7852. }
  7853. }
  7854. );
  7855. if(isMuted) {
  7856. APP.UI.setVideoMute(true);
  7857. return;
  7858. }
  7859. this.flipX = stream.videoType != "screen";
  7860. var localVideo = document.createElement('video');
  7861. localVideo.id = 'localVideo_' +
  7862. APP.RTC.getStreamID(stream.getOriginalStream());
  7863. if (!RTCBrowserType.isIExplorer()) {
  7864. localVideo.autoplay = true;
  7865. localVideo.volume = 0; // is it required if audio is separated ?
  7866. }
  7867. localVideo.oncontextmenu = function () { return false; };
  7868. var localVideoContainer = document.getElementById('localVideoWrapper');
  7869. localVideoContainer.appendChild(localVideo);
  7870. var localVideoSelector = $('#' + localVideo.id);
  7871. // Add click handler to both video and video wrapper elements in case
  7872. // there's no video.
  7873. // onclick has to be used with Temasys plugin
  7874. localVideo.onclick = localVideoClick;
  7875. if (this.flipX) {
  7876. localVideoSelector.addClass("flipVideoX");
  7877. }
  7878. // Attach WebRTC stream
  7879. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7880. // Add stream ended handler
  7881. stream.getOriginalStream().onended = function () {
  7882. // We have to re-select after attach when Temasys plugin is used,
  7883. // because <video> element is replaced with <object>
  7884. localVideo = $('#' + localVideo.id)[0];
  7885. localVideoContainer.removeChild(localVideo);
  7886. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7887. };
  7888. };
  7889. LocalVideo.prototype.joined = function (jid) {
  7890. this.peerJid = jid;
  7891. };
  7892. LocalVideo.prototype.getResourceJid = function () {
  7893. var myResource = APP.xmpp.myResource();
  7894. if (!myResource) {
  7895. console.error("Requested local resource before we're in the MUC");
  7896. }
  7897. return myResource;
  7898. };
  7899. module.exports = LocalVideo;
  7900. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7901. /* global $, APP, require, Strophe, interfaceConfig */
  7902. var ConnectionIndicator = require("./ConnectionIndicator");
  7903. var SmallVideo = require("./SmallVideo");
  7904. var AudioLevels = require("../audio_levels/AudioLevels");
  7905. var LargeVideo = require("./LargeVideo");
  7906. var Avatar = require("../avatar/Avatar");
  7907. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7908. function RemoteVideo(peerJid, VideoLayout) {
  7909. this.peerJid = peerJid;
  7910. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7911. this.videoSpanId = 'participant_' + this.resourceJid;
  7912. this.VideoLayout = VideoLayout;
  7913. this.addRemoteVideoContainer();
  7914. this.connectionIndicator = new ConnectionIndicator(
  7915. this, this.peerJid);
  7916. this.setDisplayName();
  7917. var nickfield = document.createElement('span');
  7918. nickfield.className = "nick";
  7919. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7920. this.container.appendChild(nickfield);
  7921. this.flipX = false;
  7922. this.isLocal = false;
  7923. }
  7924. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7925. RemoteVideo.prototype.constructor = RemoteVideo;
  7926. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7927. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7928. if (APP.xmpp.isModerator())
  7929. this.addRemoteVideoMenu();
  7930. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7931. return this.container;
  7932. };
  7933. /**
  7934. * Adds the remote video menu element for the given <tt>jid</tt> in the
  7935. * given <tt>parentElement</tt>.
  7936. *
  7937. * @param jid the jid indicating the video for which we're adding a menu.
  7938. * @param parentElement the parent element where this menu will be added
  7939. */
  7940. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  7941. var spanElement = document.createElement('span');
  7942. spanElement.className = 'remotevideomenu';
  7943. this.container.appendChild(spanElement);
  7944. var menuElement = document.createElement('i');
  7945. menuElement.className = 'fa fa-angle-down';
  7946. menuElement.title = 'Remote user controls';
  7947. spanElement.appendChild(menuElement);
  7948. var popupmenuElement = document.createElement('ul');
  7949. popupmenuElement.className = 'popupmenu';
  7950. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  7951. spanElement.appendChild(popupmenuElement);
  7952. var muteMenuItem = document.createElement('li');
  7953. var muteLinkItem = document.createElement('a');
  7954. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  7955. if (!this.isMuted) {
  7956. muteLinkItem.innerHTML = mutedIndicator +
  7957. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7958. muteLinkItem.className = 'mutelink';
  7959. }
  7960. else {
  7961. muteLinkItem.innerHTML = mutedIndicator +
  7962. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7963. muteLinkItem.className = 'mutelink disabled';
  7964. }
  7965. var self = this;
  7966. muteLinkItem.onclick = function(){
  7967. if ($(this).attr('disabled') != undefined) {
  7968. event.preventDefault();
  7969. }
  7970. var isMute = self.isMuted == true;
  7971. APP.xmpp.setMute(self.peerJid, !isMute);
  7972. popupmenuElement.setAttribute('style', 'display:none;');
  7973. if (isMute) {
  7974. this.innerHTML = mutedIndicator +
  7975. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7976. this.className = 'mutelink disabled';
  7977. }
  7978. else {
  7979. this.innerHTML = mutedIndicator +
  7980. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7981. this.className = 'mutelink';
  7982. }
  7983. };
  7984. muteMenuItem.appendChild(muteLinkItem);
  7985. popupmenuElement.appendChild(muteMenuItem);
  7986. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  7987. var ejectMenuItem = document.createElement('li');
  7988. var ejectLinkItem = document.createElement('a');
  7989. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  7990. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  7991. ejectLinkItem.onclick = function(){
  7992. APP.xmpp.eject(self.peerJid);
  7993. popupmenuElement.setAttribute('style', 'display:none;');
  7994. };
  7995. ejectMenuItem.appendChild(ejectLinkItem);
  7996. popupmenuElement.appendChild(ejectMenuItem);
  7997. var paddingSpan = document.createElement('span');
  7998. paddingSpan.className = 'popupmenuPadding';
  7999. popupmenuElement.appendChild(paddingSpan);
  8000. APP.translation.translateElement(
  8001. $("#" + popupmenuElement.id + " > li > a > div"));
  8002. };
  8003. /**
  8004. * Removes the remote stream element corresponding to the given stream and
  8005. * parent container.
  8006. *
  8007. * @param stream the stream
  8008. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8009. */
  8010. RemoteVideo.prototype.removeRemoteStreamElement =
  8011. function (stream, isVideo, id) {
  8012. if (!this.container)
  8013. return false;
  8014. var select = null;
  8015. if (isVideo) {
  8016. select = $('#' + id);
  8017. }
  8018. else
  8019. select = $('#' + this.videoSpanId + '>audio');
  8020. select.remove();
  8021. console.info((isVideo ? "Video" : "Audio") +
  8022. " removed " + this.getResourceJid(), select);
  8023. if (isVideo)
  8024. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8025. };
  8026. /**
  8027. * Removes RemoteVideo from the page.
  8028. */
  8029. RemoteVideo.prototype.remove = function () {
  8030. console.log("Remove thumbnail", this.peerJid);
  8031. this.removeConnectionIndicator();
  8032. // Remove whole container
  8033. if (this.container.parentNode)
  8034. this.container.parentNode.removeChild(this.container);
  8035. };
  8036. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8037. var isVideo = stream.getVideoTracks().length > 0;
  8038. if (!isVideo || stream.id === 'mixedmslabel') {
  8039. return;
  8040. }
  8041. var self = this;
  8042. var resourceJid = this.getResourceJid();
  8043. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8044. // when video playback starts
  8045. var onPlayingHandler = function () {
  8046. // FIXME: why do i have to do this for FF?
  8047. if (RTCBrowserType.isFirefox()) {
  8048. APP.RTC.attachMediaStream(sel, stream);
  8049. }
  8050. if (RTCBrowserType.isTemasysPluginUsed()) {
  8051. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8052. }
  8053. self.VideoLayout.videoactive(sel, resourceJid);
  8054. sel[0].onplaying = null;
  8055. if (RTCBrowserType.isTemasysPluginUsed()) {
  8056. // 'currentTime' is used to check if the video has started
  8057. // and the value is not set by the plugin, so we do it
  8058. sel[0].currentTime = 1;
  8059. }
  8060. };
  8061. sel[0].onplaying = onPlayingHandler;
  8062. };
  8063. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8064. if (!this.container)
  8065. return;
  8066. var self = this;
  8067. var isVideo = stream.getVideoTracks().length > 0;
  8068. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8069. var newElementId = streamElement.id;
  8070. this.container.appendChild(streamElement);
  8071. var sel = $('#' + newElementId);
  8072. sel.hide();
  8073. // If the container is currently visible we attach the stream.
  8074. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8075. this.waitForPlayback(sel, stream);
  8076. APP.RTC.attachMediaStream(sel, stream);
  8077. }
  8078. stream.onended = function () {
  8079. console.log('stream ended', this);
  8080. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8081. };
  8082. // Name of video element name is different for IE/Safari
  8083. var videoElem = APP.RTC.getVideoElementName();
  8084. // Add click handler.
  8085. var onClickHandler = function (event) {
  8086. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8087. // On IE we need to populate this handler on video <object>
  8088. // and it does not give event instance as an argument,
  8089. // so we check here for methods.
  8090. if (event.stopPropagation && event.preventDefault) {
  8091. event.stopPropagation();
  8092. event.preventDefault();
  8093. }
  8094. return false;
  8095. };
  8096. this.container.onclick = onClickHandler;
  8097. // reselect
  8098. if (RTCBrowserType.isTemasysPluginUsed())
  8099. sel = $('#' + newElementId);
  8100. sel[0].onclick = onClickHandler;
  8101. //FIXME
  8102. // Add hover handler
  8103. $(this.container).hover(
  8104. function() {
  8105. self.showDisplayName(true);
  8106. },
  8107. function() {
  8108. // If the video has been "pinned" by the user we want to
  8109. // keep the display name on place.
  8110. if (!LargeVideo.isLargeVideoVisible() ||
  8111. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8112. self.showDisplayName(false);
  8113. }
  8114. );
  8115. },
  8116. /**
  8117. * Show/hide peer container for the given resourceJid.
  8118. */
  8119. RemoteVideo.prototype.showPeerContainer = function (state) {
  8120. if (!this.container)
  8121. return;
  8122. var isHide = state === 'hide';
  8123. var resizeThumbnails = false;
  8124. if (!isHide) {
  8125. if (!$(this.container).is(':visible')) {
  8126. resizeThumbnails = true;
  8127. $(this.container).show();
  8128. }
  8129. this.showAvatar(state !== 'show');
  8130. }
  8131. else if ($(this.container).is(':visible') && isHide)
  8132. {
  8133. resizeThumbnails = true;
  8134. $(this.container).hide();
  8135. if(this.connectionIndicator)
  8136. this.connectionIndicator.hide();
  8137. }
  8138. if (resizeThumbnails) {
  8139. this.VideoLayout.resizeThumbnails();
  8140. }
  8141. // We want to be able to pin a participant from the contact list, even
  8142. // if he's not in the lastN set!
  8143. // ContactList.setClickable(resourceJid, !isHide);
  8144. };
  8145. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8146. if (this.connectionIndicator)
  8147. this.connectionIndicator.remove();
  8148. };
  8149. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8150. if (this.connectionIndicator)
  8151. this.connectionIndicator.hide();
  8152. };
  8153. /**
  8154. * Updates the remote video menu.
  8155. *
  8156. * @param jid the jid indicating the video for which we're adding a menu.
  8157. * @param isMuted indicates the current mute state
  8158. */
  8159. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8160. var muteMenuItem
  8161. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8162. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8163. if (muteMenuItem.length) {
  8164. var muteLink = muteMenuItem.get(0);
  8165. if (isMuted === 'true') {
  8166. muteLink.innerHTML = mutedIndicator + ' Muted';
  8167. muteLink.className = 'mutelink disabled';
  8168. }
  8169. else {
  8170. muteLink.innerHTML = mutedIndicator + ' Mute';
  8171. muteLink.className = 'mutelink';
  8172. }
  8173. }
  8174. };
  8175. /**
  8176. * Sets the display name for the given video span id.
  8177. */
  8178. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8179. if (!this.container) {
  8180. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8181. " does not exist");
  8182. return;
  8183. }
  8184. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8185. // If we already have a display name for this video.
  8186. if (nameSpan.length > 0) {
  8187. if (displayName && displayName.length > 0) {
  8188. $('#' + this.videoSpanId + '_name').html(displayName);
  8189. }
  8190. else if (key && key.length > 0) {
  8191. var nameHtml = APP.translation.generateTranslationHTML(key);
  8192. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8193. }
  8194. else
  8195. $('#' + this.videoSpanId + '_name').text(
  8196. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8197. } else {
  8198. nameSpan = document.createElement('span');
  8199. nameSpan.className = 'displayname';
  8200. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8201. if (displayName && displayName.length > 0) {
  8202. nameSpan.innerText = displayName;
  8203. }
  8204. else
  8205. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8206. nameSpan.id = this.videoSpanId + '_name';
  8207. }
  8208. };
  8209. /**
  8210. * Removes remote video menu element from video element identified by
  8211. * given <tt>videoElementId</tt>.
  8212. *
  8213. * @param videoElementId the id of local or remote video element.
  8214. */
  8215. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8216. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8217. if (menuSpan.length) {
  8218. menuSpan.remove();
  8219. }
  8220. };
  8221. RemoteVideo.prototype.getResourceJid = function () {
  8222. if (!this.resourceJid) {
  8223. console.error("Undefined resource jid");
  8224. }
  8225. return this.resourceJid;
  8226. };
  8227. RemoteVideo.createContainer = function (spanId) {
  8228. var container = document.createElement('span');
  8229. container.id = spanId;
  8230. container.className = 'videocontainer';
  8231. var remotes = document.getElementById('remoteVideos');
  8232. return remotes.appendChild(container);
  8233. };
  8234. module.exports = RemoteVideo;
  8235. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8236. /* global $, APP, require */
  8237. var Avatar = require("../avatar/Avatar");
  8238. var UIUtil = require("../util/UIUtil");
  8239. var LargeVideo = require("./LargeVideo");
  8240. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8241. function SmallVideo() {
  8242. this.isMuted = false;
  8243. this.hasAvatar = false;
  8244. }
  8245. function setVisibility(selector, show) {
  8246. if (selector && selector.length > 0) {
  8247. selector.css("visibility", show ? "visible" : "hidden");
  8248. }
  8249. }
  8250. SmallVideo.prototype.showDisplayName = function(isShow) {
  8251. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8252. if (isShow) {
  8253. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8254. nameSpan.setAttribute("style", "display:inline-block;");
  8255. }
  8256. else {
  8257. if (nameSpan)
  8258. nameSpan.setAttribute("style", "display:none;");
  8259. }
  8260. };
  8261. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8262. if(!this.container)
  8263. return;
  8264. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8265. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8266. noMic.remove();
  8267. noVideo.remove();
  8268. if (!devices.audio) {
  8269. this.container.appendChild(
  8270. document.createElement("div")).setAttribute("class", "noMic");
  8271. }
  8272. if (!devices.video) {
  8273. this.container.appendChild(
  8274. document.createElement("div")).setAttribute("class", "noVideo");
  8275. }
  8276. if (!devices.audio && !devices.video) {
  8277. noMic.css("background-position", "75%");
  8278. noVideo.css("background-position", "25%");
  8279. noVideo.css("background-color", "transparent");
  8280. }
  8281. };
  8282. /**
  8283. * Shows the presence status message for the given video.
  8284. */
  8285. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8286. if (!this.container) {
  8287. // No container
  8288. return;
  8289. }
  8290. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8291. if (!statusSpan.length) {
  8292. //Add status span
  8293. statusSpan = document.createElement('span');
  8294. statusSpan.className = 'status';
  8295. statusSpan.id = this.videoSpanId + '_status';
  8296. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8297. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8298. }
  8299. // Display status
  8300. if (statusMsg && statusMsg.length) {
  8301. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8302. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8303. }
  8304. else {
  8305. // Hide
  8306. statusSpan.get(0).setAttribute("style", "display:none;");
  8307. }
  8308. };
  8309. /**
  8310. * Creates an audio or video stream element.
  8311. */
  8312. SmallVideo.createStreamElement = function (sid, stream) {
  8313. var isVideo = stream.getVideoTracks().length > 0;
  8314. var element = isVideo ? document.createElement('video')
  8315. : document.createElement('audio');
  8316. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8317. APP.RTC.getStreamID(stream);
  8318. element.id = id;
  8319. if (!RTCBrowserType.isIExplorer()) {
  8320. element.autoplay = true;
  8321. }
  8322. element.oncontextmenu = function () { return false; };
  8323. return element;
  8324. };
  8325. /**
  8326. * Updates the data for the indicator
  8327. * @param id the id of the indicator
  8328. * @param percent the percent for connection quality
  8329. * @param object the data
  8330. */
  8331. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8332. if(this.connectionIndicator)
  8333. this.connectionIndicator.updateConnectionQuality(percent, object);
  8334. };
  8335. SmallVideo.prototype.hideIndicator = function () {
  8336. if(this.connectionIndicator)
  8337. this.connectionIndicator.hideIndicator();
  8338. };
  8339. /**
  8340. * Shows audio muted indicator over small videos.
  8341. * @param {string} isMuted
  8342. */
  8343. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8344. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8345. if (!isMuted) {
  8346. if (audioMutedSpan.length > 0) {
  8347. audioMutedSpan.popover('hide');
  8348. audioMutedSpan.remove();
  8349. }
  8350. }
  8351. else {
  8352. if(audioMutedSpan.length == 0 ) {
  8353. audioMutedSpan = document.createElement('span');
  8354. audioMutedSpan.className = 'audioMuted';
  8355. UIUtil.setTooltip(audioMutedSpan,
  8356. "videothumbnail.mute",
  8357. "top");
  8358. this.container.appendChild(audioMutedSpan);
  8359. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8360. var mutedIndicator = document.createElement('i');
  8361. mutedIndicator.className = 'icon-mic-disabled';
  8362. audioMutedSpan.appendChild(mutedIndicator);
  8363. }
  8364. this.updateIconPositions();
  8365. }
  8366. this.isMuted = isMuted;
  8367. };
  8368. /**
  8369. * Shows video muted indicator over small videos.
  8370. */
  8371. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8372. this.showAvatar(isMuted);
  8373. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8374. if (isMuted === false) {
  8375. if (videoMutedSpan.length > 0) {
  8376. videoMutedSpan.remove();
  8377. }
  8378. }
  8379. else {
  8380. if(videoMutedSpan.length == 0) {
  8381. videoMutedSpan = document.createElement('span');
  8382. videoMutedSpan.className = 'videoMuted';
  8383. this.container.appendChild(videoMutedSpan);
  8384. var mutedIndicator = document.createElement('i');
  8385. mutedIndicator.className = 'icon-camera-disabled';
  8386. UIUtil.setTooltip(mutedIndicator,
  8387. "videothumbnail.videomute",
  8388. "top");
  8389. videoMutedSpan.appendChild(mutedIndicator);
  8390. //translate texts for muted indicator
  8391. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8392. }
  8393. this.updateIconPositions();
  8394. }
  8395. };
  8396. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8397. var resourceJid = this.getResourceJid();
  8398. var displayName = resourceJid;
  8399. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8400. if (nameSpan.length > 0)
  8401. displayName = nameSpan.html();
  8402. console.log("UI enable dominant speaker",
  8403. displayName,
  8404. resourceJid,
  8405. isEnable);
  8406. if (!this.container) {
  8407. return;
  8408. }
  8409. if (isEnable) {
  8410. this.showDisplayName(LargeVideo.getState() === "video");
  8411. if (!this.container.classList.contains("dominantspeaker"))
  8412. this.container.classList.add("dominantspeaker");
  8413. }
  8414. else {
  8415. this.showDisplayName(false);
  8416. if (this.container.classList.contains("dominantspeaker"))
  8417. this.container.classList.remove("dominantspeaker");
  8418. }
  8419. this.showAvatar();
  8420. };
  8421. SmallVideo.prototype.updateIconPositions = function () {
  8422. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8423. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8424. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8425. if(connectionIndicator.length > 0 &&
  8426. connectionIndicator[0].style.display != "none") {
  8427. audioMutedSpan.css({right: "23px"});
  8428. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8429. } else {
  8430. audioMutedSpan.css({right: "0px"});
  8431. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8432. }
  8433. };
  8434. /**
  8435. * Creates the element indicating the moderator(owner) of the conference.
  8436. *
  8437. * @param parentElement the parent element where the owner indicator will
  8438. * be added
  8439. */
  8440. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8441. // Show moderator indicator
  8442. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8443. if (!indicatorSpan || indicatorSpan.length === 0) {
  8444. indicatorSpan = document.createElement('span');
  8445. indicatorSpan.className = 'focusindicator';
  8446. this.container.appendChild(indicatorSpan);
  8447. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8448. }
  8449. if (indicatorSpan.children().length !== 0)
  8450. return;
  8451. var moderatorIndicator = document.createElement('i');
  8452. moderatorIndicator.className = 'fa fa-star';
  8453. indicatorSpan[0].appendChild(moderatorIndicator);
  8454. UIUtil.setTooltip(indicatorSpan[0],
  8455. "videothumbnail.moderator",
  8456. "top");
  8457. //translates text in focus indicators
  8458. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8459. };
  8460. SmallVideo.prototype.getSrc = function () {
  8461. var videoElement = APP.RTC.getVideoElementName();
  8462. return APP.RTC.getVideoSrc(
  8463. $('#' + this.videoSpanId).find(videoElement).get(0));
  8464. };
  8465. SmallVideo.prototype.focus = function(isFocused) {
  8466. if(!isFocused) {
  8467. this.container.classList.remove("videoContainerFocused");
  8468. } else {
  8469. this.container.classList.add("videoContainerFocused");
  8470. }
  8471. };
  8472. SmallVideo.prototype.hasVideo = function () {
  8473. return $("#" + this.videoSpanId).find(
  8474. APP.RTC.getVideoElementName()).length !== 0;
  8475. };
  8476. /**
  8477. * Hides or shows the user's avatar
  8478. * @param show whether we should show the avatar or not
  8479. * video because there is no dominant speaker and no focused speaker
  8480. */
  8481. SmallVideo.prototype.showAvatar = function (show) {
  8482. if (!this.hasAvatar) {
  8483. if (this.peerJid) {
  8484. // Init avatar
  8485. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8486. } else {
  8487. console.error("Unable to init avatar - no peerjid", this);
  8488. return;
  8489. }
  8490. }
  8491. var resourceJid = this.getResourceJid();
  8492. var videoElem = APP.RTC.getVideoElementName();
  8493. var video = $('#' + this.videoSpanId).find(videoElem);
  8494. var avatar = $('#avatar_' + resourceJid);
  8495. if (show === undefined || show === null) {
  8496. if (!this.isLocal &&
  8497. !this.VideoLayout.isInLastN(resourceJid)) {
  8498. show = true;
  8499. } else {
  8500. // We want to show the avatar when the video is muted or not exists
  8501. // that is when 'true' or 'null' is returned
  8502. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8503. }
  8504. }
  8505. if (LargeVideo.showAvatar(resourceJid, show)) {
  8506. setVisibility(avatar, false);
  8507. setVisibility(video, false);
  8508. } else {
  8509. if (video && video.length > 0) {
  8510. setVisibility(video, !show);
  8511. }
  8512. setVisibility(avatar, show);
  8513. }
  8514. };
  8515. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8516. var thumbnail = $('#' + this.videoSpanId);
  8517. var resourceJid = this.getResourceJid();
  8518. var avatar = $('#avatar_' + resourceJid);
  8519. this.hasAvatar = true;
  8520. // set the avatar in the thumbnail
  8521. if (avatar && avatar.length > 0) {
  8522. avatar[0].src = thumbUrl;
  8523. } else {
  8524. if (thumbnail && thumbnail.length > 0) {
  8525. avatar = document.createElement('img');
  8526. avatar.id = 'avatar_' + resourceJid;
  8527. avatar.className = 'userAvatar';
  8528. avatar.src = thumbUrl;
  8529. thumbnail.append(avatar);
  8530. }
  8531. }
  8532. };
  8533. module.exports = SmallVideo;
  8534. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8535. /* global config, APP, $, Strophe, require, interfaceConfig */
  8536. var AudioLevels = require("../audio_levels/AudioLevels");
  8537. var ContactList = require("../side_pannels/contactlist/ContactList");
  8538. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8539. var UIEvents = require("../../../service/UI/UIEvents");
  8540. var RTC = require("../../RTC/RTC");
  8541. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8542. var RemoteVideo = require("./RemoteVideo");
  8543. var LargeVideo = require("./LargeVideo");
  8544. var LocalVideo = require("./LocalVideo");
  8545. var remoteVideos = {};
  8546. var localVideoThumbnail = null;
  8547. var currentDominantSpeaker = null;
  8548. var lastNCount = config.channelLastN;
  8549. var localLastNCount = config.channelLastN;
  8550. var localLastNSet = [];
  8551. var lastNEndpointsCache = [];
  8552. var lastNPickupJid = null;
  8553. var eventEmitter = null;
  8554. /**
  8555. * Currently focused video jid
  8556. * @type {String}
  8557. */
  8558. var focusedVideoResourceJid = null;
  8559. var VideoLayout = (function (my) {
  8560. my.init = function (emitter) {
  8561. eventEmitter = emitter;
  8562. localVideoThumbnail = new LocalVideo(VideoLayout);
  8563. LargeVideo.init(VideoLayout, emitter);
  8564. VideoLayout.resizeLargeVideoContainer();
  8565. };
  8566. my.isInLastN = function(resource) {
  8567. return lastNCount < 0 || // lastN is disabled
  8568. // lastNEndpoints cache not built yet
  8569. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8570. (lastNEndpointsCache &&
  8571. lastNEndpointsCache.indexOf(resource) !== -1);
  8572. };
  8573. my.changeLocalStream = function (stream, isMuted) {
  8574. VideoLayout.changeLocalVideo(stream, isMuted);
  8575. };
  8576. my.changeLocalAudio = function(stream, isMuted) {
  8577. if (isMuted)
  8578. APP.UI.setAudioMuted(true, true);
  8579. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8580. var localAudio = document.getElementById('localAudio');
  8581. // Writing volume not allowed in IE
  8582. if (!RTCBrowserType.isIExplorer()) {
  8583. localAudio.autoplay = true;
  8584. localAudio.volume = 0;
  8585. }
  8586. };
  8587. my.changeLocalVideo = function(stream, isMuted) {
  8588. // Set default display name.
  8589. localVideoThumbnail.setDisplayName();
  8590. localVideoThumbnail.createConnectionIndicator();
  8591. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8592. localVideoThumbnail.changeVideo(stream, isMuted);
  8593. /* force update if we're currently being displayed */
  8594. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8595. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8596. }
  8597. };
  8598. my.mucJoined = function () {
  8599. var myResourceJid = APP.xmpp.myResource();
  8600. localVideoThumbnail.joined(APP.xmpp.myJid());
  8601. if (!LargeVideo.getResourceJid())
  8602. LargeVideo.updateLargeVideo(myResourceJid, true);
  8603. };
  8604. /**
  8605. * Adds or removes icons for not available camera and microphone.
  8606. * @param resourceJid the jid of user
  8607. * @param devices available devices
  8608. */
  8609. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8610. if(!devices)
  8611. return;
  8612. if(!resourceJid) {
  8613. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8614. } else {
  8615. if(remoteVideos[resourceJid])
  8616. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8617. }
  8618. };
  8619. /**
  8620. * Checks if removed video is currently displayed and tries to display
  8621. * another one instead.
  8622. * @param removedVideoSrc src stream identifier of the video.
  8623. */
  8624. my.updateRemovedVideo = function(resourceJid) {
  8625. if (resourceJid === LargeVideo.getResourceJid()) {
  8626. var newResourceJid;
  8627. // We'll show user's avatar if he is the dominant speaker or if
  8628. // his video thumbnail is pinned
  8629. if (remoteVideos[resourceJid] &&
  8630. resourceJid === focusedVideoResourceJid ||
  8631. resourceJid === currentDominantSpeaker) {
  8632. newResourceJid = resourceJid;
  8633. } else {
  8634. // Otherwise select last visible video
  8635. newResourceJid = this.electLastVisibleVideo();
  8636. }
  8637. LargeVideo.updateLargeVideo(newResourceJid);
  8638. }
  8639. };
  8640. my.electLastVisibleVideo = function() {
  8641. // pick the last visible video in the row
  8642. // if nobody else is left, this picks the local video
  8643. var jid;
  8644. var videoElem = RTC.getVideoElementName();
  8645. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8646. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8647. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8648. } else {
  8649. console.info("Last visible video no longer exists");
  8650. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8651. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8652. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8653. } else {
  8654. // Try local video
  8655. console.info("Fallback to local video...");
  8656. jid = APP.xmpp.myResource();
  8657. }
  8658. }
  8659. console.info("electLastVisibleVideo: " + jid);
  8660. return jid;
  8661. };
  8662. my.onRemoteStreamAdded = function (stream) {
  8663. if (stream.peerjid) {
  8664. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8665. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8666. remoteVideos[resourceJid].addRemoteStreamElement(
  8667. stream.sid,
  8668. stream.getOriginalStream(),
  8669. stream.ssrc);
  8670. }
  8671. };
  8672. my.getLargeVideoJid = function () {
  8673. return LargeVideo.getResourceJid();
  8674. };
  8675. /**
  8676. * Called when large video update is finished
  8677. * @param currentSmallVideo small video currently displayed on large video
  8678. */
  8679. my.largeVideoUpdated = function (currentSmallVideo) {
  8680. // Makes sure that dominant speaker UI
  8681. // is enabled only on current small video
  8682. localVideoThumbnail.enableDominantSpeaker(
  8683. localVideoThumbnail === currentSmallVideo);
  8684. Object.keys(remoteVideos).forEach(
  8685. function (resourceJid) {
  8686. var remoteVideo = remoteVideos[resourceJid];
  8687. if (remoteVideo) {
  8688. remoteVideo.enableDominantSpeaker(
  8689. remoteVideo === currentSmallVideo);
  8690. }
  8691. }
  8692. );
  8693. };
  8694. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8695. resourceJid) {
  8696. if(focusedVideoResourceJid) {
  8697. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8698. if(oldSmallVideo)
  8699. oldSmallVideo.focus(false);
  8700. }
  8701. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8702. // Unlock current focused.
  8703. if (focusedVideoResourceJid === resourceJid)
  8704. {
  8705. focusedVideoResourceJid = null;
  8706. // Enable the currently set dominant speaker.
  8707. if (currentDominantSpeaker) {
  8708. if(smallVideo && smallVideo.hasVideo()) {
  8709. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8710. }
  8711. }
  8712. if (!noPinnedEndpointChangedEvent) {
  8713. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8714. }
  8715. return;
  8716. }
  8717. // Lock new video
  8718. focusedVideoResourceJid = resourceJid;
  8719. // Update focused/pinned interface.
  8720. if (resourceJid) {
  8721. if(smallVideo)
  8722. smallVideo.focus(true);
  8723. if (!noPinnedEndpointChangedEvent) {
  8724. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8725. }
  8726. }
  8727. LargeVideo.setState("video");
  8728. LargeVideo.updateLargeVideo(resourceJid);
  8729. // Writing volume not allowed in IE
  8730. if (!RTCBrowserType.isIExplorer()) {
  8731. $('audio').each(function (idx, el) {
  8732. el.volume = 0;
  8733. el.volume = 1;
  8734. });
  8735. }
  8736. };
  8737. /**
  8738. * Checks if container for participant identified by given peerJid exists
  8739. * in the document and creates it eventually.
  8740. *
  8741. * @param peerJid peer Jid to check.
  8742. *
  8743. * @return Returns <tt>true</tt> if the peer container exists,
  8744. * <tt>false</tt> - otherwise
  8745. */
  8746. my.ensurePeerContainerExists = function(peerJid) {
  8747. ContactList.ensureAddContact(peerJid);
  8748. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8749. if(!remoteVideos[resourceJid]) {
  8750. remoteVideos[resourceJid] = new RemoteVideo(peerJid, VideoLayout);
  8751. // In case this is not currently in the last n we don't show it.
  8752. if (localLastNCount &&
  8753. localLastNCount > 0 &&
  8754. $('#remoteVideos>span').length >= localLastNCount + 2) {
  8755. remoteVideos[resourceJid].showPeerContainer('hide');
  8756. }
  8757. else
  8758. VideoLayout.resizeThumbnails();
  8759. }
  8760. };
  8761. my.inputDisplayNameHandler = function (name) {
  8762. localVideoThumbnail.inputDisplayNameHandler(name);
  8763. };
  8764. my.videoactive = function (videoelem, resourceJid) {
  8765. console.info(resourceJid + " video is now active");
  8766. videoelem.show();
  8767. VideoLayout.resizeThumbnails();
  8768. // Update the large video to the last added video only if there's no
  8769. // current dominant, focused speaker or prezi playing or update it to
  8770. // the current dominant speaker.
  8771. if ((!focusedVideoResourceJid &&
  8772. !currentDominantSpeaker &&
  8773. !require("../prezi/Prezi").isPresentationVisible()) ||
  8774. focusedVideoResourceJid === resourceJid ||
  8775. (resourceJid &&
  8776. currentDominantSpeaker === resourceJid)) {
  8777. LargeVideo.updateLargeVideo(resourceJid, true);
  8778. }
  8779. };
  8780. /**
  8781. * Shows the presence status message for the given video.
  8782. */
  8783. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8784. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8785. };
  8786. /**
  8787. * Shows a visual indicator for the moderator of the conference.
  8788. */
  8789. my.showModeratorIndicator = function () {
  8790. var isModerator = APP.xmpp.isModerator();
  8791. if (isModerator) {
  8792. localVideoThumbnail.createModeratorIndicatorElement();
  8793. }
  8794. var members = APP.xmpp.getMembers();
  8795. Object.keys(members).forEach(function (jid) {
  8796. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8797. // Skip server side focus
  8798. return;
  8799. }
  8800. var resourceJid = Strophe.getResourceFromJid(jid);
  8801. var member = members[jid];
  8802. if (member.role === 'moderator') {
  8803. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8804. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8805. } else if (isModerator) {
  8806. // We are moderator, but user is not - add menu
  8807. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8808. remoteVideos[resourceJid].addRemoteVideoMenu();
  8809. }
  8810. }
  8811. });
  8812. };
  8813. /*
  8814. * Shows or hides the audio muted indicator over the local thumbnail video.
  8815. * @param {boolean} isMuted
  8816. */
  8817. my.showLocalAudioIndicator = function(isMuted) {
  8818. localVideoThumbnail.showAudioIndicator(isMuted);
  8819. };
  8820. /**
  8821. * Resizes the large video container.
  8822. */
  8823. my.resizeLargeVideoContainer = function () {
  8824. LargeVideo.resize();
  8825. VideoLayout.resizeThumbnails();
  8826. LargeVideo.position();
  8827. };
  8828. /**
  8829. * Resizes thumbnails.
  8830. */
  8831. my.resizeThumbnails = function(animate) {
  8832. var videoSpaceWidth = $('#remoteVideos').width();
  8833. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8834. var width = thumbnailSize[0];
  8835. var height = thumbnailSize[1];
  8836. $('.userAvatar').css('left', (width - height) / 2);
  8837. if(animate) {
  8838. $('#remoteVideos').animate({
  8839. height: height
  8840. },
  8841. {
  8842. queue: false,
  8843. duration: 500
  8844. });
  8845. $('#remoteVideos>span').animate({
  8846. height: height,
  8847. width: width
  8848. },
  8849. {
  8850. queue: false,
  8851. duration: 500,
  8852. complete: function () {
  8853. $(document).trigger(
  8854. "remotevideo.resized",
  8855. [width,
  8856. height]);
  8857. }
  8858. });
  8859. } else {
  8860. // size videos so that while keeping AR and max height, we have a
  8861. // nice fit
  8862. $('#remoteVideos').height(height);
  8863. $('#remoteVideos>span').width(width);
  8864. $('#remoteVideos>span').height(height);
  8865. $(document).trigger("remotevideo.resized", [width, height]);
  8866. }
  8867. };
  8868. /**
  8869. * Calculates the thumbnail size.
  8870. *
  8871. * @param videoSpaceWidth the width of the video space
  8872. */
  8873. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8874. // Calculate the available height, which is the inner window height minus
  8875. // 39px for the header minus 2px for the delimiter lines on the top and
  8876. // bottom of the large video, minus the 36px space inside the remoteVideos
  8877. // container used for highlighting shadow.
  8878. var availableHeight = 100;
  8879. var numvids = $('#remoteVideos>span:visible').length;
  8880. if (localLastNCount && localLastNCount > 0) {
  8881. numvids = Math.min(localLastNCount + 1, numvids);
  8882. }
  8883. // Remove the 3px borders arround videos and border around the remote
  8884. // videos area and the 4 pixels between the local video and the others
  8885. //TODO: Find out where the 4 pixels come from and remove them
  8886. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8887. var availableWidth = availableWinWidth / numvids;
  8888. var aspectRatio = 16.0 / 9.0;
  8889. var maxHeight = Math.min(160, availableHeight);
  8890. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  8891. if (availableHeight < availableWidth / aspectRatio) {
  8892. availableWidth = Math.floor(availableHeight * aspectRatio);
  8893. }
  8894. return [availableWidth, availableHeight];
  8895. };
  8896. /**
  8897. * Returns the corresponding resource jid to the given peer container
  8898. * DOM element.
  8899. *
  8900. * @return the corresponding resource jid to the given peer container
  8901. * DOM element
  8902. */
  8903. my.getPeerContainerResourceJid = function (containerElement) {
  8904. var i = containerElement.id.indexOf('participant_');
  8905. if (i >= 0)
  8906. return containerElement.id.substring(i + 12);
  8907. };
  8908. my.getPeerVideoSel = function (peerResourceJid) {
  8909. return $('#participant_' + peerResourceJid +
  8910. '>' + APP.RTC.getVideoElementName());
  8911. };
  8912. /**
  8913. * On contact list item clicked.
  8914. */
  8915. $(ContactList).bind('contactclicked', function(event, jid) {
  8916. if (!jid) {
  8917. return;
  8918. }
  8919. if (jid === APP.xmpp.myJid()) {
  8920. $("#localVideoContainer").click();
  8921. return;
  8922. }
  8923. var resource = Strophe.getResourceFromJid(jid);
  8924. var videoSel = VideoLayout.getPeerVideoSel(resource);
  8925. if (videoSel.length > 0) {
  8926. var videoThumb = videoSel[0];
  8927. // It is not always the case that a videoThumb exists (if there is
  8928. // no actual video).
  8929. if (RTC.getVideoSrc(videoThumb)) {
  8930. // We have a video src, great! Let's update the large video
  8931. // now.
  8932. VideoLayout.handleVideoThumbClicked(
  8933. false,
  8934. Strophe.getResourceFromJid(jid));
  8935. } else {
  8936. // If we don't have a video src for jid, there's absolutely
  8937. // no point in calling handleVideoThumbClicked; Quite
  8938. // simply, it won't work because it needs an src to attach
  8939. // to the large video.
  8940. //
  8941. // Instead, we trigger the pinned endpoint changed event to
  8942. // let the bridge adjust its lastN set for myjid and store
  8943. // the pinned user in the lastNPickupJid variable to be
  8944. // picked up later by the lastN changed event handler.
  8945. lastNPickupJid = jid;
  8946. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  8947. Strophe.getResourceFromJid(jid));
  8948. }
  8949. }
  8950. });
  8951. /**
  8952. * On audio muted event.
  8953. */
  8954. my.onAudioMute = function (jid, isMuted) {
  8955. var resourceJid = Strophe.getResourceFromJid(jid);
  8956. if (resourceJid === APP.xmpp.myResource()) {
  8957. localVideoThumbnail.showAudioIndicator(isMuted);
  8958. } else {
  8959. VideoLayout.ensurePeerContainerExists(jid);
  8960. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  8961. if (APP.xmpp.isModerator()) {
  8962. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  8963. }
  8964. }
  8965. };
  8966. /**
  8967. * On video muted event.
  8968. */
  8969. my.onVideoMute = function (jid, value) {
  8970. if (jid !== APP.xmpp.myJid() &&
  8971. !APP.RTC.muteRemoteVideoStream(jid, value))
  8972. return;
  8973. if (jid === APP.xmpp.myJid()) {
  8974. localVideoThumbnail.showVideoIndicator(value);
  8975. } else {
  8976. var resource = Strophe.getResourceFromJid(jid);
  8977. VideoLayout.ensurePeerContainerExists(jid);
  8978. remoteVideos[resource].showVideoIndicator(value);
  8979. var el = VideoLayout.getPeerVideoSel(resource);
  8980. if (!value)
  8981. el.show();
  8982. else
  8983. el.hide();
  8984. }
  8985. };
  8986. /**
  8987. * Display name changed.
  8988. */
  8989. my.onDisplayNameChanged =
  8990. function (jid, displayName, status) {
  8991. if (jid === 'localVideoContainer' ||
  8992. jid === APP.xmpp.myJid()) {
  8993. localVideoThumbnail.setDisplayName(displayName);
  8994. } else {
  8995. VideoLayout.ensurePeerContainerExists(jid);
  8996. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  8997. displayName,
  8998. status);
  8999. }
  9000. };
  9001. /**
  9002. * On dominant speaker changed event.
  9003. */
  9004. my.onDominantSpeakerChanged = function (resourceJid) {
  9005. // We ignore local user events.
  9006. if (resourceJid === APP.xmpp.myResource())
  9007. return;
  9008. var members = APP.xmpp.getMembers();
  9009. // Update the current dominant speaker.
  9010. if (resourceJid !== currentDominantSpeaker) {
  9011. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9012. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9013. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9014. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9015. remoteVideos[resourceJid].setDisplayName(null);
  9016. }
  9017. if(resourceJid && (!members || !members[newJID] ||
  9018. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9019. remoteVideos[resourceJid].setDisplayName(null,
  9020. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9021. }
  9022. currentDominantSpeaker = resourceJid;
  9023. } else {
  9024. return;
  9025. }
  9026. // Obtain container for new dominant speaker.
  9027. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9028. // Local video will not have container found, but that's ok
  9029. // since we don't want to switch to local video.
  9030. if (!focusedVideoResourceJid && videoSel.length) {
  9031. // Update the large video if the video source is already available,
  9032. // otherwise wait for the "videoactive.jingle" event.
  9033. if (videoSel[0].currentTime > 0) {
  9034. LargeVideo.updateLargeVideo(resourceJid);
  9035. }
  9036. }
  9037. };
  9038. /**
  9039. * On last N change event.
  9040. *
  9041. * @param lastNEndpoints the list of last N endpoints
  9042. * @param endpointsEnteringLastN the list currently entering last N
  9043. * endpoints
  9044. */
  9045. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9046. endpointsEnteringLastN,
  9047. stream) {
  9048. if (lastNCount !== lastNEndpoints.length)
  9049. lastNCount = lastNEndpoints.length;
  9050. lastNEndpointsCache = lastNEndpoints;
  9051. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9052. //
  9053. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9054. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9055. // so E sees them. C is only in E's local LastN set.
  9056. //
  9057. // If F starts talking and LastN = 3, then E should see thumbnails for
  9058. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9059. // enters E's local LastN ejecting C.
  9060. // Increase the local LastN set size, if necessary.
  9061. if (lastNCount > localLastNCount) {
  9062. localLastNCount = lastNCount;
  9063. }
  9064. // Update the local LastN set preserving the order in which the
  9065. // endpoints appeared in the LastN/local LastN set.
  9066. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9067. for (var i = 0; i < localLastNSet.length; i++) {
  9068. if (nextLocalLastNSet.length >= localLastNCount) {
  9069. break;
  9070. }
  9071. var resourceJid = localLastNSet[i];
  9072. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9073. nextLocalLastNSet.push(resourceJid);
  9074. }
  9075. }
  9076. localLastNSet = nextLocalLastNSet;
  9077. var updateLargeVideo = false;
  9078. // Handle LastN/local LastN changes.
  9079. $('#remoteVideos>span').each(function( index, element ) {
  9080. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9081. var isReceived = true;
  9082. if (resourceJid &&
  9083. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9084. localLastNSet.indexOf(resourceJid) < 0) {
  9085. console.log("Remove from last N", resourceJid);
  9086. remoteVideos[resourceJid].showPeerContainer('hide');
  9087. isReceived = false;
  9088. } else if (resourceJid &&
  9089. $('#participant_' + resourceJid).is(':visible') &&
  9090. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9091. localLastNSet.indexOf(resourceJid) >= 0) {
  9092. remoteVideos[resourceJid].showPeerContainer('avatar');
  9093. isReceived = false;
  9094. }
  9095. if (!isReceived) {
  9096. // resourceJid has dropped out of the server side lastN set, so
  9097. // it is no longer being received. If resourceJid was being
  9098. // displayed in the large video we have to switch to another
  9099. // user.
  9100. if (!updateLargeVideo &&
  9101. resourceJid === LargeVideo.getResourceJid()) {
  9102. updateLargeVideo = true;
  9103. }
  9104. }
  9105. });
  9106. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9107. endpointsEnteringLastN = lastNEndpoints;
  9108. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9109. endpointsEnteringLastN.forEach(function (resourceJid) {
  9110. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9111. remoteVideos[resourceJid].showPeerContainer('show');
  9112. if (!isVisible) {
  9113. console.log("Add to last N", resourceJid);
  9114. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9115. var mediaStream =
  9116. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9117. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9118. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9119. if (lastNPickupJid == mediaStream.peerjid) {
  9120. // Clean up the lastN pickup jid.
  9121. lastNPickupJid = null;
  9122. // Don't fire the events again, they've already
  9123. // been fired in the contact list click handler.
  9124. VideoLayout.handleVideoThumbClicked(
  9125. false,
  9126. Strophe.getResourceFromJid(mediaStream.peerjid));
  9127. updateLargeVideo = false;
  9128. }
  9129. remoteVideos[resourceJid].
  9130. waitForPlayback(sel, mediaStream.stream);
  9131. }
  9132. });
  9133. }
  9134. // The endpoint that was being shown in the large video has dropped out
  9135. // of the lastN set and there was no lastN pickup jid. We need to update
  9136. // the large video now.
  9137. if (updateLargeVideo) {
  9138. var resource;
  9139. var myResource
  9140. = APP.xmpp.myResource();
  9141. // Find out which endpoint to show in the large video.
  9142. for (i = 0; i < lastNEndpoints.length; i++) {
  9143. resource = lastNEndpoints[i];
  9144. if (!resource || resource === myResource)
  9145. continue;
  9146. // videoSrcToSsrc needs to be update for this call to succeed.
  9147. LargeVideo.updateLargeVideo(resource);
  9148. break;
  9149. }
  9150. }
  9151. };
  9152. /**
  9153. * Updates local stats
  9154. * @param percent
  9155. * @param object
  9156. */
  9157. my.updateLocalConnectionStats = function (percent, object) {
  9158. var resolution = null;
  9159. if (object.resolution !== null) {
  9160. resolution = object.resolution;
  9161. object.resolution = resolution[APP.xmpp.myJid()];
  9162. delete resolution[APP.xmpp.myJid()];
  9163. }
  9164. localVideoThumbnail.updateStatsIndicator(percent, object);
  9165. for (var jid in resolution) {
  9166. if (resolution[jid] === null)
  9167. continue;
  9168. var resourceJid = Strophe.getResourceFromJid(jid);
  9169. if (remoteVideos[resourceJid] &&
  9170. remoteVideos[resourceJid].connectionIndicator) {
  9171. remoteVideos[resourceJid].connectionIndicator.
  9172. updateResolution(resolution[jid]);
  9173. }
  9174. }
  9175. };
  9176. /**
  9177. * Updates remote stats.
  9178. * @param jid the jid associated with the stats
  9179. * @param percent the connection quality percent
  9180. * @param object the stats data
  9181. */
  9182. my.updateConnectionStats = function (jid, percent, object) {
  9183. var resourceJid = Strophe.getResourceFromJid(jid);
  9184. if (remoteVideos[resourceJid])
  9185. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9186. };
  9187. /**
  9188. * Hides the connection indicator
  9189. * @param jid
  9190. */
  9191. my.hideConnectionIndicator = function (jid) {
  9192. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9193. };
  9194. /**
  9195. * Hides all the indicators
  9196. */
  9197. my.onStatsStop = function () {
  9198. for(var video in remoteVideos) {
  9199. remoteVideos[video].hideIndicator();
  9200. }
  9201. localVideoThumbnail.hideIndicator();
  9202. };
  9203. my.participantLeft = function (jid) {
  9204. // Unlock large video
  9205. var resourceJid = Strophe.getResourceFromJid(jid);
  9206. if (focusedVideoResourceJid === resourceJid) {
  9207. console.info("Focused video owner has left the conference");
  9208. focusedVideoResourceJid = null;
  9209. }
  9210. if (currentDominantSpeaker === resourceJid)
  9211. {
  9212. console.info("Dominant speaker has left the conference");
  9213. currentDominantSpeaker = null;
  9214. }
  9215. var remoteVideo = remoteVideos[resourceJid];
  9216. if (remoteVideo) {
  9217. // Remove remote video
  9218. console.info("Removing remote video: " + resourceJid);
  9219. remoteVideo.remove();
  9220. delete remoteVideos[resourceJid];
  9221. } else {
  9222. console.warn("No remote video for " + resourceJid);
  9223. }
  9224. VideoLayout.resizeThumbnails();
  9225. };
  9226. my.onVideoTypeChanged = function (jid) {
  9227. LargeVideo.onVideoTypeChanged(jid);
  9228. };
  9229. my.showMore = function (jid) {
  9230. if (jid === 'local') {
  9231. localVideoThumbnail.connectionIndicator.showMore();
  9232. } else {
  9233. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9234. if (remoteVideo) {
  9235. remoteVideo.connectionIndicator.showMore();
  9236. } else {
  9237. console.info("Error - no remote video for jid: " + jid);
  9238. }
  9239. }
  9240. };
  9241. my.addPreziContainer = function (id) {
  9242. var container = RemoteVideo.createContainer(id);
  9243. VideoLayout.resizeThumbnails();
  9244. return container;
  9245. };
  9246. my.setLargeVideoVisible = function (isVisible) {
  9247. LargeVideo.setLargeVideoVisible(isVisible);
  9248. if(!isVisible && focusedVideoResourceJid) {
  9249. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9250. if(smallVideo) {
  9251. smallVideo.focus(false);
  9252. smallVideo.showAvatar();
  9253. }
  9254. focusedVideoResourceJid = null;
  9255. }
  9256. };
  9257. /**
  9258. * Resizes the video area
  9259. * @param callback a function to be called when the video space is
  9260. * resized.
  9261. */
  9262. my.resizeVideoArea = function(isVisible, callback) {
  9263. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9264. VideoLayout.resizeThumbnails(true);
  9265. };
  9266. my.getSmallVideo = function (resourceJid) {
  9267. if(resourceJid == APP.xmpp.myResource()) {
  9268. return localVideoThumbnail;
  9269. } else {
  9270. if(!remoteVideos[resourceJid])
  9271. return null;
  9272. return remoteVideos[resourceJid];
  9273. }
  9274. };
  9275. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9276. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9277. if(smallVideo)
  9278. smallVideo.avatarChanged(thumbUrl);
  9279. else
  9280. console.warn(
  9281. "Missed avatar update - no small video yet for " + resourceJid);
  9282. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9283. };
  9284. my.createEtherpadIframe = function(src, onloadHandler)
  9285. {
  9286. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9287. };
  9288. my.setLargeVideoState = function (state) {
  9289. LargeVideo.setState(state);
  9290. };
  9291. my.getLargeVideoState = function () {
  9292. return LargeVideo.getState();
  9293. };
  9294. my.setLargeVideoHover = function (inHandler, outHandler) {
  9295. LargeVideo.setHover(inHandler, outHandler);
  9296. };
  9297. /**
  9298. * Indicates that the video has been interrupted.
  9299. */
  9300. my.onVideoInterrupted = function () {
  9301. LargeVideo.enableVideoProblemFilter(true);
  9302. var reconnectingKey = "connection.RECONNECTING";
  9303. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9304. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9305. $('#videoConnectionMessage').css({display: "block"});
  9306. };
  9307. /**
  9308. * Indicates that the video has been restored.
  9309. */
  9310. my.onVideoRestored = function () {
  9311. LargeVideo.enableVideoProblemFilter(false);
  9312. $('#videoConnectionMessage').css({display: "none"});
  9313. };
  9314. return my;
  9315. }(VideoLayout || {}));
  9316. module.exports = VideoLayout;
  9317. },{"../../../service/RTC/MediaStreamTypes":106,"../../../service/UI/UIEvents":110,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  9318. //var nouns = [
  9319. //];
  9320. var pluralNouns = [
  9321. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9322. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9323. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9324. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9325. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9326. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9327. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9328. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9329. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9330. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9331. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9332. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9333. ];
  9334. //var places = [
  9335. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9336. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9337. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9338. // "Bridge"
  9339. //];
  9340. var verbs = [
  9341. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9342. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9343. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9344. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9345. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9346. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9347. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9348. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9349. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9350. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9351. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9352. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9353. ];
  9354. var adverbs = [
  9355. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9356. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9357. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9358. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9359. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9360. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9361. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9362. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9363. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9364. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9365. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9366. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9367. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9368. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9369. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9370. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9371. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9372. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9373. ];
  9374. var adjectives = [
  9375. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9376. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9377. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9378. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9379. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9380. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9381. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9382. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9383. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9384. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9385. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9386. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9387. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9388. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9389. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9390. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9391. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9392. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9393. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9394. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9395. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9396. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9397. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9398. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9399. "Zealous"
  9400. ];
  9401. //var pronouns = [
  9402. //];
  9403. //var conjunctions = [
  9404. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9405. //];
  9406. /*
  9407. * Maps a string (category name) to the array of words from that category.
  9408. */
  9409. var CATEGORIES =
  9410. {
  9411. //"_NOUN_": nouns,
  9412. "_PLURALNOUN_": pluralNouns,
  9413. //"_PLACE_": places,
  9414. "_VERB_": verbs,
  9415. "_ADVERB_": adverbs,
  9416. "_ADJECTIVE_": adjectives
  9417. //"_PRONOUN_": pronouns,
  9418. //"_CONJUNCTION_": conjunctions,
  9419. };
  9420. var PATTERNS = [
  9421. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9422. // BeautifulFungiOrSpaghetti
  9423. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9424. // AmazinglyScaryToy
  9425. //"_ADVERB__ADJECTIVE__NOUN_",
  9426. // NeitherTrashNorRifle
  9427. //"Neither_NOUN_Nor_NOUN_",
  9428. //"Either_NOUN_Or_NOUN_",
  9429. // EitherCopulateOrInvestigate
  9430. //"Either_VERB_Or_VERB_",
  9431. //"Neither_VERB_Nor_VERB_",
  9432. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9433. //"The_ADVERB__ADJECTIVE__NOUN_",
  9434. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9435. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9436. // WolvesComputeBadly
  9437. //"_PLURALNOUN__VERB__ADVERB_",
  9438. // UniteFacilitateAndMerge
  9439. //"_VERB__VERB_And_VERB_",
  9440. //NastyWitchesAtThePub
  9441. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9442. ];
  9443. /*
  9444. * Returns a random element from the array 'arr'
  9445. */
  9446. function randomElement(arr) {
  9447. return arr[Math.floor(Math.random() * arr.length)];
  9448. }
  9449. /*
  9450. * Returns true if the string 's' contains one of the
  9451. * template strings.
  9452. */
  9453. function hasTemplate(s) {
  9454. for (var template in CATEGORIES){
  9455. if (s.indexOf(template) >= 0){
  9456. return true;
  9457. }
  9458. }
  9459. }
  9460. /**
  9461. * Generates new room name.
  9462. */
  9463. var RoomNameGenerator = {
  9464. generateRoomWithoutSeparator: function() {
  9465. // Note that if more than one pattern is available, the choice of
  9466. // 'name' won't have a uniform distribution amongst all patterns (names
  9467. // from patterns with fewer options will have higher probability of
  9468. // being chosen that names from patterns with more options).
  9469. var name = randomElement(PATTERNS);
  9470. var word;
  9471. while (hasTemplate(name)) {
  9472. for (var template in CATEGORIES) {
  9473. word = randomElement(CATEGORIES[template]);
  9474. name = name.replace(template, word);
  9475. }
  9476. }
  9477. return name;
  9478. }
  9479. };
  9480. module.exports = RoomNameGenerator;
  9481. },{}],41:[function(require,module,exports){
  9482. /* global $, interfaceConfig */
  9483. var animateTimeout, updateTimeout;
  9484. var RoomNameGenerator = require("./RoomnameGenerator");
  9485. function enter_room() {
  9486. var val = $("#enter_room_field").val();
  9487. if(!val) {
  9488. val = $("#enter_room_field").attr("room_name");
  9489. }
  9490. if (val) {
  9491. window.location.pathname = "/" + val;
  9492. }
  9493. }
  9494. function animate(word) {
  9495. var currentVal = $("#enter_room_field").attr("placeholder");
  9496. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9497. animateTimeout = setTimeout(function() {
  9498. animate(word.substring(1, word.length))
  9499. }, 70);
  9500. }
  9501. function update_roomname() {
  9502. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9503. $("#enter_room_field").attr("room_name", word);
  9504. $("#enter_room_field").attr("placeholder", "");
  9505. clearTimeout(animateTimeout);
  9506. animate(word);
  9507. updateTimeout = setTimeout(update_roomname, 10000);
  9508. }
  9509. function setupWelcomePage() {
  9510. $("#videoconference_page").hide();
  9511. $("#domain_name").text(
  9512. window.location.protocol + "//" + window.location.host + "/");
  9513. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9514. var leftWatermarkDiv =
  9515. $("#welcome_page_header div[class='watermark leftwatermark']");
  9516. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9517. leftWatermarkDiv.css({display: 'block'});
  9518. leftWatermarkDiv.parent().get(0).href =
  9519. interfaceConfig.JITSI_WATERMARK_LINK;
  9520. }
  9521. }
  9522. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9523. var rightWatermarkDiv =
  9524. $("#welcome_page_header div[class='watermark rightwatermark']");
  9525. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9526. rightWatermarkDiv.css({display: 'block'});
  9527. rightWatermarkDiv.parent().get(0).href =
  9528. interfaceConfig.BRAND_WATERMARK_LINK;
  9529. rightWatermarkDiv.get(0).style.backgroundImage =
  9530. "url(images/rightwatermark.png)";
  9531. }
  9532. }
  9533. if (interfaceConfig.SHOW_POWERED_BY) {
  9534. $("#welcome_page_header>a[class='poweredby']")
  9535. .css({display: 'block'});
  9536. }
  9537. $("#enter_room_button").click(function() {
  9538. enter_room();
  9539. });
  9540. $("#enter_room_field").keydown(function (event) {
  9541. if (event.keyCode === 13 /* enter */) {
  9542. enter_room();
  9543. }
  9544. });
  9545. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9546. var updateTimeout;
  9547. var animateTimeout;
  9548. var selector = $("#reload_roomname");
  9549. selector.click(function () {
  9550. clearTimeout(updateTimeout);
  9551. clearTimeout(animateTimeout);
  9552. update_roomname();
  9553. });
  9554. selector.show();
  9555. update_roomname();
  9556. }
  9557. $("#disable_welcome").click(function () {
  9558. window.localStorage.welcomePageDisabled =
  9559. $("#disable_welcome").is(":checked");
  9560. });
  9561. }
  9562. module.exports = setupWelcomePage;
  9563. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9564. /* global $, $iq, config */
  9565. var params = {};
  9566. function getConfigParamsFromUrl() {
  9567. if(!location.hash)
  9568. return {};
  9569. var hash = location.hash.substr(1);
  9570. var result = {};
  9571. hash.split("&").forEach(function(part) {
  9572. var item = part.split("=");
  9573. result[item[0]] = JSON.parse(
  9574. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9575. });
  9576. return result;
  9577. }
  9578. params = getConfigParamsFromUrl();
  9579. var URLProcessor = {
  9580. setConfigParametersFromUrl: function () {
  9581. for(var k in params)
  9582. {
  9583. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9584. continue;
  9585. var v = params[k];
  9586. var confKey = k.substr(7);
  9587. if(config[confKey] && typeof config[confKey] !== typeof v)
  9588. {
  9589. console.warn("The type of " + k +
  9590. " is wrong. That parameter won't be updated in config.js.");
  9591. continue;
  9592. }
  9593. config[confKey] = v;
  9594. }
  9595. }
  9596. };
  9597. module.exports = URLProcessor;
  9598. },{}],43:[function(require,module,exports){
  9599. /* global APP, require */
  9600. var EventEmitter = require("events");
  9601. var eventEmitter = new EventEmitter();
  9602. var CQEvents = require("../../service/connectionquality/CQEvents");
  9603. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9604. /**
  9605. * local stats
  9606. * @type {{}}
  9607. */
  9608. var stats = {};
  9609. /**
  9610. * remote stats
  9611. * @type {{}}
  9612. */
  9613. var remoteStats = {};
  9614. /**
  9615. * Interval for sending statistics to other participants
  9616. * @type {null}
  9617. */
  9618. var sendIntervalId = null;
  9619. /**
  9620. * Start statistics sending.
  9621. */
  9622. function startSendingStats() {
  9623. sendStats();
  9624. sendIntervalId = setInterval(sendStats, 10000);
  9625. }
  9626. /**
  9627. * Sends statistics to other participants
  9628. */
  9629. function sendStats() {
  9630. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9631. }
  9632. /**
  9633. * Converts statistics to format for sending through XMPP
  9634. * @param stats the statistics
  9635. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9636. */
  9637. function convertToMUCStats(stats) {
  9638. return {
  9639. "bitrate_download": stats.bitrate.download,
  9640. "bitrate_upload": stats.bitrate.upload,
  9641. "packetLoss_total": stats.packetLoss.total,
  9642. "packetLoss_download": stats.packetLoss.download,
  9643. "packetLoss_upload": stats.packetLoss.upload
  9644. };
  9645. }
  9646. /**
  9647. * Converts statistics to format used by VideoLayout
  9648. * @param stats
  9649. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9650. */
  9651. function parseMUCStats(stats) {
  9652. return {
  9653. bitrate: {
  9654. download: stats.bitrate_download,
  9655. upload: stats.bitrate_upload
  9656. },
  9657. packetLoss: {
  9658. total: stats.packetLoss_total,
  9659. download: stats.packetLoss_download,
  9660. upload: stats.packetLoss_upload
  9661. }
  9662. };
  9663. }
  9664. var ConnectionQuality = {
  9665. init: function () {
  9666. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9667. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9668. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9669. },
  9670. /**
  9671. * Updates the local statistics
  9672. * @param data new statistics
  9673. */
  9674. updateLocalStats: function (data) {
  9675. stats = data;
  9676. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9677. if (sendIntervalId == null) {
  9678. startSendingStats();
  9679. }
  9680. },
  9681. /**
  9682. * Updates remote statistics
  9683. * @param jid the jid associated with the statistics
  9684. * @param data the statistics
  9685. */
  9686. updateRemoteStats: function (jid, data) {
  9687. if (data == null || data.packetLoss_total == null) {
  9688. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9689. return;
  9690. }
  9691. remoteStats[jid] = parseMUCStats(data);
  9692. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9693. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9694. },
  9695. /**
  9696. * Stops statistics sending.
  9697. */
  9698. stopSendingStats: function () {
  9699. clearInterval(sendIntervalId);
  9700. sendIntervalId = null;
  9701. //notify UI about stopping statistics gathering
  9702. eventEmitter.emit(CQEvents.STOP);
  9703. },
  9704. /**
  9705. * Returns the local statistics.
  9706. */
  9707. getStats: function () {
  9708. return stats;
  9709. },
  9710. addListener: function (type, listener) {
  9711. eventEmitter.on(type, listener);
  9712. }
  9713. };
  9714. module.exports = ConnectionQuality;
  9715. },{"../../service/connectionquality/CQEvents":112,"../../service/xmpp/XMPPEvents":116,"events":117}],44:[function(require,module,exports){
  9716. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9717. getUserMediaWithConstraints */
  9718. /**
  9719. * Indicates that desktop stream is currently in use(for toggle purpose).
  9720. * @type {boolean}
  9721. */
  9722. var isUsingScreenStream = false;
  9723. /**
  9724. * Indicates that switch stream operation is in progress and prevent from
  9725. * triggering new events.
  9726. * @type {boolean}
  9727. */
  9728. var switchInProgress = false;
  9729. /**
  9730. * Method used to get screen sharing stream.
  9731. *
  9732. * @type {function (stream_callback, failure_callback}
  9733. */
  9734. var obtainDesktopStream = null;
  9735. /**
  9736. * Indicates whether desktop sharing extension is installed.
  9737. * @type {boolean}
  9738. */
  9739. var extInstalled = false;
  9740. /**
  9741. * Indicates whether update of desktop sharing extension is required.
  9742. * @type {boolean}
  9743. */
  9744. var extUpdateRequired = false;
  9745. var AdapterJS = require("../RTC/adapter.screenshare");
  9746. var EventEmitter = require("events");
  9747. var eventEmitter = new EventEmitter();
  9748. var DesktopSharingEventTypes
  9749. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9750. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9751. var RTCEvents = require("../../service/RTC/RTCEvents");
  9752. /**
  9753. * Method obtains desktop stream from WebRTC 'screen' source.
  9754. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9755. */
  9756. function obtainWebRTCScreen(streamCallback, failCallback) {
  9757. APP.RTC.getUserMediaWithConstraints(
  9758. ['screen'],
  9759. streamCallback,
  9760. failCallback
  9761. );
  9762. }
  9763. /**
  9764. * Constructs inline install URL for Chrome desktop streaming extension.
  9765. * The 'chromeExtensionId' must be defined in config.js.
  9766. * @returns {string}
  9767. */
  9768. function getWebStoreInstallUrl()
  9769. {
  9770. return "https://chrome.google.com/webstore/detail/" +
  9771. config.chromeExtensionId;
  9772. }
  9773. /**
  9774. * Checks whether extension update is required.
  9775. * @param minVersion minimal required version
  9776. * @param extVersion current extension version
  9777. * @returns {boolean}
  9778. */
  9779. function isUpdateRequired(minVersion, extVersion)
  9780. {
  9781. try
  9782. {
  9783. var s1 = minVersion.split('.');
  9784. var s2 = extVersion.split('.');
  9785. var len = Math.max(s1.length, s2.length);
  9786. for (var i = 0; i < len; i++)
  9787. {
  9788. var n1 = 0,
  9789. n2 = 0;
  9790. if (i < s1.length)
  9791. n1 = parseInt(s1[i]);
  9792. if (i < s2.length)
  9793. n2 = parseInt(s2[i]);
  9794. if (isNaN(n1) || isNaN(n2))
  9795. {
  9796. return true;
  9797. }
  9798. else if (n1 !== n2)
  9799. {
  9800. return n1 > n2;
  9801. }
  9802. }
  9803. // will happen if boths version has identical numbers in
  9804. // their components (even if one of them is longer, has more components)
  9805. return false;
  9806. }
  9807. catch (e)
  9808. {
  9809. console.error("Failed to parse extension version", e);
  9810. APP.UI.messageHandler.showError("dialog.error",
  9811. "dialog.detectext");
  9812. return true;
  9813. }
  9814. }
  9815. function checkChromeExtInstalled(callback) {
  9816. if (!chrome.runtime) {
  9817. // No API, so no extension for sure
  9818. callback(false, false);
  9819. return;
  9820. }
  9821. chrome.runtime.sendMessage(
  9822. config.chromeExtensionId,
  9823. { getVersion: true },
  9824. function (response) {
  9825. if (!response || !response.version) {
  9826. // Communication failure - assume that no endpoint exists
  9827. console.warn(
  9828. "Extension not installed?: ", chrome.runtime.lastError);
  9829. callback(false, false);
  9830. return;
  9831. }
  9832. // Check installed extension version
  9833. var extVersion = response.version;
  9834. console.log('Extension version is: ' + extVersion);
  9835. var updateRequired
  9836. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  9837. callback(!updateRequired, updateRequired);
  9838. }
  9839. );
  9840. }
  9841. function doGetStreamFromExtension(streamCallback, failCallback) {
  9842. // Sends 'getStream' msg to the extension.
  9843. // Extension id must be defined in the config.
  9844. chrome.runtime.sendMessage(
  9845. config.chromeExtensionId,
  9846. { getStream: true, sources: config.desktopSharingSources },
  9847. function (response) {
  9848. if (!response) {
  9849. failCallback(chrome.runtime.lastError);
  9850. return;
  9851. }
  9852. console.log("Response from extension: " + response);
  9853. if (response.streamId) {
  9854. APP.RTC.getUserMediaWithConstraints(
  9855. ['desktop'],
  9856. function (stream) {
  9857. streamCallback(stream);
  9858. },
  9859. failCallback,
  9860. null, null, null,
  9861. response.streamId);
  9862. } else {
  9863. failCallback("Extension failed to get the stream");
  9864. }
  9865. }
  9866. );
  9867. }
  9868. /**
  9869. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  9870. * stream for returned stream token.
  9871. */
  9872. function obtainScreenFromExtension(streamCallback, failCallback) {
  9873. if (extInstalled) {
  9874. doGetStreamFromExtension(streamCallback, failCallback);
  9875. } else {
  9876. if (extUpdateRequired) {
  9877. alert(
  9878. 'Jitsi Desktop Streamer requires update. ' +
  9879. 'Changes will take effect after next Chrome restart.');
  9880. }
  9881. chrome.webstore.install(
  9882. getWebStoreInstallUrl(),
  9883. function (arg) {
  9884. console.log("Extension installed successfully", arg);
  9885. extInstalled = true;
  9886. // We need to give a moment for the endpoint to become available
  9887. window.setTimeout(function () {
  9888. doGetStreamFromExtension(streamCallback, failCallback);
  9889. }, 500);
  9890. },
  9891. function (arg) {
  9892. console.log("Failed to install the extension", arg);
  9893. failCallback(arg);
  9894. APP.UI.messageHandler.showError("dialog.error",
  9895. "dialog.failtoinstall");
  9896. }
  9897. );
  9898. }
  9899. }
  9900. /**
  9901. * Call this method to toggle desktop sharing feature.
  9902. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  9903. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  9904. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  9905. * enabled), pass any other string or nothing in order to disable this
  9906. * feature completely.
  9907. */
  9908. function setDesktopSharing(method) {
  9909. obtainDesktopStream = null;
  9910. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  9911. // care about 'method' parameter
  9912. if (RTCBrowserType.isTemasysPluginUsed()) {
  9913. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  9914. console.info("Screensharing not supported by this plugin version");
  9915. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  9916. console.info(
  9917. "Screensharing not available with Temasys plugin on this site");
  9918. } else {
  9919. obtainDesktopStream = obtainWebRTCScreen;
  9920. console.info("Using Temasys plugin for desktop sharing");
  9921. }
  9922. } else if (RTCBrowserType.isChrome()) {
  9923. if (method == "ext") {
  9924. if (RTCBrowserType.getChromeVersion() >= 34) {
  9925. obtainDesktopStream = obtainScreenFromExtension;
  9926. console.info("Using Chrome extension for desktop sharing");
  9927. initChromeExtension();
  9928. } else {
  9929. console.info("Chrome extension not supported until ver 34");
  9930. }
  9931. } else if (method == "webrtc") {
  9932. obtainDesktopStream = obtainWebRTCScreen;
  9933. console.info("Using Chrome WebRTC for desktop sharing");
  9934. }
  9935. }
  9936. if (!obtainDesktopStream) {
  9937. console.info("Desktop sharing disabled");
  9938. }
  9939. }
  9940. /**
  9941. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  9942. * config.js to support inline installs. Host site must be selected as main
  9943. * website of published extension.
  9944. */
  9945. function initInlineInstalls()
  9946. {
  9947. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  9948. }
  9949. function initChromeExtension() {
  9950. // Initialize Chrome extension inline installs
  9951. initInlineInstalls();
  9952. // Check if extension is installed
  9953. checkChromeExtInstalled(function (installed, updateRequired) {
  9954. extInstalled = installed;
  9955. extUpdateRequired = updateRequired;
  9956. console.info(
  9957. "Chrome extension installed: " + extInstalled +
  9958. " updateRequired: " + extUpdateRequired);
  9959. });
  9960. }
  9961. function getVideoStreamFailed(error) {
  9962. console.error("Failed to obtain the stream to switch to", error);
  9963. switchInProgress = false;
  9964. isUsingScreenStream = false;
  9965. newStreamCreated(null);
  9966. }
  9967. function getDesktopStreamFailed(error) {
  9968. console.error("Failed to obtain the stream to switch to", error);
  9969. switchInProgress = false;
  9970. }
  9971. function streamSwitchDone() {
  9972. switchInProgress = false;
  9973. eventEmitter.emit(
  9974. DesktopSharingEventTypes.SWITCHING_DONE,
  9975. isUsingScreenStream);
  9976. }
  9977. function newStreamCreated(stream)
  9978. {
  9979. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  9980. stream, isUsingScreenStream, streamSwitchDone);
  9981. }
  9982. function onEndedHandler(stream) {
  9983. if (!switchInProgress && isUsingScreenStream) {
  9984. APP.desktopsharing.toggleScreenSharing();
  9985. }
  9986. //FIXME: to be verified
  9987. if (stream.removeEventListener) {
  9988. stream.removeEventListener('ended', onEndedHandler);
  9989. } else {
  9990. stream.detachEvent('ended', onEndedHandler);
  9991. }
  9992. }
  9993. // Called when RTC finishes initialization
  9994. function onWebRtcReady() {
  9995. setDesktopSharing(config.desktopSharing);
  9996. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  9997. }
  9998. module.exports = {
  9999. isUsingScreenStream: function () {
  10000. return isUsingScreenStream;
  10001. },
  10002. /**
  10003. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10004. * and enabled.
  10005. */
  10006. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10007. init: function () {
  10008. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10009. },
  10010. addListener: function (listener, type)
  10011. {
  10012. eventEmitter.on(type, listener);
  10013. },
  10014. removeListener: function (listener, type) {
  10015. eventEmitter.removeListener(type, listener);
  10016. },
  10017. /*
  10018. * Toggles screen sharing.
  10019. */
  10020. toggleScreenSharing: function () {
  10021. if (switchInProgress || !obtainDesktopStream) {
  10022. console.warn("Switch in progress or no method defined");
  10023. return;
  10024. }
  10025. switchInProgress = true;
  10026. if (!isUsingScreenStream)
  10027. {
  10028. // Switch to desktop stream
  10029. obtainDesktopStream(
  10030. function (stream) {
  10031. // We now use screen stream
  10032. isUsingScreenStream = true;
  10033. // Hook 'ended' event to restore camera
  10034. // when screen stream stops
  10035. //FIXME: to be verified
  10036. if (stream.addEventListener) {
  10037. stream.addEventListener('ended', function () {
  10038. onEndedHandler(stream);
  10039. });
  10040. } else {
  10041. stream.attachEvent('ended', function () {
  10042. onEndedHandler(stream);
  10043. });
  10044. }
  10045. newStreamCreated(stream);
  10046. },
  10047. getDesktopStreamFailed);
  10048. } else {
  10049. // Disable screen stream
  10050. APP.RTC.getUserMediaWithConstraints(
  10051. ['video'],
  10052. function (stream) {
  10053. // We are now using camera stream
  10054. isUsingScreenStream = false;
  10055. newStreamCreated(stream);
  10056. },
  10057. getVideoStreamFailed, config.resolution || '360'
  10058. );
  10059. }
  10060. }
  10061. };
  10062. },{"../../service/RTC/RTCEvents":107,"../../service/desktopsharing/DesktopSharingEventTypes":113,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":117}],45:[function(require,module,exports){
  10063. /* global APP, $ */
  10064. //maps keycode to character, id of popover for given function and function
  10065. var shortcuts = {};
  10066. function initShortcutHandlers() {
  10067. shortcuts = {
  10068. 67: {
  10069. character: "C",
  10070. id: "toggleChatPopover",
  10071. function: APP.UI.toggleChat
  10072. },
  10073. 70: {
  10074. character: "F",
  10075. id: "filmstripPopover",
  10076. function: APP.UI.toggleFilmStrip
  10077. },
  10078. 77: {
  10079. character: "M",
  10080. id: "mutePopover",
  10081. function: APP.UI.toggleAudio
  10082. },
  10083. 84: {
  10084. character: "T",
  10085. function: function() {
  10086. if(!APP.RTC.localAudio.isMuted()) {
  10087. APP.UI.toggleAudio();
  10088. }
  10089. }
  10090. },
  10091. 86: {
  10092. character: "V",
  10093. id: "toggleVideoPopover",
  10094. function: APP.UI.toggleVideo
  10095. }
  10096. };
  10097. }
  10098. var KeyboardShortcut = {
  10099. init: function () {
  10100. initShortcutHandlers();
  10101. window.onkeyup = function(e) {
  10102. var keycode = e.which;
  10103. if(!($(":focus").is("input[type=text]") ||
  10104. $(":focus").is("input[type=password]") ||
  10105. $(":focus").is("textarea"))) {
  10106. if (typeof shortcuts[keycode] === "object") {
  10107. shortcuts[keycode].function();
  10108. }
  10109. else if (keycode >= "0".charCodeAt(0) &&
  10110. keycode <= "9".charCodeAt(0)) {
  10111. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10112. }
  10113. //esc while the smileys are visible hides them
  10114. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10115. APP.UI.toggleSmileys();
  10116. }
  10117. };
  10118. window.onkeydown = function(e) {
  10119. if(!($(":focus").is("input[type=text]") ||
  10120. $(":focus").is("input[type=password]") ||
  10121. $(":focus").is("textarea"))) {
  10122. if(e.which === "T".charCodeAt(0)) {
  10123. if(APP.RTC.localAudio.isMuted()) {
  10124. APP.UI.toggleAudio();
  10125. }
  10126. }
  10127. }
  10128. };
  10129. var self = this;
  10130. $('body').popover({ selector: '[data-toggle=popover]',
  10131. trigger: 'click hover',
  10132. content: function() {
  10133. return this.getAttribute("content") +
  10134. self.getShortcut(this.getAttribute("shortcut"));
  10135. }
  10136. });
  10137. },
  10138. /**
  10139. *
  10140. * @param id indicates the popover associated with the shortcut
  10141. * @returns {string} the keyboard shortcut used for the id given
  10142. */
  10143. getShortcut: function (id) {
  10144. for (var keycode in shortcuts) {
  10145. if (shortcuts.hasOwnProperty(keycode)) {
  10146. if (shortcuts[keycode].id === id) {
  10147. return " (" + shortcuts[keycode].character + ")";
  10148. }
  10149. }
  10150. }
  10151. return "";
  10152. }
  10153. };
  10154. module.exports = KeyboardShortcut;
  10155. },{}],46:[function(require,module,exports){
  10156. /* global APP, require, $ */
  10157. /**
  10158. * This module is meant to (eventually) contain and manage all information
  10159. * about members/participants of the conference, so that other modules don't
  10160. * have to do it on their own, and so that other modules can access members'
  10161. * information from a single place.
  10162. *
  10163. * Currently this module only manages information about the support of jingle
  10164. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10165. * be added as needed.
  10166. */
  10167. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10168. var Events = require("../../service/members/Events");
  10169. var EventEmitter = require("events");
  10170. var eventEmitter = new EventEmitter();
  10171. /**
  10172. * The actual container.
  10173. */
  10174. var members = {};
  10175. /**
  10176. * There is at least one member that supports DTMF (i.e. is jigasi).
  10177. */
  10178. var atLeastOneDtmf = false;
  10179. function registerListeners() {
  10180. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10181. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10182. }
  10183. /**
  10184. * Handles a new member joining the MUC.
  10185. */
  10186. function onMucMemberJoined(jid, id, displayName) {
  10187. var member = {
  10188. displayName: displayName
  10189. };
  10190. APP.xmpp.getConnection().disco.info(
  10191. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10192. members[jid] = member;
  10193. }
  10194. /**
  10195. * Handles a member leaving the MUC.
  10196. */
  10197. function onMucMemberLeft(jid) {
  10198. delete members[jid];
  10199. updateAtLeastOneDtmf();
  10200. }
  10201. /**
  10202. * Handles the reception of a disco#info packet from a particular JID.
  10203. * @param jid the JID sending the packet.
  10204. * @param iq the packet.
  10205. */
  10206. function onDiscoInfoReceived(jid, iq) {
  10207. if (!members[jid])
  10208. return;
  10209. var supportsDtmf
  10210. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10211. updateDtmf(jid, supportsDtmf);
  10212. }
  10213. /**
  10214. * Updates the 'supportsDtmf' field for a member.
  10215. * @param jid the jid of the member.
  10216. * @param newValue the new value for the 'supportsDtmf' field.
  10217. */
  10218. function updateDtmf(jid, newValue) {
  10219. var oldValue = members[jid].supportsDtmf;
  10220. members[jid].supportsDtmf = newValue;
  10221. if (newValue != oldValue) {
  10222. updateAtLeastOneDtmf();
  10223. }
  10224. }
  10225. /**
  10226. * Checks each member's 'supportsDtmf' field and updates
  10227. * 'atLastOneSupportsDtmf'.
  10228. */
  10229. function updateAtLeastOneDtmf() {
  10230. var newAtLeastOneDtmf = false;
  10231. for (var key in members) {
  10232. if (typeof members[key].supportsDtmf !== 'undefined'
  10233. && members[key].supportsDtmf) {
  10234. newAtLeastOneDtmf= true;
  10235. break;
  10236. }
  10237. }
  10238. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10239. atLeastOneDtmf = newAtLeastOneDtmf;
  10240. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10241. }
  10242. }
  10243. /**
  10244. * Exported interface.
  10245. */
  10246. var Members = {
  10247. start: function() {
  10248. registerListeners();
  10249. },
  10250. addListener: function(type, listener) {
  10251. eventEmitter.on(type, listener);
  10252. },
  10253. removeListener: function (type, listener) {
  10254. eventEmitter.removeListener(type, listener);
  10255. },
  10256. size: function () {
  10257. return Object.keys(members).length;
  10258. },
  10259. getMembers: function () {
  10260. return members;
  10261. }
  10262. };
  10263. module.exports = Members;
  10264. },{"../../service/members/Events":114,"../../service/xmpp/XMPPEvents":116,"events":117}],47:[function(require,module,exports){
  10265. var email = '';
  10266. var displayName = '';
  10267. var userId;
  10268. var language = null;
  10269. function supportsLocalStorage() {
  10270. try {
  10271. return 'localStorage' in window && window.localStorage !== null;
  10272. } catch (e) {
  10273. console.log("localstorage is not supported");
  10274. return false;
  10275. }
  10276. }
  10277. function generateUniqueId() {
  10278. function _p8() {
  10279. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10280. }
  10281. return _p8() + _p8() + _p8() + _p8();
  10282. }
  10283. if (supportsLocalStorage()) {
  10284. if (!window.localStorage.jitsiMeetId) {
  10285. window.localStorage.jitsiMeetId = generateUniqueId();
  10286. console.log("generated id", window.localStorage.jitsiMeetId);
  10287. }
  10288. userId = window.localStorage.jitsiMeetId || '';
  10289. email = window.localStorage.email || '';
  10290. displayName = window.localStorage.displayname || '';
  10291. language = window.localStorage.language;
  10292. } else {
  10293. console.log("local storage is not supported");
  10294. userId = generateUniqueId();
  10295. }
  10296. var Settings = {
  10297. setDisplayName: function (newDisplayName) {
  10298. displayName = newDisplayName;
  10299. window.localStorage.displayname = displayName;
  10300. return displayName;
  10301. },
  10302. setEmail: function (newEmail) {
  10303. email = newEmail;
  10304. window.localStorage.email = newEmail;
  10305. return email;
  10306. },
  10307. getSettings: function () {
  10308. return {
  10309. email: email,
  10310. displayName: displayName,
  10311. uid: userId,
  10312. language: language
  10313. };
  10314. },
  10315. setLanguage: function (lang) {
  10316. language = lang;
  10317. window.localStorage.language = lang;
  10318. }
  10319. };
  10320. module.exports = Settings;
  10321. },{}],48:[function(require,module,exports){
  10322. /* global config, $, APP, Strophe, callstats */
  10323. var callStats = null;
  10324. function initCallback (err, msg) {
  10325. console.log("Initializing Status: err="+err+" msg="+msg);
  10326. }
  10327. var CallStats = {
  10328. init: function (jingleSession) {
  10329. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10330. return;
  10331. callStats = new callstats($,io,jsSHA);
  10332. this.session = jingleSession;
  10333. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10334. this.userID = APP.xmpp.myResource();
  10335. var location = window.location;
  10336. this.confID = location.protocol + "//" +
  10337. location.hostname + location.pathname;
  10338. //userID is generated or given by the origin server
  10339. callStats.initialize(config.callStatsID,
  10340. config.callStatsSecret,
  10341. this.userID,
  10342. initCallback);
  10343. var usage = callStats.fabricUsage.unbundled;
  10344. if(config.useBundle)
  10345. usage = callStats.fabricUsage.multiplex;
  10346. callStats.addNewFabric(this.peerconnection,
  10347. Strophe.getResourceFromJid(jingleSession.peerjid),
  10348. usage,
  10349. this.confID,
  10350. this.pcCallback.bind(this));
  10351. },
  10352. pcCallback: function (err, msg) {
  10353. if (!callStats)
  10354. return;
  10355. console.log("Monitoring status: "+ err + " msg: " + msg);
  10356. callStats.sendFabricEvent(this.peerconnection,
  10357. callStats.fabricEvent.fabricSetup, this.confID);
  10358. },
  10359. sendMuteEvent: function (mute, type) {
  10360. if (!callStats)
  10361. return;
  10362. var event = null;
  10363. if (type === "video") {
  10364. event = (mute? callStats.fabricEvent.videoPause :
  10365. callStats.fabricEvent.videoResume);
  10366. }
  10367. else {
  10368. event = (mute? callStats.fabricEvent.audioMute :
  10369. callStats.fabricEvent.audioUnmute);
  10370. }
  10371. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10372. },
  10373. sendTerminateEvent: function () {
  10374. if(!callStats) {
  10375. return;
  10376. }
  10377. callStats.sendFabricEvent(this.peerconnection,
  10378. callStats.fabricEvent.fabricTerminated, this.confID);
  10379. },
  10380. sendSetupFailedEvent: function () {
  10381. if(!callStats) {
  10382. return;
  10383. }
  10384. callStats.sendFabricEvent(this.peerconnection,
  10385. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10386. }
  10387. };
  10388. module.exports = CallStats;
  10389. },{}],49:[function(require,module,exports){
  10390. /* global config */
  10391. /**
  10392. * Provides statistics for the local stream.
  10393. */
  10394. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10395. /**
  10396. * Size of the webaudio analyzer buffer.
  10397. * @type {number}
  10398. */
  10399. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10400. /**
  10401. * Value of the webaudio analyzer smoothing time parameter.
  10402. * @type {number}
  10403. */
  10404. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10405. /**
  10406. * Converts time domain data array to audio level.
  10407. * @param samples the time domain data array.
  10408. * @returns {number} the audio level
  10409. */
  10410. function timeDomainDataToAudioLevel(samples) {
  10411. var maxVolume = 0;
  10412. var length = samples.length;
  10413. for (var i = 0; i < length; i++) {
  10414. if (maxVolume < samples[i])
  10415. maxVolume = samples[i];
  10416. }
  10417. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10418. }
  10419. /**
  10420. * Animates audio level change
  10421. * @param newLevel the new audio level
  10422. * @param lastLevel the last audio level
  10423. * @returns {Number} the audio level to be set
  10424. */
  10425. function animateLevel(newLevel, lastLevel) {
  10426. var value = 0;
  10427. var diff = lastLevel - newLevel;
  10428. if(diff > 0.2) {
  10429. value = lastLevel - 0.2;
  10430. }
  10431. else if(diff < -0.4) {
  10432. value = lastLevel + 0.4;
  10433. }
  10434. else {
  10435. value = newLevel;
  10436. }
  10437. return parseFloat(value.toFixed(3));
  10438. }
  10439. /**
  10440. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10441. *
  10442. * @param stream the local stream
  10443. * @param interval stats refresh interval given in ms.
  10444. * @constructor
  10445. */
  10446. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10447. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10448. this.stream = stream;
  10449. this.intervalId = null;
  10450. this.intervalMilis = interval;
  10451. this.eventEmitter = eventEmitter;
  10452. this.audioLevel = 0;
  10453. this.statisticsService = statisticsService;
  10454. }
  10455. /**
  10456. * Starts the collecting the statistics.
  10457. */
  10458. LocalStatsCollector.prototype.start = function () {
  10459. if (config.disableAudioLevels || !window.AudioContext ||
  10460. RTCBrowserType.isTemasysPluginUsed())
  10461. return;
  10462. var context = new AudioContext();
  10463. var analyser = context.createAnalyser();
  10464. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10465. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10466. var source = context.createMediaStreamSource(this.stream);
  10467. source.connect(analyser);
  10468. var self = this;
  10469. this.intervalId = setInterval(
  10470. function () {
  10471. var array = new Uint8Array(analyser.frequencyBinCount);
  10472. analyser.getByteTimeDomainData(array);
  10473. var audioLevel = timeDomainDataToAudioLevel(array);
  10474. if (audioLevel != self.audioLevel) {
  10475. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10476. self.eventEmitter.emit(
  10477. "statistics.audioLevel",
  10478. self.statisticsService.LOCAL_JID,
  10479. self.audioLevel);
  10480. }
  10481. },
  10482. this.intervalMilis
  10483. );
  10484. };
  10485. /**
  10486. * Stops collecting the statistics.
  10487. */
  10488. LocalStatsCollector.prototype.stop = function () {
  10489. if (this.intervalId) {
  10490. clearInterval(this.intervalId);
  10491. this.intervalId = null;
  10492. }
  10493. };
  10494. module.exports = LocalStatsCollector;
  10495. },{"../RTC/RTCBrowserType":8}],50:[function(require,module,exports){
  10496. /* global require, ssrc2jid */
  10497. /* jshint -W117 */
  10498. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10499. /* Whether we support the browser we are running into for logging statistics */
  10500. var browserSupported = RTCBrowserType.isChrome() ||
  10501. RTCBrowserType.isChrome();
  10502. /**
  10503. * Calculates packet lost percent using the number of lost packets and the
  10504. * number of all packet.
  10505. * @param lostPackets the number of lost packets
  10506. * @param totalPackets the number of all packets.
  10507. * @returns {number} packet loss percent
  10508. */
  10509. function calculatePacketLoss(lostPackets, totalPackets) {
  10510. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10511. return 0;
  10512. return Math.round((lostPackets/totalPackets)*100);
  10513. }
  10514. function getStatValue(item, name) {
  10515. var browserType = RTCBrowserType.getBrowserType();
  10516. if (!keyMap[browserType][name])
  10517. throw "The property isn't supported!";
  10518. var key = keyMap[browserType][name];
  10519. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10520. item.stat(key) : item[key];
  10521. }
  10522. /**
  10523. * Peer statistics data holder.
  10524. * @constructor
  10525. */
  10526. function PeerStats()
  10527. {
  10528. this.ssrc2Loss = {};
  10529. this.ssrc2AudioLevel = {};
  10530. this.ssrc2bitrate = {};
  10531. this.ssrc2resolution = {};
  10532. }
  10533. /**
  10534. * The bandwidth
  10535. * @type {{}}
  10536. */
  10537. PeerStats.bandwidth = {};
  10538. /**
  10539. * The bit rate
  10540. * @type {{}}
  10541. */
  10542. PeerStats.bitrate = {};
  10543. /**
  10544. * The packet loss rate
  10545. * @type {{}}
  10546. */
  10547. PeerStats.packetLoss = null;
  10548. /**
  10549. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10550. * represented by this instance.
  10551. * @param ssrc audio or video RTP stream SSRC.
  10552. * @param lossRate new packet loss rate value to be set.
  10553. */
  10554. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10555. {
  10556. this.ssrc2Loss[ssrc] = lossRate;
  10557. };
  10558. /**
  10559. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10560. * represented by this instance.
  10561. * @param ssrc audio or video RTP stream SSRC.
  10562. * @param resolution new resolution value to be set.
  10563. */
  10564. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10565. {
  10566. if(resolution === null && this.ssrc2resolution[ssrc])
  10567. {
  10568. delete this.ssrc2resolution[ssrc];
  10569. }
  10570. else if(resolution !== null)
  10571. this.ssrc2resolution[ssrc] = resolution;
  10572. };
  10573. /**
  10574. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10575. * represented by this instance.
  10576. * @param ssrc audio or video RTP stream SSRC.
  10577. * @param bitrate new bitrate value to be set.
  10578. */
  10579. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10580. {
  10581. if(this.ssrc2bitrate[ssrc])
  10582. {
  10583. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10584. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10585. }
  10586. else {
  10587. this.ssrc2bitrate[ssrc] = bitrate;
  10588. }
  10589. };
  10590. /**
  10591. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10592. * the stream which belongs to the peer represented by this instance.
  10593. * @param ssrc RTP stream SSRC for which current audio level value will be
  10594. * updated.
  10595. * @param audioLevel the new audio level value to be set. Value is truncated to
  10596. * fit the range from 0 to 1.
  10597. */
  10598. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10599. {
  10600. // Range limit 0 - 1
  10601. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10602. };
  10603. function formatAudioLevel(audioLevel) {
  10604. return Math.min(Math.max(audioLevel, 0), 1);
  10605. }
  10606. /**
  10607. * Array with the transport information.
  10608. * @type {Array}
  10609. */
  10610. PeerStats.transport = [];
  10611. /**
  10612. * <tt>StatsCollector</tt> registers for stats updates of given
  10613. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10614. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10615. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10616. * instance as an event source.
  10617. *
  10618. * @param peerconnection webRTC peer connection object.
  10619. * @param interval stats refresh interval given in ms.
  10620. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10621. * called on stats update.
  10622. * @constructor
  10623. */
  10624. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10625. {
  10626. this.peerconnection = peerconnection;
  10627. this.baselineAudioLevelsReport = null;
  10628. this.currentAudioLevelsReport = null;
  10629. this.currentStatsReport = null;
  10630. this.baselineStatsReport = null;
  10631. this.audioLevelsIntervalId = null;
  10632. this.eventEmitter = eventEmitter;
  10633. /**
  10634. * Gather PeerConnection stats once every this many milliseconds.
  10635. */
  10636. this.GATHER_INTERVAL = 15000;
  10637. /**
  10638. * Log stats via the focus once every this many milliseconds.
  10639. */
  10640. this.LOG_INTERVAL = 60000;
  10641. /**
  10642. * Gather stats and store them in this.statsToBeLogged.
  10643. */
  10644. this.gatherStatsIntervalId = null;
  10645. /**
  10646. * Send the stats already saved in this.statsToBeLogged to be logged via
  10647. * the focus.
  10648. */
  10649. this.logStatsIntervalId = null;
  10650. /**
  10651. * Stores the statistics which will be send to the focus to be logged.
  10652. */
  10653. this.statsToBeLogged =
  10654. {
  10655. timestamps: [],
  10656. stats: {}
  10657. };
  10658. // Updates stats interval
  10659. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10660. this.statsIntervalId = null;
  10661. this.statsIntervalMilis = statsInterval;
  10662. // Map of jids to PeerStats
  10663. this.jid2stats = {};
  10664. }
  10665. module.exports = StatsCollector;
  10666. /**
  10667. * Stops stats updates.
  10668. */
  10669. StatsCollector.prototype.stop = function () {
  10670. if (this.audioLevelsIntervalId) {
  10671. clearInterval(this.audioLevelsIntervalId);
  10672. this.audioLevelsIntervalId = null;
  10673. }
  10674. if (this.statsIntervalId)
  10675. {
  10676. clearInterval(this.statsIntervalId);
  10677. this.statsIntervalId = null;
  10678. }
  10679. if(this.logStatsIntervalId)
  10680. {
  10681. clearInterval(this.logStatsIntervalId);
  10682. this.logStatsIntervalId = null;
  10683. }
  10684. if(this.gatherStatsIntervalId)
  10685. {
  10686. clearInterval(this.gatherStatsIntervalId);
  10687. this.gatherStatsIntervalId = null;
  10688. }
  10689. };
  10690. /**
  10691. * Callback passed to <tt>getStats</tt> method.
  10692. * @param error an error that occurred on <tt>getStats</tt> call.
  10693. */
  10694. StatsCollector.prototype.errorCallback = function (error)
  10695. {
  10696. console.error("Get stats error", error);
  10697. this.stop();
  10698. };
  10699. /**
  10700. * Starts stats updates.
  10701. */
  10702. StatsCollector.prototype.start = function ()
  10703. {
  10704. var self = this;
  10705. if (!config.disableAudioLevels) {
  10706. this.audioLevelsIntervalId = setInterval(
  10707. function () {
  10708. // Interval updates
  10709. self.peerconnection.getStats(
  10710. function (report) {
  10711. var results = null;
  10712. if (!report || !report.result ||
  10713. typeof report.result != 'function') {
  10714. results = report;
  10715. }
  10716. else {
  10717. results = report.result();
  10718. }
  10719. //console.error("Got interval report", results);
  10720. self.currentAudioLevelsReport = results;
  10721. self.processAudioLevelReport();
  10722. self.baselineAudioLevelsReport =
  10723. self.currentAudioLevelsReport;
  10724. },
  10725. self.errorCallback
  10726. );
  10727. },
  10728. self.audioLevelsIntervalMilis
  10729. );
  10730. }
  10731. if (!config.disableStats && browserSupported) {
  10732. this.statsIntervalId = setInterval(
  10733. function () {
  10734. // Interval updates
  10735. self.peerconnection.getStats(
  10736. function (report) {
  10737. var results = null;
  10738. if (!report || !report.result ||
  10739. typeof report.result != 'function') {
  10740. //firefox
  10741. results = report;
  10742. }
  10743. else {
  10744. //chrome
  10745. results = report.result();
  10746. }
  10747. //console.error("Got interval report", results);
  10748. self.currentStatsReport = results;
  10749. try {
  10750. self.processStatsReport();
  10751. }
  10752. catch (e) {
  10753. console.error("Unsupported key:" + e, e);
  10754. }
  10755. self.baselineStatsReport = self.currentStatsReport;
  10756. },
  10757. self.errorCallback
  10758. );
  10759. },
  10760. self.statsIntervalMilis
  10761. );
  10762. }
  10763. if (config.logStats && browserSupported) {
  10764. this.gatherStatsIntervalId = setInterval(
  10765. function () {
  10766. self.peerconnection.getStats(
  10767. function (report) {
  10768. self.addStatsToBeLogged(report.result());
  10769. },
  10770. function () {
  10771. }
  10772. );
  10773. },
  10774. this.GATHER_INTERVAL
  10775. );
  10776. this.logStatsIntervalId = setInterval(
  10777. function() { self.logStats(); },
  10778. this.LOG_INTERVAL);
  10779. }
  10780. };
  10781. /**
  10782. * Checks whether a certain record should be included in the logged statistics.
  10783. */
  10784. function acceptStat(reportId, reportType, statName) {
  10785. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10786. return false;
  10787. if (reportType == "ssrc") {
  10788. if (statName == "googTrackId" ||
  10789. statName == "transportId" ||
  10790. statName == "ssrc")
  10791. return false;
  10792. }
  10793. return true;
  10794. }
  10795. /**
  10796. * Checks whether a certain record should be included in the logged statistics.
  10797. */
  10798. function acceptReport(id, type) {
  10799. if (id.substring(0, 15) == "googCertificate" ||
  10800. id.substring(0, 9) == "googTrack" ||
  10801. id.substring(0, 20) == "googLibjingleSession")
  10802. return false;
  10803. if (type == "googComponent")
  10804. return false;
  10805. return true;
  10806. }
  10807. /**
  10808. * Converts the stats to the format used for logging, and saves the data in
  10809. * this.statsToBeLogged.
  10810. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10811. */
  10812. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10813. var self = this;
  10814. var num_records = this.statsToBeLogged.timestamps.length;
  10815. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10816. reports.map(function (report) {
  10817. if (!acceptReport(report.id, report.type))
  10818. return;
  10819. var stat = self.statsToBeLogged.stats[report.id];
  10820. if (!stat) {
  10821. stat = self.statsToBeLogged.stats[report.id] = {};
  10822. }
  10823. stat.type = report.type;
  10824. report.names().map(function (name) {
  10825. if (!acceptStat(report.id, report.type, name))
  10826. return;
  10827. var values = stat[name];
  10828. if (!values) {
  10829. values = stat[name] = [];
  10830. }
  10831. while (values.length < num_records) {
  10832. values.push(null);
  10833. }
  10834. values.push(report.stat(name));
  10835. });
  10836. });
  10837. };
  10838. StatsCollector.prototype.logStats = function () {
  10839. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10840. return;
  10841. // Reset the stats
  10842. this.statsToBeLogged.stats = {};
  10843. this.statsToBeLogged.timestamps = [];
  10844. };
  10845. var keyMap = {};
  10846. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10847. "ssrc": "ssrc",
  10848. "packetsReceived": "packetsReceived",
  10849. "packetsLost": "packetsLost",
  10850. "packetsSent": "packetsSent",
  10851. "bytesReceived": "bytesReceived",
  10852. "bytesSent": "bytesSent"
  10853. };
  10854. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10855. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10856. "sendBandwidth": "googAvailableSendBandwidth",
  10857. "remoteAddress": "googRemoteAddress",
  10858. "transportType": "googTransportType",
  10859. "localAddress": "googLocalAddress",
  10860. "activeConnection": "googActiveConnection",
  10861. "ssrc": "ssrc",
  10862. "packetsReceived": "packetsReceived",
  10863. "packetsSent": "packetsSent",
  10864. "packetsLost": "packetsLost",
  10865. "bytesReceived": "bytesReceived",
  10866. "bytesSent": "bytesSent",
  10867. "googFrameHeightReceived": "googFrameHeightReceived",
  10868. "googFrameWidthReceived": "googFrameWidthReceived",
  10869. "googFrameHeightSent": "googFrameHeightSent",
  10870. "googFrameWidthSent": "googFrameWidthSent",
  10871. "audioInputLevel": "audioInputLevel",
  10872. "audioOutputLevel": "audioOutputLevel"
  10873. };
  10874. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  10875. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  10876. /**
  10877. * Stats processing logic.
  10878. */
  10879. StatsCollector.prototype.processStatsReport = function () {
  10880. if (!this.baselineStatsReport) {
  10881. return;
  10882. }
  10883. for (var idx in this.currentStatsReport) {
  10884. var now = this.currentStatsReport[idx];
  10885. try {
  10886. if (getStatValue(now, 'receiveBandwidth') ||
  10887. getStatValue(now, 'sendBandwidth')) {
  10888. PeerStats.bandwidth = {
  10889. "download": Math.round(
  10890. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10891. "upload": Math.round(
  10892. (getStatValue(now, 'sendBandwidth')) / 1000)
  10893. };
  10894. }
  10895. }
  10896. catch(e){/*not supported*/}
  10897. if(now.type == 'googCandidatePair')
  10898. {
  10899. var ip, type, localIP, active;
  10900. try {
  10901. ip = getStatValue(now, 'remoteAddress');
  10902. type = getStatValue(now, "transportType");
  10903. localIP = getStatValue(now, "localAddress");
  10904. active = getStatValue(now, "activeConnection");
  10905. }
  10906. catch(e){/*not supported*/}
  10907. if(!ip || !type || !localIP || active != "true")
  10908. continue;
  10909. var addressSaved = false;
  10910. for(var i = 0; i < PeerStats.transport.length; i++)
  10911. {
  10912. if(PeerStats.transport[i].ip == ip &&
  10913. PeerStats.transport[i].type == type &&
  10914. PeerStats.transport[i].localip == localIP)
  10915. {
  10916. addressSaved = true;
  10917. }
  10918. }
  10919. if(addressSaved)
  10920. continue;
  10921. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10922. continue;
  10923. }
  10924. if(now.type == "candidatepair")
  10925. {
  10926. if(now.state == "succeeded")
  10927. continue;
  10928. var local = this.currentStatsReport[now.localCandidateId];
  10929. var remote = this.currentStatsReport[now.remoteCandidateId];
  10930. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10931. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10932. }
  10933. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10934. now.type != "inboundrtp") {
  10935. continue;
  10936. }
  10937. var before = this.baselineStatsReport[idx];
  10938. if (!before) {
  10939. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10940. continue;
  10941. }
  10942. var ssrc = getStatValue(now, 'ssrc');
  10943. if(!ssrc)
  10944. continue;
  10945. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10946. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10947. console.warn("No jid for ssrc: " + ssrc);
  10948. continue;
  10949. }
  10950. var jidStats = this.jid2stats[jid];
  10951. if (!jidStats) {
  10952. jidStats = new PeerStats();
  10953. this.jid2stats[jid] = jidStats;
  10954. }
  10955. var isDownloadStream = true;
  10956. var key = 'packetsReceived';
  10957. if (!getStatValue(now, key))
  10958. {
  10959. isDownloadStream = false;
  10960. key = 'packetsSent';
  10961. if (!getStatValue(now, key))
  10962. {
  10963. console.warn("No packetsReceived nor packetSent stat found");
  10964. continue;
  10965. }
  10966. }
  10967. var packetsNow = getStatValue(now, key);
  10968. if(!packetsNow || packetsNow < 0)
  10969. packetsNow = 0;
  10970. var packetsBefore = getStatValue(before, key);
  10971. if(!packetsBefore || packetsBefore < 0)
  10972. packetsBefore = 0;
  10973. var packetRate = packetsNow - packetsBefore;
  10974. if(!packetRate || packetRate < 0)
  10975. packetRate = 0;
  10976. var currentLoss = getStatValue(now, 'packetsLost');
  10977. if(!currentLoss || currentLoss < 0)
  10978. currentLoss = 0;
  10979. var previousLoss = getStatValue(before, 'packetsLost');
  10980. if(!previousLoss || previousLoss < 0)
  10981. previousLoss = 0;
  10982. var lossRate = currentLoss - previousLoss;
  10983. if(!lossRate || lossRate < 0)
  10984. lossRate = 0;
  10985. var packetsTotal = (packetRate + lossRate);
  10986. jidStats.setSsrcLoss(ssrc,
  10987. {"packetsTotal": packetsTotal,
  10988. "packetsLost": lossRate,
  10989. "isDownloadStream": isDownloadStream});
  10990. var bytesReceived = 0, bytesSent = 0;
  10991. if(getStatValue(now, "bytesReceived"))
  10992. {
  10993. bytesReceived = getStatValue(now, "bytesReceived") -
  10994. getStatValue(before, "bytesReceived");
  10995. }
  10996. if(getStatValue(now, "bytesSent"))
  10997. {
  10998. bytesSent = getStatValue(now, "bytesSent") -
  10999. getStatValue(before, "bytesSent");
  11000. }
  11001. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11002. if(bytesReceived <= 0 || time <= 0)
  11003. {
  11004. bytesReceived = 0;
  11005. }
  11006. else
  11007. {
  11008. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11009. }
  11010. if(bytesSent <= 0 || time <= 0)
  11011. {
  11012. bytesSent = 0;
  11013. }
  11014. else
  11015. {
  11016. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11017. }
  11018. jidStats.setSsrcBitrate(ssrc, {
  11019. "download": bytesReceived,
  11020. "upload": bytesSent});
  11021. var resolution = {height: null, width: null};
  11022. try {
  11023. if (getStatValue(now, "googFrameHeightReceived") &&
  11024. getStatValue(now, "googFrameWidthReceived")) {
  11025. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11026. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11027. }
  11028. else if (getStatValue(now, "googFrameHeightSent") &&
  11029. getStatValue(now, "googFrameWidthSent")) {
  11030. resolution.height = getStatValue(now, "googFrameHeightSent");
  11031. resolution.width = getStatValue(now, "googFrameWidthSent");
  11032. }
  11033. }
  11034. catch(e){/*not supported*/}
  11035. if(resolution.height && resolution.width)
  11036. {
  11037. jidStats.setSsrcResolution(ssrc, resolution);
  11038. }
  11039. else
  11040. {
  11041. jidStats.setSsrcResolution(ssrc, null);
  11042. }
  11043. }
  11044. var self = this;
  11045. // Jid stats
  11046. var totalPackets = {download: 0, upload: 0};
  11047. var lostPackets = {download: 0, upload: 0};
  11048. var bitrateDownload = 0;
  11049. var bitrateUpload = 0;
  11050. var resolutions = {};
  11051. Object.keys(this.jid2stats).forEach(
  11052. function (jid)
  11053. {
  11054. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11055. function (ssrc)
  11056. {
  11057. var type = "upload";
  11058. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11059. type = "download";
  11060. totalPackets[type] +=
  11061. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11062. lostPackets[type] +=
  11063. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11064. }
  11065. );
  11066. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11067. function (ssrc) {
  11068. bitrateDownload +=
  11069. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11070. bitrateUpload +=
  11071. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11072. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11073. }
  11074. );
  11075. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11076. }
  11077. );
  11078. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11079. PeerStats.packetLoss = {
  11080. total:
  11081. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11082. totalPackets.download + totalPackets.upload),
  11083. download:
  11084. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11085. upload:
  11086. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11087. };
  11088. this.eventEmitter.emit("statistics.connectionstats",
  11089. {
  11090. "bitrate": PeerStats.bitrate,
  11091. "packetLoss": PeerStats.packetLoss,
  11092. "bandwidth": PeerStats.bandwidth,
  11093. "resolution": resolutions,
  11094. "transport": PeerStats.transport
  11095. });
  11096. PeerStats.transport = [];
  11097. };
  11098. /**
  11099. * Stats processing logic.
  11100. */
  11101. StatsCollector.prototype.processAudioLevelReport = function () {
  11102. if (!this.baselineAudioLevelsReport) {
  11103. return;
  11104. }
  11105. for (var idx in this.currentAudioLevelsReport) {
  11106. var now = this.currentAudioLevelsReport[idx];
  11107. if (now.type != 'ssrc') {
  11108. continue;
  11109. }
  11110. var before = this.baselineAudioLevelsReport[idx];
  11111. if (!before) {
  11112. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11113. continue;
  11114. }
  11115. var ssrc = getStatValue(now, 'ssrc');
  11116. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11117. if (!jid) {
  11118. if((Date.now() - now.timestamp) < 3000)
  11119. console.warn("No jid for ssrc: " + ssrc);
  11120. continue;
  11121. }
  11122. var jidStats = this.jid2stats[jid];
  11123. if (!jidStats) {
  11124. jidStats = new PeerStats();
  11125. this.jid2stats[jid] = jidStats;
  11126. }
  11127. // Audio level
  11128. var audioLevel = null;
  11129. try {
  11130. audioLevel = getStatValue(now, 'audioInputLevel');
  11131. if (!audioLevel)
  11132. audioLevel = getStatValue(now, 'audioOutputLevel');
  11133. }
  11134. catch(e) {/*not supported*/
  11135. console.warn("Audio Levels are not available in the statistics.");
  11136. clearInterval(this.audioLevelsIntervalId);
  11137. return;
  11138. }
  11139. if (audioLevel) {
  11140. // TODO: can't find specs about what this value really is,
  11141. // but it seems to vary between 0 and around 32k.
  11142. audioLevel = audioLevel / 32767;
  11143. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11144. if(jid != APP.xmpp.myJid())
  11145. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11146. }
  11147. }
  11148. };
  11149. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11150. /* global require, APP */
  11151. /**
  11152. * Created by hristo on 8/4/14.
  11153. */
  11154. var LocalStats = require("./LocalStatsCollector.js");
  11155. var RTPStats = require("./RTPStatsCollector.js");
  11156. var EventEmitter = require("events");
  11157. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11158. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11159. var CallStats = require("./CallStats");
  11160. var RTCEvents = require("../../service/RTC/RTCEvents");
  11161. var eventEmitter = new EventEmitter();
  11162. var localStats = null;
  11163. var rtpStats = null;
  11164. function stopLocal() {
  11165. if (localStats) {
  11166. localStats.stop();
  11167. localStats = null;
  11168. }
  11169. }
  11170. function stopRemote() {
  11171. if (rtpStats) {
  11172. rtpStats.stop();
  11173. eventEmitter.emit("statistics.stop");
  11174. rtpStats = null;
  11175. }
  11176. }
  11177. function startRemoteStats (peerconnection) {
  11178. if (rtpStats) {
  11179. rtpStats.stop();
  11180. }
  11181. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11182. rtpStats.start();
  11183. }
  11184. function onStreamCreated(stream) {
  11185. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11186. return;
  11187. }
  11188. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11189. eventEmitter);
  11190. localStats.start();
  11191. }
  11192. function onDisposeConference(onUnload) {
  11193. CallStats.sendTerminateEvent();
  11194. stopRemote();
  11195. if(onUnload) {
  11196. stopLocal();
  11197. eventEmitter.removeAllListeners();
  11198. }
  11199. }
  11200. var statistics = {
  11201. /**
  11202. * Indicates that this audio level is for local jid.
  11203. * @type {string}
  11204. */
  11205. LOCAL_JID: 'local',
  11206. addAudioLevelListener: function(listener)
  11207. {
  11208. eventEmitter.on("statistics.audioLevel", listener);
  11209. },
  11210. removeAudioLevelListener: function(listener)
  11211. {
  11212. eventEmitter.removeListener("statistics.audioLevel", listener);
  11213. },
  11214. addConnectionStatsListener: function(listener)
  11215. {
  11216. eventEmitter.on("statistics.connectionstats", listener);
  11217. },
  11218. removeConnectionStatsListener: function(listener)
  11219. {
  11220. eventEmitter.removeListener("statistics.connectionstats", listener);
  11221. },
  11222. addRemoteStatsStopListener: function(listener)
  11223. {
  11224. eventEmitter.on("statistics.stop", listener);
  11225. },
  11226. removeRemoteStatsStopListener: function(listener)
  11227. {
  11228. eventEmitter.removeListener("statistics.stop", listener);
  11229. },
  11230. stop: function () {
  11231. stopLocal();
  11232. stopRemote();
  11233. if(eventEmitter)
  11234. {
  11235. eventEmitter.removeAllListeners();
  11236. }
  11237. },
  11238. stopRemoteStatistics: function()
  11239. {
  11240. stopRemote();
  11241. },
  11242. start: function () {
  11243. APP.RTC.addStreamListener(onStreamCreated,
  11244. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11245. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11246. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11247. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11248. startRemoteStats(event.peerconnection);
  11249. // CallStats.init(event);
  11250. });
  11251. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11252. CallStats.init(session);
  11253. });
  11254. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11255. CallStats.sendMuteEvent(mute, "audio");
  11256. });
  11257. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11258. CallStats.sendSetupFailedEvent();
  11259. });
  11260. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11261. CallStats.sendMuteEvent(mute, "video");
  11262. });
  11263. }
  11264. };
  11265. module.exports = statistics;
  11266. },{"../../service/RTC/RTCEvents":107,"../../service/RTC/StreamEventTypes.js":109,"../../service/xmpp/XMPPEvents":116,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":117}],52:[function(require,module,exports){
  11267. /* global $, require, config, interfaceConfig */
  11268. var i18n = require("i18next-client");
  11269. var languages = require("../../service/translation/languages");
  11270. var Settings = require("../settings/Settings");
  11271. var DEFAULT_LANG = languages.EN;
  11272. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11273. return value.replace("__app__", interfaceConfig.APP_NAME);
  11274. });
  11275. var defaultOptions = {
  11276. detectLngQS: "lang",
  11277. useCookie: false,
  11278. fallbackLng: DEFAULT_LANG,
  11279. load: "unspecific",
  11280. resGetPath: 'lang/__ns__-__lng__.json',
  11281. ns: {
  11282. namespaces: ['main', 'languages'],
  11283. defaultNs: 'main'
  11284. },
  11285. lngWhitelist : languages.getLanguages(),
  11286. fallbackOnNull: true,
  11287. fallbackOnEmpty: true,
  11288. useDataAttrOptions: true,
  11289. app: interfaceConfig.APP_NAME,
  11290. getAsync: false,
  11291. defaultValueFromContent: false,
  11292. customLoad: function(lng, ns, options, done) {
  11293. var resPath = "lang/__ns__-__lng__.json";
  11294. if(lng === languages.EN)
  11295. resPath = "lang/__ns__.json";
  11296. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11297. i18n.functions.ajax({
  11298. url: url,
  11299. success: function(data, status, xhr) {
  11300. i18n.functions.log('loaded: ' + url);
  11301. done(null, data);
  11302. },
  11303. error : function(xhr, status, error) {
  11304. if ((status && status == 200) ||
  11305. (xhr && xhr.status && xhr.status == 200)) {
  11306. // file loaded but invalid json, stop waste time !
  11307. i18n.functions.error('There is a typo in: ' + url);
  11308. } else if ((status && status == 404) ||
  11309. (xhr && xhr.status && xhr.status == 404)) {
  11310. i18n.functions.log('Does not exist: ' + url);
  11311. } else {
  11312. var theStatus = status ? status :
  11313. ((xhr && xhr.status) ? xhr.status : null);
  11314. i18n.functions.log(theStatus + ' when loading ' + url);
  11315. }
  11316. done(error, {});
  11317. },
  11318. dataType: "json",
  11319. async : options.getAsync
  11320. });
  11321. }
  11322. // options for caching
  11323. // useLocalStorage: true,
  11324. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11325. };
  11326. function initCompleted(t) {
  11327. $("[data-i18n]").i18n();
  11328. }
  11329. function checkForParameter() {
  11330. var query = window.location.search.substring(1);
  11331. var vars = query.split("&");
  11332. for (var i=0;i<vars.length;i++) {
  11333. var pair = vars[i].split("=");
  11334. if(pair[0] == "lang")
  11335. {
  11336. return pair[1];
  11337. }
  11338. }
  11339. return null;
  11340. }
  11341. module.exports = {
  11342. init: function (lang) {
  11343. var options = defaultOptions;
  11344. if(!lang)
  11345. {
  11346. lang = checkForParameter();
  11347. if(!lang)
  11348. {
  11349. var settings = Settings.getSettings();
  11350. if(settings)
  11351. lang = settings.language;
  11352. if(!lang && config.defaultLanguage)
  11353. {
  11354. lang = config.defaultLanguage;
  11355. }
  11356. }
  11357. }
  11358. if(lang) {
  11359. options.lng = lang;
  11360. }
  11361. i18n.init(options, initCompleted);
  11362. },
  11363. translateString: function (key, options) {
  11364. return i18n.t(key, options);
  11365. },
  11366. setLanguage: function (lang) {
  11367. if(!lang)
  11368. lang = DEFAULT_LANG;
  11369. i18n.setLng(lang, defaultOptions, initCompleted);
  11370. },
  11371. getCurrentLanguage: function () {
  11372. return i18n.lng();
  11373. },
  11374. translateElement: function (selector) {
  11375. selector.i18n();
  11376. },
  11377. generateTranslationHTML: function (key, options) {
  11378. var str = "<span data-i18n=\"" + key + "\"";
  11379. if(options)
  11380. {
  11381. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11382. }
  11383. str += ">";
  11384. str += this.translateString(key, options);
  11385. str += "</span>";
  11386. return str;
  11387. }
  11388. };
  11389. },{"../../service/translation/languages":115,"../settings/Settings":47,"i18next-client":68}],53:[function(require,module,exports){
  11390. /* jshint -W117 */
  11391. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11392. var SDPDiffer = require("./SDPDiffer");
  11393. var SDPUtil = require("./SDPUtil");
  11394. var SDP = require("./SDP");
  11395. var async = require("async");
  11396. var transform = require("sdp-transform");
  11397. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11398. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11399. // Jingle stuff
  11400. function JingleSession(me, sid, connection, service, eventEmitter) {
  11401. this.me = me;
  11402. this.sid = sid;
  11403. this.connection = connection;
  11404. this.initiator = null;
  11405. this.responder = null;
  11406. this.isInitiator = null;
  11407. this.peerjid = null;
  11408. this.state = null;
  11409. this.localSDP = null;
  11410. this.remoteSDP = null;
  11411. this.relayedStreams = [];
  11412. this.startTime = null;
  11413. this.stopTime = null;
  11414. this.media_constraints = null;
  11415. this.pc_constraints = null;
  11416. this.ice_config = {};
  11417. this.drip_container = [];
  11418. this.service = service;
  11419. this.eventEmitter = eventEmitter;
  11420. this.usetrickle = true;
  11421. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11422. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11423. this.hadstuncandidate = false;
  11424. this.hadturncandidate = false;
  11425. this.lasticecandidate = false;
  11426. this.statsinterval = null;
  11427. this.reason = null;
  11428. this.addssrc = [];
  11429. this.removessrc = [];
  11430. this.pendingop = null;
  11431. this.switchstreams = false;
  11432. this.wait = true;
  11433. this.localStreamsSSRC = null;
  11434. this.ssrcOwners = {};
  11435. this.ssrcVideoTypes = {};
  11436. this.eventEmitter = eventEmitter;
  11437. /**
  11438. * The indicator which determines whether the (local) video has been muted
  11439. * in response to a user command in contrast to an automatic decision made
  11440. * by the application logic.
  11441. */
  11442. this.videoMuteByUser = false;
  11443. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11444. // We start with the queue paused. We resume it when the signaling state is
  11445. // stable and the ice connection state is connected.
  11446. this.modifySourcesQueue.pause();
  11447. }
  11448. JingleSession.prototype.updateModifySourcesQueue = function() {
  11449. var signalingState = this.peerconnection.signalingState;
  11450. var iceConnectionState = this.peerconnection.iceConnectionState;
  11451. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11452. this.modifySourcesQueue.resume();
  11453. } else {
  11454. this.modifySourcesQueue.pause();
  11455. }
  11456. };
  11457. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11458. var self = this;
  11459. if (this.state !== null) {
  11460. console.error('attempt to initiate on session ' + this.sid +
  11461. 'in state ' + this.state);
  11462. return;
  11463. }
  11464. this.isInitiator = isInitiator;
  11465. this.state = 'pending';
  11466. this.initiator = isInitiator ? this.me : peerjid;
  11467. this.responder = !isInitiator ? this.me : peerjid;
  11468. this.peerjid = peerjid;
  11469. this.hadstuncandidate = false;
  11470. this.hadturncandidate = false;
  11471. this.lasticecandidate = false;
  11472. this.isreconnect = false;
  11473. this.peerconnection
  11474. = new TraceablePeerConnection(
  11475. this.connection.jingle.ice_config,
  11476. this.connection.jingle.pc_constraints,
  11477. this);
  11478. this.peerconnection.onicecandidate = function (event) {
  11479. self.sendIceCandidate(event.candidate);
  11480. };
  11481. this.peerconnection.onaddstream = function (event) {
  11482. if (event.stream.id !== 'default') {
  11483. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11484. self.remoteStreamAdded(event);
  11485. } else {
  11486. // This is a recvonly stream. Clients that implement Unified Plan,
  11487. // such as Firefox use recvonly "streams/channels/tracks" for
  11488. // receiving remote stream/tracks, as opposed to Plan B where there
  11489. // are only 3 channels: audio, video and data.
  11490. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11491. }
  11492. };
  11493. this.peerconnection.onremovestream = function (event) {
  11494. // Remove the stream from remoteStreams
  11495. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11496. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11497. };
  11498. this.peerconnection.onsignalingstatechange = function (event) {
  11499. if (!(self && self.peerconnection)) return;
  11500. self.updateModifySourcesQueue();
  11501. };
  11502. /**
  11503. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  11504. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  11505. * RTCPeerConnection.iceConnectionState changes.
  11506. *
  11507. * @param event the event containing information about the change
  11508. */
  11509. this.peerconnection.oniceconnectionstatechange = function (event) {
  11510. if (!(self && self.peerconnection)) return;
  11511. self.updateModifySourcesQueue();
  11512. switch (self.peerconnection.iceConnectionState) {
  11513. case 'connected':
  11514. self.startTime = new Date();
  11515. // Informs interested parties that the connection has been restored.
  11516. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  11517. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  11518. self.isreconnect = false;
  11519. break;
  11520. case 'disconnected':
  11521. self.isreconnect = true;
  11522. self.stopTime = new Date();
  11523. // Informs interested parties that the connection has been interrupted.
  11524. if (self.peerconnection.signalingState === 'stable')
  11525. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  11526. break;
  11527. case 'failed':
  11528. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11529. break;
  11530. }
  11531. onIceConnectionStateChange(self.sid, self);
  11532. };
  11533. this.peerconnection.onnegotiationneeded = function (event) {
  11534. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11535. };
  11536. // add any local and relayed stream
  11537. APP.RTC.localStreams.forEach(function(stream) {
  11538. self.peerconnection.addStream(stream.getOriginalStream());
  11539. });
  11540. this.relayedStreams.forEach(function(stream) {
  11541. self.peerconnection.addStream(stream);
  11542. });
  11543. };
  11544. function onIceConnectionStateChange(sid, session) {
  11545. switch (session.peerconnection.iceConnectionState) {
  11546. case 'checking':
  11547. session.timeChecking = (new Date()).getTime();
  11548. session.firstconnect = true;
  11549. break;
  11550. case 'completed': // on caller side
  11551. case 'connected':
  11552. if (session.firstconnect) {
  11553. session.firstconnect = false;
  11554. var metadata = {};
  11555. metadata.setupTime
  11556. = (new Date()).getTime() - session.timeChecking;
  11557. session.peerconnection.getStats(function (res) {
  11558. if(res && res.result) {
  11559. res.result().forEach(function (report) {
  11560. if (report.type == 'googCandidatePair' &&
  11561. report.stat('googActiveConnection') == 'true') {
  11562. metadata.localCandidateType
  11563. = report.stat('googLocalCandidateType');
  11564. metadata.remoteCandidateType
  11565. = report.stat('googRemoteCandidateType');
  11566. // log pair as well so we can get nice pie
  11567. // charts
  11568. metadata.candidatePair
  11569. = report.stat('googLocalCandidateType') +
  11570. ';' +
  11571. report.stat('googRemoteCandidateType');
  11572. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11573. {
  11574. metadata.ipv6 = true;
  11575. }
  11576. }
  11577. });
  11578. }
  11579. });
  11580. }
  11581. break;
  11582. }
  11583. }
  11584. JingleSession.prototype.getVideoType = function () {
  11585. return APP.desktopsharing.isUsingScreenStream() ? 'screen' : 'camera';
  11586. };
  11587. JingleSession.prototype.accept = function () {
  11588. this.state = 'active';
  11589. var pranswer = this.peerconnection.localDescription;
  11590. if (!pranswer || pranswer.type != 'pranswer') {
  11591. return;
  11592. }
  11593. console.log('going from pranswer to answer');
  11594. if (this.usetrickle) {
  11595. // remove candidates already sent from session-accept
  11596. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11597. for (var i = 0; i < lines.length; i++) {
  11598. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11599. }
  11600. }
  11601. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11602. // FIXME: change any inactive to sendrecv or whatever they were originally
  11603. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11604. }
  11605. var prsdp = new SDP(pranswer.sdp);
  11606. var accept = $iq({to: this.peerjid,
  11607. type: 'set'})
  11608. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11609. action: 'session-accept',
  11610. initiator: this.initiator,
  11611. responder: this.responder,
  11612. sid: this.sid });
  11613. // FIXME why do we generate session-accept in 3 different places ?
  11614. prsdp.toJingle(
  11615. accept,
  11616. this.initiator == this.me ? 'initiator' : 'responder',
  11617. this.localStreamsSSRC,
  11618. self.getVideoType());
  11619. var sdp = this.peerconnection.localDescription.sdp;
  11620. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11621. // FIXME: change any inactive to sendrecv or whatever they were originally
  11622. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11623. }
  11624. var self = this;
  11625. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11626. function () {
  11627. //console.log('setLocalDescription success');
  11628. self.setLocalDescription();
  11629. self.connection.sendIQ(accept,
  11630. function () {
  11631. var ack = {};
  11632. ack.source = 'answer';
  11633. $(document).trigger('ack.jingle', [self.sid, ack]);
  11634. },
  11635. function (stanza) {
  11636. var error = ($(stanza).find('error').length) ? {
  11637. code: $(stanza).find('error').attr('code'),
  11638. reason: $(stanza).find('error :first')[0].tagName
  11639. }:{};
  11640. error.source = 'answer';
  11641. JingleSession.onJingleError(self.sid, error);
  11642. },
  11643. 10000);
  11644. },
  11645. function (e) {
  11646. console.error('setLocalDescription failed', e);
  11647. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11648. }
  11649. );
  11650. };
  11651. JingleSession.prototype.terminate = function (reason) {
  11652. this.state = 'ended';
  11653. this.reason = reason;
  11654. this.peerconnection.close();
  11655. if (this.statsinterval !== null) {
  11656. window.clearInterval(this.statsinterval);
  11657. this.statsinterval = null;
  11658. }
  11659. };
  11660. JingleSession.prototype.active = function () {
  11661. return this.state == 'active';
  11662. };
  11663. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11664. var self = this;
  11665. if (candidate && !this.lasticecandidate) {
  11666. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11667. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11668. if (!(ice && jcand)) {
  11669. console.error('failed to get ice && jcand');
  11670. return;
  11671. }
  11672. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11673. if (jcand.type === 'srflx') {
  11674. this.hadstuncandidate = true;
  11675. } else if (jcand.type === 'relay') {
  11676. this.hadturncandidate = true;
  11677. }
  11678. if (this.usetrickle) {
  11679. if (this.usedrip) {
  11680. if (this.drip_container.length === 0) {
  11681. // start 20ms callout
  11682. window.setTimeout(function () {
  11683. if (self.drip_container.length === 0) return;
  11684. self.sendIceCandidates(self.drip_container);
  11685. self.drip_container = [];
  11686. }, 20);
  11687. }
  11688. this.drip_container.push(candidate);
  11689. return;
  11690. } else {
  11691. self.sendIceCandidate([candidate]);
  11692. }
  11693. }
  11694. } else {
  11695. //console.log('sendIceCandidate: last candidate.');
  11696. if (!this.usetrickle) {
  11697. //console.log('should send full offer now...');
  11698. //FIXME why do we generate session-accept in 3 different places ?
  11699. var init = $iq({to: this.peerjid,
  11700. type: 'set'})
  11701. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11702. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11703. initiator: this.initiator,
  11704. sid: this.sid});
  11705. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11706. var self = this;
  11707. var sendJingle = function (ssrc) {
  11708. if(!ssrc)
  11709. ssrc = {};
  11710. self.localSDP.toJingle(
  11711. init,
  11712. self.initiator == self.me ? 'initiator' : 'responder',
  11713. ssrc,
  11714. self.getVideoType());
  11715. self.connection.sendIQ(init,
  11716. function () {
  11717. //console.log('session initiate ack');
  11718. var ack = {};
  11719. ack.source = 'offer';
  11720. $(document).trigger('ack.jingle', [self.sid, ack]);
  11721. },
  11722. function (stanza) {
  11723. self.state = 'error';
  11724. self.peerconnection.close();
  11725. var error = ($(stanza).find('error').length) ? {
  11726. code: $(stanza).find('error').attr('code'),
  11727. reason: $(stanza).find('error :first')[0].tagName,
  11728. }:{};
  11729. error.source = 'offer';
  11730. JingleSession.onJingleError(self.sid, error);
  11731. },
  11732. 10000);
  11733. }
  11734. sendJingle();
  11735. }
  11736. this.lasticecandidate = true;
  11737. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11738. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11739. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11740. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11741. }
  11742. }
  11743. };
  11744. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11745. console.log('sendIceCandidates', candidates);
  11746. var cand = $iq({to: this.peerjid, type: 'set'})
  11747. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11748. action: 'transport-info',
  11749. initiator: this.initiator,
  11750. sid: this.sid});
  11751. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11752. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11753. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11754. if (cands.length > 0) {
  11755. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11756. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11757. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11758. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11759. }).c('transport', ice);
  11760. for (var i = 0; i < cands.length; i++) {
  11761. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11762. }
  11763. // add fingerprint
  11764. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11765. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11766. tmp.required = true;
  11767. cand.c(
  11768. 'fingerprint',
  11769. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11770. .t(tmp.fingerprint);
  11771. delete tmp.fingerprint;
  11772. cand.attrs(tmp);
  11773. cand.up();
  11774. }
  11775. cand.up(); // transport
  11776. cand.up(); // content
  11777. }
  11778. }
  11779. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11780. //console.log('was this the last candidate', this.lasticecandidate);
  11781. this.connection.sendIQ(cand,
  11782. function () {
  11783. var ack = {};
  11784. ack.source = 'transportinfo';
  11785. $(document).trigger('ack.jingle', [this.sid, ack]);
  11786. },
  11787. function (stanza) {
  11788. var error = ($(stanza).find('error').length) ? {
  11789. code: $(stanza).find('error').attr('code'),
  11790. reason: $(stanza).find('error :first')[0].tagName,
  11791. }:{};
  11792. error.source = 'transportinfo';
  11793. JingleSession.onJingleError(this.sid, error);
  11794. },
  11795. 10000);
  11796. };
  11797. JingleSession.prototype.sendOffer = function () {
  11798. //console.log('sendOffer...');
  11799. var self = this;
  11800. this.peerconnection.createOffer(function (sdp) {
  11801. self.createdOffer(sdp);
  11802. },
  11803. function (e) {
  11804. console.error('createOffer failed', e);
  11805. },
  11806. this.media_constraints
  11807. );
  11808. };
  11809. // FIXME createdOffer is never used in jitsi-meet
  11810. JingleSession.prototype.createdOffer = function (sdp) {
  11811. //console.log('createdOffer', sdp);
  11812. var self = this;
  11813. this.localSDP = new SDP(sdp.sdp);
  11814. //this.localSDP.mangle();
  11815. var sendJingle = function () {
  11816. var init = $iq({to: this.peerjid,
  11817. type: 'set'})
  11818. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11819. action: 'session-initiate',
  11820. initiator: this.initiator,
  11821. sid: this.sid});
  11822. self.localSDP.toJingle(
  11823. init,
  11824. this.initiator == this.me ? 'initiator' : 'responder',
  11825. this.localStreamsSSRC,
  11826. self.getVideoType());
  11827. self.connection.sendIQ(init,
  11828. function () {
  11829. var ack = {};
  11830. ack.source = 'offer';
  11831. $(document).trigger('ack.jingle', [self.sid, ack]);
  11832. },
  11833. function (stanza) {
  11834. self.state = 'error';
  11835. self.peerconnection.close();
  11836. var error = ($(stanza).find('error').length) ? {
  11837. code: $(stanza).find('error').attr('code'),
  11838. reason: $(stanza).find('error :first')[0].tagName,
  11839. }:{};
  11840. error.source = 'offer';
  11841. JingleSession.onJingleError(self.sid, error);
  11842. },
  11843. 10000);
  11844. }
  11845. sdp.sdp = this.localSDP.raw;
  11846. this.peerconnection.setLocalDescription(sdp,
  11847. function () {
  11848. if(self.usetrickle)
  11849. {
  11850. sendJingle();
  11851. }
  11852. self.setLocalDescription();
  11853. //console.log('setLocalDescription success');
  11854. },
  11855. function (e) {
  11856. console.error('setLocalDescription failed', e);
  11857. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11858. }
  11859. );
  11860. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11861. for (var i = 0; i < cands.length; i++) {
  11862. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11863. if (cand.type == 'srflx') {
  11864. this.hadstuncandidate = true;
  11865. } else if (cand.type == 'relay') {
  11866. this.hadturncandidate = true;
  11867. }
  11868. }
  11869. };
  11870. JingleSession.prototype.readSsrcInfo = function (contents) {
  11871. var self = this;
  11872. $(contents).each(function (idx, content) {
  11873. var name = $(content).attr('name');
  11874. var mediaType = this.getAttribute('name');
  11875. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11876. ssrcs.each(function () {
  11877. var ssrc = this.getAttribute('ssrc');
  11878. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  11879. function () {
  11880. var owner = this.getAttribute('owner');
  11881. var videoType = this.getAttribute('video-type');
  11882. self.ssrcOwners[ssrc] = owner;
  11883. self.ssrcVideoTypes[ssrc] = videoType;
  11884. }
  11885. );
  11886. });
  11887. });
  11888. };
  11889. JingleSession.prototype.getSsrcOwner = function (ssrc) {
  11890. return this.ssrcOwners[ssrc];
  11891. };
  11892. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11893. //console.log('setting remote description... ', desctype);
  11894. this.remoteSDP = new SDP('');
  11895. this.remoteSDP.fromJingle(elem);
  11896. this.readSsrcInfo($(elem).find(">content"));
  11897. if (this.peerconnection.remoteDescription !== null) {
  11898. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11899. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11900. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11901. for (var i = 0; i < pranswer.media.length; i++) {
  11902. // make sure we have ice ufrag and pwd
  11903. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11904. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11905. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11906. } else {
  11907. console.warn('no ice ufrag?');
  11908. }
  11909. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11910. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11911. } else {
  11912. console.warn('no ice pwd?');
  11913. }
  11914. }
  11915. // copy over candidates
  11916. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11917. for (var j = 0; j < lines.length; j++) {
  11918. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11919. }
  11920. }
  11921. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11922. }
  11923. }
  11924. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11925. this.peerconnection.setRemoteDescription(remotedesc,
  11926. function () {
  11927. //console.log('setRemoteDescription success');
  11928. },
  11929. function (e) {
  11930. console.error('setRemoteDescription error', e);
  11931. JingleSession.onJingleFatalError(self, e);
  11932. }
  11933. );
  11934. };
  11935. JingleSession.prototype.addIceCandidate = function (elem) {
  11936. var self = this;
  11937. if (this.peerconnection.signalingState == 'closed') {
  11938. return;
  11939. }
  11940. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11941. console.log('trickle ice candidate arriving before session accept...');
  11942. // create a PRANSWER for setRemoteDescription
  11943. if (!this.remoteSDP) {
  11944. var cobbled = 'v=0\r\n' +
  11945. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11946. 's=-\r\n' +
  11947. 't=0 0\r\n';
  11948. // first, take some things from the local description
  11949. for (var i = 0; i < this.localSDP.media.length; i++) {
  11950. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11951. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11952. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11953. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11954. }
  11955. cobbled += 'a=inactive\r\n';
  11956. }
  11957. this.remoteSDP = new SDP(cobbled);
  11958. }
  11959. // then add things like ice and dtls from remote candidate
  11960. elem.each(function () {
  11961. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11962. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11963. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11964. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11965. var tmp = $(this).find('transport');
  11966. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11967. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11968. tmp = $(this).find('transport>fingerprint');
  11969. if (tmp.length) {
  11970. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11971. } else {
  11972. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11973. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11974. }
  11975. break;
  11976. }
  11977. }
  11978. }
  11979. });
  11980. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11981. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11982. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11983. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11984. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11985. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11986. }).length == this.remoteSDP.media.length;
  11987. if (iscomplete) {
  11988. console.log('setting pranswer');
  11989. try {
  11990. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11991. function() {
  11992. },
  11993. function(e) {
  11994. console.log('setRemoteDescription pranswer failed', e.toString());
  11995. });
  11996. } catch (e) {
  11997. console.error('setting pranswer failed', e);
  11998. }
  11999. } else {
  12000. //console.log('not yet setting pranswer');
  12001. }
  12002. }
  12003. // operate on each content element
  12004. elem.each(function () {
  12005. // would love to deactivate this, but firefox still requires it
  12006. var idx = -1;
  12007. var i;
  12008. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12009. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12010. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12011. idx = i;
  12012. break;
  12013. }
  12014. }
  12015. if (idx == -1) { // fall back to localdescription
  12016. for (i = 0; i < self.localSDP.media.length; i++) {
  12017. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12018. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12019. idx = i;
  12020. break;
  12021. }
  12022. }
  12023. }
  12024. var name = $(this).attr('name');
  12025. // TODO: check ice-pwd and ice-ufrag?
  12026. $(this).find('transport>candidate').each(function () {
  12027. var line, candidate;
  12028. line = SDPUtil.candidateFromJingle(this);
  12029. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12030. sdpMid: name,
  12031. candidate: line});
  12032. try {
  12033. self.peerconnection.addIceCandidate(candidate);
  12034. } catch (e) {
  12035. console.error('addIceCandidate failed', e.toString(), line);
  12036. }
  12037. });
  12038. });
  12039. };
  12040. JingleSession.prototype.sendAnswer = function (provisional) {
  12041. //console.log('createAnswer', provisional);
  12042. var self = this;
  12043. this.peerconnection.createAnswer(
  12044. function (sdp) {
  12045. self.createdAnswer(sdp, provisional);
  12046. },
  12047. function (e) {
  12048. console.error('createAnswer failed', e);
  12049. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12050. },
  12051. this.media_constraints
  12052. );
  12053. };
  12054. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  12055. //console.log('createAnswer callback');
  12056. var self = this;
  12057. this.localSDP = new SDP(sdp.sdp);
  12058. //this.localSDP.mangle();
  12059. this.usepranswer = provisional === true;
  12060. if (this.usetrickle) {
  12061. if (this.usepranswer) {
  12062. sdp.type = 'pranswer';
  12063. for (var i = 0; i < this.localSDP.media.length; i++) {
  12064. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12065. }
  12066. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12067. }
  12068. }
  12069. var self = this;
  12070. var sendJingle = function (ssrcs) {
  12071. // FIXME why do we generate session-accept in 3 different places ?
  12072. var accept = $iq({to: self.peerjid,
  12073. type: 'set'})
  12074. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12075. action: 'session-accept',
  12076. initiator: self.initiator,
  12077. responder: self.responder,
  12078. sid: self.sid });
  12079. self.localSDP.toJingle(
  12080. accept,
  12081. self.initiator == self.me ? 'initiator' : 'responder',
  12082. ssrcs,
  12083. self.getVideoType());
  12084. self.connection.sendIQ(accept,
  12085. function () {
  12086. var ack = {};
  12087. ack.source = 'answer';
  12088. $(document).trigger('ack.jingle', [self.sid, ack]);
  12089. },
  12090. function (stanza) {
  12091. var error = ($(stanza).find('error').length) ? {
  12092. code: $(stanza).find('error').attr('code'),
  12093. reason: $(stanza).find('error :first')[0].tagName,
  12094. }:{};
  12095. error.source = 'answer';
  12096. JingleSession.onJingleError(self.sid, error);
  12097. },
  12098. 10000);
  12099. }
  12100. sdp.sdp = this.localSDP.raw;
  12101. this.peerconnection.setLocalDescription(sdp,
  12102. function () {
  12103. //console.log('setLocalDescription success');
  12104. if (self.usetrickle && !self.usepranswer) {
  12105. sendJingle();
  12106. }
  12107. self.setLocalDescription();
  12108. },
  12109. function (e) {
  12110. console.error('setLocalDescription failed', e);
  12111. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12112. }
  12113. );
  12114. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12115. for (var j = 0; j < cands.length; j++) {
  12116. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12117. if (cand.type == 'srflx') {
  12118. this.hadstuncandidate = true;
  12119. } else if (cand.type == 'relay') {
  12120. this.hadturncandidate = true;
  12121. }
  12122. }
  12123. };
  12124. JingleSession.prototype.sendTerminate = function (reason, text) {
  12125. var self = this,
  12126. term = $iq({to: this.peerjid,
  12127. type: 'set'})
  12128. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12129. action: 'session-terminate',
  12130. initiator: this.initiator,
  12131. sid: this.sid})
  12132. .c('reason')
  12133. .c(reason || 'success');
  12134. if (text) {
  12135. term.up().c('text').t(text);
  12136. }
  12137. this.connection.sendIQ(term,
  12138. function () {
  12139. self.peerconnection.close();
  12140. self.peerconnection = null;
  12141. self.terminate();
  12142. var ack = {};
  12143. ack.source = 'terminate';
  12144. $(document).trigger('ack.jingle', [self.sid, ack]);
  12145. },
  12146. function (stanza) {
  12147. var error = ($(stanza).find('error').length) ? {
  12148. code: $(stanza).find('error').attr('code'),
  12149. reason: $(stanza).find('error :first')[0].tagName,
  12150. }:{};
  12151. $(document).trigger('ack.jingle', [self.sid, error]);
  12152. },
  12153. 10000);
  12154. if (this.statsinterval !== null) {
  12155. window.clearInterval(this.statsinterval);
  12156. this.statsinterval = null;
  12157. }
  12158. };
  12159. JingleSession.prototype.addSource = function (elem, fromJid) {
  12160. var self = this;
  12161. // FIXME: dirty waiting
  12162. if (!this.peerconnection.localDescription)
  12163. {
  12164. console.warn("addSource - localDescription not ready yet")
  12165. setTimeout(function()
  12166. {
  12167. self.addSource(elem, fromJid);
  12168. },
  12169. 200
  12170. );
  12171. return;
  12172. }
  12173. console.log('addssrc', new Date().getTime());
  12174. console.log('ice', this.peerconnection.iceConnectionState);
  12175. this.readSsrcInfo(elem);
  12176. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12177. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12178. $(elem).each(function (idx, content) {
  12179. var name = $(content).attr('name');
  12180. var lines = '';
  12181. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12182. var semantics = this.getAttribute('semantics');
  12183. var ssrcs = $(this).find('>source').map(function () {
  12184. return this.getAttribute('ssrc');
  12185. }).get();
  12186. if (ssrcs.length != 0) {
  12187. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12188. }
  12189. });
  12190. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12191. tmp.each(function () {
  12192. var ssrc = $(this).attr('ssrc');
  12193. if(mySdp.containsSSRC(ssrc)){
  12194. /**
  12195. * This happens when multiple participants change their streams at the same time and
  12196. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12197. * addssrc are scheduled for update IQ. See
  12198. */
  12199. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12200. return;
  12201. }
  12202. if (sdp.containsSSRC(ssrc)) {
  12203. console.warn("Source-add request for existing SSRC: " + ssrc);
  12204. return;
  12205. }
  12206. $(this).find('>parameter').each(function () {
  12207. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12208. if ($(this).attr('value') && $(this).attr('value').length)
  12209. lines += ':' + $(this).attr('value');
  12210. lines += '\r\n';
  12211. });
  12212. });
  12213. sdp.media.forEach(function(media, idx) {
  12214. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12215. return;
  12216. sdp.media[idx] += lines;
  12217. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12218. self.addssrc[idx] += lines;
  12219. });
  12220. sdp.raw = sdp.session + sdp.media.join('');
  12221. });
  12222. this.modifySourcesQueue.push(function() {
  12223. // When a source is added and if this is FF, a new channel is allocated
  12224. // for receiving the added source. We need to diffuse the SSRC of this
  12225. // new recvonly channel to the rest of the peers.
  12226. console.log('modify sources done');
  12227. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12228. console.log("SDPs", mySdp, newSdp);
  12229. self.notifyMySSRCUpdate(mySdp, newSdp);
  12230. });
  12231. };
  12232. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12233. var self = this;
  12234. // FIXME: dirty waiting
  12235. if (!this.peerconnection.localDescription)
  12236. {
  12237. console.warn("removeSource - localDescription not ready yet")
  12238. setTimeout(function()
  12239. {
  12240. self.removeSource(elem, fromJid);
  12241. },
  12242. 200
  12243. );
  12244. return;
  12245. }
  12246. console.log('removessrc', new Date().getTime());
  12247. console.log('ice', this.peerconnection.iceConnectionState);
  12248. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12249. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12250. $(elem).each(function (idx, content) {
  12251. var name = $(content).attr('name');
  12252. var lines = '';
  12253. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12254. var semantics = this.getAttribute('semantics');
  12255. var ssrcs = $(this).find('>source').map(function () {
  12256. return this.getAttribute('ssrc');
  12257. }).get();
  12258. if (ssrcs.length != 0) {
  12259. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12260. }
  12261. });
  12262. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12263. tmp.each(function () {
  12264. var ssrc = $(this).attr('ssrc');
  12265. // This should never happen, but can be useful for bug detection
  12266. if(mySdp.containsSSRC(ssrc)){
  12267. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12268. return;
  12269. }
  12270. $(this).find('>parameter').each(function () {
  12271. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12272. if ($(this).attr('value') && $(this).attr('value').length)
  12273. lines += ':' + $(this).attr('value');
  12274. lines += '\r\n';
  12275. });
  12276. });
  12277. sdp.media.forEach(function(media, idx) {
  12278. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12279. return;
  12280. sdp.media[idx] += lines;
  12281. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12282. self.removessrc[idx] += lines;
  12283. });
  12284. sdp.raw = sdp.session + sdp.media.join('');
  12285. });
  12286. this.modifySourcesQueue.push(function() {
  12287. // When a source is removed and if this is FF, the recvonly channel that
  12288. // receives the remote stream is deactivated . We need to diffuse the
  12289. // recvonly SSRC removal to the rest of the peers.
  12290. console.log('modify sources done');
  12291. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12292. console.log("SDPs", mySdp, newSdp);
  12293. self.notifyMySSRCUpdate(mySdp, newSdp);
  12294. });
  12295. };
  12296. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12297. var self = this;
  12298. if (this.peerconnection.signalingState == 'closed') return;
  12299. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12300. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12301. this.setLocalDescription();
  12302. if(successCallback){
  12303. successCallback();
  12304. }
  12305. queueCallback();
  12306. return;
  12307. }
  12308. // Reset switch streams flag
  12309. this.switchstreams = false;
  12310. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12311. // add sources
  12312. this.addssrc.forEach(function(lines, idx) {
  12313. sdp.media[idx] += lines;
  12314. });
  12315. this.addssrc = [];
  12316. // remove sources
  12317. this.removessrc.forEach(function(lines, idx) {
  12318. lines = lines.split('\r\n');
  12319. lines.pop(); // remove empty last element;
  12320. lines.forEach(function(line) {
  12321. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12322. });
  12323. });
  12324. this.removessrc = [];
  12325. sdp.raw = sdp.session + sdp.media.join('');
  12326. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12327. function() {
  12328. if(self.signalingState == 'closed') {
  12329. console.error("createAnswer attempt on closed state");
  12330. queueCallback("createAnswer attempt on closed state");
  12331. return;
  12332. }
  12333. self.peerconnection.createAnswer(
  12334. function(modifiedAnswer) {
  12335. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12336. if (self.pendingop !== null) {
  12337. var sdp = new SDP(modifiedAnswer.sdp);
  12338. if (sdp.media.length > 1) {
  12339. switch(self.pendingop) {
  12340. case 'mute':
  12341. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12342. break;
  12343. case 'unmute':
  12344. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12345. break;
  12346. }
  12347. sdp.raw = sdp.session + sdp.media.join('');
  12348. modifiedAnswer.sdp = sdp.raw;
  12349. }
  12350. self.pendingop = null;
  12351. }
  12352. // FIXME: pushing down an answer while ice connection state
  12353. // is still checking is bad...
  12354. //console.log(self.peerconnection.iceConnectionState);
  12355. // trying to work around another chrome bug
  12356. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12357. self.peerconnection.setLocalDescription(modifiedAnswer,
  12358. function() {
  12359. //console.log('modified setLocalDescription ok');
  12360. self.setLocalDescription();
  12361. if(successCallback){
  12362. successCallback();
  12363. }
  12364. queueCallback();
  12365. },
  12366. function(error) {
  12367. console.error('modified setLocalDescription failed', error);
  12368. queueCallback(error);
  12369. }
  12370. );
  12371. },
  12372. function(error) {
  12373. console.error('modified answer failed', error);
  12374. queueCallback(error);
  12375. }
  12376. );
  12377. },
  12378. function(error) {
  12379. console.error('modify failed', error);
  12380. queueCallback(error);
  12381. }
  12382. );
  12383. };
  12384. /**
  12385. * Switches video streams.
  12386. * @param new_stream new stream that will be used as video of this session.
  12387. * @param oldStream old video stream of this session.
  12388. * @param success_callback callback executed after successful stream switch.
  12389. */
  12390. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12391. var self = this;
  12392. // Remember SDP to figure out added/removed SSRCs
  12393. var oldSdp = null;
  12394. if(self.peerconnection) {
  12395. if(self.peerconnection.localDescription) {
  12396. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12397. }
  12398. self.peerconnection.removeStream(oldStream, true);
  12399. if(new_stream)
  12400. self.peerconnection.addStream(new_stream);
  12401. }
  12402. // Conference is not active
  12403. if(!oldSdp || !self.peerconnection) {
  12404. success_callback();
  12405. return;
  12406. }
  12407. self.switchstreams = true;
  12408. self.modifySourcesQueue.push(function() {
  12409. console.log('modify sources done');
  12410. success_callback();
  12411. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12412. console.log("SDPs", oldSdp, newSdp);
  12413. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12414. });
  12415. };
  12416. /**
  12417. * Figures out added/removed ssrcs and send update IQs.
  12418. * @param old_sdp SDP object for old description.
  12419. * @param new_sdp SDP object for new description.
  12420. */
  12421. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12422. if (!(this.peerconnection.signalingState == 'stable' &&
  12423. this.peerconnection.iceConnectionState == 'connected')){
  12424. console.log("Too early to send updates");
  12425. return;
  12426. }
  12427. // send source-remove IQ.
  12428. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12429. var remove = $iq({to: this.peerjid, type: 'set'})
  12430. .c('jingle', {
  12431. xmlns: 'urn:xmpp:jingle:1',
  12432. action: 'source-remove',
  12433. initiator: this.initiator,
  12434. sid: this.sid
  12435. }
  12436. );
  12437. var removed = sdpDiffer.toJingle(remove);
  12438. if (removed) {
  12439. this.connection.sendIQ(remove,
  12440. function (res) {
  12441. console.info('got remove result', res);
  12442. },
  12443. function (err) {
  12444. console.error('got remove error', err);
  12445. }
  12446. );
  12447. } else {
  12448. console.log('removal not necessary');
  12449. }
  12450. // send source-add IQ.
  12451. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12452. var add = $iq({to: this.peerjid, type: 'set'})
  12453. .c('jingle', {
  12454. xmlns: 'urn:xmpp:jingle:1',
  12455. action: 'source-add',
  12456. initiator: this.initiator,
  12457. sid: this.sid
  12458. }
  12459. );
  12460. var added = sdpDiffer.toJingle(add, this.getVideoType());
  12461. if (added) {
  12462. this.connection.sendIQ(add,
  12463. function (res) {
  12464. console.info('got add result', res);
  12465. },
  12466. function (err) {
  12467. console.error('got add error', err);
  12468. }
  12469. );
  12470. } else {
  12471. console.log('addition not necessary');
  12472. }
  12473. };
  12474. /**
  12475. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12476. *
  12477. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12478. * tracks; otherwise, <tt>false</tt>
  12479. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12480. * tracks have been enabled/disabled. The function may, optionally, return
  12481. * another function which is to be invoked after the whole mute/unmute operation
  12482. * has completed successfully.
  12483. * @param options an object which specifies optional arguments such as the
  12484. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12485. * specifies whether the method was initiated in response to a user command (in
  12486. * contrast to an automatic decision made by the application logic)
  12487. */
  12488. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12489. var byUser;
  12490. if (options) {
  12491. byUser = options.byUser;
  12492. if (typeof byUser === 'undefined') {
  12493. byUser = true;
  12494. }
  12495. } else {
  12496. byUser = true;
  12497. }
  12498. // The user's command to mute the (local) video takes precedence over any
  12499. // automatic decision made by the application logic.
  12500. if (byUser) {
  12501. this.videoMuteByUser = mute;
  12502. } else if (this.videoMuteByUser) {
  12503. return;
  12504. }
  12505. this.hardMuteVideo(mute);
  12506. var self = this;
  12507. var oldSdp = null;
  12508. if(self.peerconnection) {
  12509. if(self.peerconnection.localDescription) {
  12510. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12511. }
  12512. }
  12513. this.modifySourcesQueue.push(function() {
  12514. console.log('modify sources done');
  12515. callback(mute);
  12516. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12517. console.log("SDPs", oldSdp, newSdp);
  12518. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12519. });
  12520. };
  12521. JingleSession.prototype.hardMuteVideo = function (muted) {
  12522. this.pendingop = muted ? 'mute' : 'unmute';
  12523. };
  12524. JingleSession.prototype.sendMute = function (muted, content) {
  12525. var info = $iq({to: this.peerjid,
  12526. type: 'set'})
  12527. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12528. action: 'session-info',
  12529. initiator: this.initiator,
  12530. sid: this.sid });
  12531. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12532. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12533. if (content) {
  12534. info.attrs({'name': content});
  12535. }
  12536. this.connection.send(info);
  12537. };
  12538. JingleSession.prototype.sendRinging = function () {
  12539. var info = $iq({to: this.peerjid,
  12540. type: 'set'})
  12541. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12542. action: 'session-info',
  12543. initiator: this.initiator,
  12544. sid: this.sid });
  12545. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12546. this.connection.send(info);
  12547. };
  12548. JingleSession.prototype.getStats = function (interval) {
  12549. var self = this;
  12550. var recv = {audio: 0, video: 0};
  12551. var lost = {audio: 0, video: 0};
  12552. var lastrecv = {audio: 0, video: 0};
  12553. var lastlost = {audio: 0, video: 0};
  12554. var loss = {audio: 0, video: 0};
  12555. var delta = {audio: 0, video: 0};
  12556. this.statsinterval = window.setInterval(function () {
  12557. if (self && self.peerconnection && self.peerconnection.getStats) {
  12558. self.peerconnection.getStats(function (stats) {
  12559. var results = stats.result();
  12560. // TODO: there are so much statistics you can get from this..
  12561. for (var i = 0; i < results.length; ++i) {
  12562. if (results[i].type == 'ssrc') {
  12563. var packetsrecv = results[i].stat('packetsReceived');
  12564. var packetslost = results[i].stat('packetsLost');
  12565. if (packetsrecv && packetslost) {
  12566. packetsrecv = parseInt(packetsrecv, 10);
  12567. packetslost = parseInt(packetslost, 10);
  12568. if (results[i].stat('googFrameRateReceived')) {
  12569. lastlost.video = lost.video;
  12570. lastrecv.video = recv.video;
  12571. recv.video = packetsrecv;
  12572. lost.video = packetslost;
  12573. } else {
  12574. lastlost.audio = lost.audio;
  12575. lastrecv.audio = recv.audio;
  12576. recv.audio = packetsrecv;
  12577. lost.audio = packetslost;
  12578. }
  12579. }
  12580. }
  12581. }
  12582. delta.audio = recv.audio - lastrecv.audio;
  12583. delta.video = recv.video - lastrecv.video;
  12584. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12585. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12586. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12587. });
  12588. }
  12589. }, interval || 3000);
  12590. return this.statsinterval;
  12591. };
  12592. JingleSession.onJingleError = function (session, error)
  12593. {
  12594. console.error("Jingle error", error);
  12595. }
  12596. JingleSession.onJingleFatalError = function (session, error)
  12597. {
  12598. this.service.sessionTerminated = true;
  12599. this.connection.emuc.doLeave();
  12600. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12601. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12602. }
  12603. JingleSession.prototype.setLocalDescription = function () {
  12604. var self = this;
  12605. var newssrcs = [];
  12606. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12607. session.media.forEach(function (media) {
  12608. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12609. // TODO(gp) maybe exclude FID streams?
  12610. media.ssrcs.forEach(function (ssrc) {
  12611. if (ssrc.attribute !== 'cname') {
  12612. return;
  12613. }
  12614. newssrcs.push({
  12615. 'ssrc': ssrc.id,
  12616. 'type': media.type
  12617. });
  12618. });
  12619. }
  12620. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12621. {
  12622. newssrcs.push({
  12623. 'ssrc': self.localStreamsSSRC[media.type],
  12624. 'type': media.type
  12625. });
  12626. }
  12627. });
  12628. console.log('new ssrcs', newssrcs);
  12629. // Bind us as local SSRCs owner
  12630. if (newssrcs.length > 0) {
  12631. for (var i = 1; i <= newssrcs.length; i ++) {
  12632. var ssrc = newssrcs[i-1].ssrc;
  12633. var myJid = self.connection.emuc.myroomjid;
  12634. self.ssrcOwners[ssrc] = myJid;
  12635. if (newssrcs[i-1].type === 'video'){
  12636. self.ssrcVideoTypes[ssrc] = self.getVideoType();
  12637. }
  12638. }
  12639. }
  12640. }
  12641. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12642. function sendKeyframe(pc) {
  12643. console.log('sendkeyframe', pc.iceConnectionState);
  12644. if (pc.iceConnectionState !== 'connected') return; // safe...
  12645. var self = this;
  12646. pc.setRemoteDescription(
  12647. pc.remoteDescription,
  12648. function () {
  12649. pc.createAnswer(
  12650. function (modifiedAnswer) {
  12651. pc.setLocalDescription(
  12652. modifiedAnswer,
  12653. function () {
  12654. // noop
  12655. },
  12656. function (error) {
  12657. console.log('triggerKeyframe setLocalDescription failed', error);
  12658. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  12659. }
  12660. );
  12661. },
  12662. function (error) {
  12663. console.log('triggerKeyframe createAnswer failed', error);
  12664. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  12665. }
  12666. );
  12667. },
  12668. function (error) {
  12669. console.log('triggerKeyframe setRemoteDescription failed', error);
  12670. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  12671. }
  12672. );
  12673. }
  12674. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12675. var self = this;
  12676. var thessrc;
  12677. var streamId = APP.RTC.getStreamID(data.stream);
  12678. // look up an associated JID for a stream id
  12679. if (!streamId) {
  12680. console.error("No stream ID for", data.stream);
  12681. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12682. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12683. var ssrclines
  12684. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12685. ssrclines = ssrclines.filter(function (line) {
  12686. // NOTE(gp) previously we filtered on the mslabel, but that property
  12687. // is not always present.
  12688. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12689. if (RTCBrowserType.isTemasysPluginUsed()) {
  12690. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12691. } else {
  12692. return ((line.indexOf('msid:' + streamId) !== -1));
  12693. }
  12694. });
  12695. if (ssrclines.length) {
  12696. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12697. if (!self.ssrcOwners[thessrc]) {
  12698. console.error("No SSRC owner known for: " + thessrc);
  12699. return;
  12700. }
  12701. data.peerjid = self.ssrcOwners[thessrc];
  12702. data.videoType = self.ssrcVideoTypes[thessrc]
  12703. console.log('associated jid', self.ssrcOwners[thessrc],
  12704. thessrc, data.videoType);
  12705. } else {
  12706. console.error("No SSRC lines for ", streamId);
  12707. }
  12708. }
  12709. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12710. var isVideo = data.stream.getVideoTracks().length > 0;
  12711. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12712. if (isVideo &&
  12713. data.peerjid && this.peerjid === data.peerjid &&
  12714. data.stream.getVideoTracks().length === 0 &&
  12715. APP.RTC.localVideo.getTracks().length > 0) {
  12716. window.setTimeout(function () {
  12717. sendKeyframe(self.peerconnection);
  12718. }, 3000);
  12719. }
  12720. }
  12721. module.exports = JingleSession;
  12722. },{"../../service/xmpp/XMPPEvents":116,"../RTC/RTCBrowserType":8,"./SDP":54,"./SDPDiffer":55,"./SDPUtil":56,"./TraceablePeerConnection":57,"async":67,"sdp-transform":103}],54:[function(require,module,exports){
  12723. /* jshint -W117 */
  12724. var SDPUtil = require("./SDPUtil");
  12725. // SDP STUFF
  12726. function SDP(sdp) {
  12727. this.media = sdp.split('\r\nm=');
  12728. for (var i = 1; i < this.media.length; i++) {
  12729. this.media[i] = 'm=' + this.media[i];
  12730. if (i != this.media.length - 1) {
  12731. this.media[i] += '\r\n';
  12732. }
  12733. }
  12734. this.session = this.media.shift() + '\r\n';
  12735. this.raw = this.session + this.media.join('');
  12736. }
  12737. /**
  12738. * Returns map of MediaChannel mapped per channel idx.
  12739. */
  12740. SDP.prototype.getMediaSsrcMap = function() {
  12741. var self = this;
  12742. var media_ssrcs = {};
  12743. var tmp;
  12744. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12745. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12746. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12747. var media = {
  12748. mediaindex: mediaindex,
  12749. mid: mid,
  12750. ssrcs: {},
  12751. ssrcGroups: []
  12752. };
  12753. media_ssrcs[mediaindex] = media;
  12754. tmp.forEach(function (line) {
  12755. var linessrc = line.substring(7).split(' ')[0];
  12756. // allocate new ChannelSsrc
  12757. if(!media.ssrcs[linessrc]) {
  12758. media.ssrcs[linessrc] = {
  12759. ssrc: linessrc,
  12760. lines: []
  12761. };
  12762. }
  12763. media.ssrcs[linessrc].lines.push(line);
  12764. });
  12765. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12766. tmp.forEach(function(line){
  12767. var semantics = line.substr(0, idx).substr(13);
  12768. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12769. if (ssrcs.length != 0) {
  12770. media.ssrcGroups.push({
  12771. semantics: semantics,
  12772. ssrcs: ssrcs
  12773. });
  12774. }
  12775. });
  12776. }
  12777. return media_ssrcs;
  12778. };
  12779. /**
  12780. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12781. * @param ssrc the ssrc to check.
  12782. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12783. */
  12784. SDP.prototype.containsSSRC = function(ssrc) {
  12785. var medias = this.getMediaSsrcMap();
  12786. var contains = false;
  12787. Object.keys(medias).forEach(function(mediaindex){
  12788. var media = medias[mediaindex];
  12789. //console.log("Check", channel, ssrc);
  12790. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12791. contains = true;
  12792. }
  12793. });
  12794. return contains;
  12795. };
  12796. // remove iSAC and CN from SDP
  12797. SDP.prototype.mangle = function () {
  12798. var i, j, mline, lines, rtpmap, newdesc;
  12799. for (i = 0; i < this.media.length; i++) {
  12800. lines = this.media[i].split('\r\n');
  12801. lines.pop(); // remove empty last element
  12802. mline = SDPUtil.parse_mline(lines.shift());
  12803. if (mline.media != 'audio')
  12804. continue;
  12805. newdesc = '';
  12806. mline.fmt.length = 0;
  12807. for (j = 0; j < lines.length; j++) {
  12808. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12809. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12810. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12811. continue;
  12812. mline.fmt.push(rtpmap.id);
  12813. newdesc += lines[j] + '\r\n';
  12814. } else {
  12815. newdesc += lines[j] + '\r\n';
  12816. }
  12817. }
  12818. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12819. this.media[i] += newdesc;
  12820. }
  12821. this.raw = this.session + this.media.join('');
  12822. };
  12823. // remove lines matching prefix from session section
  12824. SDP.prototype.removeSessionLines = function(prefix) {
  12825. var self = this;
  12826. var lines = SDPUtil.find_lines(this.session, prefix);
  12827. lines.forEach(function(line) {
  12828. self.session = self.session.replace(line + '\r\n', '');
  12829. });
  12830. this.raw = this.session + this.media.join('');
  12831. return lines;
  12832. }
  12833. // remove lines matching prefix from a media section specified by mediaindex
  12834. // TODO: non-numeric mediaindex could match mid
  12835. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12836. var self = this;
  12837. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12838. lines.forEach(function(line) {
  12839. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12840. });
  12841. this.raw = this.session + this.media.join('');
  12842. return lines;
  12843. }
  12844. // add content's to a jingle element
  12845. SDP.prototype.toJingle = function (elem, thecreator, ssrcs, videoType) {
  12846. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12847. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12848. var self = this;
  12849. // new bundle plan
  12850. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12851. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12852. for (i = 0; i < lines.length; i++) {
  12853. tmp = lines[i].split(' ');
  12854. var semantics = tmp.shift().substr(8);
  12855. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12856. for (j = 0; j < tmp.length; j++) {
  12857. elem.c('content', {name: tmp[j]}).up();
  12858. }
  12859. elem.up();
  12860. }
  12861. }
  12862. for (i = 0; i < this.media.length; i++) {
  12863. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12864. if (!(mline.media === 'audio' ||
  12865. mline.media === 'video' ||
  12866. mline.media === 'application'))
  12867. {
  12868. continue;
  12869. }
  12870. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12871. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12872. } else {
  12873. if(ssrcs && ssrcs[mline.media])
  12874. {
  12875. ssrc = ssrcs[mline.media];
  12876. }
  12877. else
  12878. ssrc = false;
  12879. }
  12880. elem.c('content', {creator: thecreator, name: mline.media});
  12881. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12882. // prefer identifier from a=mid if present
  12883. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12884. elem.attrs({ name: mid });
  12885. }
  12886. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12887. {
  12888. elem.c('description',
  12889. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12890. media: mline.media });
  12891. if (ssrc) {
  12892. elem.attrs({ssrc: ssrc});
  12893. }
  12894. for (j = 0; j < mline.fmt.length; j++) {
  12895. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12896. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12897. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12898. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12899. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12900. for (k = 0; k < tmp.length; k++) {
  12901. elem.c('parameter', tmp[k]).up();
  12902. }
  12903. }
  12904. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12905. elem.up();
  12906. }
  12907. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12908. elem.c('encryption', {required: 1});
  12909. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12910. crypto.forEach(function(line) {
  12911. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12912. });
  12913. elem.up(); // end of encryption
  12914. }
  12915. if (ssrc) {
  12916. // new style mapping
  12917. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12918. // FIXME: group by ssrc and support multiple different ssrcs
  12919. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12920. if(ssrclines.length > 0) {
  12921. ssrclines.forEach(function (line) {
  12922. idx = line.indexOf(' ');
  12923. var linessrc = line.substr(0, idx).substr(7);
  12924. if (linessrc != ssrc) {
  12925. elem.up();
  12926. ssrc = linessrc;
  12927. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12928. }
  12929. var kv = line.substr(idx + 1);
  12930. elem.c('parameter');
  12931. if (kv.indexOf(':') == -1) {
  12932. elem.attrs({ name: kv });
  12933. } else {
  12934. var k = kv.split(':', 2)[0];
  12935. elem.attrs({ name: k });
  12936. var v = kv.split(':', 2)[1];
  12937. v = SDPUtil.filter_special_chars(v);
  12938. elem.attrs({ value: v });
  12939. }
  12940. elem.up();
  12941. });
  12942. }
  12943. else
  12944. {
  12945. elem.up();
  12946. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12947. elem.c('parameter');
  12948. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12949. elem.up();
  12950. var msid = null;
  12951. if(mline.media == "audio")
  12952. {
  12953. msid = APP.RTC.localAudio.getId();
  12954. }
  12955. else
  12956. {
  12957. msid = APP.RTC.localVideo.getId();
  12958. }
  12959. if(msid != null)
  12960. {
  12961. msid = SDPUtil.filter_special_chars(msid);
  12962. elem.c('parameter');
  12963. elem.attrs({name: "msid", value:msid});
  12964. elem.up();
  12965. elem.c('parameter');
  12966. elem.attrs({name: "mslabel", value:msid});
  12967. elem.up();
  12968. elem.c('parameter');
  12969. elem.attrs({name: "label", value:msid});
  12970. elem.up();
  12971. }
  12972. }
  12973. // Video type
  12974. if (videoType && mline.media == "video") {
  12975. elem.c('ssrc-info',
  12976. {
  12977. xmlns: 'http://jitsi.org/jitmeet',
  12978. 'video-type': videoType
  12979. }).up();
  12980. }
  12981. elem.up();
  12982. // XEP-0339 handle ssrc-group attributes
  12983. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12984. ssrc_group_lines.forEach(function(line) {
  12985. idx = line.indexOf(' ');
  12986. var semantics = line.substr(0, idx).substr(13);
  12987. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12988. if (ssrcs.length != 0) {
  12989. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12990. ssrcs.forEach(function(ssrc) {
  12991. elem.c('source', { ssrc: ssrc })
  12992. .up();
  12993. });
  12994. elem.up();
  12995. }
  12996. });
  12997. }
  12998. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12999. elem.c('rtcp-mux').up();
  13000. }
  13001. // XEP-0293 -- map a=rtcp-fb:*
  13002. this.RtcpFbToJingle(i, elem, '*');
  13003. // XEP-0294
  13004. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13005. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13006. for (j = 0; j < lines.length; j++) {
  13007. tmp = SDPUtil.parse_extmap(lines[j]);
  13008. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13009. uri: tmp.uri,
  13010. id: tmp.value });
  13011. if (tmp.hasOwnProperty('direction')) {
  13012. switch (tmp.direction) {
  13013. case 'sendonly':
  13014. elem.attrs({senders: 'responder'});
  13015. break;
  13016. case 'recvonly':
  13017. elem.attrs({senders: 'initiator'});
  13018. break;
  13019. case 'sendrecv':
  13020. elem.attrs({senders: 'both'});
  13021. break;
  13022. case 'inactive':
  13023. elem.attrs({senders: 'none'});
  13024. break;
  13025. }
  13026. }
  13027. // TODO: handle params
  13028. elem.up();
  13029. }
  13030. }
  13031. elem.up(); // end of description
  13032. }
  13033. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13034. this.TransportToJingle(i, elem);
  13035. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13036. elem.attrs({senders: 'both'});
  13037. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13038. elem.attrs({senders: 'initiator'});
  13039. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13040. elem.attrs({senders: 'responder'});
  13041. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13042. elem.attrs({senders: 'none'});
  13043. }
  13044. if (mline.port == '0') {
  13045. // estos hack to reject an m-line
  13046. elem.attrs({senders: 'rejected'});
  13047. }
  13048. elem.up(); // end of content
  13049. }
  13050. elem.up();
  13051. return elem;
  13052. };
  13053. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13054. var i = mediaindex;
  13055. var tmp;
  13056. var self = this;
  13057. elem.c('transport');
  13058. // XEP-0343 DTLS/SCTP
  13059. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13060. {
  13061. var sctpmap = SDPUtil.find_line(
  13062. this.media[i], 'a=sctpmap:', self.session);
  13063. if (sctpmap)
  13064. {
  13065. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13066. elem.c('sctpmap',
  13067. {
  13068. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13069. number: sctpAttrs[0], /* SCTP port */
  13070. protocol: sctpAttrs[1], /* protocol */
  13071. });
  13072. // Optional stream count attribute
  13073. if (sctpAttrs.length > 2)
  13074. elem.attrs({ streams: sctpAttrs[2]});
  13075. elem.up();
  13076. }
  13077. }
  13078. // XEP-0320
  13079. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13080. fingerprints.forEach(function(line) {
  13081. tmp = SDPUtil.parse_fingerprint(line);
  13082. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13083. elem.c('fingerprint').t(tmp.fingerprint);
  13084. delete tmp.fingerprint;
  13085. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13086. if (line) {
  13087. tmp.setup = line.substr(8);
  13088. }
  13089. elem.attrs(tmp);
  13090. elem.up(); // end of fingerprint
  13091. });
  13092. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13093. if (tmp) {
  13094. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13095. elem.attrs(tmp);
  13096. // XEP-0176
  13097. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13098. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13099. lines.forEach(function (line) {
  13100. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13101. });
  13102. }
  13103. }
  13104. elem.up(); // end of transport
  13105. }
  13106. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13107. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13108. lines.forEach(function (line) {
  13109. var tmp = SDPUtil.parse_rtcpfb(line);
  13110. if (tmp.type == 'trr-int') {
  13111. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13112. elem.up();
  13113. } else {
  13114. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13115. if (tmp.params.length > 0) {
  13116. elem.attrs({'subtype': tmp.params[0]});
  13117. }
  13118. elem.up();
  13119. }
  13120. });
  13121. };
  13122. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13123. var media = '';
  13124. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13125. if (tmp.length) {
  13126. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13127. if (tmp.attr('value')) {
  13128. media += tmp.attr('value');
  13129. } else {
  13130. media += '0';
  13131. }
  13132. media += '\r\n';
  13133. }
  13134. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13135. tmp.each(function () {
  13136. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13137. if ($(this).attr('subtype')) {
  13138. media += ' ' + $(this).attr('subtype');
  13139. }
  13140. media += '\r\n';
  13141. });
  13142. return media;
  13143. };
  13144. // construct an SDP from a jingle stanza
  13145. SDP.prototype.fromJingle = function (jingle) {
  13146. var self = this;
  13147. this.raw = 'v=0\r\n' +
  13148. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13149. 's=-\r\n' +
  13150. 't=0 0\r\n';
  13151. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13152. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13153. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13154. var contents = $(group).find('>content').map(function (idx, content) {
  13155. return content.getAttribute('name');
  13156. }).get();
  13157. if (contents.length > 0) {
  13158. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13159. }
  13160. });
  13161. }
  13162. this.session = this.raw;
  13163. jingle.find('>content').each(function () {
  13164. var m = self.jingle2media($(this));
  13165. self.media.push(m);
  13166. });
  13167. // reconstruct msid-semantic -- apparently not necessary
  13168. /*
  13169. var msid = SDPUtil.parse_ssrc(this.raw);
  13170. if (msid.hasOwnProperty('mslabel')) {
  13171. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13172. }
  13173. */
  13174. this.raw = this.session + this.media.join('');
  13175. };
  13176. // translate a jingle content element into an an SDP media part
  13177. SDP.prototype.jingle2media = function (content) {
  13178. var media = '',
  13179. desc = content.find('description'),
  13180. ssrc = desc.attr('ssrc'),
  13181. self = this,
  13182. tmp;
  13183. var sctp = content.find(
  13184. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13185. tmp = { media: desc.attr('media') };
  13186. tmp.port = '1';
  13187. if (content.attr('senders') == 'rejected') {
  13188. // estos hack to reject an m-line.
  13189. tmp.port = '0';
  13190. }
  13191. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13192. if (sctp.length)
  13193. tmp.proto = 'DTLS/SCTP';
  13194. else
  13195. tmp.proto = 'RTP/SAVPF';
  13196. } else {
  13197. tmp.proto = 'RTP/AVPF';
  13198. }
  13199. if (!sctp.length)
  13200. {
  13201. tmp.fmt = desc.find('payload-type').map(
  13202. function () { return this.getAttribute('id'); }).get();
  13203. media += SDPUtil.build_mline(tmp) + '\r\n';
  13204. }
  13205. else
  13206. {
  13207. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13208. media += 'a=sctpmap:' + sctp.attr('number') +
  13209. ' ' + sctp.attr('protocol');
  13210. var streamCount = sctp.attr('streams');
  13211. if (streamCount)
  13212. media += ' ' + streamCount + '\r\n';
  13213. else
  13214. media += '\r\n';
  13215. }
  13216. media += 'c=IN IP4 0.0.0.0\r\n';
  13217. if (!sctp.length)
  13218. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13219. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13220. if (tmp.length) {
  13221. if (tmp.attr('ufrag')) {
  13222. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13223. }
  13224. if (tmp.attr('pwd')) {
  13225. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13226. }
  13227. tmp.find('>fingerprint').each(function () {
  13228. // FIXME: check namespace at some point
  13229. media += 'a=fingerprint:' + this.getAttribute('hash');
  13230. media += ' ' + $(this).text();
  13231. media += '\r\n';
  13232. if (this.getAttribute('setup')) {
  13233. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13234. }
  13235. });
  13236. }
  13237. switch (content.attr('senders')) {
  13238. case 'initiator':
  13239. media += 'a=sendonly\r\n';
  13240. break;
  13241. case 'responder':
  13242. media += 'a=recvonly\r\n';
  13243. break;
  13244. case 'none':
  13245. media += 'a=inactive\r\n';
  13246. break;
  13247. case 'both':
  13248. media += 'a=sendrecv\r\n';
  13249. break;
  13250. }
  13251. media += 'a=mid:' + content.attr('name') + '\r\n';
  13252. // <description><rtcp-mux/></description>
  13253. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13254. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13255. if (desc.find('rtcp-mux').length) {
  13256. media += 'a=rtcp-mux\r\n';
  13257. }
  13258. if (desc.find('encryption').length) {
  13259. desc.find('encryption>crypto').each(function () {
  13260. media += 'a=crypto:' + this.getAttribute('tag');
  13261. media += ' ' + this.getAttribute('crypto-suite');
  13262. media += ' ' + this.getAttribute('key-params');
  13263. if (this.getAttribute('session-params')) {
  13264. media += ' ' + this.getAttribute('session-params');
  13265. }
  13266. media += '\r\n';
  13267. });
  13268. }
  13269. desc.find('payload-type').each(function () {
  13270. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13271. if ($(this).find('>parameter').length) {
  13272. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13273. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13274. media += '\r\n';
  13275. }
  13276. // xep-0293
  13277. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13278. });
  13279. // xep-0293
  13280. media += self.RtcpFbFromJingle(desc, '*');
  13281. // xep-0294
  13282. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13283. tmp.each(function () {
  13284. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13285. });
  13286. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13287. media += SDPUtil.candidateFromJingle(this);
  13288. });
  13289. // XEP-0339 handle ssrc-group attributes
  13290. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13291. var semantics = this.getAttribute('semantics');
  13292. var ssrcs = $(this).find('>source').map(function() {
  13293. return this.getAttribute('ssrc');
  13294. }).get();
  13295. if (ssrcs.length != 0) {
  13296. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13297. }
  13298. });
  13299. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13300. tmp.each(function () {
  13301. var ssrc = this.getAttribute('ssrc');
  13302. $(this).find('>parameter').each(function () {
  13303. var name = this.getAttribute('name');
  13304. var value = this.getAttribute('value');
  13305. value = SDPUtil.filter_special_chars(value);
  13306. media += 'a=ssrc:' + ssrc + ' ' + name;
  13307. if (value && value.length)
  13308. media += ':' + value;
  13309. media += '\r\n';
  13310. });
  13311. });
  13312. return media;
  13313. };
  13314. module.exports = SDP;
  13315. },{"./SDPUtil":56}],55:[function(require,module,exports){
  13316. var SDPUtil = require("./SDPUtil");
  13317. function SDPDiffer(mySDP, otherSDP) {
  13318. this.mySDP = mySDP;
  13319. this.otherSDP = otherSDP;
  13320. }
  13321. /**
  13322. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13323. * @param otherSdp the other SDP to check ssrc with.
  13324. */
  13325. SDPDiffer.prototype.getNewMedia = function() {
  13326. // this could be useful in Array.prototype.
  13327. function arrayEquals(array) {
  13328. // if the other array is a falsy value, return
  13329. if (!array)
  13330. return false;
  13331. // compare lengths - can save a lot of time
  13332. if (this.length != array.length)
  13333. return false;
  13334. for (var i = 0, l=this.length; i < l; i++) {
  13335. // Check if we have nested arrays
  13336. if (this[i] instanceof Array && array[i] instanceof Array) {
  13337. // recurse into the nested arrays
  13338. if (!this[i].equals(array[i]))
  13339. return false;
  13340. }
  13341. else if (this[i] != array[i]) {
  13342. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13343. return false;
  13344. }
  13345. }
  13346. return true;
  13347. }
  13348. var myMedias = this.mySDP.getMediaSsrcMap();
  13349. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13350. var newMedia = {};
  13351. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13352. var myMedia = myMedias[othersMediaIdx];
  13353. var othersMedia = othersMedias[othersMediaIdx];
  13354. if(!myMedia && othersMedia) {
  13355. // Add whole channel
  13356. newMedia[othersMediaIdx] = othersMedia;
  13357. return;
  13358. }
  13359. // Look for new ssrcs accross the channel
  13360. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13361. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13362. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13363. if(!newMedia[othersMediaIdx]){
  13364. newMedia[othersMediaIdx] = {
  13365. mediaindex: othersMedia.mediaindex,
  13366. mid: othersMedia.mid,
  13367. ssrcs: {},
  13368. ssrcGroups: []
  13369. };
  13370. }
  13371. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13372. }
  13373. });
  13374. // Look for new ssrc groups across the channels
  13375. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13376. // try to match the other ssrc-group with an ssrc-group of ours
  13377. var matched = false;
  13378. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13379. var mySsrcGroup = myMedia.ssrcGroups[i];
  13380. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13381. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13382. matched = true;
  13383. break;
  13384. }
  13385. }
  13386. if (!matched) {
  13387. // Allocate channel if we've found an ssrc-group that doesn't
  13388. // exist in our channel
  13389. if(!newMedia[othersMediaIdx]){
  13390. newMedia[othersMediaIdx] = {
  13391. mediaindex: othersMedia.mediaindex,
  13392. mid: othersMedia.mid,
  13393. ssrcs: {},
  13394. ssrcGroups: []
  13395. };
  13396. }
  13397. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13398. }
  13399. });
  13400. });
  13401. return newMedia;
  13402. };
  13403. /**
  13404. * Sends SSRC update IQ.
  13405. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13406. * @param sid session identifier that will be put into the IQ.
  13407. * @param initiator initiator identifier.
  13408. * @param toJid destination Jid
  13409. * @param isAdd indicates if this is remove or add operation.
  13410. */
  13411. SDPDiffer.prototype.toJingle = function(modify, videoType) {
  13412. var sdpMediaSsrcs = this.getNewMedia();
  13413. var self = this;
  13414. // FIXME: only announce video ssrcs since we mix audio and dont need
  13415. // the audio ssrcs therefore
  13416. var modified = false;
  13417. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13418. modified = true;
  13419. var media = sdpMediaSsrcs[mediaindex];
  13420. modify.c('content', {name: media.mid});
  13421. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13422. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13423. // generate sources from lines
  13424. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13425. var mediaSsrc = media.ssrcs[ssrcNum];
  13426. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13427. modify.attrs({ssrc: mediaSsrc.ssrc});
  13428. // iterate over ssrc lines
  13429. mediaSsrc.lines.forEach(function (line) {
  13430. var idx = line.indexOf(' ');
  13431. var kv = line.substr(idx + 1);
  13432. modify.c('parameter');
  13433. if (kv.indexOf(':') == -1) {
  13434. modify.attrs({ name: kv });
  13435. } else {
  13436. var nv = kv.split(':', 2);
  13437. var name = nv[0];
  13438. var value = SDPUtil.filter_special_chars(nv[1]);
  13439. modify.attrs({ name: name });
  13440. modify.attrs({ value: value });
  13441. }
  13442. modify.up(); // end of parameter
  13443. });
  13444. // indicate video type
  13445. if (videoType && media.mid == 'video') {
  13446. modify.c('ssrc-info',
  13447. {
  13448. xmlns: 'http://jitsi.org/jitmeet',
  13449. 'video-type': videoType
  13450. })
  13451. .up();
  13452. }
  13453. modify.up(); // end of source
  13454. });
  13455. // generate source groups from lines
  13456. media.ssrcGroups.forEach(function(ssrcGroup) {
  13457. if (ssrcGroup.ssrcs.length != 0) {
  13458. modify.c('ssrc-group', {
  13459. semantics: ssrcGroup.semantics,
  13460. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13461. });
  13462. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13463. modify.c('source', { ssrc: ssrc })
  13464. .up(); // end of source
  13465. });
  13466. modify.up(); // end of ssrc-group
  13467. }
  13468. });
  13469. modify.up(); // end of description
  13470. modify.up(); // end of content
  13471. });
  13472. return modified;
  13473. };
  13474. module.exports = SDPDiffer;
  13475. },{"./SDPUtil":56}],56:[function(require,module,exports){
  13476. SDPUtil = {
  13477. filter_special_chars: function (text) {
  13478. return text.replace(/[\\\/\{,\}\+]/g, "");
  13479. },
  13480. iceparams: function (mediadesc, sessiondesc) {
  13481. var data = null;
  13482. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13483. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13484. data = {
  13485. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13486. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13487. };
  13488. }
  13489. return data;
  13490. },
  13491. parse_iceufrag: function (line) {
  13492. return line.substring(12);
  13493. },
  13494. build_iceufrag: function (frag) {
  13495. return 'a=ice-ufrag:' + frag;
  13496. },
  13497. parse_icepwd: function (line) {
  13498. return line.substring(10);
  13499. },
  13500. build_icepwd: function (pwd) {
  13501. return 'a=ice-pwd:' + pwd;
  13502. },
  13503. parse_mid: function (line) {
  13504. return line.substring(6);
  13505. },
  13506. parse_mline: function (line) {
  13507. var parts = line.substring(2).split(' '),
  13508. data = {};
  13509. data.media = parts.shift();
  13510. data.port = parts.shift();
  13511. data.proto = parts.shift();
  13512. if (parts[parts.length - 1] === '') { // trailing whitespace
  13513. parts.pop();
  13514. }
  13515. data.fmt = parts;
  13516. return data;
  13517. },
  13518. build_mline: function (mline) {
  13519. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13520. },
  13521. parse_rtpmap: function (line) {
  13522. var parts = line.substring(9).split(' '),
  13523. data = {};
  13524. data.id = parts.shift();
  13525. parts = parts[0].split('/');
  13526. data.name = parts.shift();
  13527. data.clockrate = parts.shift();
  13528. data.channels = parts.length ? parts.shift() : '1';
  13529. return data;
  13530. },
  13531. /**
  13532. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13533. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13534. * @returns [SCTP port number, protocol, streams]
  13535. */
  13536. parse_sctpmap: function (line)
  13537. {
  13538. var parts = line.substring(10).split(' ');
  13539. var sctpPort = parts[0];
  13540. var protocol = parts[1];
  13541. // Stream count is optional
  13542. var streamCount = parts.length > 2 ? parts[2] : null;
  13543. return [sctpPort, protocol, streamCount];// SCTP port
  13544. },
  13545. build_rtpmap: function (el) {
  13546. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13547. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13548. line += '/' + el.getAttribute('channels');
  13549. }
  13550. return line;
  13551. },
  13552. parse_crypto: function (line) {
  13553. var parts = line.substring(9).split(' '),
  13554. data = {};
  13555. data.tag = parts.shift();
  13556. data['crypto-suite'] = parts.shift();
  13557. data['key-params'] = parts.shift();
  13558. if (parts.length) {
  13559. data['session-params'] = parts.join(' ');
  13560. }
  13561. return data;
  13562. },
  13563. parse_fingerprint: function (line) { // RFC 4572
  13564. var parts = line.substring(14).split(' '),
  13565. data = {};
  13566. data.hash = parts.shift();
  13567. data.fingerprint = parts.shift();
  13568. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13569. return data;
  13570. },
  13571. parse_fmtp: function (line) {
  13572. var parts = line.split(' '),
  13573. i, key, value,
  13574. data = [];
  13575. parts.shift();
  13576. parts = parts.join(' ').split(';');
  13577. for (i = 0; i < parts.length; i++) {
  13578. key = parts[i].split('=')[0];
  13579. while (key.length && key[0] == ' ') {
  13580. key = key.substring(1);
  13581. }
  13582. value = parts[i].split('=')[1];
  13583. if (key && value) {
  13584. data.push({name: key, value: value});
  13585. } else if (key) {
  13586. // rfc 4733 (DTMF) style stuff
  13587. data.push({name: '', value: key});
  13588. }
  13589. }
  13590. return data;
  13591. },
  13592. parse_icecandidate: function (line) {
  13593. var candidate = {},
  13594. elems = line.split(' ');
  13595. candidate.foundation = elems[0].substring(12);
  13596. candidate.component = elems[1];
  13597. candidate.protocol = elems[2].toLowerCase();
  13598. candidate.priority = elems[3];
  13599. candidate.ip = elems[4];
  13600. candidate.port = elems[5];
  13601. // elems[6] => "typ"
  13602. candidate.type = elems[7];
  13603. candidate.generation = 0; // default value, may be overwritten below
  13604. for (var i = 8; i < elems.length; i += 2) {
  13605. switch (elems[i]) {
  13606. case 'raddr':
  13607. candidate['rel-addr'] = elems[i + 1];
  13608. break;
  13609. case 'rport':
  13610. candidate['rel-port'] = elems[i + 1];
  13611. break;
  13612. case 'generation':
  13613. candidate.generation = elems[i + 1];
  13614. break;
  13615. case 'tcptype':
  13616. candidate.tcptype = elems[i + 1];
  13617. break;
  13618. default: // TODO
  13619. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13620. }
  13621. }
  13622. candidate.network = '1';
  13623. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13624. return candidate;
  13625. },
  13626. build_icecandidate: function (cand) {
  13627. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13628. line += ' ';
  13629. switch (cand.type) {
  13630. case 'srflx':
  13631. case 'prflx':
  13632. case 'relay':
  13633. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13634. line += 'raddr';
  13635. line += ' ';
  13636. line += cand['rel-addr'];
  13637. line += ' ';
  13638. line += 'rport';
  13639. line += ' ';
  13640. line += cand['rel-port'];
  13641. line += ' ';
  13642. }
  13643. break;
  13644. }
  13645. if (cand.hasOwnAttribute('tcptype')) {
  13646. line += 'tcptype';
  13647. line += ' ';
  13648. line += cand.tcptype;
  13649. line += ' ';
  13650. }
  13651. line += 'generation';
  13652. line += ' ';
  13653. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13654. return line;
  13655. },
  13656. parse_ssrc: function (desc) {
  13657. // proprietary mapping of a=ssrc lines
  13658. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13659. // and parse according to that
  13660. var lines = desc.split('\r\n'),
  13661. data = {};
  13662. for (var i = 0; i < lines.length; i++) {
  13663. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13664. var idx = lines[i].indexOf(' ');
  13665. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13666. }
  13667. }
  13668. return data;
  13669. },
  13670. parse_rtcpfb: function (line) {
  13671. var parts = line.substr(10).split(' ');
  13672. var data = {};
  13673. data.pt = parts.shift();
  13674. data.type = parts.shift();
  13675. data.params = parts;
  13676. return data;
  13677. },
  13678. parse_extmap: function (line) {
  13679. var parts = line.substr(9).split(' ');
  13680. var data = {};
  13681. data.value = parts.shift();
  13682. if (data.value.indexOf('/') != -1) {
  13683. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13684. data.value = data.value.substr(0, data.value.indexOf('/'));
  13685. } else {
  13686. data.direction = 'both';
  13687. }
  13688. data.uri = parts.shift();
  13689. data.params = parts;
  13690. return data;
  13691. },
  13692. find_line: function (haystack, needle, sessionpart) {
  13693. var lines = haystack.split('\r\n');
  13694. for (var i = 0; i < lines.length; i++) {
  13695. if (lines[i].substring(0, needle.length) == needle) {
  13696. return lines[i];
  13697. }
  13698. }
  13699. if (!sessionpart) {
  13700. return false;
  13701. }
  13702. // search session part
  13703. lines = sessionpart.split('\r\n');
  13704. for (var j = 0; j < lines.length; j++) {
  13705. if (lines[j].substring(0, needle.length) == needle) {
  13706. return lines[j];
  13707. }
  13708. }
  13709. return false;
  13710. },
  13711. find_lines: function (haystack, needle, sessionpart) {
  13712. var lines = haystack.split('\r\n'),
  13713. needles = [];
  13714. for (var i = 0; i < lines.length; i++) {
  13715. if (lines[i].substring(0, needle.length) == needle)
  13716. needles.push(lines[i]);
  13717. }
  13718. if (needles.length || !sessionpart) {
  13719. return needles;
  13720. }
  13721. // search session part
  13722. lines = sessionpart.split('\r\n');
  13723. for (var j = 0; j < lines.length; j++) {
  13724. if (lines[j].substring(0, needle.length) == needle) {
  13725. needles.push(lines[j]);
  13726. }
  13727. }
  13728. return needles;
  13729. },
  13730. candidateToJingle: function (line) {
  13731. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13732. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13733. if (line.indexOf('candidate:') === 0) {
  13734. line = 'a=' + line;
  13735. } else if (line.substring(0, 12) != 'a=candidate:') {
  13736. console.log('parseCandidate called with a line that is not a candidate line');
  13737. console.log(line);
  13738. return null;
  13739. }
  13740. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13741. line = line.substring(0, line.length - 2);
  13742. var candidate = {},
  13743. elems = line.split(' '),
  13744. i;
  13745. if (elems[6] != 'typ') {
  13746. console.log('did not find typ in the right place');
  13747. console.log(line);
  13748. return null;
  13749. }
  13750. candidate.foundation = elems[0].substring(12);
  13751. candidate.component = elems[1];
  13752. candidate.protocol = elems[2].toLowerCase();
  13753. candidate.priority = elems[3];
  13754. candidate.ip = elems[4];
  13755. candidate.port = elems[5];
  13756. // elems[6] => "typ"
  13757. candidate.type = elems[7];
  13758. candidate.generation = '0'; // default, may be overwritten below
  13759. for (i = 8; i < elems.length; i += 2) {
  13760. switch (elems[i]) {
  13761. case 'raddr':
  13762. candidate['rel-addr'] = elems[i + 1];
  13763. break;
  13764. case 'rport':
  13765. candidate['rel-port'] = elems[i + 1];
  13766. break;
  13767. case 'generation':
  13768. candidate.generation = elems[i + 1];
  13769. break;
  13770. case 'tcptype':
  13771. candidate.tcptype = elems[i + 1];
  13772. break;
  13773. default: // TODO
  13774. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13775. }
  13776. }
  13777. candidate.network = '1';
  13778. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13779. return candidate;
  13780. },
  13781. candidateFromJingle: function (cand) {
  13782. var line = 'a=candidate:';
  13783. line += cand.getAttribute('foundation');
  13784. line += ' ';
  13785. line += cand.getAttribute('component');
  13786. line += ' ';
  13787. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13788. line += ' ';
  13789. line += cand.getAttribute('priority');
  13790. line += ' ';
  13791. line += cand.getAttribute('ip');
  13792. line += ' ';
  13793. line += cand.getAttribute('port');
  13794. line += ' ';
  13795. line += 'typ';
  13796. line += ' ' + cand.getAttribute('type');
  13797. line += ' ';
  13798. switch (cand.getAttribute('type')) {
  13799. case 'srflx':
  13800. case 'prflx':
  13801. case 'relay':
  13802. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13803. line += 'raddr';
  13804. line += ' ';
  13805. line += cand.getAttribute('rel-addr');
  13806. line += ' ';
  13807. line += 'rport';
  13808. line += ' ';
  13809. line += cand.getAttribute('rel-port');
  13810. line += ' ';
  13811. }
  13812. break;
  13813. }
  13814. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13815. line += 'tcptype';
  13816. line += ' ';
  13817. line += cand.getAttribute('tcptype');
  13818. line += ' ';
  13819. }
  13820. line += 'generation';
  13821. line += ' ';
  13822. line += cand.getAttribute('generation') || '0';
  13823. return line + '\r\n';
  13824. }
  13825. };
  13826. module.exports = SDPUtil;
  13827. },{}],57:[function(require,module,exports){
  13828. var RTC = require('../RTC/RTC');
  13829. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  13830. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13831. function TraceablePeerConnection(ice_config, constraints, session) {
  13832. var self = this;
  13833. var RTCPeerConnectionType = null;
  13834. if (RTCBrowserType.isFirefox()) {
  13835. RTCPeerConnectionType = mozRTCPeerConnection;
  13836. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  13837. RTCPeerConnectionType = RTCPeerConnection;
  13838. } else {
  13839. RTCPeerConnectionType = webkitRTCPeerConnection;
  13840. }
  13841. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  13842. this.updateLog = [];
  13843. this.stats = {};
  13844. this.statsinterval = null;
  13845. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13846. var Interop = require('sdp-interop').Interop;
  13847. this.interop = new Interop();
  13848. var Simulcast = require('sdp-simulcast');
  13849. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  13850. // override as desired
  13851. this.trace = function (what, info) {
  13852. /*console.warn('WTRACE', what, info);
  13853. if (info && RTCBrowserType.isIExplorer()) {
  13854. if (info.length > 1024) {
  13855. console.warn('WTRACE', what, info.substr(1024));
  13856. }
  13857. if (info.length > 2048) {
  13858. console.warn('WTRACE', what, info.substr(2048));
  13859. }
  13860. }*/
  13861. self.updateLog.push({
  13862. time: new Date(),
  13863. type: what,
  13864. value: info || ""
  13865. });
  13866. };
  13867. this.onicecandidate = null;
  13868. this.peerconnection.onicecandidate = function (event) {
  13869. // FIXME: this causes stack overflow with Temasys Plugin
  13870. if (!RTCBrowserType.isTemasysPluginUsed())
  13871. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13872. if (self.onicecandidate !== null) {
  13873. self.onicecandidate(event);
  13874. }
  13875. };
  13876. this.onaddstream = null;
  13877. this.peerconnection.onaddstream = function (event) {
  13878. self.trace('onaddstream', event.stream.id);
  13879. if (self.onaddstream !== null) {
  13880. self.onaddstream(event);
  13881. }
  13882. };
  13883. this.onremovestream = null;
  13884. this.peerconnection.onremovestream = function (event) {
  13885. self.trace('onremovestream', event.stream.id);
  13886. if (self.onremovestream !== null) {
  13887. self.onremovestream(event);
  13888. }
  13889. };
  13890. this.onsignalingstatechange = null;
  13891. this.peerconnection.onsignalingstatechange = function (event) {
  13892. self.trace('onsignalingstatechange', self.signalingState);
  13893. if (self.onsignalingstatechange !== null) {
  13894. self.onsignalingstatechange(event);
  13895. }
  13896. };
  13897. this.oniceconnectionstatechange = null;
  13898. this.peerconnection.oniceconnectionstatechange = function (event) {
  13899. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13900. if (self.oniceconnectionstatechange !== null) {
  13901. self.oniceconnectionstatechange(event);
  13902. }
  13903. };
  13904. this.onnegotiationneeded = null;
  13905. this.peerconnection.onnegotiationneeded = function (event) {
  13906. self.trace('onnegotiationneeded');
  13907. if (self.onnegotiationneeded !== null) {
  13908. self.onnegotiationneeded(event);
  13909. }
  13910. };
  13911. self.ondatachannel = null;
  13912. this.peerconnection.ondatachannel = function (event) {
  13913. self.trace('ondatachannel', event);
  13914. if (self.ondatachannel !== null) {
  13915. self.ondatachannel(event);
  13916. }
  13917. };
  13918. // XXX: do all non-firefox browsers which we support also support this?
  13919. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  13920. this.statsinterval = window.setInterval(function() {
  13921. self.peerconnection.getStats(function(stats) {
  13922. var results = stats.result();
  13923. var now = new Date();
  13924. for (var i = 0; i < results.length; ++i) {
  13925. results[i].names().forEach(function (name) {
  13926. var id = results[i].id + '-' + name;
  13927. if (!self.stats[id]) {
  13928. self.stats[id] = {
  13929. startTime: now,
  13930. endTime: now,
  13931. values: [],
  13932. times: []
  13933. };
  13934. }
  13935. self.stats[id].values.push(results[i].stat(name));
  13936. self.stats[id].times.push(now.getTime());
  13937. if (self.stats[id].values.length > self.maxstats) {
  13938. self.stats[id].values.shift();
  13939. self.stats[id].times.shift();
  13940. }
  13941. self.stats[id].endTime = now;
  13942. });
  13943. }
  13944. });
  13945. }, 1000);
  13946. }
  13947. }
  13948. /**
  13949. * Returns a string representation of a SessionDescription object.
  13950. */
  13951. var dumpSDP = function(description) {
  13952. if (typeof description === 'undefined' || description == null) {
  13953. return '';
  13954. }
  13955. return 'type: ' + description.type + '\r\n' + description.sdp;
  13956. };
  13957. /**
  13958. * Takes a SessionDescription object and returns a "normalized" version.
  13959. * Currently it only takes care of ordering the a=ssrc lines.
  13960. */
  13961. var normalizePlanB = function(desc) {
  13962. if (typeof desc !== 'object' || desc === null ||
  13963. typeof desc.sdp !== 'string') {
  13964. console.warn('An empty description was passed as an argument.');
  13965. return desc;
  13966. }
  13967. var transform = require('sdp-transform');
  13968. var session = transform.parse(desc.sdp);
  13969. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  13970. Array.isArray(session.media)) {
  13971. session.media.forEach(function (mLine) {
  13972. // Chrome appears to be picky about the order in which a=ssrc lines
  13973. // are listed in an m-line when rtx is enabled (and thus there are
  13974. // a=ssrc-group lines with FID semantics). Specifically if we have
  13975. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  13976. // the "a=ssrc:S1" lines, SRD fails.
  13977. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  13978. // first.
  13979. var firstSsrcs = [];
  13980. var newSsrcLines = [];
  13981. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  13982. mLine.ssrcGroups.forEach(function (group) {
  13983. if (typeof group.semantics !== 'undefined' &&
  13984. group.semantics === 'FID') {
  13985. if (typeof group.ssrcs !== 'undefined') {
  13986. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  13987. }
  13988. }
  13989. });
  13990. }
  13991. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  13992. for (var i = 0; i<mLine.ssrcs.length; i++){
  13993. if (typeof mLine.ssrcs[i] === 'object'
  13994. && typeof mLine.ssrcs[i].id !== 'undefined'
  13995. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  13996. newSsrcLines.push(mLine.ssrcs[i]);
  13997. delete mLine.ssrcs[i];
  13998. }
  13999. }
  14000. for (var i = 0; i<mLine.ssrcs.length; i++){
  14001. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14002. newSsrcLines.push(mLine.ssrcs[i]);
  14003. }
  14004. }
  14005. mLine.ssrcs = newSsrcLines;
  14006. }
  14007. });
  14008. }
  14009. var resStr = transform.write(session);
  14010. return new RTCSessionDescription({
  14011. type: desc.type,
  14012. sdp: resStr
  14013. });
  14014. };
  14015. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14016. TraceablePeerConnection.prototype.__defineGetter__(
  14017. 'signalingState',
  14018. function() { return this.peerconnection.signalingState; });
  14019. TraceablePeerConnection.prototype.__defineGetter__(
  14020. 'iceConnectionState',
  14021. function() { return this.peerconnection.iceConnectionState; });
  14022. TraceablePeerConnection.prototype.__defineGetter__(
  14023. 'localDescription',
  14024. function() {
  14025. var desc = this.peerconnection.localDescription;
  14026. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14027. // if we're running on FF, transform to Plan B first.
  14028. if (RTCBrowserType.usesUnifiedPlan()) {
  14029. desc = this.interop.toPlanB(desc);
  14030. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14031. }
  14032. return desc;
  14033. });
  14034. TraceablePeerConnection.prototype.__defineGetter__(
  14035. 'remoteDescription',
  14036. function() {
  14037. var desc = this.peerconnection.remoteDescription;
  14038. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14039. // if we're running on FF, transform to Plan B first.
  14040. if (RTCBrowserType.usesUnifiedPlan()) {
  14041. desc = this.interop.toPlanB(desc);
  14042. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14043. }
  14044. return desc;
  14045. });
  14046. }
  14047. TraceablePeerConnection.prototype.addStream = function (stream) {
  14048. this.trace('addStream', stream.id);
  14049. try
  14050. {
  14051. this.peerconnection.addStream(stream);
  14052. }
  14053. catch (e)
  14054. {
  14055. console.error(e);
  14056. }
  14057. };
  14058. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14059. this.trace('removeStream', stream.id);
  14060. if(stopStreams) {
  14061. stream.getAudioTracks().forEach(function (track) {
  14062. // stop() not supported with IE
  14063. if (track.stop) {
  14064. track.stop();
  14065. }
  14066. });
  14067. stream.getVideoTracks().forEach(function (track) {
  14068. // stop() not supported with IE
  14069. if (track.stop) {
  14070. track.stop();
  14071. }
  14072. });
  14073. if (stream.stop) {
  14074. stream.stop();
  14075. }
  14076. }
  14077. try {
  14078. // FF doesn't support this yet.
  14079. if (this.peerconnection.removeStream)
  14080. this.peerconnection.removeStream(stream);
  14081. } catch (e) {
  14082. console.error(e);
  14083. }
  14084. };
  14085. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14086. this.trace('createDataChannel', label, opts);
  14087. return this.peerconnection.createDataChannel(label, opts);
  14088. };
  14089. TraceablePeerConnection.prototype.setLocalDescription
  14090. = function (description, successCallback, failureCallback) {
  14091. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14092. // if we're running on FF, transform to Plan A first.
  14093. if (RTCBrowserType.usesUnifiedPlan()) {
  14094. description = this.interop.toUnifiedPlan(description);
  14095. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14096. }
  14097. var self = this;
  14098. this.peerconnection.setLocalDescription(description,
  14099. function () {
  14100. self.trace('setLocalDescriptionOnSuccess');
  14101. successCallback();
  14102. },
  14103. function (err) {
  14104. self.trace('setLocalDescriptionOnFailure', err);
  14105. failureCallback(err);
  14106. }
  14107. );
  14108. /*
  14109. if (this.statsinterval === null && this.maxstats > 0) {
  14110. // start gathering stats
  14111. }
  14112. */
  14113. };
  14114. TraceablePeerConnection.prototype.setRemoteDescription
  14115. = function (description, successCallback, failureCallback) {
  14116. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14117. // TODO the focus should squeze or explode the remote simulcast
  14118. description = this.simulcast.mungeRemoteDescription(description);
  14119. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14120. // if we're running on FF, transform to Plan A first.
  14121. if (RTCBrowserType.usesUnifiedPlan()) {
  14122. description = this.interop.toUnifiedPlan(description);
  14123. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14124. }
  14125. if (RTCBrowserType.usesPlanB()) {
  14126. description = normalizePlanB(description);
  14127. }
  14128. var self = this;
  14129. this.peerconnection.setRemoteDescription(description,
  14130. function () {
  14131. self.trace('setRemoteDescriptionOnSuccess');
  14132. successCallback();
  14133. },
  14134. function (err) {
  14135. self.trace('setRemoteDescriptionOnFailure', err);
  14136. failureCallback(err);
  14137. }
  14138. );
  14139. /*
  14140. if (this.statsinterval === null && this.maxstats > 0) {
  14141. // start gathering stats
  14142. }
  14143. */
  14144. };
  14145. TraceablePeerConnection.prototype.close = function () {
  14146. this.trace('stop');
  14147. if (this.statsinterval !== null) {
  14148. window.clearInterval(this.statsinterval);
  14149. this.statsinterval = null;
  14150. }
  14151. this.peerconnection.close();
  14152. };
  14153. TraceablePeerConnection.prototype.createOffer
  14154. = function (successCallback, failureCallback, constraints) {
  14155. var self = this;
  14156. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14157. this.peerconnection.createOffer(
  14158. function (offer) {
  14159. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14160. // if we're running on FF, transform to Plan B first.
  14161. // NOTE this is not tested because in meet the focus generates the
  14162. // offer.
  14163. if (RTCBrowserType.usesUnifiedPlan()) {
  14164. offer = self.interop.toPlanB(offer);
  14165. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14166. }
  14167. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14168. offer = self.simulcast.mungeLocalDescription(offer);
  14169. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14170. }
  14171. successCallback(offer);
  14172. },
  14173. function(err) {
  14174. self.trace('createOfferOnFailure', err);
  14175. failureCallback(err);
  14176. },
  14177. constraints
  14178. );
  14179. };
  14180. TraceablePeerConnection.prototype.createAnswer
  14181. = function (successCallback, failureCallback, constraints) {
  14182. var self = this;
  14183. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14184. this.peerconnection.createAnswer(
  14185. function (answer) {
  14186. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14187. // if we're running on FF, transform to Plan A first.
  14188. if (RTCBrowserType.usesUnifiedPlan()) {
  14189. answer = self.interop.toPlanB(answer);
  14190. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14191. }
  14192. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14193. answer = self.simulcast.mungeLocalDescription(answer);
  14194. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14195. }
  14196. successCallback(answer);
  14197. },
  14198. function(err) {
  14199. self.trace('createAnswerOnFailure', err);
  14200. failureCallback(err);
  14201. },
  14202. constraints
  14203. );
  14204. };
  14205. TraceablePeerConnection.prototype.addIceCandidate
  14206. = function (candidate, successCallback, failureCallback) {
  14207. //var self = this;
  14208. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14209. this.peerconnection.addIceCandidate(candidate);
  14210. /* maybe later
  14211. this.peerconnection.addIceCandidate(candidate,
  14212. function () {
  14213. self.trace('addIceCandidateOnSuccess');
  14214. successCallback();
  14215. },
  14216. function (err) {
  14217. self.trace('addIceCandidateOnFailure', err);
  14218. failureCallback(err);
  14219. }
  14220. );
  14221. */
  14222. };
  14223. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14224. // TODO: Is this the correct way to handle Opera, Temasys?
  14225. if (RTCBrowserType.isFirefox()) {
  14226. // ignore for now...
  14227. if(!errback)
  14228. errback = function () {};
  14229. this.peerconnection.getStats(null, callback, errback);
  14230. } else {
  14231. this.peerconnection.getStats(callback);
  14232. }
  14233. };
  14234. module.exports = TraceablePeerConnection;
  14235. },{"../../service/xmpp/XMPPEvents":116,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"sdp-interop":89,"sdp-simulcast":96,"sdp-transform":103}],58:[function(require,module,exports){
  14236. /* global $, $iq, APP, config, messageHandler,
  14237. roomName, sessionTerminated, Strophe, Util */
  14238. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14239. var Settings = require("../settings/Settings");
  14240. var AuthenticationEvents
  14241. = require("../../service/authentication/AuthenticationEvents");
  14242. /**
  14243. * Contains logic responsible for enabling/disabling functionality available
  14244. * only to moderator users.
  14245. */
  14246. var connection = null;
  14247. var focusUserJid;
  14248. function createExpBackoffTimer(step) {
  14249. var count = 1;
  14250. return function (reset) {
  14251. // Reset call
  14252. if (reset) {
  14253. count = 1;
  14254. return;
  14255. }
  14256. // Calculate next timeout
  14257. var timeout = Math.pow(2, count - 1);
  14258. count += 1;
  14259. return timeout * step;
  14260. };
  14261. }
  14262. var getNextTimeout = createExpBackoffTimer(1000);
  14263. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14264. // External authentication stuff
  14265. var externalAuthEnabled = false;
  14266. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14267. // it will be enabled automatically if focus detects the component through
  14268. // service discovery.
  14269. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14270. var eventEmitter = null;
  14271. var Moderator = {
  14272. isModerator: function () {
  14273. return connection && connection.emuc.isModerator();
  14274. },
  14275. isPeerModerator: function (peerJid) {
  14276. return connection &&
  14277. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14278. },
  14279. isExternalAuthEnabled: function () {
  14280. return externalAuthEnabled;
  14281. },
  14282. isSipGatewayEnabled: function () {
  14283. return sipGatewayEnabled;
  14284. },
  14285. setConnection: function (con) {
  14286. connection = con;
  14287. },
  14288. init: function (xmpp, emitter) {
  14289. this.xmppService = xmpp;
  14290. eventEmitter = emitter;
  14291. // Message listener that talks to POPUP window
  14292. function listener(event) {
  14293. if (event.data && event.data.sessionId) {
  14294. if (event.origin !== window.location.origin) {
  14295. console.warn("Ignoring sessionId from different origin: " +
  14296. event.origin);
  14297. return;
  14298. }
  14299. localStorage.setItem('sessionId', event.data.sessionId);
  14300. // After popup is closed we will authenticate
  14301. }
  14302. }
  14303. // Register
  14304. if (window.addEventListener) {
  14305. window.addEventListener("message", listener, false);
  14306. } else {
  14307. window.attachEvent("onmessage", listener);
  14308. }
  14309. },
  14310. onMucMemberLeft: function (jid) {
  14311. console.info("Someone left is it focus ? " + jid);
  14312. var resource = Strophe.getResourceFromJid(jid);
  14313. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14314. console.info(
  14315. "Focus has left the room - leaving conference");
  14316. //hangUp();
  14317. // We'd rather reload to have everything re-initialized
  14318. // FIXME: show some message before reload
  14319. location.reload();
  14320. }
  14321. },
  14322. setFocusUserJid: function (focusJid) {
  14323. if (!focusUserJid) {
  14324. focusUserJid = focusJid;
  14325. console.info("Focus jid set to: " + focusUserJid);
  14326. }
  14327. },
  14328. getFocusUserJid: function () {
  14329. return focusUserJid;
  14330. },
  14331. getFocusComponent: function () {
  14332. // Get focus component address
  14333. var focusComponent = config.hosts.focus;
  14334. // If not specified use default: 'focus.domain'
  14335. if (!focusComponent) {
  14336. focusComponent = 'focus.' + config.hosts.domain;
  14337. }
  14338. return focusComponent;
  14339. },
  14340. createConferenceIq: function (roomName) {
  14341. // Generate create conference IQ
  14342. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14343. // Session Id used for authentication
  14344. var sessionId = localStorage.getItem('sessionId');
  14345. var machineUID = Settings.getSettings().uid;
  14346. console.info(
  14347. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14348. elem.c('conference', {
  14349. xmlns: 'http://jitsi.org/protocol/focus',
  14350. room: roomName,
  14351. 'machine-uid': machineUID
  14352. });
  14353. if (sessionId) {
  14354. elem.attrs({ 'session-id': sessionId});
  14355. }
  14356. if (config.hosts.bridge !== undefined) {
  14357. elem.c(
  14358. 'property',
  14359. { name: 'bridge', value: config.hosts.bridge})
  14360. .up();
  14361. }
  14362. // Tell the focus we have Jigasi configured
  14363. if (config.hosts.call_control !== undefined) {
  14364. elem.c(
  14365. 'property',
  14366. { name: 'call_control', value: config.hosts.call_control})
  14367. .up();
  14368. }
  14369. if (config.channelLastN !== undefined) {
  14370. elem.c(
  14371. 'property',
  14372. { name: 'channelLastN', value: config.channelLastN})
  14373. .up();
  14374. }
  14375. if (config.adaptiveLastN !== undefined) {
  14376. elem.c(
  14377. 'property',
  14378. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14379. .up();
  14380. }
  14381. if (config.adaptiveSimulcast !== undefined) {
  14382. elem.c(
  14383. 'property',
  14384. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14385. .up();
  14386. }
  14387. if (config.openSctp !== undefined) {
  14388. elem.c(
  14389. 'property',
  14390. { name: 'openSctp', value: config.openSctp})
  14391. .up();
  14392. }
  14393. if(config.startAudioMuted !== undefined)
  14394. {
  14395. elem.c(
  14396. 'property',
  14397. { name: 'startAudioMuted', value: config.startAudioMuted})
  14398. .up();
  14399. }
  14400. if(config.startVideoMuted !== undefined)
  14401. {
  14402. elem.c(
  14403. 'property',
  14404. { name: 'startVideoMuted', value: config.startVideoMuted})
  14405. .up();
  14406. }
  14407. elem.c(
  14408. 'property',
  14409. { name: 'simulcastMode', value: 'rewriting'})
  14410. .up();
  14411. elem.up();
  14412. return elem;
  14413. },
  14414. parseSessionId: function (resultIq) {
  14415. var sessionId = $(resultIq).find('conference').attr('session-id');
  14416. if (sessionId) {
  14417. console.info('Received sessionId: ' + sessionId);
  14418. localStorage.setItem('sessionId', sessionId);
  14419. }
  14420. },
  14421. parseConfigOptions: function (resultIq) {
  14422. Moderator.setFocusUserJid(
  14423. $(resultIq).find('conference').attr('focusjid'));
  14424. var authenticationEnabled
  14425. = $(resultIq).find(
  14426. '>conference>property' +
  14427. '[name=\'authentication\'][value=\'true\']').length > 0;
  14428. console.info("Authentication enabled: " + authenticationEnabled);
  14429. externalAuthEnabled = $(resultIq).find(
  14430. '>conference>property' +
  14431. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14432. console.info('External authentication enabled: ' + externalAuthEnabled);
  14433. if (!externalAuthEnabled) {
  14434. // We expect to receive sessionId in 'internal' authentication mode
  14435. Moderator.parseSessionId(resultIq);
  14436. }
  14437. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14438. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14439. authenticationEnabled, authIdentity);
  14440. // Check if focus has auto-detected Jigasi component(this will be also
  14441. // included if we have passed our host from the config)
  14442. if ($(resultIq).find(
  14443. '>conference>property' +
  14444. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14445. sipGatewayEnabled = true;
  14446. }
  14447. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14448. },
  14449. // FIXME: we need to show the fact that we're waiting for the focus
  14450. // to the user(or that focus is not available)
  14451. allocateConferenceFocus: function (roomName, callback) {
  14452. // Try to use focus user JID from the config
  14453. Moderator.setFocusUserJid(config.focusUserJid);
  14454. // Send create conference IQ
  14455. var iq = Moderator.createConferenceIq(roomName);
  14456. var self = this;
  14457. connection.sendIQ(
  14458. iq,
  14459. function (result) {
  14460. // Setup config options
  14461. Moderator.parseConfigOptions(result);
  14462. if ('true' === $(result).find('conference').attr('ready')) {
  14463. // Reset both timers
  14464. getNextTimeout(true);
  14465. getNextErrorTimeout(true);
  14466. // Exec callback
  14467. callback();
  14468. } else {
  14469. var waitMs = getNextTimeout();
  14470. console.info("Waiting for the focus... " + waitMs);
  14471. // Reset error timeout
  14472. getNextErrorTimeout(true);
  14473. window.setTimeout(
  14474. function () {
  14475. Moderator.allocateConferenceFocus(
  14476. roomName, callback);
  14477. }, waitMs);
  14478. }
  14479. },
  14480. function (error) {
  14481. // Invalid session ? remove and try again
  14482. // without session ID to get a new one
  14483. var invalidSession
  14484. = $(error).find('>error>session-invalid').length;
  14485. if (invalidSession) {
  14486. console.info("Session expired! - removing");
  14487. localStorage.removeItem("sessionId");
  14488. }
  14489. if ($(error).find('>error>graceful-shutdown').length) {
  14490. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14491. return;
  14492. }
  14493. // Check for error returned by the reservation system
  14494. var reservationErr = $(error).find('>error>reservation-error');
  14495. if (reservationErr.length) {
  14496. // Trigger error event
  14497. var errorCode = reservationErr.attr('error-code');
  14498. var errorMsg;
  14499. if ($(error).find('>error>text')) {
  14500. errorMsg = $(error).find('>error>text').text();
  14501. }
  14502. eventEmitter.emit(
  14503. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14504. return;
  14505. }
  14506. // Not authorized to create new room
  14507. if ($(error).find('>error>not-authorized').length) {
  14508. console.warn("Unauthorized to start the conference", error);
  14509. var toDomain
  14510. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14511. if (toDomain !== config.hosts.anonymousdomain) {
  14512. // FIXME: "is external" should come either from
  14513. // the focus or config.js
  14514. externalAuthEnabled = true;
  14515. }
  14516. eventEmitter.emit(
  14517. XMPPEvents.AUTHENTICATION_REQUIRED,
  14518. function () {
  14519. Moderator.allocateConferenceFocus(
  14520. roomName, callback);
  14521. });
  14522. return;
  14523. }
  14524. var waitMs = getNextErrorTimeout();
  14525. console.error("Focus error, retry after " + waitMs, error);
  14526. // Show message
  14527. var focusComponent = Moderator.getFocusComponent();
  14528. var retrySec = waitMs / 1000;
  14529. // FIXME: message is duplicated ?
  14530. // Do not show in case of session invalid
  14531. // which means just a retry
  14532. if (!invalidSession) {
  14533. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  14534. focusComponent, retrySec);
  14535. }
  14536. // Reset response timeout
  14537. getNextTimeout(true);
  14538. window.setTimeout(
  14539. function () {
  14540. Moderator.allocateConferenceFocus(roomName, callback);
  14541. }, waitMs);
  14542. }
  14543. );
  14544. },
  14545. getLoginUrl: function (roomName, urlCallback) {
  14546. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14547. iq.c('login-url', {
  14548. xmlns: 'http://jitsi.org/protocol/focus',
  14549. room: roomName,
  14550. 'machine-uid': Settings.getSettings().uid
  14551. });
  14552. connection.sendIQ(
  14553. iq,
  14554. function (result) {
  14555. var url = $(result).find('login-url').attr('url');
  14556. url = url = decodeURIComponent(url);
  14557. if (url) {
  14558. console.info("Got auth url: " + url);
  14559. urlCallback(url);
  14560. } else {
  14561. console.error(
  14562. "Failed to get auth url from the focus", result);
  14563. }
  14564. },
  14565. function (error) {
  14566. console.error("Get auth url error", error);
  14567. }
  14568. );
  14569. },
  14570. getPopupLoginUrl: function (roomName, urlCallback) {
  14571. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14572. iq.c('login-url', {
  14573. xmlns: 'http://jitsi.org/protocol/focus',
  14574. room: roomName,
  14575. 'machine-uid': Settings.getSettings().uid,
  14576. popup: true
  14577. });
  14578. connection.sendIQ(
  14579. iq,
  14580. function (result) {
  14581. var url = $(result).find('login-url').attr('url');
  14582. url = url = decodeURIComponent(url);
  14583. if (url) {
  14584. console.info("Got POPUP auth url: " + url);
  14585. urlCallback(url);
  14586. } else {
  14587. console.error(
  14588. "Failed to get POPUP auth url from the focus", result);
  14589. }
  14590. },
  14591. function (error) {
  14592. console.error('Get POPUP auth url error', error);
  14593. }
  14594. );
  14595. },
  14596. logout: function (callback) {
  14597. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14598. var sessionId = localStorage.getItem('sessionId');
  14599. if (!sessionId) {
  14600. callback();
  14601. return;
  14602. }
  14603. iq.c('logout', {
  14604. xmlns: 'http://jitsi.org/protocol/focus',
  14605. 'session-id': sessionId
  14606. });
  14607. connection.sendIQ(
  14608. iq,
  14609. function (result) {
  14610. var logoutUrl = $(result).find('logout').attr('logout-url');
  14611. if (logoutUrl) {
  14612. logoutUrl = decodeURIComponent(logoutUrl);
  14613. }
  14614. console.info("Log out OK, url: " + logoutUrl, result);
  14615. localStorage.removeItem('sessionId');
  14616. callback(logoutUrl);
  14617. },
  14618. function (error) {
  14619. console.error("Logout error", error);
  14620. }
  14621. );
  14622. }
  14623. };
  14624. module.exports = Moderator;
  14625. },{"../../service/authentication/AuthenticationEvents":111,"../../service/xmpp/XMPPEvents":116,"../settings/Settings":47}],59:[function(require,module,exports){
  14626. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  14627. Toolbar, Util */
  14628. var Moderator = require("./moderator");
  14629. var recordingToken = null;
  14630. var recordingEnabled;
  14631. /**
  14632. * Whether to use a jirecon component for recording, or use the videobridge
  14633. * through COLIBRI.
  14634. */
  14635. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14636. /**
  14637. * The ID of the jirecon recording session. Jirecon generates it when we
  14638. * initially start recording, and it needs to be used in subsequent requests
  14639. * to jirecon.
  14640. */
  14641. var jireconRid = null;
  14642. function setRecordingToken(token) {
  14643. recordingToken = token;
  14644. }
  14645. function setRecordingJirecon(state, token, callback, connection) {
  14646. if (state == recordingEnabled){
  14647. return;
  14648. }
  14649. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14650. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14651. action: state ? 'start' : 'stop',
  14652. mucjid: connection.emuc.roomjid});
  14653. if (!state){
  14654. iq.attrs({rid: jireconRid});
  14655. }
  14656. console.log('Start recording');
  14657. connection.sendIQ(
  14658. iq,
  14659. function (result) {
  14660. // TODO wait for an IQ with the real status, since this is
  14661. // provisional?
  14662. jireconRid = $(result).find('recording').attr('rid');
  14663. console.log('Recording ' + (state ? 'started' : 'stopped') +
  14664. '(jirecon)' + result);
  14665. recordingEnabled = state;
  14666. if (!state){
  14667. jireconRid = null;
  14668. }
  14669. callback(state);
  14670. },
  14671. function (error) {
  14672. console.log('Failed to start recording, error: ', error);
  14673. callback(recordingEnabled);
  14674. });
  14675. }
  14676. // Sends a COLIBRI message which enables or disables (according to 'state')
  14677. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14678. // with the new recording state, according to the IQ.
  14679. function setRecordingColibri(state, token, callback, connection) {
  14680. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14681. elem.c('conference', {
  14682. xmlns: 'http://jitsi.org/protocol/colibri'
  14683. });
  14684. elem.c('recording', {state: state, token: token});
  14685. connection.sendIQ(elem,
  14686. function (result) {
  14687. console.log('Set recording "', state, '". Result:', result);
  14688. var recordingElem = $(result).find('>conference>recording');
  14689. var newState = ('true' === recordingElem.attr('state'));
  14690. recordingEnabled = newState;
  14691. callback(newState);
  14692. },
  14693. function (error) {
  14694. console.warn(error);
  14695. callback(recordingEnabled);
  14696. }
  14697. );
  14698. }
  14699. function setRecording(state, token, callback, connection) {
  14700. if (useJirecon){
  14701. setRecordingJirecon(state, token, callback, connection);
  14702. } else {
  14703. setRecordingColibri(state, token, callback, connection);
  14704. }
  14705. }
  14706. var Recording = {
  14707. toggleRecording: function (tokenEmptyCallback,
  14708. startingCallback, startedCallback, connection) {
  14709. if (!Moderator.isModerator()) {
  14710. console.log(
  14711. 'non-focus, or conference not yet organized:' +
  14712. ' not enabling recording');
  14713. return;
  14714. }
  14715. var self = this;
  14716. // Jirecon does not (currently) support a token.
  14717. if (!recordingToken && !useJirecon) {
  14718. tokenEmptyCallback(function (value) {
  14719. setRecordingToken(value);
  14720. self.toggleRecording(tokenEmptyCallback,
  14721. startingCallback, startedCallback, connection);
  14722. });
  14723. return;
  14724. }
  14725. var oldState = recordingEnabled;
  14726. startingCallback(!oldState);
  14727. setRecording(!oldState,
  14728. recordingToken,
  14729. function (state) {
  14730. console.log("New recording state: ", state);
  14731. if (state === oldState) {
  14732. // FIXME: new focus:
  14733. // this will not work when moderator changes
  14734. // during active session. Then it will assume that
  14735. // recording status has changed to true, but it might have
  14736. // been already true(and we only received actual status from
  14737. // the focus).
  14738. //
  14739. // SO we start with status null, so that it is initialized
  14740. // here and will fail only after second click, so if invalid
  14741. // token was used we have to press the button twice before
  14742. // current status will be fetched and token will be reset.
  14743. //
  14744. // Reliable way would be to return authentication error.
  14745. // Or status update when moderator connects.
  14746. // Or we have to stop recording session when current
  14747. // moderator leaves the room.
  14748. // Failed to change, reset the token because it might
  14749. // have been wrong
  14750. setRecordingToken(null);
  14751. }
  14752. startedCallback(state);
  14753. },
  14754. connection
  14755. );
  14756. }
  14757. };
  14758. module.exports = Recording;
  14759. },{"./moderator":58}],60:[function(require,module,exports){
  14760. /* jshint -W117 */
  14761. /* a simple MUC connection plugin
  14762. * can only handle a single MUC room
  14763. */
  14764. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14765. var Moderator = require("./moderator");
  14766. module.exports = function(XMPP, eventEmitter) {
  14767. Strophe.addConnectionPlugin('emuc', {
  14768. connection: null,
  14769. roomjid: null,
  14770. myroomjid: null,
  14771. members: {},
  14772. list_members: [], // so we can elect a new focus
  14773. presMap: {},
  14774. preziMap: {},
  14775. joined: false,
  14776. isOwner: false,
  14777. role: null,
  14778. focusMucJid: null,
  14779. bridgeIsDown: false,
  14780. init: function (conn) {
  14781. this.connection = conn;
  14782. },
  14783. initPresenceMap: function (myroomjid) {
  14784. this.presMap['to'] = myroomjid;
  14785. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14786. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  14787. this.addAudioInfoToPresence(true);
  14788. }
  14789. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  14790. this.addVideoInfoToPresence(true);
  14791. }
  14792. },
  14793. doJoin: function (jid, password) {
  14794. this.myroomjid = jid;
  14795. console.info("Joined MUC as " + this.myroomjid);
  14796. this.initPresenceMap(this.myroomjid);
  14797. if (!this.roomjid) {
  14798. this.roomjid = Strophe.getBareJidFromJid(jid);
  14799. // add handlers (just once)
  14800. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14801. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14802. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14803. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14804. }
  14805. if (password !== undefined) {
  14806. this.presMap['password'] = password;
  14807. }
  14808. this.sendPresence();
  14809. },
  14810. doLeave: function () {
  14811. console.log("do leave", this.myroomjid);
  14812. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14813. this.presMap.length = 0;
  14814. this.connection.send(pres);
  14815. },
  14816. createNonAnonymousRoom: function () {
  14817. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  14818. var getForm = $iq({type: 'get', to: this.roomjid})
  14819. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  14820. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14821. var self = this;
  14822. this.connection.sendIQ(getForm, function (form) {
  14823. if (!$(form).find(
  14824. '>query>x[xmlns="jabber:x:data"]' +
  14825. '>field[var="muc#roomconfig_whois"]').length) {
  14826. console.error('non-anonymous rooms not supported');
  14827. return;
  14828. }
  14829. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  14830. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14831. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14832. formSubmit.c('field', {'var': 'FORM_TYPE'})
  14833. .c('value')
  14834. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14835. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  14836. .c('value').t('anyone').up().up();
  14837. self.connection.sendIQ(formSubmit);
  14838. }, function (error) {
  14839. console.error("Error getting room configuration form");
  14840. });
  14841. },
  14842. onPresence: function (pres) {
  14843. var from = pres.getAttribute('from');
  14844. // What is this for? A workaround for something?
  14845. if (pres.getAttribute('type')) {
  14846. return true;
  14847. }
  14848. // Parse etherpad tag.
  14849. var etherpad = $(pres).find('>etherpad');
  14850. if (etherpad.length) {
  14851. if (config.etherpad_base) {
  14852. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  14853. }
  14854. }
  14855. // Parse prezi tag.
  14856. var presentation = $(pres).find('>prezi');
  14857. if (presentation.length) {
  14858. var url = presentation.attr('url');
  14859. var current = presentation.find('>current').text();
  14860. console.log('presentation info received from', from, url);
  14861. if (this.preziMap[from] == null) {
  14862. this.preziMap[from] = url;
  14863. $(document).trigger('presentationadded.muc', [from, url, current]);
  14864. }
  14865. else {
  14866. $(document).trigger('gotoslide.muc', [from, url, current]);
  14867. }
  14868. }
  14869. else if (this.preziMap[from] != null) {
  14870. var url = this.preziMap[from];
  14871. delete this.preziMap[from];
  14872. $(document).trigger('presentationremoved.muc', [from, url]);
  14873. }
  14874. // Parse audio info tag.
  14875. var audioMuted = $(pres).find('>audiomuted');
  14876. if (audioMuted.length) {
  14877. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  14878. from, (audioMuted.text() === "true"));
  14879. }
  14880. // Parse video info tag.
  14881. var videoMuted = $(pres).find('>videomuted');
  14882. if (videoMuted.length) {
  14883. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  14884. from, (videoMuted.text() === "true"));
  14885. }
  14886. var startMuted = $(pres).find('>startmuted');
  14887. if (startMuted.length)
  14888. {
  14889. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  14890. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  14891. }
  14892. var devices = $(pres).find('>devices');
  14893. if(devices.length)
  14894. {
  14895. var audio = devices.find('>audio');
  14896. var video = devices.find('>video');
  14897. var devicesValues = {audio: false, video: false};
  14898. if(audio.length && audio.text() === "true")
  14899. {
  14900. devicesValues.audio = true;
  14901. }
  14902. if(video.length && video.text() === "true")
  14903. {
  14904. devicesValues.video = true;
  14905. }
  14906. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  14907. Strophe.getResourceFromJid(from), devicesValues);
  14908. }
  14909. var stats = $(pres).find('>stats');
  14910. if (stats.length) {
  14911. var statsObj = {};
  14912. Strophe.forEachChild(stats[0], "stat", function (el) {
  14913. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  14914. });
  14915. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  14916. }
  14917. // Parse status.
  14918. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  14919. this.isOwner = true;
  14920. this.createNonAnonymousRoom();
  14921. }
  14922. // Parse roles.
  14923. var member = {};
  14924. member.show = $(pres).find('>show').text();
  14925. member.status = $(pres).find('>status').text();
  14926. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  14927. member.affiliation = tmp.attr('affiliation');
  14928. member.role = tmp.attr('role');
  14929. // Focus recognition
  14930. member.jid = tmp.attr('jid');
  14931. member.isFocus = false;
  14932. if (member.jid
  14933. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  14934. member.isFocus = true;
  14935. }
  14936. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  14937. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  14938. if (from == this.myroomjid) {
  14939. if (member.affiliation == 'owner') this.isOwner = true;
  14940. if (this.role !== member.role) {
  14941. this.role = member.role;
  14942. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  14943. from, member, pres, Moderator.isModerator());
  14944. }
  14945. if (!this.joined) {
  14946. this.joined = true;
  14947. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  14948. this.list_members.push(from);
  14949. }
  14950. } else if (this.members[from] === undefined) {
  14951. // new participant
  14952. this.members[from] = member;
  14953. this.list_members.push(from);
  14954. console.log('entered', from, member);
  14955. if (member.isFocus) {
  14956. this.focusMucJid = from;
  14957. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  14958. }
  14959. else {
  14960. var id = $(pres).find('>userId').text();
  14961. var email = $(pres).find('>email');
  14962. if (email.length > 0) {
  14963. id = email.text();
  14964. }
  14965. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  14966. }
  14967. } else {
  14968. // Presence update for existing participant
  14969. // Watch role change:
  14970. if (this.members[from].role != member.role) {
  14971. this.members[from].role = member.role;
  14972. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  14973. member.role, member.displayName);
  14974. }
  14975. }
  14976. // Always trigger presence to update bindings
  14977. this.parsePresence(from, member, pres);
  14978. // Trigger status message update
  14979. if (member.status) {
  14980. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  14981. }
  14982. return true;
  14983. },
  14984. onPresenceUnavailable: function (pres) {
  14985. var from = pres.getAttribute('from');
  14986. // room destroyed ?
  14987. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14988. '>destroy').length) {
  14989. var reason;
  14990. var reasonSelect = $(pres).find(
  14991. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14992. '>destroy>reason');
  14993. if (reasonSelect.length) {
  14994. reason = reasonSelect.text();
  14995. }
  14996. XMPP.disposeConference(false);
  14997. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  14998. return true;
  14999. }
  15000. // Status code 110 indicates that this notification is "self-presence".
  15001. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15002. delete this.members[from];
  15003. this.list_members.splice(this.list_members.indexOf(from), 1);
  15004. this.onParticipantLeft(from);
  15005. }
  15006. // If the status code is 110 this means we're leaving and we would like
  15007. // to remove everyone else from our view, so we trigger the event.
  15008. else if (this.list_members.length > 1) {
  15009. for (var i = 0; i < this.list_members.length; i++) {
  15010. var member = this.list_members[i];
  15011. delete this.members[i];
  15012. this.list_members.splice(i, 1);
  15013. this.onParticipantLeft(member);
  15014. }
  15015. }
  15016. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15017. $(document).trigger('kicked.muc', [from]);
  15018. if (this.myroomjid === from) {
  15019. XMPP.disposeConference(false);
  15020. eventEmitter.emit(XMPPEvents.KICKED);
  15021. }
  15022. }
  15023. return true;
  15024. },
  15025. onPresenceError: function (pres) {
  15026. var from = pres.getAttribute('from');
  15027. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15028. console.log('on password required', from);
  15029. var self = this;
  15030. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15031. self.doJoin(from, value);
  15032. });
  15033. } else if ($(pres).find(
  15034. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15035. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15036. if (toDomain === config.hosts.anonymousdomain) {
  15037. // enter the room by replying with 'not-authorized'. This would
  15038. // result in reconnection from authorized domain.
  15039. // We're either missing Jicofo/Prosody config for anonymous
  15040. // domains or something is wrong.
  15041. // XMPP.promptLogin();
  15042. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15043. } else {
  15044. console.warn('onPresError ', pres);
  15045. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15046. }
  15047. } else {
  15048. console.warn('onPresError ', pres);
  15049. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15050. }
  15051. return true;
  15052. },
  15053. sendMessage: function (body, nickname) {
  15054. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15055. msg.c('body', body).up();
  15056. if (nickname) {
  15057. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15058. }
  15059. this.connection.send(msg);
  15060. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15061. },
  15062. setSubject: function (subject) {
  15063. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15064. msg.c('subject', subject);
  15065. this.connection.send(msg);
  15066. console.log("topic changed to " + subject);
  15067. },
  15068. onMessage: function (msg) {
  15069. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15070. var from = msg.getAttribute('from');
  15071. var nick =
  15072. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15073. .text() ||
  15074. Strophe.getResourceFromJid(from);
  15075. var txt = $(msg).find('>body').text();
  15076. var type = msg.getAttribute("type");
  15077. if (type == "error") {
  15078. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15079. $(msg).find('>text').text(), txt);
  15080. return true;
  15081. }
  15082. var subject = $(msg).find('>subject');
  15083. if (subject.length) {
  15084. var subjectText = subject.text();
  15085. if (subjectText || subjectText == "") {
  15086. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15087. console.log("Subject is changed to " + subjectText);
  15088. }
  15089. }
  15090. // xep-0203 delay
  15091. var stamp = $(msg).find('>delay').attr('stamp');
  15092. if (!stamp) {
  15093. // or xep-0091 delay, UTC timestamp
  15094. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15095. if (stamp) {
  15096. // the format is CCYYMMDDThh:mm:ss
  15097. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15098. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15099. }
  15100. }
  15101. if (txt) {
  15102. console.log('chat', nick, txt);
  15103. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15104. from, nick, txt, this.myroomjid, stamp);
  15105. }
  15106. return true;
  15107. },
  15108. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15109. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15110. var ob = this;
  15111. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15112. function (res) {
  15113. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15114. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15115. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15116. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15117. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15118. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15119. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15120. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15121. ob.connection.sendIQ(formsubmit,
  15122. onSuccess,
  15123. onError);
  15124. } else {
  15125. onNotSupported();
  15126. }
  15127. }, onError);
  15128. },
  15129. kick: function (jid) {
  15130. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15131. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15132. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15133. .c('reason').t('You have been kicked.').up().up().up();
  15134. this.connection.sendIQ(
  15135. kickIQ,
  15136. function (result) {
  15137. console.log('Kick participant with jid: ', jid, result);
  15138. },
  15139. function (error) {
  15140. console.log('Kick participant error: ', error);
  15141. });
  15142. },
  15143. sendPresence: function () {
  15144. if (!this.presMap['to']) {
  15145. // Too early to send presence - not initialized
  15146. return;
  15147. }
  15148. var pres = $pres({to: this.presMap['to'] });
  15149. pres.c('x', {xmlns: this.presMap['xns']});
  15150. if (this.presMap['password']) {
  15151. pres.c('password').t(this.presMap['password']).up();
  15152. }
  15153. pres.up();
  15154. // Send XEP-0115 'c' stanza that contains our capabilities info
  15155. if (this.connection.caps) {
  15156. this.connection.caps.node = config.clientNode;
  15157. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15158. }
  15159. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15160. .t(navigator.userAgent).up();
  15161. if (this.presMap['bridgeIsDown']) {
  15162. pres.c('bridgeIsDown').up();
  15163. }
  15164. if (this.presMap['email']) {
  15165. pres.c('email').t(this.presMap['email']).up();
  15166. }
  15167. if (this.presMap['userId']) {
  15168. pres.c('userId').t(this.presMap['userId']).up();
  15169. }
  15170. if (this.presMap['displayName']) {
  15171. // XEP-0172
  15172. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15173. .t(this.presMap['displayName']).up();
  15174. }
  15175. if(this.presMap["devices"])
  15176. {
  15177. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15178. .c('video').t(this.presMap['devices'].video).up().up();
  15179. }
  15180. if (this.presMap['audions']) {
  15181. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15182. .t(this.presMap['audiomuted']).up();
  15183. }
  15184. if (this.presMap['videons']) {
  15185. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15186. .t(this.presMap['videomuted']).up();
  15187. }
  15188. if (this.presMap['statsns']) {
  15189. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15190. for (var stat in this.presMap["stats"])
  15191. if (this.presMap["stats"][stat] != null)
  15192. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15193. pres.up();
  15194. }
  15195. if (this.presMap['prezins']) {
  15196. pres.c('prezi',
  15197. {xmlns: this.presMap['prezins'],
  15198. 'url': this.presMap['preziurl']})
  15199. .c('current').t(this.presMap['prezicurrent']).up().up();
  15200. }
  15201. if(this.presMap["startMuted"] !== undefined)
  15202. {
  15203. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15204. video: this.presMap["startMuted"].video,
  15205. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15206. delete this.presMap["startMuted"];
  15207. }
  15208. pres.up();
  15209. this.connection.send(pres);
  15210. },
  15211. addDisplayNameToPresence: function (displayName) {
  15212. this.presMap['displayName'] = displayName;
  15213. },
  15214. addDevicesToPresence: function (devices) {
  15215. this.presMap['devices'] = devices;
  15216. },
  15217. addPreziToPresence: function (url, currentSlide) {
  15218. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15219. this.presMap['preziurl'] = url;
  15220. this.presMap['prezicurrent'] = currentSlide;
  15221. },
  15222. removePreziFromPresence: function () {
  15223. delete this.presMap['prezins'];
  15224. delete this.presMap['preziurl'];
  15225. delete this.presMap['prezicurrent'];
  15226. },
  15227. addCurrentSlideToPresence: function (currentSlide) {
  15228. this.presMap['prezicurrent'] = currentSlide;
  15229. },
  15230. getPrezi: function (roomjid) {
  15231. return this.preziMap[roomjid];
  15232. },
  15233. addAudioInfoToPresence: function (isMuted) {
  15234. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15235. this.presMap['audiomuted'] = isMuted.toString();
  15236. },
  15237. addVideoInfoToPresence: function (isMuted) {
  15238. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15239. this.presMap['videomuted'] = isMuted.toString();
  15240. },
  15241. addConnectionInfoToPresence: function (stats) {
  15242. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15243. this.presMap['stats'] = stats;
  15244. },
  15245. findJidFromResource: function (resourceJid) {
  15246. if (resourceJid &&
  15247. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15248. return this.myroomjid;
  15249. }
  15250. var peerJid = null;
  15251. Object.keys(this.members).some(function (jid) {
  15252. peerJid = jid;
  15253. return Strophe.getResourceFromJid(jid) === resourceJid;
  15254. });
  15255. return peerJid;
  15256. },
  15257. addBridgeIsDownToPresence: function () {
  15258. this.presMap['bridgeIsDown'] = true;
  15259. },
  15260. addEmailToPresence: function (email) {
  15261. this.presMap['email'] = email;
  15262. },
  15263. addUserIdToPresence: function (userId) {
  15264. this.presMap['userId'] = userId;
  15265. },
  15266. addStartMutedToPresence: function (audio, video) {
  15267. this.presMap["startMuted"] = {audio: audio, video: video};
  15268. },
  15269. isModerator: function () {
  15270. return this.role === 'moderator';
  15271. },
  15272. getMemberRole: function (peerJid) {
  15273. if (this.members[peerJid]) {
  15274. return this.members[peerJid].role;
  15275. }
  15276. return null;
  15277. },
  15278. onParticipantLeft: function (jid) {
  15279. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15280. this.connection.jingle.terminateByJid(jid);
  15281. if (this.getPrezi(jid)) {
  15282. $(document).trigger('presentationremoved.muc',
  15283. [jid, this.getPrezi(jid)]);
  15284. }
  15285. Moderator.onMucMemberLeft(jid);
  15286. },
  15287. parsePresence: function (from, member, pres) {
  15288. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  15289. this.bridgeIsDown = true;
  15290. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15291. }
  15292. if(member.isFocus)
  15293. return;
  15294. var displayName = !config.displayJids
  15295. ? member.displayName : Strophe.getResourceFromJid(from);
  15296. if (displayName && displayName.length > 0) {
  15297. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15298. }
  15299. var id = $(pres).find('>userID').text();
  15300. var email = $(pres).find('>email');
  15301. if (email.length > 0) {
  15302. id = email.text();
  15303. }
  15304. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15305. }
  15306. });
  15307. };
  15308. },{"../../service/xmpp/XMPPEvents":116,"./moderator":58}],61:[function(require,module,exports){
  15309. /* jshint -W117 */
  15310. var JingleSession = require("./JingleSession");
  15311. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15312. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15313. module.exports = function(XMPP, eventEmitter) {
  15314. function CallIncomingJingle(sid, connection) {
  15315. var sess = connection.jingle.sessions[sid];
  15316. // TODO: do we check activecall == null?
  15317. connection.jingle.activecall = sess;
  15318. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15319. // TODO: check affiliation and/or role
  15320. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15321. sess.usedrip = true; // not-so-naive trickle ice
  15322. sess.sendAnswer();
  15323. sess.accept();
  15324. }
  15325. Strophe.addConnectionPlugin('jingle', {
  15326. connection: null,
  15327. sessions: {},
  15328. jid2session: {},
  15329. ice_config: {iceServers: []},
  15330. pc_constraints: {},
  15331. activecall: null,
  15332. media_constraints: {
  15333. mandatory: {
  15334. 'OfferToReceiveAudio': true,
  15335. 'OfferToReceiveVideo': true
  15336. }
  15337. // MozDontOfferDataChannel: true when this is firefox
  15338. },
  15339. init: function (conn) {
  15340. this.connection = conn;
  15341. if (this.connection.disco) {
  15342. // http://xmpp.org/extensions/xep-0167.html#support
  15343. // http://xmpp.org/extensions/xep-0176.html#support
  15344. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15345. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15346. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15347. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15348. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15349. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15350. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15351. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15352. || RTCBrowserType.isTemasysPluginUsed()) {
  15353. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15354. }
  15355. // this is dealt with by SDP O/A so we don't need to annouce this
  15356. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15357. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15358. if (config.useRtcpMux) {
  15359. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15360. }
  15361. if (config.useBundle) {
  15362. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15363. }
  15364. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15365. }
  15366. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15367. },
  15368. onJingle: function (iq) {
  15369. var sid = $(iq).find('jingle').attr('sid');
  15370. var action = $(iq).find('jingle').attr('action');
  15371. var fromJid = iq.getAttribute('from');
  15372. // send ack first
  15373. var ack = $iq({type: 'result',
  15374. to: fromJid,
  15375. id: iq.getAttribute('id')
  15376. });
  15377. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15378. var sess = this.sessions[sid];
  15379. if ('session-initiate' != action) {
  15380. if (sess === null) {
  15381. ack.type = 'error';
  15382. ack.c('error', {type: 'cancel'})
  15383. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15384. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15385. this.connection.send(ack);
  15386. return true;
  15387. }
  15388. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  15389. // local jid is not checked
  15390. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  15391. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15392. ack.type = 'error';
  15393. ack.c('error', {type: 'cancel'})
  15394. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15395. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15396. this.connection.send(ack);
  15397. return true;
  15398. }
  15399. } else if (sess !== undefined) {
  15400. // existing session with same session id
  15401. // this might be out-of-order if the sess.peerjid is the same as from
  15402. ack.type = 'error';
  15403. ack.c('error', {type: 'cancel'})
  15404. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15405. console.warn('duplicate session id', sid);
  15406. this.connection.send(ack);
  15407. return true;
  15408. }
  15409. // FIXME: check for a defined action
  15410. this.connection.send(ack);
  15411. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15412. switch (action) {
  15413. case 'session-initiate':
  15414. var startMuted = $(iq).find('jingle>startmuted');
  15415. if (startMuted && startMuted.length > 0) {
  15416. var audioMuted = startMuted.attr("audio");
  15417. var videoMuted = startMuted.attr("video");
  15418. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15419. audioMuted === "true", videoMuted === "true");
  15420. }
  15421. sess = new JingleSession(
  15422. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15423. this.connection, XMPP, eventEmitter);
  15424. // configure session
  15425. sess.media_constraints = this.media_constraints;
  15426. sess.pc_constraints = this.pc_constraints;
  15427. sess.ice_config = this.ice_config;
  15428. sess.initiate(fromJid, false);
  15429. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15430. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15431. this.sessions[sess.sid] = sess;
  15432. this.jid2session[sess.peerjid] = sess;
  15433. // the callback should either
  15434. // .sendAnswer and .accept
  15435. // or .sendTerminate -- not necessarily synchronus
  15436. CallIncomingJingle(sess.sid, this.connection);
  15437. break;
  15438. case 'session-accept':
  15439. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15440. sess.accept();
  15441. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15442. break;
  15443. case 'session-terminate':
  15444. // If this is not the focus sending the terminate, we have
  15445. // nothing more to do here.
  15446. if (Object.keys(this.sessions).length < 1
  15447. || !(this.sessions[Object.keys(this.sessions)[0]]
  15448. instanceof JingleSession))
  15449. {
  15450. break;
  15451. }
  15452. console.log('terminating...', sess.sid);
  15453. sess.terminate();
  15454. this.terminate(sess.sid);
  15455. if ($(iq).find('>jingle>reason').length) {
  15456. $(document).trigger('callterminated.jingle', [
  15457. sess.sid,
  15458. sess.peerjid,
  15459. $(iq).find('>jingle>reason>:first')[0].tagName,
  15460. $(iq).find('>jingle>reason>text').text()
  15461. ]);
  15462. } else {
  15463. $(document).trigger('callterminated.jingle',
  15464. [sess.sid, sess.peerjid]);
  15465. }
  15466. break;
  15467. case 'transport-info':
  15468. sess.addIceCandidate($(iq).find('>jingle>content'));
  15469. break;
  15470. case 'session-info':
  15471. var affected;
  15472. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15473. $(document).trigger('ringing.jingle', [sess.sid]);
  15474. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15475. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15476. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15477. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15478. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15479. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15480. }
  15481. break;
  15482. case 'addsource': // FIXME: proprietary, un-jingleish
  15483. case 'source-add': // FIXME: proprietary
  15484. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15485. break;
  15486. case 'removesource': // FIXME: proprietary, un-jingleish
  15487. case 'source-remove': // FIXME: proprietary
  15488. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15489. break;
  15490. default:
  15491. console.warn('jingle action not implemented', action);
  15492. break;
  15493. }
  15494. return true;
  15495. },
  15496. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15497. var sess = new JingleSession(myjid || this.connection.jid,
  15498. Math.random().toString(36).substr(2, 12), // random string
  15499. this.connection, XMPP, eventEmitter);
  15500. // configure session
  15501. sess.media_constraints = this.media_constraints;
  15502. sess.pc_constraints = this.pc_constraints;
  15503. sess.ice_config = this.ice_config;
  15504. sess.initiate(peerjid, true);
  15505. this.sessions[sess.sid] = sess;
  15506. this.jid2session[sess.peerjid] = sess;
  15507. sess.sendOffer();
  15508. return sess;
  15509. },
  15510. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15511. if (sid === null || sid === undefined) {
  15512. for (sid in this.sessions) {
  15513. if (this.sessions[sid].state != 'ended') {
  15514. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15515. this.sessions[sid].terminate();
  15516. }
  15517. delete this.jid2session[this.sessions[sid].peerjid];
  15518. delete this.sessions[sid];
  15519. }
  15520. } else if (this.sessions.hasOwnProperty(sid)) {
  15521. if (this.sessions[sid].state != 'ended') {
  15522. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15523. this.sessions[sid].terminate();
  15524. }
  15525. delete this.jid2session[this.sessions[sid].peerjid];
  15526. delete this.sessions[sid];
  15527. }
  15528. },
  15529. // Used to terminate a session when an unavailable presence is received.
  15530. terminateByJid: function (jid) {
  15531. if (this.jid2session.hasOwnProperty(jid)) {
  15532. var sess = this.jid2session[jid];
  15533. if (sess) {
  15534. sess.terminate();
  15535. console.log('peer went away silently', jid);
  15536. delete this.sessions[sess.sid];
  15537. delete this.jid2session[jid];
  15538. $(document).trigger('callterminated.jingle',
  15539. [sess.sid, jid], 'gone');
  15540. }
  15541. }
  15542. },
  15543. terminateRemoteByJid: function (jid, reason) {
  15544. if (this.jid2session.hasOwnProperty(jid)) {
  15545. var sess = this.jid2session[jid];
  15546. if (sess) {
  15547. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15548. sess.terminate();
  15549. console.log('terminate peer with jid', sess.sid, jid);
  15550. delete this.sessions[sess.sid];
  15551. delete this.jid2session[jid];
  15552. $(document).trigger('callterminated.jingle',
  15553. [sess.sid, jid, 'kicked']);
  15554. }
  15555. }
  15556. },
  15557. getStunAndTurnCredentials: function () {
  15558. // get stun and turn configuration from server via xep-0215
  15559. // uses time-limited credentials as described in
  15560. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15561. //
  15562. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15563. // for a prosody module which implements this
  15564. //
  15565. // currently, this doesn't work with updateIce and therefore credentials with a long
  15566. // validity have to be fetched before creating the peerconnection
  15567. // TODO: implement refresh via updateIce as described in
  15568. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15569. var self = this;
  15570. this.connection.sendIQ(
  15571. $iq({type: 'get', to: this.connection.domain})
  15572. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15573. function (res) {
  15574. var iceservers = [];
  15575. $(res).find('>services>service').each(function (idx, el) {
  15576. el = $(el);
  15577. var dict = {};
  15578. var type = el.attr('type');
  15579. switch (type) {
  15580. case 'stun':
  15581. dict.url = 'stun:' + el.attr('host');
  15582. if (el.attr('port')) {
  15583. dict.url += ':' + el.attr('port');
  15584. }
  15585. iceservers.push(dict);
  15586. break;
  15587. case 'turn':
  15588. case 'turns':
  15589. dict.url = type + ':';
  15590. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15591. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15592. dict.url += el.attr('username') + '@';
  15593. } else {
  15594. dict.username = el.attr('username'); // only works in M28
  15595. }
  15596. }
  15597. dict.url += el.attr('host');
  15598. if (el.attr('port') && el.attr('port') != '3478') {
  15599. dict.url += ':' + el.attr('port');
  15600. }
  15601. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15602. dict.url += '?transport=' + el.attr('transport');
  15603. }
  15604. if (el.attr('password')) {
  15605. dict.credential = el.attr('password');
  15606. }
  15607. iceservers.push(dict);
  15608. break;
  15609. }
  15610. });
  15611. self.ice_config.iceServers = iceservers;
  15612. },
  15613. function (err) {
  15614. console.warn('getting turn credentials failed', err);
  15615. console.warn('is mod_turncredentials or similar installed?');
  15616. }
  15617. );
  15618. // implement push?
  15619. },
  15620. /**
  15621. * Returns the data saved in 'updateLog' in a format to be logged.
  15622. */
  15623. getLog: function () {
  15624. var data = {};
  15625. var self = this;
  15626. Object.keys(this.sessions).forEach(function (sid) {
  15627. var session = self.sessions[sid];
  15628. if (session.peerconnection && session.peerconnection.updateLog) {
  15629. // FIXME: should probably be a .dump call
  15630. data["jingle_" + session.sid] = {
  15631. updateLog: session.peerconnection.updateLog,
  15632. stats: session.peerconnection.stats,
  15633. url: window.location.href
  15634. };
  15635. }
  15636. });
  15637. return data;
  15638. }
  15639. });
  15640. };
  15641. },{"../../service/xmpp/XMPPEvents":116,"../RTC/RTCBrowserType":8,"./JingleSession":53}],62:[function(require,module,exports){
  15642. /* global Strophe */
  15643. module.exports = function () {
  15644. Strophe.addConnectionPlugin('logger', {
  15645. // logs raw stanzas and makes them available for download as JSON
  15646. connection: null,
  15647. log: [],
  15648. init: function (conn) {
  15649. this.connection = conn;
  15650. this.connection.rawInput = this.log_incoming.bind(this);
  15651. this.connection.rawOutput = this.log_outgoing.bind(this);
  15652. },
  15653. log_incoming: function (stanza) {
  15654. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15655. },
  15656. log_outgoing: function (stanza) {
  15657. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15658. }
  15659. });
  15660. };
  15661. },{}],63:[function(require,module,exports){
  15662. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15663. setAudioMuted, Strophe */
  15664. /**
  15665. * Moderate connection plugin.
  15666. */
  15667. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15668. module.exports = function (XMPP, eventEmitter) {
  15669. Strophe.addConnectionPlugin('moderate', {
  15670. connection: null,
  15671. init: function (conn) {
  15672. this.connection = conn;
  15673. this.connection.addHandler(this.onMute.bind(this),
  15674. 'http://jitsi.org/jitmeet/audio',
  15675. 'iq',
  15676. 'set',
  15677. null,
  15678. null);
  15679. },
  15680. setMute: function (jid, mute) {
  15681. console.info("set mute", mute);
  15682. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15683. .c('mute', {
  15684. xmlns: 'http://jitsi.org/jitmeet/audio',
  15685. jid: jid
  15686. })
  15687. .t(mute.toString())
  15688. .up();
  15689. this.connection.sendIQ(
  15690. iqToFocus,
  15691. function (result) {
  15692. console.log('set mute', result);
  15693. },
  15694. function (error) {
  15695. console.log('set mute error', error);
  15696. });
  15697. },
  15698. onMute: function (iq) {
  15699. var from = iq.getAttribute('from');
  15700. if (from !== this.connection.emuc.focusMucJid) {
  15701. console.warn("Ignored mute from non focus peer");
  15702. return false;
  15703. }
  15704. var mute = $(iq).find('mute');
  15705. if (mute.length) {
  15706. var doMuteAudio = mute.text() === "true";
  15707. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  15708. XMPP.forceMuted = doMuteAudio;
  15709. }
  15710. return true;
  15711. },
  15712. eject: function (jid) {
  15713. // We're not the focus, so can't terminate
  15714. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15715. this.connection.emuc.kick(jid);
  15716. }
  15717. });
  15718. }
  15719. },{"../../service/xmpp/XMPPEvents":116}],64:[function(require,module,exports){
  15720. /* jshint -W117 */
  15721. module.exports = function() {
  15722. Strophe.addConnectionPlugin('rayo',
  15723. {
  15724. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15725. connection: null,
  15726. init: function (conn) {
  15727. this.connection = conn;
  15728. if (this.connection.disco) {
  15729. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15730. }
  15731. this.connection.addHandler(
  15732. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15733. },
  15734. onRayo: function (iq) {
  15735. console.info("Rayo IQ", iq);
  15736. },
  15737. dial: function (to, from, roomName, roomPass) {
  15738. var self = this;
  15739. var req = $iq(
  15740. {
  15741. type: 'set',
  15742. to: this.connection.emuc.focusMucJid
  15743. }
  15744. );
  15745. req.c('dial',
  15746. {
  15747. xmlns: this.RAYO_XMLNS,
  15748. to: to,
  15749. from: from
  15750. });
  15751. req.c('header',
  15752. {
  15753. name: 'JvbRoomName',
  15754. value: roomName
  15755. }).up();
  15756. if (roomPass !== null && roomPass.length) {
  15757. req.c('header',
  15758. {
  15759. name: 'JvbRoomPassword',
  15760. value: roomPass
  15761. }).up();
  15762. }
  15763. this.connection.sendIQ(
  15764. req,
  15765. function (result) {
  15766. console.info('Dial result ', result);
  15767. var resource = $(result).find('ref').attr('uri');
  15768. this.call_resource = resource.substr('xmpp:'.length);
  15769. console.info(
  15770. "Received call resource: " + this.call_resource);
  15771. },
  15772. function (error) {
  15773. console.info('Dial error ', error);
  15774. }
  15775. );
  15776. },
  15777. hang_up: function () {
  15778. if (!this.call_resource) {
  15779. console.warn("No call in progress");
  15780. return;
  15781. }
  15782. var self = this;
  15783. var req = $iq(
  15784. {
  15785. type: 'set',
  15786. to: this.call_resource
  15787. }
  15788. );
  15789. req.c('hangup',
  15790. {
  15791. xmlns: this.RAYO_XMLNS
  15792. });
  15793. this.connection.sendIQ(
  15794. req,
  15795. function (result) {
  15796. console.info('Hangup result ', result);
  15797. self.call_resource = null;
  15798. },
  15799. function (error) {
  15800. console.info('Hangup error ', error);
  15801. self.call_resource = null;
  15802. }
  15803. );
  15804. }
  15805. }
  15806. );
  15807. };
  15808. },{}],65:[function(require,module,exports){
  15809. /**
  15810. * Strophe logger implementation. Logs from level WARN and above.
  15811. */
  15812. module.exports = function () {
  15813. Strophe.log = function (level, msg) {
  15814. switch (level) {
  15815. case Strophe.LogLevel.WARN:
  15816. console.warn("Strophe: " + msg);
  15817. break;
  15818. case Strophe.LogLevel.ERROR:
  15819. case Strophe.LogLevel.FATAL:
  15820. console.error("Strophe: " + msg);
  15821. break;
  15822. }
  15823. };
  15824. Strophe.getStatusString = function (status) {
  15825. switch (status) {
  15826. case Strophe.Status.ERROR:
  15827. return "ERROR";
  15828. case Strophe.Status.CONNECTING:
  15829. return "CONNECTING";
  15830. case Strophe.Status.CONNFAIL:
  15831. return "CONNFAIL";
  15832. case Strophe.Status.AUTHENTICATING:
  15833. return "AUTHENTICATING";
  15834. case Strophe.Status.AUTHFAIL:
  15835. return "AUTHFAIL";
  15836. case Strophe.Status.CONNECTED:
  15837. return "CONNECTED";
  15838. case Strophe.Status.DISCONNECTED:
  15839. return "DISCONNECTED";
  15840. case Strophe.Status.DISCONNECTING:
  15841. return "DISCONNECTING";
  15842. case Strophe.Status.ATTACHED:
  15843. return "ATTACHED";
  15844. default:
  15845. return "unknown";
  15846. }
  15847. };
  15848. };
  15849. },{}],66:[function(require,module,exports){
  15850. /* global $, APP, config, Strophe*/
  15851. var Moderator = require("./moderator");
  15852. var EventEmitter = require("events");
  15853. var Recording = require("./recording");
  15854. var SDP = require("./SDP");
  15855. var Settings = require("../settings/Settings");
  15856. var Pako = require("pako");
  15857. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  15858. var RTCEvents = require("../../service/RTC/RTCEvents");
  15859. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15860. var retry = require('retry');
  15861. var eventEmitter = new EventEmitter();
  15862. var connection = null;
  15863. var authenticatedUser = false;
  15864. function connect(jid, password) {
  15865. var faultTolerantConnect = retry.operation({
  15866. retries: 3
  15867. });
  15868. // fault tolerant connect
  15869. faultTolerantConnect.attempt(function () {
  15870. connection = XMPP.createConnection();
  15871. Moderator.setConnection(connection);
  15872. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  15873. if (config.useIPv6) {
  15874. // https://code.google.com/p/webrtc/issues/detail?id=2828
  15875. if (!connection.jingle.pc_constraints.optional)
  15876. connection.jingle.pc_constraints.optional = [];
  15877. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  15878. }
  15879. // Include user info in MUC presence
  15880. var settings = Settings.getSettings();
  15881. if (settings.email) {
  15882. connection.emuc.addEmailToPresence(settings.email);
  15883. }
  15884. if (settings.uid) {
  15885. connection.emuc.addUserIdToPresence(settings.uid);
  15886. }
  15887. if (settings.displayName) {
  15888. connection.emuc.addDisplayNameToPresence(settings.displayName);
  15889. }
  15890. // connection.connect() starts the connection process.
  15891. //
  15892. // As the connection process proceeds, the user supplied callback will
  15893. // be triggered multiple times with status updates. The callback should
  15894. // take two arguments - the status code and the error condition.
  15895. //
  15896. // The status code will be one of the values in the Strophe.Status
  15897. // constants. The error condition will be one of the conditions defined
  15898. // in RFC 3920 or the condition ‘strophe-parsererror’.
  15899. //
  15900. // The Parameters wait, hold and route are optional and only relevant
  15901. // for BOSH connections. Please see XEP 124 for a more detailed
  15902. // explanation of the optional parameters.
  15903. //
  15904. // Connection status constants for use by the connection handler
  15905. // callback.
  15906. //
  15907. // Status.ERROR - An error has occurred (websockets specific)
  15908. // Status.CONNECTING - The connection is currently being made
  15909. // Status.CONNFAIL - The connection attempt failed
  15910. // Status.AUTHENTICATING - The connection is authenticating
  15911. // Status.AUTHFAIL - The authentication attempt failed
  15912. // Status.CONNECTED - The connection has succeeded
  15913. // Status.DISCONNECTED - The connection has been terminated
  15914. // Status.DISCONNECTING - The connection is currently being terminated
  15915. // Status.ATTACHED - The connection has been attached
  15916. var anonymousConnectionFailed = false;
  15917. var connectionFailed = false;
  15918. var lastErrorMsg;
  15919. connection.connect(jid, password, function (status, msg) {
  15920. console.log('Strophe status changed to',
  15921. Strophe.getStatusString(status), msg);
  15922. if (status === Strophe.Status.CONNECTED) {
  15923. if (config.useStunTurn) {
  15924. connection.jingle.getStunAndTurnCredentials();
  15925. }
  15926. console.info("My Jabber ID: " + connection.jid);
  15927. if (password)
  15928. authenticatedUser = true;
  15929. maybeDoJoin();
  15930. } else if (status === Strophe.Status.CONNFAIL) {
  15931. if (msg === 'x-strophe-bad-non-anon-jid') {
  15932. anonymousConnectionFailed = true;
  15933. } else {
  15934. connectionFailed = true;
  15935. }
  15936. lastErrorMsg = msg;
  15937. } else if (status === Strophe.Status.DISCONNECTED) {
  15938. if (anonymousConnectionFailed) {
  15939. // prompt user for username and password
  15940. XMPP.promptLogin();
  15941. } else {
  15942. // Strophe already has built-in HTTP/BOSH error handling and
  15943. // request retry logic. Requests are resent automatically
  15944. // until their error count reaches 5. Strophe.js disconnects
  15945. // if the error count is > 5. We are not replicating this
  15946. // here.
  15947. //
  15948. // The "problem" is that failed HTTP/BOSH requests don't
  15949. // trigger a callback with a status update, so when a
  15950. // callback with status Strophe.Status.DISCONNECTED arrives,
  15951. // we can't be sure if it's a graceful disconnect or if it's
  15952. // triggered by some HTTP/BOSH error.
  15953. //
  15954. // But that's a minor issue in Jitsi Meet as we never
  15955. // disconnect anyway, not even when the user closes the
  15956. // browser window (which is kind of wrong, but the point is
  15957. // that we should never ever get disconnected).
  15958. //
  15959. // On the other hand, failed connections due to XMPP layer
  15960. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  15961. //
  15962. // Here we implement retry logic for failed connections due
  15963. // to XMPP layer errors and we display an error to the user
  15964. // if we get disconnected from the XMPP server permanently.
  15965. // If the connection failed, retry.
  15966. if (connectionFailed &&
  15967. faultTolerantConnect.retry("connection-failed")) {
  15968. return;
  15969. }
  15970. // If we failed to connect to the XMPP server, fire an event
  15971. // to let all the interested module now about it.
  15972. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  15973. msg ? msg : lastErrorMsg);
  15974. }
  15975. } else if (status === Strophe.Status.AUTHFAIL) {
  15976. // wrong password or username, prompt user
  15977. XMPP.promptLogin();
  15978. }
  15979. });
  15980. });
  15981. }
  15982. function maybeDoJoin() {
  15983. if (connection && connection.connected &&
  15984. Strophe.getResourceFromJid(connection.jid) &&
  15985. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15986. // .connected is true while connecting?
  15987. doJoin();
  15988. }
  15989. }
  15990. function doJoin() {
  15991. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  15992. }
  15993. function initStrophePlugins()
  15994. {
  15995. require("./strophe.emuc")(XMPP, eventEmitter);
  15996. require("./strophe.jingle")(XMPP, eventEmitter);
  15997. require("./strophe.moderate")(XMPP, eventEmitter);
  15998. require("./strophe.util")();
  15999. require("./strophe.rayo")();
  16000. require("./strophe.logger")();
  16001. }
  16002. function registerListeners() {
  16003. APP.RTC.addStreamListener(maybeDoJoin,
  16004. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  16005. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16006. XMPP.addToPresence("devices", devices);
  16007. });
  16008. }
  16009. var unload = (function () {
  16010. var unloaded = false;
  16011. return function () {
  16012. if (unloaded) { return; }
  16013. unloaded = true;
  16014. if (connection && connection.connected) {
  16015. // ensure signout
  16016. $.ajax({
  16017. type: 'POST',
  16018. url: config.bosh,
  16019. async: false,
  16020. cache: false,
  16021. contentType: 'application/xml',
  16022. data: "<body rid='" +
  16023. (connection.rid || connection._proto.rid) +
  16024. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16025. (connection.sid || connection._proto.sid) +
  16026. "' type='terminate'>" +
  16027. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16028. "</body>",
  16029. success: function (data) {
  16030. console.log('signed out');
  16031. console.log(data);
  16032. },
  16033. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16034. console.log('signout error',
  16035. textStatus + ' (' + errorThrown + ')');
  16036. }
  16037. });
  16038. }
  16039. XMPP.disposeConference(true);
  16040. };
  16041. })();
  16042. function setupEvents() {
  16043. // In recent versions of FF the 'beforeunload' event is not fired when the
  16044. // window or the tab is closed. It is only fired when we leave the page
  16045. // (change URL). If this participant doesn't unload properly, then it
  16046. // becomes a ghost for the rest of the participants that stay in the
  16047. // conference. Thankfully handling the 'unload' event in addition to the
  16048. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16049. // method at least once.
  16050. //
  16051. // The 'unload' method can safely be run multiple times, it will actually do
  16052. // something only the first time that it's run, so we're don't have to worry
  16053. // about browsers that fire both events.
  16054. $(window).bind('beforeunload', unload);
  16055. $(window).bind('unload', unload);
  16056. }
  16057. var XMPP = {
  16058. getConnection: function(){ return connection; },
  16059. sessionTerminated: false,
  16060. /**
  16061. * XMPP connection status
  16062. */
  16063. Status: Strophe.Status,
  16064. /**
  16065. * Remembers if we were muted by the focus.
  16066. * @type {boolean}
  16067. */
  16068. forceMuted: false,
  16069. start: function () {
  16070. setupEvents();
  16071. initStrophePlugins();
  16072. registerListeners();
  16073. Moderator.init(this, eventEmitter);
  16074. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16075. // Force authenticated domain if room is appended with '?login=true'
  16076. if (config.hosts.anonymousdomain &&
  16077. window.location.search.indexOf("login=true") !== -1) {
  16078. configDomain = config.hosts.domain;
  16079. }
  16080. var jid = configDomain || window.location.hostname;
  16081. connect(jid, null);
  16082. },
  16083. createConnection: function () {
  16084. var bosh = config.bosh || '/http-bind';
  16085. return new Strophe.Connection(bosh);
  16086. },
  16087. getStatusString: function (status) {
  16088. return Strophe.getStatusString(status);
  16089. },
  16090. promptLogin: function () {
  16091. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16092. },
  16093. joinRoom: function(roomName, useNicks, nick) {
  16094. var roomjid = roomName;
  16095. if (useNicks) {
  16096. if (nick) {
  16097. roomjid += '/' + nick;
  16098. } else {
  16099. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16100. }
  16101. } else {
  16102. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16103. if(!authenticatedUser)
  16104. tmpJid = tmpJid.substr(0, 8);
  16105. roomjid += '/' + tmpJid;
  16106. }
  16107. connection.emuc.doJoin(roomjid);
  16108. },
  16109. myJid: function () {
  16110. if(!connection)
  16111. return null;
  16112. return connection.emuc.myroomjid;
  16113. },
  16114. myResource: function () {
  16115. if(!connection || ! connection.emuc.myroomjid)
  16116. return null;
  16117. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16118. },
  16119. disposeConference: function (onUnload) {
  16120. var handler = connection.jingle.activecall;
  16121. if (handler && handler.peerconnection) {
  16122. // FIXME: probably removing streams is not required and close() should
  16123. // be enough
  16124. if (APP.RTC.localAudio) {
  16125. handler.peerconnection.removeStream(
  16126. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16127. }
  16128. if (APP.RTC.localVideo) {
  16129. handler.peerconnection.removeStream(
  16130. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16131. }
  16132. handler.peerconnection.close();
  16133. }
  16134. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16135. connection.jingle.activecall = null;
  16136. if (!onUnload) {
  16137. this.sessionTerminated = true;
  16138. connection.emuc.doLeave();
  16139. }
  16140. },
  16141. addListener: function(type, listener) {
  16142. eventEmitter.on(type, listener);
  16143. },
  16144. removeListener: function (type, listener) {
  16145. eventEmitter.removeListener(type, listener);
  16146. },
  16147. allocateConferenceFocus: function(roomName, callback) {
  16148. Moderator.allocateConferenceFocus(roomName, callback);
  16149. },
  16150. getLoginUrl: function (roomName, callback) {
  16151. Moderator.getLoginUrl(roomName, callback);
  16152. },
  16153. getPopupLoginUrl: function (roomName, callback) {
  16154. Moderator.getPopupLoginUrl(roomName, callback);
  16155. },
  16156. isModerator: function () {
  16157. return Moderator.isModerator();
  16158. },
  16159. isSipGatewayEnabled: function () {
  16160. return Moderator.isSipGatewayEnabled();
  16161. },
  16162. isExternalAuthEnabled: function () {
  16163. return Moderator.isExternalAuthEnabled();
  16164. },
  16165. isConferenceInProgress: function () {
  16166. return connection && connection.jingle.activecall &&
  16167. connection.jingle.activecall.peerconnection;
  16168. },
  16169. switchStreams: function (stream, oldStream, callback, isAudio) {
  16170. if (this.isConferenceInProgress()) {
  16171. // FIXME: will block switchInProgress on true value in case of exception
  16172. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16173. } else {
  16174. // We are done immediately
  16175. console.warn("No conference handler or conference not started yet");
  16176. callback();
  16177. }
  16178. },
  16179. sendVideoInfoPresence: function (mute) {
  16180. if(!connection)
  16181. return;
  16182. connection.emuc.addVideoInfoToPresence(mute);
  16183. connection.emuc.sendPresence();
  16184. },
  16185. setVideoMute: function (mute, callback, options) {
  16186. if(!connection)
  16187. return;
  16188. var self = this;
  16189. var localCallback = function (mute) {
  16190. self.sendVideoInfoPresence(mute);
  16191. return callback(mute);
  16192. };
  16193. if(connection.jingle.activecall)
  16194. {
  16195. connection.jingle.activecall.setVideoMute(
  16196. mute, localCallback, options);
  16197. }
  16198. else {
  16199. localCallback(mute);
  16200. }
  16201. },
  16202. setAudioMute: function (mute, callback) {
  16203. if (!(connection && APP.RTC.localAudio)) {
  16204. return false;
  16205. }
  16206. if (this.forceMuted && !mute) {
  16207. console.info("Asking focus for unmute");
  16208. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16209. // FIXME: wait for result before resetting muted status
  16210. this.forceMuted = false;
  16211. }
  16212. if (mute == APP.RTC.localAudio.isMuted()) {
  16213. // Nothing to do
  16214. return true;
  16215. }
  16216. APP.RTC.localAudio.setMute(mute);
  16217. this.sendAudioInfoPresence(mute, callback);
  16218. return true;
  16219. },
  16220. sendAudioInfoPresence: function(mute, callback) {
  16221. if(connection) {
  16222. connection.emuc.addAudioInfoToPresence(mute);
  16223. connection.emuc.sendPresence();
  16224. }
  16225. callback();
  16226. return true;
  16227. },
  16228. toggleRecording: function (tokenEmptyCallback,
  16229. startingCallback, startedCallback) {
  16230. Recording.toggleRecording(tokenEmptyCallback,
  16231. startingCallback, startedCallback, connection);
  16232. },
  16233. addToPresence: function (name, value, dontSend) {
  16234. switch (name) {
  16235. case "displayName":
  16236. connection.emuc.addDisplayNameToPresence(value);
  16237. break;
  16238. case "prezi":
  16239. connection.emuc.addPreziToPresence(value, 0);
  16240. break;
  16241. case "preziSlide":
  16242. connection.emuc.addCurrentSlideToPresence(value);
  16243. break;
  16244. case "connectionQuality":
  16245. connection.emuc.addConnectionInfoToPresence(value);
  16246. break;
  16247. case "email":
  16248. connection.emuc.addEmailToPresence(value);
  16249. break;
  16250. case "devices":
  16251. connection.emuc.addDevicesToPresence(value);
  16252. break;
  16253. case "startMuted":
  16254. if(!Moderator.isModerator())
  16255. return;
  16256. connection.emuc.addStartMutedToPresence(value[0],
  16257. value[1]);
  16258. break;
  16259. default :
  16260. console.log("Unknown tag for presence: " + name);
  16261. return;
  16262. }
  16263. if (!dontSend)
  16264. connection.emuc.sendPresence();
  16265. },
  16266. /**
  16267. * Sends 'data' as a log message to the focus. Returns true iff a message
  16268. * was sent.
  16269. * @param data
  16270. * @returns {boolean} true iff a message was sent.
  16271. */
  16272. sendLogs: function (data) {
  16273. if(!connection.emuc.focusMucJid)
  16274. return false;
  16275. var deflate = true;
  16276. var content = JSON.stringify(data);
  16277. if (deflate) {
  16278. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16279. }
  16280. content = Base64.encode(content);
  16281. // XEP-0337-ish
  16282. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16283. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16284. id: 'PeerConnectionStats'});
  16285. message.c('message').t(content).up();
  16286. if (deflate) {
  16287. message.c('tag', {name: "deflated", value: "true"}).up();
  16288. }
  16289. message.up();
  16290. connection.send(message);
  16291. return true;
  16292. },
  16293. // Gets the logs from strophe.jingle.
  16294. getJingleLog: function () {
  16295. return connection.jingle ? connection.jingle.getLog() : {};
  16296. },
  16297. // Gets the logs from strophe.
  16298. getXmppLog: function () {
  16299. return connection.logger ? connection.logger.log : null;
  16300. },
  16301. getPrezi: function () {
  16302. return connection.emuc.getPrezi(this.myJid());
  16303. },
  16304. removePreziFromPresence: function () {
  16305. connection.emuc.removePreziFromPresence();
  16306. connection.emuc.sendPresence();
  16307. },
  16308. sendChatMessage: function (message, nickname) {
  16309. connection.emuc.sendMessage(message, nickname);
  16310. },
  16311. setSubject: function (topic) {
  16312. connection.emuc.setSubject(topic);
  16313. },
  16314. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16315. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16316. },
  16317. dial: function (to, from, roomName,roomPass) {
  16318. connection.rayo.dial(to, from, roomName,roomPass);
  16319. },
  16320. setMute: function (jid, mute) {
  16321. connection.moderate.setMute(jid, mute);
  16322. },
  16323. eject: function (jid) {
  16324. connection.moderate.eject(jid);
  16325. },
  16326. logout: function (callback) {
  16327. Moderator.logout(callback);
  16328. },
  16329. findJidFromResource: function (resource) {
  16330. return connection.emuc.findJidFromResource(resource);
  16331. },
  16332. getMembers: function () {
  16333. return connection.emuc.members;
  16334. },
  16335. getJidFromSSRC: function (ssrc) {
  16336. if (!this.isConferenceInProgress())
  16337. return null;
  16338. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16339. },
  16340. // Returns true iff we have joined the MUC.
  16341. isMUCJoined: function () {
  16342. return connection.emuc.joined;
  16343. },
  16344. getSessions: function () {
  16345. return connection.jingle.sessions;
  16346. },
  16347. removeStream: function (stream) {
  16348. if (!this.isConferenceInProgress())
  16349. return;
  16350. connection.jingle.activecall.peerconnection.removeStream(stream);
  16351. }
  16352. };
  16353. module.exports = XMPP;
  16354. },{"../../service/RTC/RTCEvents":107,"../../service/RTC/StreamEventTypes":109,"../../service/xmpp/XMPPEvents":116,"../settings/Settings":47,"./SDP":54,"./moderator":58,"./recording":59,"./strophe.emuc":60,"./strophe.jingle":61,"./strophe.logger":62,"./strophe.moderate":63,"./strophe.rayo":64,"./strophe.util":65,"events":117,"pako":69,"retry":85}],67:[function(require,module,exports){
  16355. (function (process){
  16356. /*!
  16357. * async
  16358. * https://github.com/caolan/async
  16359. *
  16360. * Copyright 2010-2014 Caolan McMahon
  16361. * Released under the MIT license
  16362. */
  16363. /*jshint onevar: false, indent:4 */
  16364. /*global setImmediate: false, setTimeout: false, console: false */
  16365. (function () {
  16366. var async = {};
  16367. // global on the server, window in the browser
  16368. var root, previous_async;
  16369. root = this;
  16370. if (root != null) {
  16371. previous_async = root.async;
  16372. }
  16373. async.noConflict = function () {
  16374. root.async = previous_async;
  16375. return async;
  16376. };
  16377. function only_once(fn) {
  16378. var called = false;
  16379. return function() {
  16380. if (called) throw new Error("Callback was already called.");
  16381. called = true;
  16382. fn.apply(root, arguments);
  16383. }
  16384. }
  16385. //// cross-browser compatiblity functions ////
  16386. var _toString = Object.prototype.toString;
  16387. var _isArray = Array.isArray || function (obj) {
  16388. return _toString.call(obj) === '[object Array]';
  16389. };
  16390. var _each = function (arr, iterator) {
  16391. if (arr.forEach) {
  16392. return arr.forEach(iterator);
  16393. }
  16394. for (var i = 0; i < arr.length; i += 1) {
  16395. iterator(arr[i], i, arr);
  16396. }
  16397. };
  16398. var _map = function (arr, iterator) {
  16399. if (arr.map) {
  16400. return arr.map(iterator);
  16401. }
  16402. var results = [];
  16403. _each(arr, function (x, i, a) {
  16404. results.push(iterator(x, i, a));
  16405. });
  16406. return results;
  16407. };
  16408. var _reduce = function (arr, iterator, memo) {
  16409. if (arr.reduce) {
  16410. return arr.reduce(iterator, memo);
  16411. }
  16412. _each(arr, function (x, i, a) {
  16413. memo = iterator(memo, x, i, a);
  16414. });
  16415. return memo;
  16416. };
  16417. var _keys = function (obj) {
  16418. if (Object.keys) {
  16419. return Object.keys(obj);
  16420. }
  16421. var keys = [];
  16422. for (var k in obj) {
  16423. if (obj.hasOwnProperty(k)) {
  16424. keys.push(k);
  16425. }
  16426. }
  16427. return keys;
  16428. };
  16429. //// exported async module functions ////
  16430. //// nextTick implementation with browser-compatible fallback ////
  16431. if (typeof process === 'undefined' || !(process.nextTick)) {
  16432. if (typeof setImmediate === 'function') {
  16433. async.nextTick = function (fn) {
  16434. // not a direct alias for IE10 compatibility
  16435. setImmediate(fn);
  16436. };
  16437. async.setImmediate = async.nextTick;
  16438. }
  16439. else {
  16440. async.nextTick = function (fn) {
  16441. setTimeout(fn, 0);
  16442. };
  16443. async.setImmediate = async.nextTick;
  16444. }
  16445. }
  16446. else {
  16447. async.nextTick = process.nextTick;
  16448. if (typeof setImmediate !== 'undefined') {
  16449. async.setImmediate = function (fn) {
  16450. // not a direct alias for IE10 compatibility
  16451. setImmediate(fn);
  16452. };
  16453. }
  16454. else {
  16455. async.setImmediate = async.nextTick;
  16456. }
  16457. }
  16458. async.each = function (arr, iterator, callback) {
  16459. callback = callback || function () {};
  16460. if (!arr.length) {
  16461. return callback();
  16462. }
  16463. var completed = 0;
  16464. _each(arr, function (x) {
  16465. iterator(x, only_once(done) );
  16466. });
  16467. function done(err) {
  16468. if (err) {
  16469. callback(err);
  16470. callback = function () {};
  16471. }
  16472. else {
  16473. completed += 1;
  16474. if (completed >= arr.length) {
  16475. callback();
  16476. }
  16477. }
  16478. }
  16479. };
  16480. async.forEach = async.each;
  16481. async.eachSeries = function (arr, iterator, callback) {
  16482. callback = callback || function () {};
  16483. if (!arr.length) {
  16484. return callback();
  16485. }
  16486. var completed = 0;
  16487. var iterate = function () {
  16488. iterator(arr[completed], function (err) {
  16489. if (err) {
  16490. callback(err);
  16491. callback = function () {};
  16492. }
  16493. else {
  16494. completed += 1;
  16495. if (completed >= arr.length) {
  16496. callback();
  16497. }
  16498. else {
  16499. iterate();
  16500. }
  16501. }
  16502. });
  16503. };
  16504. iterate();
  16505. };
  16506. async.forEachSeries = async.eachSeries;
  16507. async.eachLimit = function (arr, limit, iterator, callback) {
  16508. var fn = _eachLimit(limit);
  16509. fn.apply(null, [arr, iterator, callback]);
  16510. };
  16511. async.forEachLimit = async.eachLimit;
  16512. var _eachLimit = function (limit) {
  16513. return function (arr, iterator, callback) {
  16514. callback = callback || function () {};
  16515. if (!arr.length || limit <= 0) {
  16516. return callback();
  16517. }
  16518. var completed = 0;
  16519. var started = 0;
  16520. var running = 0;
  16521. (function replenish () {
  16522. if (completed >= arr.length) {
  16523. return callback();
  16524. }
  16525. while (running < limit && started < arr.length) {
  16526. started += 1;
  16527. running += 1;
  16528. iterator(arr[started - 1], function (err) {
  16529. if (err) {
  16530. callback(err);
  16531. callback = function () {};
  16532. }
  16533. else {
  16534. completed += 1;
  16535. running -= 1;
  16536. if (completed >= arr.length) {
  16537. callback();
  16538. }
  16539. else {
  16540. replenish();
  16541. }
  16542. }
  16543. });
  16544. }
  16545. })();
  16546. };
  16547. };
  16548. var doParallel = function (fn) {
  16549. return function () {
  16550. var args = Array.prototype.slice.call(arguments);
  16551. return fn.apply(null, [async.each].concat(args));
  16552. };
  16553. };
  16554. var doParallelLimit = function(limit, fn) {
  16555. return function () {
  16556. var args = Array.prototype.slice.call(arguments);
  16557. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16558. };
  16559. };
  16560. var doSeries = function (fn) {
  16561. return function () {
  16562. var args = Array.prototype.slice.call(arguments);
  16563. return fn.apply(null, [async.eachSeries].concat(args));
  16564. };
  16565. };
  16566. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16567. arr = _map(arr, function (x, i) {
  16568. return {index: i, value: x};
  16569. });
  16570. if (!callback) {
  16571. eachfn(arr, function (x, callback) {
  16572. iterator(x.value, function (err) {
  16573. callback(err);
  16574. });
  16575. });
  16576. } else {
  16577. var results = [];
  16578. eachfn(arr, function (x, callback) {
  16579. iterator(x.value, function (err, v) {
  16580. results[x.index] = v;
  16581. callback(err);
  16582. });
  16583. }, function (err) {
  16584. callback(err, results);
  16585. });
  16586. }
  16587. };
  16588. async.map = doParallel(_asyncMap);
  16589. async.mapSeries = doSeries(_asyncMap);
  16590. async.mapLimit = function (arr, limit, iterator, callback) {
  16591. return _mapLimit(limit)(arr, iterator, callback);
  16592. };
  16593. var _mapLimit = function(limit) {
  16594. return doParallelLimit(limit, _asyncMap);
  16595. };
  16596. // reduce only has a series version, as doing reduce in parallel won't
  16597. // work in many situations.
  16598. async.reduce = function (arr, memo, iterator, callback) {
  16599. async.eachSeries(arr, function (x, callback) {
  16600. iterator(memo, x, function (err, v) {
  16601. memo = v;
  16602. callback(err);
  16603. });
  16604. }, function (err) {
  16605. callback(err, memo);
  16606. });
  16607. };
  16608. // inject alias
  16609. async.inject = async.reduce;
  16610. // foldl alias
  16611. async.foldl = async.reduce;
  16612. async.reduceRight = function (arr, memo, iterator, callback) {
  16613. var reversed = _map(arr, function (x) {
  16614. return x;
  16615. }).reverse();
  16616. async.reduce(reversed, memo, iterator, callback);
  16617. };
  16618. // foldr alias
  16619. async.foldr = async.reduceRight;
  16620. var _filter = function (eachfn, arr, iterator, callback) {
  16621. var results = [];
  16622. arr = _map(arr, function (x, i) {
  16623. return {index: i, value: x};
  16624. });
  16625. eachfn(arr, function (x, callback) {
  16626. iterator(x.value, function (v) {
  16627. if (v) {
  16628. results.push(x);
  16629. }
  16630. callback();
  16631. });
  16632. }, function (err) {
  16633. callback(_map(results.sort(function (a, b) {
  16634. return a.index - b.index;
  16635. }), function (x) {
  16636. return x.value;
  16637. }));
  16638. });
  16639. };
  16640. async.filter = doParallel(_filter);
  16641. async.filterSeries = doSeries(_filter);
  16642. // select alias
  16643. async.select = async.filter;
  16644. async.selectSeries = async.filterSeries;
  16645. var _reject = function (eachfn, arr, iterator, callback) {
  16646. var results = [];
  16647. arr = _map(arr, function (x, i) {
  16648. return {index: i, value: x};
  16649. });
  16650. eachfn(arr, function (x, callback) {
  16651. iterator(x.value, function (v) {
  16652. if (!v) {
  16653. results.push(x);
  16654. }
  16655. callback();
  16656. });
  16657. }, function (err) {
  16658. callback(_map(results.sort(function (a, b) {
  16659. return a.index - b.index;
  16660. }), function (x) {
  16661. return x.value;
  16662. }));
  16663. });
  16664. };
  16665. async.reject = doParallel(_reject);
  16666. async.rejectSeries = doSeries(_reject);
  16667. var _detect = function (eachfn, arr, iterator, main_callback) {
  16668. eachfn(arr, function (x, callback) {
  16669. iterator(x, function (result) {
  16670. if (result) {
  16671. main_callback(x);
  16672. main_callback = function () {};
  16673. }
  16674. else {
  16675. callback();
  16676. }
  16677. });
  16678. }, function (err) {
  16679. main_callback();
  16680. });
  16681. };
  16682. async.detect = doParallel(_detect);
  16683. async.detectSeries = doSeries(_detect);
  16684. async.some = function (arr, iterator, main_callback) {
  16685. async.each(arr, function (x, callback) {
  16686. iterator(x, function (v) {
  16687. if (v) {
  16688. main_callback(true);
  16689. main_callback = function () {};
  16690. }
  16691. callback();
  16692. });
  16693. }, function (err) {
  16694. main_callback(false);
  16695. });
  16696. };
  16697. // any alias
  16698. async.any = async.some;
  16699. async.every = function (arr, iterator, main_callback) {
  16700. async.each(arr, function (x, callback) {
  16701. iterator(x, function (v) {
  16702. if (!v) {
  16703. main_callback(false);
  16704. main_callback = function () {};
  16705. }
  16706. callback();
  16707. });
  16708. }, function (err) {
  16709. main_callback(true);
  16710. });
  16711. };
  16712. // all alias
  16713. async.all = async.every;
  16714. async.sortBy = function (arr, iterator, callback) {
  16715. async.map(arr, function (x, callback) {
  16716. iterator(x, function (err, criteria) {
  16717. if (err) {
  16718. callback(err);
  16719. }
  16720. else {
  16721. callback(null, {value: x, criteria: criteria});
  16722. }
  16723. });
  16724. }, function (err, results) {
  16725. if (err) {
  16726. return callback(err);
  16727. }
  16728. else {
  16729. var fn = function (left, right) {
  16730. var a = left.criteria, b = right.criteria;
  16731. return a < b ? -1 : a > b ? 1 : 0;
  16732. };
  16733. callback(null, _map(results.sort(fn), function (x) {
  16734. return x.value;
  16735. }));
  16736. }
  16737. });
  16738. };
  16739. async.auto = function (tasks, callback) {
  16740. callback = callback || function () {};
  16741. var keys = _keys(tasks);
  16742. var remainingTasks = keys.length
  16743. if (!remainingTasks) {
  16744. return callback();
  16745. }
  16746. var results = {};
  16747. var listeners = [];
  16748. var addListener = function (fn) {
  16749. listeners.unshift(fn);
  16750. };
  16751. var removeListener = function (fn) {
  16752. for (var i = 0; i < listeners.length; i += 1) {
  16753. if (listeners[i] === fn) {
  16754. listeners.splice(i, 1);
  16755. return;
  16756. }
  16757. }
  16758. };
  16759. var taskComplete = function () {
  16760. remainingTasks--
  16761. _each(listeners.slice(0), function (fn) {
  16762. fn();
  16763. });
  16764. };
  16765. addListener(function () {
  16766. if (!remainingTasks) {
  16767. var theCallback = callback;
  16768. // prevent final callback from calling itself if it errors
  16769. callback = function () {};
  16770. theCallback(null, results);
  16771. }
  16772. });
  16773. _each(keys, function (k) {
  16774. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  16775. var taskCallback = function (err) {
  16776. var args = Array.prototype.slice.call(arguments, 1);
  16777. if (args.length <= 1) {
  16778. args = args[0];
  16779. }
  16780. if (err) {
  16781. var safeResults = {};
  16782. _each(_keys(results), function(rkey) {
  16783. safeResults[rkey] = results[rkey];
  16784. });
  16785. safeResults[k] = args;
  16786. callback(err, safeResults);
  16787. // stop subsequent errors hitting callback multiple times
  16788. callback = function () {};
  16789. }
  16790. else {
  16791. results[k] = args;
  16792. async.setImmediate(taskComplete);
  16793. }
  16794. };
  16795. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  16796. var ready = function () {
  16797. return _reduce(requires, function (a, x) {
  16798. return (a && results.hasOwnProperty(x));
  16799. }, true) && !results.hasOwnProperty(k);
  16800. };
  16801. if (ready()) {
  16802. task[task.length - 1](taskCallback, results);
  16803. }
  16804. else {
  16805. var listener = function () {
  16806. if (ready()) {
  16807. removeListener(listener);
  16808. task[task.length - 1](taskCallback, results);
  16809. }
  16810. };
  16811. addListener(listener);
  16812. }
  16813. });
  16814. };
  16815. async.retry = function(times, task, callback) {
  16816. var DEFAULT_TIMES = 5;
  16817. var attempts = [];
  16818. // Use defaults if times not passed
  16819. if (typeof times === 'function') {
  16820. callback = task;
  16821. task = times;
  16822. times = DEFAULT_TIMES;
  16823. }
  16824. // Make sure times is a number
  16825. times = parseInt(times, 10) || DEFAULT_TIMES;
  16826. var wrappedTask = function(wrappedCallback, wrappedResults) {
  16827. var retryAttempt = function(task, finalAttempt) {
  16828. return function(seriesCallback) {
  16829. task(function(err, result){
  16830. seriesCallback(!err || finalAttempt, {err: err, result: result});
  16831. }, wrappedResults);
  16832. };
  16833. };
  16834. while (times) {
  16835. attempts.push(retryAttempt(task, !(times-=1)));
  16836. }
  16837. async.series(attempts, function(done, data){
  16838. data = data[data.length - 1];
  16839. (wrappedCallback || callback)(data.err, data.result);
  16840. });
  16841. }
  16842. // If a callback is passed, run this as a controll flow
  16843. return callback ? wrappedTask() : wrappedTask
  16844. };
  16845. async.waterfall = function (tasks, callback) {
  16846. callback = callback || function () {};
  16847. if (!_isArray(tasks)) {
  16848. var err = new Error('First argument to waterfall must be an array of functions');
  16849. return callback(err);
  16850. }
  16851. if (!tasks.length) {
  16852. return callback();
  16853. }
  16854. var wrapIterator = function (iterator) {
  16855. return function (err) {
  16856. if (err) {
  16857. callback.apply(null, arguments);
  16858. callback = function () {};
  16859. }
  16860. else {
  16861. var args = Array.prototype.slice.call(arguments, 1);
  16862. var next = iterator.next();
  16863. if (next) {
  16864. args.push(wrapIterator(next));
  16865. }
  16866. else {
  16867. args.push(callback);
  16868. }
  16869. async.setImmediate(function () {
  16870. iterator.apply(null, args);
  16871. });
  16872. }
  16873. };
  16874. };
  16875. wrapIterator(async.iterator(tasks))();
  16876. };
  16877. var _parallel = function(eachfn, tasks, callback) {
  16878. callback = callback || function () {};
  16879. if (_isArray(tasks)) {
  16880. eachfn.map(tasks, function (fn, callback) {
  16881. if (fn) {
  16882. fn(function (err) {
  16883. var args = Array.prototype.slice.call(arguments, 1);
  16884. if (args.length <= 1) {
  16885. args = args[0];
  16886. }
  16887. callback.call(null, err, args);
  16888. });
  16889. }
  16890. }, callback);
  16891. }
  16892. else {
  16893. var results = {};
  16894. eachfn.each(_keys(tasks), function (k, callback) {
  16895. tasks[k](function (err) {
  16896. var args = Array.prototype.slice.call(arguments, 1);
  16897. if (args.length <= 1) {
  16898. args = args[0];
  16899. }
  16900. results[k] = args;
  16901. callback(err);
  16902. });
  16903. }, function (err) {
  16904. callback(err, results);
  16905. });
  16906. }
  16907. };
  16908. async.parallel = function (tasks, callback) {
  16909. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16910. };
  16911. async.parallelLimit = function(tasks, limit, callback) {
  16912. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16913. };
  16914. async.series = function (tasks, callback) {
  16915. callback = callback || function () {};
  16916. if (_isArray(tasks)) {
  16917. async.mapSeries(tasks, function (fn, callback) {
  16918. if (fn) {
  16919. fn(function (err) {
  16920. var args = Array.prototype.slice.call(arguments, 1);
  16921. if (args.length <= 1) {
  16922. args = args[0];
  16923. }
  16924. callback.call(null, err, args);
  16925. });
  16926. }
  16927. }, callback);
  16928. }
  16929. else {
  16930. var results = {};
  16931. async.eachSeries(_keys(tasks), function (k, callback) {
  16932. tasks[k](function (err) {
  16933. var args = Array.prototype.slice.call(arguments, 1);
  16934. if (args.length <= 1) {
  16935. args = args[0];
  16936. }
  16937. results[k] = args;
  16938. callback(err);
  16939. });
  16940. }, function (err) {
  16941. callback(err, results);
  16942. });
  16943. }
  16944. };
  16945. async.iterator = function (tasks) {
  16946. var makeCallback = function (index) {
  16947. var fn = function () {
  16948. if (tasks.length) {
  16949. tasks[index].apply(null, arguments);
  16950. }
  16951. return fn.next();
  16952. };
  16953. fn.next = function () {
  16954. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  16955. };
  16956. return fn;
  16957. };
  16958. return makeCallback(0);
  16959. };
  16960. async.apply = function (fn) {
  16961. var args = Array.prototype.slice.call(arguments, 1);
  16962. return function () {
  16963. return fn.apply(
  16964. null, args.concat(Array.prototype.slice.call(arguments))
  16965. );
  16966. };
  16967. };
  16968. var _concat = function (eachfn, arr, fn, callback) {
  16969. var r = [];
  16970. eachfn(arr, function (x, cb) {
  16971. fn(x, function (err, y) {
  16972. r = r.concat(y || []);
  16973. cb(err);
  16974. });
  16975. }, function (err) {
  16976. callback(err, r);
  16977. });
  16978. };
  16979. async.concat = doParallel(_concat);
  16980. async.concatSeries = doSeries(_concat);
  16981. async.whilst = function (test, iterator, callback) {
  16982. if (test()) {
  16983. iterator(function (err) {
  16984. if (err) {
  16985. return callback(err);
  16986. }
  16987. async.whilst(test, iterator, callback);
  16988. });
  16989. }
  16990. else {
  16991. callback();
  16992. }
  16993. };
  16994. async.doWhilst = function (iterator, test, callback) {
  16995. iterator(function (err) {
  16996. if (err) {
  16997. return callback(err);
  16998. }
  16999. var args = Array.prototype.slice.call(arguments, 1);
  17000. if (test.apply(null, args)) {
  17001. async.doWhilst(iterator, test, callback);
  17002. }
  17003. else {
  17004. callback();
  17005. }
  17006. });
  17007. };
  17008. async.until = function (test, iterator, callback) {
  17009. if (!test()) {
  17010. iterator(function (err) {
  17011. if (err) {
  17012. return callback(err);
  17013. }
  17014. async.until(test, iterator, callback);
  17015. });
  17016. }
  17017. else {
  17018. callback();
  17019. }
  17020. };
  17021. async.doUntil = function (iterator, test, callback) {
  17022. iterator(function (err) {
  17023. if (err) {
  17024. return callback(err);
  17025. }
  17026. var args = Array.prototype.slice.call(arguments, 1);
  17027. if (!test.apply(null, args)) {
  17028. async.doUntil(iterator, test, callback);
  17029. }
  17030. else {
  17031. callback();
  17032. }
  17033. });
  17034. };
  17035. async.queue = function (worker, concurrency) {
  17036. if (concurrency === undefined) {
  17037. concurrency = 1;
  17038. }
  17039. function _insert(q, data, pos, callback) {
  17040. if (!q.started){
  17041. q.started = true;
  17042. }
  17043. if (!_isArray(data)) {
  17044. data = [data];
  17045. }
  17046. if(data.length == 0) {
  17047. // call drain immediately if there are no tasks
  17048. return async.setImmediate(function() {
  17049. if (q.drain) {
  17050. q.drain();
  17051. }
  17052. });
  17053. }
  17054. _each(data, function(task) {
  17055. var item = {
  17056. data: task,
  17057. callback: typeof callback === 'function' ? callback : null
  17058. };
  17059. if (pos) {
  17060. q.tasks.unshift(item);
  17061. } else {
  17062. q.tasks.push(item);
  17063. }
  17064. if (q.saturated && q.tasks.length === q.concurrency) {
  17065. q.saturated();
  17066. }
  17067. async.setImmediate(q.process);
  17068. });
  17069. }
  17070. var workers = 0;
  17071. var q = {
  17072. tasks: [],
  17073. concurrency: concurrency,
  17074. saturated: null,
  17075. empty: null,
  17076. drain: null,
  17077. started: false,
  17078. paused: false,
  17079. push: function (data, callback) {
  17080. _insert(q, data, false, callback);
  17081. },
  17082. kill: function () {
  17083. q.drain = null;
  17084. q.tasks = [];
  17085. },
  17086. unshift: function (data, callback) {
  17087. _insert(q, data, true, callback);
  17088. },
  17089. process: function () {
  17090. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17091. var task = q.tasks.shift();
  17092. if (q.empty && q.tasks.length === 0) {
  17093. q.empty();
  17094. }
  17095. workers += 1;
  17096. var next = function () {
  17097. workers -= 1;
  17098. if (task.callback) {
  17099. task.callback.apply(task, arguments);
  17100. }
  17101. if (q.drain && q.tasks.length + workers === 0) {
  17102. q.drain();
  17103. }
  17104. q.process();
  17105. };
  17106. var cb = only_once(next);
  17107. worker(task.data, cb);
  17108. }
  17109. },
  17110. length: function () {
  17111. return q.tasks.length;
  17112. },
  17113. running: function () {
  17114. return workers;
  17115. },
  17116. idle: function() {
  17117. return q.tasks.length + workers === 0;
  17118. },
  17119. pause: function () {
  17120. if (q.paused === true) { return; }
  17121. q.paused = true;
  17122. q.process();
  17123. },
  17124. resume: function () {
  17125. if (q.paused === false) { return; }
  17126. q.paused = false;
  17127. q.process();
  17128. }
  17129. };
  17130. return q;
  17131. };
  17132. async.priorityQueue = function (worker, concurrency) {
  17133. function _compareTasks(a, b){
  17134. return a.priority - b.priority;
  17135. };
  17136. function _binarySearch(sequence, item, compare) {
  17137. var beg = -1,
  17138. end = sequence.length - 1;
  17139. while (beg < end) {
  17140. var mid = beg + ((end - beg + 1) >>> 1);
  17141. if (compare(item, sequence[mid]) >= 0) {
  17142. beg = mid;
  17143. } else {
  17144. end = mid - 1;
  17145. }
  17146. }
  17147. return beg;
  17148. }
  17149. function _insert(q, data, priority, callback) {
  17150. if (!q.started){
  17151. q.started = true;
  17152. }
  17153. if (!_isArray(data)) {
  17154. data = [data];
  17155. }
  17156. if(data.length == 0) {
  17157. // call drain immediately if there are no tasks
  17158. return async.setImmediate(function() {
  17159. if (q.drain) {
  17160. q.drain();
  17161. }
  17162. });
  17163. }
  17164. _each(data, function(task) {
  17165. var item = {
  17166. data: task,
  17167. priority: priority,
  17168. callback: typeof callback === 'function' ? callback : null
  17169. };
  17170. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17171. if (q.saturated && q.tasks.length === q.concurrency) {
  17172. q.saturated();
  17173. }
  17174. async.setImmediate(q.process);
  17175. });
  17176. }
  17177. // Start with a normal queue
  17178. var q = async.queue(worker, concurrency);
  17179. // Override push to accept second parameter representing priority
  17180. q.push = function (data, priority, callback) {
  17181. _insert(q, data, priority, callback);
  17182. };
  17183. // Remove unshift function
  17184. delete q.unshift;
  17185. return q;
  17186. };
  17187. async.cargo = function (worker, payload) {
  17188. var working = false,
  17189. tasks = [];
  17190. var cargo = {
  17191. tasks: tasks,
  17192. payload: payload,
  17193. saturated: null,
  17194. empty: null,
  17195. drain: null,
  17196. drained: true,
  17197. push: function (data, callback) {
  17198. if (!_isArray(data)) {
  17199. data = [data];
  17200. }
  17201. _each(data, function(task) {
  17202. tasks.push({
  17203. data: task,
  17204. callback: typeof callback === 'function' ? callback : null
  17205. });
  17206. cargo.drained = false;
  17207. if (cargo.saturated && tasks.length === payload) {
  17208. cargo.saturated();
  17209. }
  17210. });
  17211. async.setImmediate(cargo.process);
  17212. },
  17213. process: function process() {
  17214. if (working) return;
  17215. if (tasks.length === 0) {
  17216. if(cargo.drain && !cargo.drained) cargo.drain();
  17217. cargo.drained = true;
  17218. return;
  17219. }
  17220. var ts = typeof payload === 'number'
  17221. ? tasks.splice(0, payload)
  17222. : tasks.splice(0, tasks.length);
  17223. var ds = _map(ts, function (task) {
  17224. return task.data;
  17225. });
  17226. if(cargo.empty) cargo.empty();
  17227. working = true;
  17228. worker(ds, function () {
  17229. working = false;
  17230. var args = arguments;
  17231. _each(ts, function (data) {
  17232. if (data.callback) {
  17233. data.callback.apply(null, args);
  17234. }
  17235. });
  17236. process();
  17237. });
  17238. },
  17239. length: function () {
  17240. return tasks.length;
  17241. },
  17242. running: function () {
  17243. return working;
  17244. }
  17245. };
  17246. return cargo;
  17247. };
  17248. var _console_fn = function (name) {
  17249. return function (fn) {
  17250. var args = Array.prototype.slice.call(arguments, 1);
  17251. fn.apply(null, args.concat([function (err) {
  17252. var args = Array.prototype.slice.call(arguments, 1);
  17253. if (typeof console !== 'undefined') {
  17254. if (err) {
  17255. if (console.error) {
  17256. console.error(err);
  17257. }
  17258. }
  17259. else if (console[name]) {
  17260. _each(args, function (x) {
  17261. console[name](x);
  17262. });
  17263. }
  17264. }
  17265. }]));
  17266. };
  17267. };
  17268. async.log = _console_fn('log');
  17269. async.dir = _console_fn('dir');
  17270. /*async.info = _console_fn('info');
  17271. async.warn = _console_fn('warn');
  17272. async.error = _console_fn('error');*/
  17273. async.memoize = function (fn, hasher) {
  17274. var memo = {};
  17275. var queues = {};
  17276. hasher = hasher || function (x) {
  17277. return x;
  17278. };
  17279. var memoized = function () {
  17280. var args = Array.prototype.slice.call(arguments);
  17281. var callback = args.pop();
  17282. var key = hasher.apply(null, args);
  17283. if (key in memo) {
  17284. async.nextTick(function () {
  17285. callback.apply(null, memo[key]);
  17286. });
  17287. }
  17288. else if (key in queues) {
  17289. queues[key].push(callback);
  17290. }
  17291. else {
  17292. queues[key] = [callback];
  17293. fn.apply(null, args.concat([function () {
  17294. memo[key] = arguments;
  17295. var q = queues[key];
  17296. delete queues[key];
  17297. for (var i = 0, l = q.length; i < l; i++) {
  17298. q[i].apply(null, arguments);
  17299. }
  17300. }]));
  17301. }
  17302. };
  17303. memoized.memo = memo;
  17304. memoized.unmemoized = fn;
  17305. return memoized;
  17306. };
  17307. async.unmemoize = function (fn) {
  17308. return function () {
  17309. return (fn.unmemoized || fn).apply(null, arguments);
  17310. };
  17311. };
  17312. async.times = function (count, iterator, callback) {
  17313. var counter = [];
  17314. for (var i = 0; i < count; i++) {
  17315. counter.push(i);
  17316. }
  17317. return async.map(counter, iterator, callback);
  17318. };
  17319. async.timesSeries = function (count, iterator, callback) {
  17320. var counter = [];
  17321. for (var i = 0; i < count; i++) {
  17322. counter.push(i);
  17323. }
  17324. return async.mapSeries(counter, iterator, callback);
  17325. };
  17326. async.seq = function (/* functions... */) {
  17327. var fns = arguments;
  17328. return function () {
  17329. var that = this;
  17330. var args = Array.prototype.slice.call(arguments);
  17331. var callback = args.pop();
  17332. async.reduce(fns, args, function (newargs, fn, cb) {
  17333. fn.apply(that, newargs.concat([function () {
  17334. var err = arguments[0];
  17335. var nextargs = Array.prototype.slice.call(arguments, 1);
  17336. cb(err, nextargs);
  17337. }]))
  17338. },
  17339. function (err, results) {
  17340. callback.apply(that, [err].concat(results));
  17341. });
  17342. };
  17343. };
  17344. async.compose = function (/* functions... */) {
  17345. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17346. };
  17347. var _applyEach = function (eachfn, fns /*args...*/) {
  17348. var go = function () {
  17349. var that = this;
  17350. var args = Array.prototype.slice.call(arguments);
  17351. var callback = args.pop();
  17352. return eachfn(fns, function (fn, cb) {
  17353. fn.apply(that, args.concat([cb]));
  17354. },
  17355. callback);
  17356. };
  17357. if (arguments.length > 2) {
  17358. var args = Array.prototype.slice.call(arguments, 2);
  17359. return go.apply(this, args);
  17360. }
  17361. else {
  17362. return go;
  17363. }
  17364. };
  17365. async.applyEach = doParallel(_applyEach);
  17366. async.applyEachSeries = doSeries(_applyEach);
  17367. async.forever = function (fn, callback) {
  17368. function next(err) {
  17369. if (err) {
  17370. if (callback) {
  17371. return callback(err);
  17372. }
  17373. throw err;
  17374. }
  17375. fn(next);
  17376. }
  17377. next();
  17378. };
  17379. // Node.js
  17380. if (typeof module !== 'undefined' && module.exports) {
  17381. module.exports = async;
  17382. }
  17383. // AMD / RequireJS
  17384. else if (typeof define !== 'undefined' && define.amd) {
  17385. define([], function () {
  17386. return async;
  17387. });
  17388. }
  17389. // included directly via <script> tag
  17390. else {
  17391. root.async = async;
  17392. }
  17393. }());
  17394. }).call(this,require('_process'))
  17395. },{"_process":118}],68:[function(require,module,exports){
  17396. // i18next, v1.7.7
  17397. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17398. // Distributed under MIT license
  17399. // http://i18next.com
  17400. (function() {
  17401. // add indexOf to non ECMA-262 standard compliant browsers
  17402. if (!Array.prototype.indexOf) {
  17403. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17404. "use strict";
  17405. if (this == null) {
  17406. throw new TypeError();
  17407. }
  17408. var t = Object(this);
  17409. var len = t.length >>> 0;
  17410. if (len === 0) {
  17411. return -1;
  17412. }
  17413. var n = 0;
  17414. if (arguments.length > 0) {
  17415. n = Number(arguments[1]);
  17416. if (n != n) { // shortcut for verifying if it's NaN
  17417. n = 0;
  17418. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17419. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17420. }
  17421. }
  17422. if (n >= len) {
  17423. return -1;
  17424. }
  17425. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17426. for (; k < len; k++) {
  17427. if (k in t && t[k] === searchElement) {
  17428. return k;
  17429. }
  17430. }
  17431. return -1;
  17432. }
  17433. }
  17434. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17435. if (!Array.prototype.lastIndexOf) {
  17436. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17437. "use strict";
  17438. if (this == null) {
  17439. throw new TypeError();
  17440. }
  17441. var t = Object(this);
  17442. var len = t.length >>> 0;
  17443. if (len === 0) {
  17444. return -1;
  17445. }
  17446. var n = len;
  17447. if (arguments.length > 1) {
  17448. n = Number(arguments[1]);
  17449. if (n != n) {
  17450. n = 0;
  17451. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17452. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17453. }
  17454. }
  17455. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17456. for (; k >= 0; k--) {
  17457. if (k in t && t[k] === searchElement) {
  17458. return k;
  17459. }
  17460. }
  17461. return -1;
  17462. };
  17463. }
  17464. // Add string trim for IE8.
  17465. if (typeof String.prototype.trim !== 'function') {
  17466. String.prototype.trim = function() {
  17467. return this.replace(/^\s+|\s+$/g, '');
  17468. }
  17469. }
  17470. var root = this
  17471. , $ = root.jQuery || root.Zepto
  17472. , i18n = {}
  17473. , resStore = {}
  17474. , currentLng
  17475. , replacementCounter = 0
  17476. , languages = []
  17477. , initialized = false
  17478. , sync = {};
  17479. // Export the i18next object for **CommonJS**.
  17480. // If we're not in CommonJS, add `i18n` to the
  17481. // global object or to jquery.
  17482. if (typeof module !== 'undefined' && module.exports) {
  17483. if (!$) {
  17484. try {
  17485. $ = require('jquery');
  17486. } catch(e) {
  17487. // just ignore
  17488. }
  17489. }
  17490. if ($) {
  17491. $.i18n = $.i18n || i18n;
  17492. }
  17493. module.exports = i18n;
  17494. } else {
  17495. if ($) {
  17496. $.i18n = $.i18n || i18n;
  17497. }
  17498. root.i18n = root.i18n || i18n;
  17499. }
  17500. sync = {
  17501. load: function(lngs, options, cb) {
  17502. if (options.useLocalStorage) {
  17503. sync._loadLocal(lngs, options, function(err, store) {
  17504. var missingLngs = [];
  17505. for (var i = 0, len = lngs.length; i < len; i++) {
  17506. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17507. }
  17508. if (missingLngs.length > 0) {
  17509. sync._fetch(missingLngs, options, function(err, fetched) {
  17510. f.extend(store, fetched);
  17511. sync._storeLocal(fetched);
  17512. cb(null, store);
  17513. });
  17514. } else {
  17515. cb(null, store);
  17516. }
  17517. });
  17518. } else {
  17519. sync._fetch(lngs, options, function(err, store){
  17520. cb(null, store);
  17521. });
  17522. }
  17523. },
  17524. _loadLocal: function(lngs, options, cb) {
  17525. var store = {}
  17526. , nowMS = new Date().getTime();
  17527. if(window.localStorage) {
  17528. var todo = lngs.length;
  17529. f.each(lngs, function(key, lng) {
  17530. var local = window.localStorage.getItem('res_' + lng);
  17531. if (local) {
  17532. local = JSON.parse(local);
  17533. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17534. store[lng] = local;
  17535. }
  17536. }
  17537. todo--; // wait for all done befor callback
  17538. if (todo === 0) cb(null, store);
  17539. });
  17540. }
  17541. },
  17542. _storeLocal: function(store) {
  17543. if(window.localStorage) {
  17544. for (var m in store) {
  17545. store[m].i18nStamp = new Date().getTime();
  17546. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17547. }
  17548. }
  17549. return;
  17550. },
  17551. _fetch: function(lngs, options, cb) {
  17552. var ns = options.ns
  17553. , store = {};
  17554. if (!options.dynamicLoad) {
  17555. var todo = ns.namespaces.length * lngs.length
  17556. , errors;
  17557. // load each file individual
  17558. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17559. f.each(lngs, function(lngIndex, lngValue) {
  17560. // Call this once our translation has returned.
  17561. var loadComplete = function(err, data) {
  17562. if (err) {
  17563. errors = errors || [];
  17564. errors.push(err);
  17565. }
  17566. store[lngValue] = store[lngValue] || {};
  17567. store[lngValue][nsValue] = data;
  17568. todo--; // wait for all done befor callback
  17569. if (todo === 0) cb(errors, store);
  17570. };
  17571. if(typeof options.customLoad == 'function'){
  17572. // Use the specified custom callback.
  17573. options.customLoad(lngValue, nsValue, options, loadComplete);
  17574. } else {
  17575. //~ // Use our inbuilt sync.
  17576. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17577. }
  17578. });
  17579. });
  17580. } else {
  17581. // Call this once our translation has returned.
  17582. var loadComplete = function(err, data) {
  17583. cb(null, data);
  17584. };
  17585. if(typeof options.customLoad == 'function'){
  17586. // Use the specified custom callback.
  17587. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17588. } else {
  17589. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17590. // load all needed stuff once
  17591. f.ajax({
  17592. url: url,
  17593. success: function(data, status, xhr) {
  17594. f.log('loaded: ' + url);
  17595. loadComplete(null, data);
  17596. },
  17597. error : function(xhr, status, error) {
  17598. f.log('failed loading: ' + url);
  17599. loadComplete('failed loading resource.json error: ' + error);
  17600. },
  17601. dataType: "json",
  17602. async : options.getAsync
  17603. });
  17604. }
  17605. }
  17606. },
  17607. _fetchOne: function(lng, ns, options, done) {
  17608. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17609. f.ajax({
  17610. url: url,
  17611. success: function(data, status, xhr) {
  17612. f.log('loaded: ' + url);
  17613. done(null, data);
  17614. },
  17615. error : function(xhr, status, error) {
  17616. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17617. // file loaded but invalid json, stop waste time !
  17618. f.error('There is a typo in: ' + url);
  17619. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17620. f.log('Does not exist: ' + url);
  17621. } else {
  17622. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17623. f.log(theStatus + ' when loading ' + url);
  17624. }
  17625. done(error, {});
  17626. },
  17627. dataType: "json",
  17628. async : options.getAsync
  17629. });
  17630. },
  17631. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17632. var payload = {};
  17633. payload[key] = defaultValue;
  17634. var urls = [];
  17635. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17636. for (var i = 0; i < o.fallbackLng.length; i++) {
  17637. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17638. }
  17639. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17640. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17641. } else if (o.sendMissingTo === 'all') {
  17642. for (var i = 0, l = lngs.length; i < l; i++) {
  17643. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17644. }
  17645. }
  17646. for (var y = 0, len = urls.length; y < len; y++) {
  17647. var item = urls[y];
  17648. f.ajax({
  17649. url: item.url,
  17650. type: o.sendType,
  17651. data: payload,
  17652. success: function(data, status, xhr) {
  17653. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17654. // add key to resStore
  17655. var keys = key.split('.');
  17656. var x = 0;
  17657. var value = resStore[item.lng][ns];
  17658. while (keys[x]) {
  17659. if (x === keys.length - 1) {
  17660. value = value[keys[x]] = defaultValue;
  17661. } else {
  17662. value = value[keys[x]] = value[keys[x]] || {};
  17663. }
  17664. x++;
  17665. }
  17666. },
  17667. error : function(xhr, status, error) {
  17668. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17669. },
  17670. dataType: "json",
  17671. async : o.postAsync
  17672. });
  17673. }
  17674. },
  17675. reload: reload
  17676. };
  17677. // defaults
  17678. var o = {
  17679. lng: undefined,
  17680. load: 'all',
  17681. preload: [],
  17682. lowerCaseLng: false,
  17683. returnObjectTrees: false,
  17684. fallbackLng: ['dev'],
  17685. fallbackNS: [],
  17686. detectLngQS: 'setLng',
  17687. detectLngFromLocalStorage: false,
  17688. ns: 'translation',
  17689. fallbackOnNull: true,
  17690. fallbackOnEmpty: false,
  17691. fallbackToDefaultNS: false,
  17692. nsseparator: ':',
  17693. keyseparator: '.',
  17694. selectorAttr: 'data-i18n',
  17695. debug: false,
  17696. resGetPath: 'locales/__lng__/__ns__.json',
  17697. resPostPath: 'locales/add/__lng__/__ns__',
  17698. getAsync: true,
  17699. postAsync: true,
  17700. resStore: undefined,
  17701. useLocalStorage: false,
  17702. localStorageExpirationTime: 7*24*60*60*1000,
  17703. dynamicLoad: false,
  17704. sendMissing: false,
  17705. sendMissingTo: 'fallback', // current | all
  17706. sendType: 'POST',
  17707. interpolationPrefix: '__',
  17708. interpolationSuffix: '__',
  17709. defaultVariables: false,
  17710. reusePrefix: '$t(',
  17711. reuseSuffix: ')',
  17712. pluralSuffix: '_plural',
  17713. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17714. contextNotFound: ['context_not_found', Math.random()].join(''),
  17715. escapeInterpolation: false,
  17716. indefiniteSuffix: '_indefinite',
  17717. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17718. setJqueryExt: true,
  17719. defaultValueFromContent: true,
  17720. useDataAttrOptions: false,
  17721. cookieExpirationTime: undefined,
  17722. useCookie: true,
  17723. cookieName: 'i18next',
  17724. cookieDomain: undefined,
  17725. objectTreeKeyHandler: undefined,
  17726. postProcess: undefined,
  17727. parseMissingKey: undefined,
  17728. missingKeyHandler: sync.postMissing,
  17729. shortcutFunction: 'sprintf' // or: defaultValue
  17730. };
  17731. function _extend(target, source) {
  17732. if (!source || typeof source === 'function') {
  17733. return target;
  17734. }
  17735. for (var attr in source) { target[attr] = source[attr]; }
  17736. return target;
  17737. }
  17738. function _deepExtend(target, source) {
  17739. for (var prop in source)
  17740. if (prop in target)
  17741. _deepExtend(target[prop], source[prop]);
  17742. else
  17743. target[prop] = source[prop];
  17744. return target;
  17745. }
  17746. function _each(object, callback, args) {
  17747. var name, i = 0,
  17748. length = object.length,
  17749. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17750. if (args) {
  17751. if (isObj) {
  17752. for (name in object) {
  17753. if (callback.apply(object[name], args) === false) {
  17754. break;
  17755. }
  17756. }
  17757. } else {
  17758. for ( ; i < length; ) {
  17759. if (callback.apply(object[i++], args) === false) {
  17760. break;
  17761. }
  17762. }
  17763. }
  17764. // A special, fast, case for the most common use of each
  17765. } else {
  17766. if (isObj) {
  17767. for (name in object) {
  17768. if (callback.call(object[name], name, object[name]) === false) {
  17769. break;
  17770. }
  17771. }
  17772. } else {
  17773. for ( ; i < length; ) {
  17774. if (callback.call(object[i], i, object[i++]) === false) {
  17775. break;
  17776. }
  17777. }
  17778. }
  17779. }
  17780. return object;
  17781. }
  17782. var _entityMap = {
  17783. "&": "&amp;",
  17784. "<": "&lt;",
  17785. ">": "&gt;",
  17786. '"': '&quot;',
  17787. "'": '&#39;',
  17788. "/": '&#x2F;'
  17789. };
  17790. function _escape(data) {
  17791. if (typeof data === 'string') {
  17792. return data.replace(/[&<>"'\/]/g, function (s) {
  17793. return _entityMap[s];
  17794. });
  17795. }else{
  17796. return data;
  17797. }
  17798. }
  17799. function _ajax(options) {
  17800. // v0.5.0 of https://github.com/goloroden/http.js
  17801. var getXhr = function (callback) {
  17802. // Use the native XHR object if the browser supports it.
  17803. if (window.XMLHttpRequest) {
  17804. return callback(null, new XMLHttpRequest());
  17805. } else if (window.ActiveXObject) {
  17806. // In Internet Explorer check for ActiveX versions of the XHR object.
  17807. try {
  17808. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  17809. } catch (e) {
  17810. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  17811. }
  17812. }
  17813. // If no XHR support was found, throw an error.
  17814. return callback(new Error());
  17815. };
  17816. var encodeUsingUrlEncoding = function (data) {
  17817. if(typeof data === 'string') {
  17818. return data;
  17819. }
  17820. var result = [];
  17821. for(var dataItem in data) {
  17822. if(data.hasOwnProperty(dataItem)) {
  17823. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  17824. }
  17825. }
  17826. return result.join('&');
  17827. };
  17828. var utf8 = function (text) {
  17829. text = text.replace(/\r\n/g, '\n');
  17830. var result = '';
  17831. for(var i = 0; i < text.length; i++) {
  17832. var c = text.charCodeAt(i);
  17833. if(c < 128) {
  17834. result += String.fromCharCode(c);
  17835. } else if((c > 127) && (c < 2048)) {
  17836. result += String.fromCharCode((c >> 6) | 192);
  17837. result += String.fromCharCode((c & 63) | 128);
  17838. } else {
  17839. result += String.fromCharCode((c >> 12) | 224);
  17840. result += String.fromCharCode(((c >> 6) & 63) | 128);
  17841. result += String.fromCharCode((c & 63) | 128);
  17842. }
  17843. }
  17844. return result;
  17845. };
  17846. var base64 = function (text) {
  17847. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17848. text = utf8(text);
  17849. var result = '',
  17850. chr1, chr2, chr3,
  17851. enc1, enc2, enc3, enc4,
  17852. i = 0;
  17853. do {
  17854. chr1 = text.charCodeAt(i++);
  17855. chr2 = text.charCodeAt(i++);
  17856. chr3 = text.charCodeAt(i++);
  17857. enc1 = chr1 >> 2;
  17858. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  17859. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  17860. enc4 = chr3 & 63;
  17861. if(isNaN(chr2)) {
  17862. enc3 = enc4 = 64;
  17863. } else if(isNaN(chr3)) {
  17864. enc4 = 64;
  17865. }
  17866. result +=
  17867. keyStr.charAt(enc1) +
  17868. keyStr.charAt(enc2) +
  17869. keyStr.charAt(enc3) +
  17870. keyStr.charAt(enc4);
  17871. chr1 = chr2 = chr3 = '';
  17872. enc1 = enc2 = enc3 = enc4 = '';
  17873. } while(i < text.length);
  17874. return result;
  17875. };
  17876. var mergeHeaders = function () {
  17877. // Use the first header object as base.
  17878. var result = arguments[0];
  17879. // Iterate through the remaining header objects and add them.
  17880. for(var i = 1; i < arguments.length; i++) {
  17881. var currentHeaders = arguments[i];
  17882. for(var header in currentHeaders) {
  17883. if(currentHeaders.hasOwnProperty(header)) {
  17884. result[header] = currentHeaders[header];
  17885. }
  17886. }
  17887. }
  17888. // Return the merged headers.
  17889. return result;
  17890. };
  17891. var ajax = function (method, url, options, callback) {
  17892. // Adjust parameters.
  17893. if(typeof options === 'function') {
  17894. callback = options;
  17895. options = {};
  17896. }
  17897. // Set default parameter values.
  17898. options.cache = options.cache || false;
  17899. options.data = options.data || {};
  17900. options.headers = options.headers || {};
  17901. options.jsonp = options.jsonp || false;
  17902. options.async = options.async === undefined ? true : options.async;
  17903. // Merge the various header objects.
  17904. var headers = mergeHeaders({
  17905. 'accept': '*/*',
  17906. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  17907. }, ajax.headers, options.headers);
  17908. // Encode the data according to the content-type.
  17909. var payload;
  17910. if (headers['content-type'] === 'application/json') {
  17911. payload = JSON.stringify(options.data);
  17912. } else {
  17913. payload = encodeUsingUrlEncoding(options.data);
  17914. }
  17915. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17916. // if neccessary.
  17917. if(method === 'GET') {
  17918. // Setup the query string.
  17919. var queryString = [];
  17920. if(payload) {
  17921. queryString.push(payload);
  17922. payload = null;
  17923. }
  17924. // Handle caching.
  17925. if(!options.cache) {
  17926. queryString.push('_=' + (new Date()).getTime());
  17927. }
  17928. // If neccessary prepare the query string for a JSONP call.
  17929. if(options.jsonp) {
  17930. queryString.push('callback=' + options.jsonp);
  17931. queryString.push('jsonp=' + options.jsonp);
  17932. }
  17933. // Merge the query string and attach it to the url.
  17934. queryString = queryString.join('&');
  17935. if (queryString.length > 1) {
  17936. if (url.indexOf('?') > -1) {
  17937. url += '&' + queryString;
  17938. } else {
  17939. url += '?' + queryString;
  17940. }
  17941. }
  17942. // Make a JSONP call if neccessary.
  17943. if(options.jsonp) {
  17944. var head = document.getElementsByTagName('head')[0];
  17945. var script = document.createElement('script');
  17946. script.type = 'text/javascript';
  17947. script.src = url;
  17948. head.appendChild(script);
  17949. return;
  17950. }
  17951. }
  17952. // Since we got here, it is no JSONP request, so make a normal XHR request.
  17953. getXhr(function (err, xhr) {
  17954. if(err) return callback(err);
  17955. // Open the request.
  17956. xhr.open(method, url, options.async);
  17957. // Set the request headers.
  17958. for(var header in headers) {
  17959. if(headers.hasOwnProperty(header)) {
  17960. xhr.setRequestHeader(header, headers[header]);
  17961. }
  17962. }
  17963. // Handle the request events.
  17964. xhr.onreadystatechange = function () {
  17965. if(xhr.readyState === 4) {
  17966. var data = xhr.responseText || '';
  17967. // If no callback is given, return.
  17968. if(!callback) {
  17969. return;
  17970. }
  17971. // Return an object that provides access to the data as text and JSON.
  17972. callback(xhr.status, {
  17973. text: function () {
  17974. return data;
  17975. },
  17976. json: function () {
  17977. try {
  17978. return JSON.parse(data)
  17979. } catch (e) {
  17980. f.error('Can not parse JSON. URL: ' + url);
  17981. return {};
  17982. }
  17983. }
  17984. });
  17985. }
  17986. };
  17987. // Actually send the XHR request.
  17988. xhr.send(payload);
  17989. });
  17990. };
  17991. // Define the external interface.
  17992. var http = {
  17993. authBasic: function (username, password) {
  17994. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  17995. },
  17996. connect: function (url, options, callback) {
  17997. return ajax('CONNECT', url, options, callback);
  17998. },
  17999. del: function (url, options, callback) {
  18000. return ajax('DELETE', url, options, callback);
  18001. },
  18002. get: function (url, options, callback) {
  18003. return ajax('GET', url, options, callback);
  18004. },
  18005. head: function (url, options, callback) {
  18006. return ajax('HEAD', url, options, callback);
  18007. },
  18008. headers: function (headers) {
  18009. ajax.headers = headers || {};
  18010. },
  18011. isAllowed: function (url, verb, callback) {
  18012. this.options(url, function (status, data) {
  18013. callback(data.text().indexOf(verb) !== -1);
  18014. });
  18015. },
  18016. options: function (url, options, callback) {
  18017. return ajax('OPTIONS', url, options, callback);
  18018. },
  18019. patch: function (url, options, callback) {
  18020. return ajax('PATCH', url, options, callback);
  18021. },
  18022. post: function (url, options, callback) {
  18023. return ajax('POST', url, options, callback);
  18024. },
  18025. put: function (url, options, callback) {
  18026. return ajax('PUT', url, options, callback);
  18027. },
  18028. trace: function (url, options, callback) {
  18029. return ajax('TRACE', url, options, callback);
  18030. }
  18031. };
  18032. var methode = options.type ? options.type.toLowerCase() : 'get';
  18033. http[methode](options.url, options, function (status, data) {
  18034. // file: protocol always gives status code 0, so check for data
  18035. if (status === 200 || (status === 0 && data.text())) {
  18036. options.success(data.json(), status, null);
  18037. } else {
  18038. options.error(data.text(), status, null);
  18039. }
  18040. });
  18041. }
  18042. var _cookie = {
  18043. create: function(name,value,minutes,domain) {
  18044. var expires;
  18045. if (minutes) {
  18046. var date = new Date();
  18047. date.setTime(date.getTime()+(minutes*60*1000));
  18048. expires = "; expires="+date.toGMTString();
  18049. }
  18050. else expires = "";
  18051. domain = (domain)? "domain="+domain+";" : "";
  18052. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18053. },
  18054. read: function(name) {
  18055. var nameEQ = name + "=";
  18056. var ca = document.cookie.split(';');
  18057. for(var i=0;i < ca.length;i++) {
  18058. var c = ca[i];
  18059. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18060. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18061. }
  18062. return null;
  18063. },
  18064. remove: function(name) {
  18065. this.create(name,"",-1);
  18066. }
  18067. };
  18068. var cookie_noop = {
  18069. create: function(name,value,minutes,domain) {},
  18070. read: function(name) { return null; },
  18071. remove: function(name) {}
  18072. };
  18073. // move dependent functions to a container so that
  18074. // they can be overriden easier in no jquery environment (node.js)
  18075. var f = {
  18076. extend: $ ? $.extend : _extend,
  18077. deepExtend: _deepExtend,
  18078. each: $ ? $.each : _each,
  18079. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18080. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18081. detectLanguage: detectLanguage,
  18082. escape: _escape,
  18083. log: function(str) {
  18084. if (o.debug && typeof console !== "undefined") console.log(str);
  18085. },
  18086. error: function(str) {
  18087. if (typeof console !== "undefined") console.error(str);
  18088. },
  18089. getCountyIndexOfLng: function(lng) {
  18090. var lng_index = 0;
  18091. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18092. return lng_index;
  18093. },
  18094. toLanguages: function(lng) {
  18095. var log = this.log;
  18096. function applyCase(l) {
  18097. var ret = l;
  18098. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18099. var parts = l.split('-');
  18100. ret = o.lowerCaseLng ?
  18101. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18102. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18103. } else {
  18104. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18105. }
  18106. return ret;
  18107. }
  18108. var languages = [];
  18109. var whitelist = o.lngWhitelist || false;
  18110. var addLanguage = function(language){
  18111. //reject langs not whitelisted
  18112. if(!whitelist || whitelist.indexOf(language) > -1){
  18113. languages.push(language);
  18114. }else{
  18115. log('rejecting non-whitelisted language: ' + language);
  18116. }
  18117. };
  18118. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18119. var parts = lng.split('-');
  18120. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18121. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18122. } else {
  18123. addLanguage(applyCase(lng));
  18124. }
  18125. for (var i = 0; i < o.fallbackLng.length; i++) {
  18126. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18127. }
  18128. return languages;
  18129. },
  18130. regexEscape: function(str) {
  18131. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18132. },
  18133. regexReplacementEscape: function(strOrFn) {
  18134. if (typeof strOrFn === 'string') {
  18135. return strOrFn.replace(/\$/g, "$$$$");
  18136. } else {
  18137. return strOrFn;
  18138. }
  18139. },
  18140. localStorage: {
  18141. setItem: function(key, value) {
  18142. if (window.localStorage) {
  18143. try {
  18144. window.localStorage.setItem(key, value);
  18145. } catch (e) {
  18146. f.log('failed to set value for key "' + key + '" to localStorage.');
  18147. }
  18148. }
  18149. }
  18150. }
  18151. };
  18152. function init(options, cb) {
  18153. if (typeof options === 'function') {
  18154. cb = options;
  18155. options = {};
  18156. }
  18157. options = options || {};
  18158. // override defaults with passed in options
  18159. f.extend(o, options);
  18160. delete o.fixLng; /* passed in each time */
  18161. // override functions: .log(), .detectLanguage(), etc
  18162. if (o.functions) {
  18163. delete o.functions;
  18164. f.extend(f, options.functions);
  18165. }
  18166. // create namespace object if namespace is passed in as string
  18167. if (typeof o.ns == 'string') {
  18168. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18169. }
  18170. // fallback namespaces
  18171. if (typeof o.fallbackNS == 'string') {
  18172. o.fallbackNS = [o.fallbackNS];
  18173. }
  18174. // fallback languages
  18175. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18176. o.fallbackLng = [o.fallbackLng];
  18177. }
  18178. // escape prefix/suffix
  18179. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18180. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18181. if (!o.lng) o.lng = f.detectLanguage();
  18182. languages = f.toLanguages(o.lng);
  18183. currentLng = languages[0];
  18184. f.log('currentLng set to: ' + currentLng);
  18185. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18186. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18187. }
  18188. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18189. f.localStorage.setItem('i18next_lng', currentLng);
  18190. }
  18191. var lngTranslate = translate;
  18192. if (options.fixLng) {
  18193. lngTranslate = function(key, options) {
  18194. options = options || {};
  18195. options.lng = options.lng || lngTranslate.lng;
  18196. return translate(key, options);
  18197. };
  18198. lngTranslate.lng = currentLng;
  18199. }
  18200. pluralExtensions.setCurrentLng(currentLng);
  18201. // add JQuery extensions
  18202. if ($ && o.setJqueryExt) addJqueryFunct();
  18203. // jQuery deferred
  18204. var deferred;
  18205. if ($ && $.Deferred) {
  18206. deferred = $.Deferred();
  18207. }
  18208. // return immidiatly if res are passed in
  18209. if (o.resStore) {
  18210. resStore = o.resStore;
  18211. initialized = true;
  18212. if (cb) cb(lngTranslate);
  18213. if (deferred) deferred.resolve(lngTranslate);
  18214. if (deferred) return deferred.promise();
  18215. return;
  18216. }
  18217. // languages to load
  18218. var lngsToLoad = f.toLanguages(o.lng);
  18219. if (typeof o.preload === 'string') o.preload = [o.preload];
  18220. for (var i = 0, l = o.preload.length; i < l; i++) {
  18221. var pres = f.toLanguages(o.preload[i]);
  18222. for (var y = 0, len = pres.length; y < len; y++) {
  18223. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18224. lngsToLoad.push(pres[y]);
  18225. }
  18226. }
  18227. }
  18228. // else load them
  18229. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18230. resStore = store;
  18231. initialized = true;
  18232. if (cb) cb(lngTranslate);
  18233. if (deferred) deferred.resolve(lngTranslate);
  18234. });
  18235. if (deferred) return deferred.promise();
  18236. }
  18237. function preload(lngs, cb) {
  18238. if (typeof lngs === 'string') lngs = [lngs];
  18239. for (var i = 0, l = lngs.length; i < l; i++) {
  18240. if (o.preload.indexOf(lngs[i]) < 0) {
  18241. o.preload.push(lngs[i]);
  18242. }
  18243. }
  18244. return init(cb);
  18245. }
  18246. function addResourceBundle(lng, ns, resources, deep) {
  18247. if (typeof ns !== 'string') {
  18248. resources = ns;
  18249. ns = o.ns.defaultNs;
  18250. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18251. o.ns.namespaces.push(ns);
  18252. }
  18253. resStore[lng] = resStore[lng] || {};
  18254. resStore[lng][ns] = resStore[lng][ns] || {};
  18255. if (deep) {
  18256. f.deepExtend(resStore[lng][ns], resources);
  18257. } else {
  18258. f.extend(resStore[lng][ns], resources);
  18259. }
  18260. }
  18261. function hasResourceBundle(lng, ns) {
  18262. if (typeof ns !== 'string') {
  18263. ns = o.ns.defaultNs;
  18264. }
  18265. resStore[lng] = resStore[lng] || {};
  18266. var res = resStore[lng][ns] || {};
  18267. var hasValues = false;
  18268. for(var prop in res) {
  18269. if (res.hasOwnProperty(prop)) {
  18270. hasValues = true;
  18271. }
  18272. }
  18273. return hasValues;
  18274. }
  18275. function removeResourceBundle(lng, ns) {
  18276. if (typeof ns !== 'string') {
  18277. ns = o.ns.defaultNs;
  18278. }
  18279. resStore[lng] = resStore[lng] || {};
  18280. resStore[lng][ns] = {};
  18281. }
  18282. function addResource(lng, ns, key, value) {
  18283. if (typeof ns !== 'string') {
  18284. resource = ns;
  18285. ns = o.ns.defaultNs;
  18286. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18287. o.ns.namespaces.push(ns);
  18288. }
  18289. resStore[lng] = resStore[lng] || {};
  18290. resStore[lng][ns] = resStore[lng][ns] || {};
  18291. var keys = key.split(o.keyseparator);
  18292. var x = 0;
  18293. var node = resStore[lng][ns];
  18294. var origRef = node;
  18295. while (keys[x]) {
  18296. if (x == keys.length - 1)
  18297. node[keys[x]] = value;
  18298. else {
  18299. if (node[keys[x]] == null)
  18300. node[keys[x]] = {};
  18301. node = node[keys[x]];
  18302. }
  18303. x++;
  18304. }
  18305. }
  18306. function addResources(lng, ns, resources) {
  18307. if (typeof ns !== 'string') {
  18308. resource = ns;
  18309. ns = o.ns.defaultNs;
  18310. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18311. o.ns.namespaces.push(ns);
  18312. }
  18313. for (var m in resources) {
  18314. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18315. }
  18316. }
  18317. function setDefaultNamespace(ns) {
  18318. o.ns.defaultNs = ns;
  18319. }
  18320. function loadNamespace(namespace, cb) {
  18321. loadNamespaces([namespace], cb);
  18322. }
  18323. function loadNamespaces(namespaces, cb) {
  18324. var opts = {
  18325. dynamicLoad: o.dynamicLoad,
  18326. resGetPath: o.resGetPath,
  18327. getAsync: o.getAsync,
  18328. customLoad: o.customLoad,
  18329. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18330. };
  18331. // languages to load
  18332. var lngsToLoad = f.toLanguages(o.lng);
  18333. if (typeof o.preload === 'string') o.preload = [o.preload];
  18334. for (var i = 0, l = o.preload.length; i < l; i++) {
  18335. var pres = f.toLanguages(o.preload[i]);
  18336. for (var y = 0, len = pres.length; y < len; y++) {
  18337. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18338. lngsToLoad.push(pres[y]);
  18339. }
  18340. }
  18341. }
  18342. // check if we have to load
  18343. var lngNeedLoad = [];
  18344. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18345. var needLoad = false;
  18346. var resSet = resStore[lngsToLoad[a]];
  18347. if (resSet) {
  18348. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18349. if (!resSet[namespaces[b]]) needLoad = true;
  18350. }
  18351. } else {
  18352. needLoad = true;
  18353. }
  18354. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18355. }
  18356. if (lngNeedLoad.length) {
  18357. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18358. var todo = namespaces.length * lngNeedLoad.length;
  18359. // load each file individual
  18360. f.each(namespaces, function(nsIndex, nsValue) {
  18361. // append namespace to namespace array
  18362. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18363. o.ns.namespaces.push(nsValue);
  18364. }
  18365. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18366. resStore[lngValue] = resStore[lngValue] || {};
  18367. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18368. todo--; // wait for all done befor callback
  18369. if (todo === 0 && cb) {
  18370. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18371. cb();
  18372. }
  18373. });
  18374. });
  18375. });
  18376. } else {
  18377. if (cb) cb();
  18378. }
  18379. }
  18380. function setLng(lng, options, cb) {
  18381. if (typeof options === 'function') {
  18382. cb = options;
  18383. options = {};
  18384. } else if (!options) {
  18385. options = {};
  18386. }
  18387. options.lng = lng;
  18388. return init(options, cb);
  18389. }
  18390. function lng() {
  18391. return currentLng;
  18392. }
  18393. function reload(cb) {
  18394. resStore = {};
  18395. setLng(currentLng, cb);
  18396. }
  18397. function addJqueryFunct() {
  18398. // $.t shortcut
  18399. $.t = $.t || translate;
  18400. function parse(ele, key, options) {
  18401. if (key.length === 0) return;
  18402. var attr = 'text';
  18403. if (key.indexOf('[') === 0) {
  18404. var parts = key.split(']');
  18405. key = parts[1];
  18406. attr = parts[0].substr(1, parts[0].length-1);
  18407. }
  18408. if (key.indexOf(';') === key.length-1) {
  18409. key = key.substr(0, key.length-2);
  18410. }
  18411. var optionsToUse;
  18412. if (attr === 'html') {
  18413. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18414. ele.html($.t(key, optionsToUse));
  18415. } else if (attr === 'text') {
  18416. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18417. ele.text($.t(key, optionsToUse));
  18418. } else if (attr === 'prepend') {
  18419. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18420. ele.prepend($.t(key, optionsToUse));
  18421. } else if (attr === 'append') {
  18422. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18423. ele.append($.t(key, optionsToUse));
  18424. } else if (attr.indexOf("data-") === 0) {
  18425. var dataAttr = attr.substr(("data-").length);
  18426. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18427. var translated = $.t(key, optionsToUse);
  18428. //we change into the data cache
  18429. ele.data(dataAttr, translated);
  18430. //we change into the dom
  18431. ele.attr(attr, translated);
  18432. } else {
  18433. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18434. ele.attr(attr, $.t(key, optionsToUse));
  18435. }
  18436. }
  18437. function localize(ele, options) {
  18438. var key = ele.attr(o.selectorAttr);
  18439. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18440. if (!key) return;
  18441. var target = ele
  18442. , targetSelector = ele.data("i18n-target");
  18443. if (targetSelector) {
  18444. target = ele.find(targetSelector) || ele;
  18445. }
  18446. if (!options && o.useDataAttrOptions === true) {
  18447. options = ele.data("i18n-options");
  18448. }
  18449. options = options || {};
  18450. if (key.indexOf(';') >= 0) {
  18451. var keys = key.split(';');
  18452. $.each(keys, function(m, k) {
  18453. if (k !== '') parse(target, k, options);
  18454. });
  18455. } else {
  18456. parse(target, key, options);
  18457. }
  18458. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18459. }
  18460. // fn
  18461. $.fn.i18n = function (options) {
  18462. return this.each(function() {
  18463. // localize element itself
  18464. localize($(this), options);
  18465. // localize childs
  18466. var elements = $(this).find('[' + o.selectorAttr + ']');
  18467. elements.each(function() {
  18468. localize($(this), options);
  18469. });
  18470. });
  18471. };
  18472. }
  18473. function applyReplacement(str, replacementHash, nestedKey, options) {
  18474. if (!str) return str;
  18475. options = options || replacementHash; // first call uses replacement hash combined with options
  18476. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18477. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18478. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18479. , unEscapingSuffix = 'HTML'+suffix;
  18480. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18481. f.each(hash, function(key, value) {
  18482. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18483. if (typeof value === 'object' && value !== null) {
  18484. str = applyReplacement(str, value, nextKey, options);
  18485. } else {
  18486. if (options.escapeInterpolation || o.escapeInterpolation) {
  18487. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18488. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18489. } else {
  18490. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18491. }
  18492. // str = options.escapeInterpolation;
  18493. }
  18494. });
  18495. return str;
  18496. }
  18497. // append it to functions
  18498. f.applyReplacement = applyReplacement;
  18499. function applyReuse(translated, options) {
  18500. var comma = ',';
  18501. var options_open = '{';
  18502. var options_close = '}';
  18503. var opts = f.extend({}, options);
  18504. delete opts.postProcess;
  18505. while (translated.indexOf(o.reusePrefix) != -1) {
  18506. replacementCounter++;
  18507. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18508. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18509. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18510. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18511. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18512. if (index_of_end_of_closing <= index_of_opening) {
  18513. f.error('there is an missing closing in following translation value', translated);
  18514. return '';
  18515. }
  18516. if (token_without_symbols.indexOf(comma) != -1) {
  18517. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18518. 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) {
  18519. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18520. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18521. try {
  18522. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18523. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18524. } catch (e) {
  18525. }
  18526. }
  18527. }
  18528. var translated_token = _translate(token_without_symbols, opts);
  18529. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18530. }
  18531. return translated;
  18532. }
  18533. function hasContext(options) {
  18534. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18535. }
  18536. function needsPlural(options, lng) {
  18537. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18538. }
  18539. function needsIndefiniteArticle(options) {
  18540. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18541. }
  18542. function exists(key, options) {
  18543. options = options || {};
  18544. var notFound = _getDefaultValue(key, options)
  18545. , found = _find(key, options);
  18546. return found !== undefined || found === notFound;
  18547. }
  18548. function translate(key, options) {
  18549. options = options || {};
  18550. if (!initialized) {
  18551. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18552. return options.defaultValue || '';
  18553. };
  18554. replacementCounter = 0;
  18555. return _translate.apply(null, arguments);
  18556. }
  18557. function _getDefaultValue(key, options) {
  18558. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18559. }
  18560. function _injectSprintfProcessor() {
  18561. var values = [];
  18562. // mh: build array from second argument onwards
  18563. for (var i = 1; i < arguments.length; i++) {
  18564. values.push(arguments[i]);
  18565. }
  18566. return {
  18567. postProcess: 'sprintf',
  18568. sprintf: values
  18569. };
  18570. }
  18571. function _translate(potentialKeys, options) {
  18572. if (options && typeof options !== 'object') {
  18573. if (o.shortcutFunction === 'sprintf') {
  18574. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18575. options = _injectSprintfProcessor.apply(null, arguments);
  18576. } else if (o.shortcutFunction === 'defaultValue') {
  18577. options = {
  18578. defaultValue: options
  18579. }
  18580. }
  18581. } else {
  18582. options = options || {};
  18583. }
  18584. if (typeof o.defaultVariables === 'object') {
  18585. options = f.extend({}, o.defaultVariables, options);
  18586. }
  18587. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18588. if (typeof potentialKeys === 'string') {
  18589. potentialKeys = [potentialKeys];
  18590. }
  18591. var key = potentialKeys[0];
  18592. if (potentialKeys.length > 1) {
  18593. for (var i = 0; i < potentialKeys.length; i++) {
  18594. key = potentialKeys[i];
  18595. if (exists(key, options)) {
  18596. break;
  18597. }
  18598. }
  18599. }
  18600. var notFound = _getDefaultValue(key, options)
  18601. , found = _find(key, options)
  18602. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18603. , ns = options.ns || o.ns.defaultNs
  18604. , parts;
  18605. // split ns and key
  18606. if (key.indexOf(o.nsseparator) > -1) {
  18607. parts = key.split(o.nsseparator);
  18608. ns = parts[0];
  18609. key = parts[1];
  18610. }
  18611. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18612. if (options.lng) {
  18613. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18614. } else {
  18615. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18616. }
  18617. }
  18618. var postProcessor = options.postProcess || o.postProcess;
  18619. if (found !== undefined && postProcessor) {
  18620. if (postProcessors[postProcessor]) {
  18621. found = postProcessors[postProcessor](found, key, options);
  18622. }
  18623. }
  18624. // process notFound if function exists
  18625. var splitNotFound = notFound;
  18626. if (notFound.indexOf(o.nsseparator) > -1) {
  18627. parts = notFound.split(o.nsseparator);
  18628. splitNotFound = parts[1];
  18629. }
  18630. if (splitNotFound === key && o.parseMissingKey) {
  18631. notFound = o.parseMissingKey(notFound);
  18632. }
  18633. if (found === undefined) {
  18634. notFound = applyReplacement(notFound, options);
  18635. notFound = applyReuse(notFound, options);
  18636. if (postProcessor && postProcessors[postProcessor]) {
  18637. var val = _getDefaultValue(key, options);
  18638. found = postProcessors[postProcessor](val, key, options);
  18639. }
  18640. }
  18641. return (found !== undefined) ? found : notFound;
  18642. }
  18643. function _find(key, options) {
  18644. options = options || {};
  18645. var optionWithoutCount, translated
  18646. , notFound = _getDefaultValue(key, options)
  18647. , lngs = languages;
  18648. if (!resStore) { return notFound; } // no resStore to translate from
  18649. // CI mode
  18650. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18651. // passed in lng
  18652. if (options.lngs) lngs = options.lngs;
  18653. if (options.lng) {
  18654. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18655. if (!resStore[lngs[0]]) {
  18656. var oldAsync = o.getAsync;
  18657. o.getAsync = false;
  18658. i18n.sync.load(lngs, o, function(err, store) {
  18659. f.extend(resStore, store);
  18660. o.getAsync = oldAsync;
  18661. });
  18662. }
  18663. }
  18664. var ns = options.ns || o.ns.defaultNs;
  18665. if (key.indexOf(o.nsseparator) > -1) {
  18666. var parts = key.split(o.nsseparator);
  18667. ns = parts[0];
  18668. key = parts[1];
  18669. }
  18670. if (hasContext(options)) {
  18671. optionWithoutCount = f.extend({}, options);
  18672. delete optionWithoutCount.context;
  18673. optionWithoutCount.defaultValue = o.contextNotFound;
  18674. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18675. translated = translate(contextKey, optionWithoutCount);
  18676. if (translated != o.contextNotFound) {
  18677. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18678. } // else continue translation with original/nonContext key
  18679. }
  18680. if (needsPlural(options, lngs[0])) {
  18681. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18682. delete optionWithoutCount.count;
  18683. delete optionWithoutCount.lng;
  18684. optionWithoutCount.defaultValue = o.pluralNotFound;
  18685. var pluralKey;
  18686. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18687. pluralKey = ns + o.nsseparator + key;
  18688. } else {
  18689. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18690. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18691. if (pluralExtension >= 0) {
  18692. pluralKey = pluralKey + '_' + pluralExtension;
  18693. } else if (pluralExtension === 1) {
  18694. pluralKey = ns + o.nsseparator + key; // singular
  18695. }
  18696. }
  18697. translated = translate(pluralKey, optionWithoutCount);
  18698. if (translated != o.pluralNotFound) {
  18699. return applyReplacement(translated, {
  18700. count: options.count,
  18701. interpolationPrefix: options.interpolationPrefix,
  18702. interpolationSuffix: options.interpolationSuffix
  18703. }); // apply replacement for count only
  18704. } else if (lngs.length > 1) {
  18705. // remove failed lng
  18706. var clone = lngs.slice();
  18707. clone.shift();
  18708. options = f.extend(options, { lngs: clone });
  18709. delete options.lng;
  18710. // retry with fallbacks
  18711. translated = translate(ns + o.nsseparator + key, options);
  18712. if (translated != o.pluralNotFound) return translated;
  18713. } else {
  18714. return translated;
  18715. }
  18716. }
  18717. if (needsIndefiniteArticle(options)) {
  18718. var optionsWithoutIndef = f.extend({}, options);
  18719. delete optionsWithoutIndef.indefinite_article;
  18720. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18721. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18722. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18723. translated = translate(indefiniteKey, optionsWithoutIndef);
  18724. if (translated != o.indefiniteNotFound) {
  18725. return translated;
  18726. }
  18727. }
  18728. var found;
  18729. var keys = key.split(o.keyseparator);
  18730. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18731. if (found !== undefined) break;
  18732. var l = lngs[i];
  18733. var x = 0;
  18734. var value = resStore[l] && resStore[l][ns];
  18735. while (keys[x]) {
  18736. value = value && value[keys[x]];
  18737. x++;
  18738. }
  18739. if (value !== undefined) {
  18740. var valueType = Object.prototype.toString.apply(value);
  18741. if (typeof value === 'string') {
  18742. value = applyReplacement(value, options);
  18743. value = applyReuse(value, options);
  18744. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18745. value = value.join('\n');
  18746. value = applyReplacement(value, options);
  18747. value = applyReuse(value, options);
  18748. } else if (value === null && o.fallbackOnNull === true) {
  18749. value = undefined;
  18750. } else if (value !== null) {
  18751. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18752. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18753. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18754. } else {
  18755. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18756. 'returned an object instead of string.';
  18757. f.log(value);
  18758. }
  18759. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18760. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18761. f.each(value, function(m) {
  18762. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18763. });
  18764. value = copy;
  18765. }
  18766. }
  18767. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18768. value = undefined;
  18769. found = value;
  18770. }
  18771. }
  18772. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18773. // set flag for fallback lookup - avoid recursion
  18774. options.isFallbackLookup = true;
  18775. if (o.fallbackNS.length) {
  18776. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  18777. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  18778. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  18779. /* compare value without namespace */
  18780. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  18781. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  18782. if (foundValue !== notFoundValue) break;
  18783. }
  18784. }
  18785. } else {
  18786. found = _find(key, options); // fallback to default NS
  18787. }
  18788. options.isFallbackLookup = false;
  18789. }
  18790. return found;
  18791. }
  18792. function detectLanguage() {
  18793. var detectedLng;
  18794. var whitelist = o.lngWhitelist || [];
  18795. var userLngChoices = [];
  18796. // get from qs
  18797. var qsParm = [];
  18798. if (typeof window !== 'undefined') {
  18799. (function() {
  18800. var query = window.location.search.substring(1);
  18801. var params = query.split('&');
  18802. for (var i=0; i<params.length; i++) {
  18803. var pos = params[i].indexOf('=');
  18804. if (pos > 0) {
  18805. var key = params[i].substring(0,pos);
  18806. if (key == o.detectLngQS) {
  18807. userLngChoices.push(params[i].substring(pos+1));
  18808. }
  18809. }
  18810. }
  18811. })();
  18812. }
  18813. // get from cookie
  18814. if (o.useCookie && typeof document !== 'undefined') {
  18815. var c = f.cookie.read(o.cookieName);
  18816. if (c) userLngChoices.push(c);
  18817. }
  18818. // get from localStorage
  18819. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  18820. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  18821. }
  18822. // get from navigator
  18823. if (typeof navigator !== 'undefined') {
  18824. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  18825. for (var i=0;i<navigator.languages.length;i++) {
  18826. userLngChoices.push(navigator.languages[i]);
  18827. }
  18828. }
  18829. if (navigator.userLanguage) {
  18830. userLngChoices.push(navigator.userLanguage);
  18831. }
  18832. if (navigator.language) {
  18833. userLngChoices.push(navigator.language);
  18834. }
  18835. }
  18836. (function() {
  18837. for (var i=0;i<userLngChoices.length;i++) {
  18838. var lng = userLngChoices[i];
  18839. if (lng.indexOf('-') > -1) {
  18840. var parts = lng.split('-');
  18841. lng = o.lowerCaseLng ?
  18842. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18843. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18844. }
  18845. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  18846. detectedLng = lng;
  18847. break;
  18848. }
  18849. }
  18850. })();
  18851. //fallback
  18852. if (!detectedLng){
  18853. detectedLng = o.fallbackLng[0];
  18854. }
  18855. return detectedLng;
  18856. }
  18857. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  18858. /* [code, name, numbers, pluralsType] */
  18859. var _rules = [
  18860. ["ach", "Acholi", [1,2], 1],
  18861. ["af", "Afrikaans",[1,2], 2],
  18862. ["ak", "Akan", [1,2], 1],
  18863. ["am", "Amharic", [1,2], 1],
  18864. ["an", "Aragonese",[1,2], 2],
  18865. ["ar", "Arabic", [0,1,2,3,11,100],5],
  18866. ["arn", "Mapudungun",[1,2], 1],
  18867. ["ast", "Asturian", [1,2], 2],
  18868. ["ay", "Aymará", [1], 3],
  18869. ["az", "Azerbaijani",[1,2],2],
  18870. ["be", "Belarusian",[1,2,5],4],
  18871. ["bg", "Bulgarian",[1,2], 2],
  18872. ["bn", "Bengali", [1,2], 2],
  18873. ["bo", "Tibetan", [1], 3],
  18874. ["br", "Breton", [1,2], 1],
  18875. ["bs", "Bosnian", [1,2,5],4],
  18876. ["ca", "Catalan", [1,2], 2],
  18877. ["cgg", "Chiga", [1], 3],
  18878. ["cs", "Czech", [1,2,5],6],
  18879. ["csb", "Kashubian",[1,2,5],7],
  18880. ["cy", "Welsh", [1,2,3,8],8],
  18881. ["da", "Danish", [1,2], 2],
  18882. ["de", "German", [1,2], 2],
  18883. ["dev", "Development Fallback", [1,2], 2],
  18884. ["dz", "Dzongkha", [1], 3],
  18885. ["el", "Greek", [1,2], 2],
  18886. ["en", "English", [1,2], 2],
  18887. ["eo", "Esperanto",[1,2], 2],
  18888. ["es", "Spanish", [1,2], 2],
  18889. ["es_ar","Argentinean Spanish", [1,2], 2],
  18890. ["et", "Estonian", [1,2], 2],
  18891. ["eu", "Basque", [1,2], 2],
  18892. ["fa", "Persian", [1], 3],
  18893. ["fi", "Finnish", [1,2], 2],
  18894. ["fil", "Filipino", [1,2], 1],
  18895. ["fo", "Faroese", [1,2], 2],
  18896. ["fr", "French", [1,2], 9],
  18897. ["fur", "Friulian", [1,2], 2],
  18898. ["fy", "Frisian", [1,2], 2],
  18899. ["ga", "Irish", [1,2,3,7,11],10],
  18900. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  18901. ["gl", "Galician", [1,2], 2],
  18902. ["gu", "Gujarati", [1,2], 2],
  18903. ["gun", "Gun", [1,2], 1],
  18904. ["ha", "Hausa", [1,2], 2],
  18905. ["he", "Hebrew", [1,2], 2],
  18906. ["hi", "Hindi", [1,2], 2],
  18907. ["hr", "Croatian", [1,2,5],4],
  18908. ["hu", "Hungarian",[1,2], 2],
  18909. ["hy", "Armenian", [1,2], 2],
  18910. ["ia", "Interlingua",[1,2],2],
  18911. ["id", "Indonesian",[1], 3],
  18912. ["is", "Icelandic",[1,2], 12],
  18913. ["it", "Italian", [1,2], 2],
  18914. ["ja", "Japanese", [1], 3],
  18915. ["jbo", "Lojban", [1], 3],
  18916. ["jv", "Javanese", [0,1], 13],
  18917. ["ka", "Georgian", [1], 3],
  18918. ["kk", "Kazakh", [1], 3],
  18919. ["km", "Khmer", [1], 3],
  18920. ["kn", "Kannada", [1,2], 2],
  18921. ["ko", "Korean", [1], 3],
  18922. ["ku", "Kurdish", [1,2], 2],
  18923. ["kw", "Cornish", [1,2,3,4],14],
  18924. ["ky", "Kyrgyz", [1], 3],
  18925. ["lb", "Letzeburgesch",[1,2],2],
  18926. ["ln", "Lingala", [1,2], 1],
  18927. ["lo", "Lao", [1], 3],
  18928. ["lt", "Lithuanian",[1,2,10],15],
  18929. ["lv", "Latvian", [1,2,0],16],
  18930. ["mai", "Maithili", [1,2], 2],
  18931. ["mfe", "Mauritian Creole",[1,2],1],
  18932. ["mg", "Malagasy", [1,2], 1],
  18933. ["mi", "Maori", [1,2], 1],
  18934. ["mk", "Macedonian",[1,2],17],
  18935. ["ml", "Malayalam",[1,2], 2],
  18936. ["mn", "Mongolian",[1,2], 2],
  18937. ["mnk", "Mandinka", [0,1,2],18],
  18938. ["mr", "Marathi", [1,2], 2],
  18939. ["ms", "Malay", [1], 3],
  18940. ["mt", "Maltese", [1,2,11,20],19],
  18941. ["nah", "Nahuatl", [1,2], 2],
  18942. ["nap", "Neapolitan",[1,2], 2],
  18943. ["nb", "Norwegian Bokmal",[1,2],2],
  18944. ["ne", "Nepali", [1,2], 2],
  18945. ["nl", "Dutch", [1,2], 2],
  18946. ["nn", "Norwegian Nynorsk",[1,2],2],
  18947. ["no", "Norwegian",[1,2], 2],
  18948. ["nso", "Northern Sotho",[1,2],2],
  18949. ["oc", "Occitan", [1,2], 1],
  18950. ["or", "Oriya", [2,1], 2],
  18951. ["pa", "Punjabi", [1,2], 2],
  18952. ["pap", "Papiamento",[1,2], 2],
  18953. ["pl", "Polish", [1,2,5],7],
  18954. ["pms", "Piemontese",[1,2], 2],
  18955. ["ps", "Pashto", [1,2], 2],
  18956. ["pt", "Portuguese",[1,2], 2],
  18957. ["pt_br","Brazilian Portuguese",[1,2], 2],
  18958. ["rm", "Romansh", [1,2], 2],
  18959. ["ro", "Romanian", [1,2,20],20],
  18960. ["ru", "Russian", [1,2,5],4],
  18961. ["sah", "Yakut", [1], 3],
  18962. ["sco", "Scots", [1,2], 2],
  18963. ["se", "Northern Sami",[1,2], 2],
  18964. ["si", "Sinhala", [1,2], 2],
  18965. ["sk", "Slovak", [1,2,5],6],
  18966. ["sl", "Slovenian",[5,1,2,3],21],
  18967. ["so", "Somali", [1,2], 2],
  18968. ["son", "Songhay", [1,2], 2],
  18969. ["sq", "Albanian", [1,2], 2],
  18970. ["sr", "Serbian", [1,2,5],4],
  18971. ["su", "Sundanese",[1], 3],
  18972. ["sv", "Swedish", [1,2], 2],
  18973. ["sw", "Swahili", [1,2], 2],
  18974. ["ta", "Tamil", [1,2], 2],
  18975. ["te", "Telugu", [1,2], 2],
  18976. ["tg", "Tajik", [1,2], 1],
  18977. ["th", "Thai", [1], 3],
  18978. ["ti", "Tigrinya", [1,2], 1],
  18979. ["tk", "Turkmen", [1,2], 2],
  18980. ["tr", "Turkish", [1,2], 1],
  18981. ["tt", "Tatar", [1], 3],
  18982. ["ug", "Uyghur", [1], 3],
  18983. ["uk", "Ukrainian",[1,2,5],4],
  18984. ["ur", "Urdu", [1,2], 2],
  18985. ["uz", "Uzbek", [1,2], 1],
  18986. ["vi", "Vietnamese",[1], 3],
  18987. ["wa", "Walloon", [1,2], 1],
  18988. ["wo", "Wolof", [1], 3],
  18989. ["yo", "Yoruba", [1,2], 2],
  18990. ["zh", "Chinese", [1], 3]
  18991. ];
  18992. var _rulesPluralsTypes = {
  18993. 1: function(n) {return Number(n > 1);},
  18994. 2: function(n) {return Number(n != 1);},
  18995. 3: function(n) {return 0;},
  18996. 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);},
  18997. 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);},
  18998. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  18999. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19000. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19001. 9: function(n) {return Number(n >= 2);},
  19002. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19003. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19004. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19005. 13: function(n) {return Number(n !== 0);},
  19006. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19007. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19008. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19009. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19010. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19011. 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);},
  19012. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19013. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19014. };
  19015. var pluralExtensions = {
  19016. rules: (function () {
  19017. var l, rules = {};
  19018. for (l=_rules.length; l-- ;) {
  19019. rules[_rules[l][0]] = {
  19020. name: _rules[l][1],
  19021. numbers: _rules[l][2],
  19022. plurals: _rulesPluralsTypes[_rules[l][3]]
  19023. }
  19024. }
  19025. return rules;
  19026. }()),
  19027. // you can add your own pluralExtensions
  19028. addRule: function(lng, obj) {
  19029. pluralExtensions.rules[lng] = obj;
  19030. },
  19031. setCurrentLng: function(lng) {
  19032. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19033. var parts = lng.split('-');
  19034. pluralExtensions.currentRule = {
  19035. lng: lng,
  19036. rule: pluralExtensions.rules[parts[0]]
  19037. };
  19038. }
  19039. },
  19040. needsPlural: function(lng, count) {
  19041. var parts = lng.split('-');
  19042. var ext;
  19043. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19044. ext = pluralExtensions.currentRule.rule;
  19045. } else {
  19046. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19047. }
  19048. if (ext && ext.numbers.length <= 1) {
  19049. return false;
  19050. } else {
  19051. return this.get(lng, count) !== 1;
  19052. }
  19053. },
  19054. get: function(lng, count) {
  19055. var parts = lng.split('-');
  19056. function getResult(l, c) {
  19057. var ext;
  19058. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19059. ext = pluralExtensions.currentRule.rule;
  19060. } else {
  19061. ext = pluralExtensions.rules[l];
  19062. }
  19063. if (ext) {
  19064. var i;
  19065. if (ext.noAbs) {
  19066. i = ext.plurals(c);
  19067. } else {
  19068. i = ext.plurals(Math.abs(c));
  19069. }
  19070. var number = ext.numbers[i];
  19071. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19072. if (number === 2) {
  19073. number = -1; // regular plural
  19074. } else if (number === 1) {
  19075. number = 1; // singular
  19076. }
  19077. }//console.log(count + '-' + number);
  19078. return number;
  19079. } else {
  19080. return c === 1 ? '1' : '-1';
  19081. }
  19082. }
  19083. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19084. }
  19085. };
  19086. var postProcessors = {};
  19087. var addPostProcessor = function(name, fc) {
  19088. postProcessors[name] = fc;
  19089. };
  19090. // sprintf support
  19091. var sprintf = (function() {
  19092. function get_type(variable) {
  19093. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19094. }
  19095. function str_repeat(input, multiplier) {
  19096. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19097. return output.join('');
  19098. }
  19099. var str_format = function() {
  19100. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19101. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19102. }
  19103. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19104. };
  19105. str_format.format = function(parse_tree, argv) {
  19106. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19107. for (i = 0; i < tree_length; i++) {
  19108. node_type = get_type(parse_tree[i]);
  19109. if (node_type === 'string') {
  19110. output.push(parse_tree[i]);
  19111. }
  19112. else if (node_type === 'array') {
  19113. match = parse_tree[i]; // convenience purposes only
  19114. if (match[2]) { // keyword argument
  19115. arg = argv[cursor];
  19116. for (k = 0; k < match[2].length; k++) {
  19117. if (!arg.hasOwnProperty(match[2][k])) {
  19118. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19119. }
  19120. arg = arg[match[2][k]];
  19121. }
  19122. }
  19123. else if (match[1]) { // positional argument (explicit)
  19124. arg = argv[match[1]];
  19125. }
  19126. else { // positional argument (implicit)
  19127. arg = argv[cursor++];
  19128. }
  19129. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19130. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19131. }
  19132. switch (match[8]) {
  19133. case 'b': arg = arg.toString(2); break;
  19134. case 'c': arg = String.fromCharCode(arg); break;
  19135. case 'd': arg = parseInt(arg, 10); break;
  19136. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19137. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19138. case 'o': arg = arg.toString(8); break;
  19139. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19140. case 'u': arg = Math.abs(arg); break;
  19141. case 'x': arg = arg.toString(16); break;
  19142. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19143. }
  19144. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19145. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19146. pad_length = match[6] - String(arg).length;
  19147. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19148. output.push(match[5] ? arg + pad : pad + arg);
  19149. }
  19150. }
  19151. return output.join('');
  19152. };
  19153. str_format.cache = {};
  19154. str_format.parse = function(fmt) {
  19155. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19156. while (_fmt) {
  19157. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19158. parse_tree.push(match[0]);
  19159. }
  19160. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19161. parse_tree.push('%');
  19162. }
  19163. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19164. if (match[2]) {
  19165. arg_names |= 1;
  19166. var field_list = [], replacement_field = match[2], field_match = [];
  19167. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19168. field_list.push(field_match[1]);
  19169. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19170. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19171. field_list.push(field_match[1]);
  19172. }
  19173. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19174. field_list.push(field_match[1]);
  19175. }
  19176. else {
  19177. throw('[sprintf] huh?');
  19178. }
  19179. }
  19180. }
  19181. else {
  19182. throw('[sprintf] huh?');
  19183. }
  19184. match[2] = field_list;
  19185. }
  19186. else {
  19187. arg_names |= 2;
  19188. }
  19189. if (arg_names === 3) {
  19190. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19191. }
  19192. parse_tree.push(match);
  19193. }
  19194. else {
  19195. throw('[sprintf] huh?');
  19196. }
  19197. _fmt = _fmt.substring(match[0].length);
  19198. }
  19199. return parse_tree;
  19200. };
  19201. return str_format;
  19202. })();
  19203. var vsprintf = function(fmt, argv) {
  19204. argv.unshift(fmt);
  19205. return sprintf.apply(null, argv);
  19206. };
  19207. addPostProcessor("sprintf", function(val, key, opts) {
  19208. if (!opts.sprintf) return val;
  19209. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19210. return vsprintf(val, opts.sprintf);
  19211. } else if (typeof opts.sprintf === 'object') {
  19212. return sprintf(val, opts.sprintf);
  19213. }
  19214. return val;
  19215. });
  19216. // public api interface
  19217. i18n.init = init;
  19218. i18n.setLng = setLng;
  19219. i18n.preload = preload;
  19220. i18n.addResourceBundle = addResourceBundle;
  19221. i18n.hasResourceBundle = hasResourceBundle;
  19222. i18n.addResource = addResource;
  19223. i18n.addResources = addResources;
  19224. i18n.removeResourceBundle = removeResourceBundle;
  19225. i18n.loadNamespace = loadNamespace;
  19226. i18n.loadNamespaces = loadNamespaces;
  19227. i18n.setDefaultNamespace = setDefaultNamespace;
  19228. i18n.t = translate;
  19229. i18n.translate = translate;
  19230. i18n.exists = exists;
  19231. i18n.detectLanguage = f.detectLanguage;
  19232. i18n.pluralExtensions = pluralExtensions;
  19233. i18n.sync = sync;
  19234. i18n.functions = f;
  19235. i18n.lng = lng;
  19236. i18n.addPostProcessor = addPostProcessor;
  19237. i18n.options = o;
  19238. })();
  19239. },{"jquery":"jquery"}],69:[function(require,module,exports){
  19240. // Top level file is just a mixin of submodules & constants
  19241. 'use strict';
  19242. var assign = require('./lib/utils/common').assign;
  19243. var deflate = require('./lib/deflate');
  19244. var inflate = require('./lib/inflate');
  19245. var constants = require('./lib/zlib/constants');
  19246. var pako = {};
  19247. assign(pako, deflate, inflate, constants);
  19248. module.exports = pako;
  19249. },{"./lib/deflate":70,"./lib/inflate":71,"./lib/utils/common":72,"./lib/zlib/constants":75}],70:[function(require,module,exports){
  19250. 'use strict';
  19251. var zlib_deflate = require('./zlib/deflate.js');
  19252. var utils = require('./utils/common');
  19253. var strings = require('./utils/strings');
  19254. var msg = require('./zlib/messages');
  19255. var zstream = require('./zlib/zstream');
  19256. var toString = Object.prototype.toString;
  19257. /* Public constants ==========================================================*/
  19258. /* ===========================================================================*/
  19259. var Z_NO_FLUSH = 0;
  19260. var Z_FINISH = 4;
  19261. var Z_OK = 0;
  19262. var Z_STREAM_END = 1;
  19263. var Z_SYNC_FLUSH = 2;
  19264. var Z_DEFAULT_COMPRESSION = -1;
  19265. var Z_DEFAULT_STRATEGY = 0;
  19266. var Z_DEFLATED = 8;
  19267. /* ===========================================================================*/
  19268. /**
  19269. * class Deflate
  19270. *
  19271. * Generic JS-style wrapper for zlib calls. If you don't need
  19272. * streaming behaviour - use more simple functions: [[deflate]],
  19273. * [[deflateRaw]] and [[gzip]].
  19274. **/
  19275. /* internal
  19276. * Deflate.chunks -> Array
  19277. *
  19278. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19279. **/
  19280. /**
  19281. * Deflate.result -> Uint8Array|Array
  19282. *
  19283. * Compressed result, generated by default [[Deflate#onData]]
  19284. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19285. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19286. * push a chunk with explicit flush (call [[Deflate#push]] with
  19287. * `Z_SYNC_FLUSH` param).
  19288. **/
  19289. /**
  19290. * Deflate.err -> Number
  19291. *
  19292. * Error code after deflate finished. 0 (Z_OK) on success.
  19293. * You will not need it in real life, because deflate errors
  19294. * are possible only on wrong options or bad `onData` / `onEnd`
  19295. * custom handlers.
  19296. **/
  19297. /**
  19298. * Deflate.msg -> String
  19299. *
  19300. * Error message, if [[Deflate.err]] != 0
  19301. **/
  19302. /**
  19303. * new Deflate(options)
  19304. * - options (Object): zlib deflate options.
  19305. *
  19306. * Creates new deflator instance with specified params. Throws exception
  19307. * on bad params. Supported options:
  19308. *
  19309. * - `level`
  19310. * - `windowBits`
  19311. * - `memLevel`
  19312. * - `strategy`
  19313. *
  19314. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19315. * for more information on these.
  19316. *
  19317. * Additional options, for internal needs:
  19318. *
  19319. * - `chunkSize` - size of generated data chunks (16K by default)
  19320. * - `raw` (Boolean) - do raw deflate
  19321. * - `gzip` (Boolean) - create gzip wrapper
  19322. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19323. * (each char code [0..255])
  19324. * - `header` (Object) - custom header for gzip
  19325. * - `text` (Boolean) - true if compressed data believed to be text
  19326. * - `time` (Number) - modification time, unix timestamp
  19327. * - `os` (Number) - operation system code
  19328. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19329. * - `name` (String) - file name (binary string)
  19330. * - `comment` (String) - comment (binary string)
  19331. * - `hcrc` (Boolean) - true if header crc should be added
  19332. *
  19333. * ##### Example:
  19334. *
  19335. * ```javascript
  19336. * var pako = require('pako')
  19337. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19338. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19339. *
  19340. * var deflate = new pako.Deflate({ level: 3});
  19341. *
  19342. * deflate.push(chunk1, false);
  19343. * deflate.push(chunk2, true); // true -> last chunk
  19344. *
  19345. * if (deflate.err) { throw new Error(deflate.err); }
  19346. *
  19347. * console.log(deflate.result);
  19348. * ```
  19349. **/
  19350. var Deflate = function(options) {
  19351. this.options = utils.assign({
  19352. level: Z_DEFAULT_COMPRESSION,
  19353. method: Z_DEFLATED,
  19354. chunkSize: 16384,
  19355. windowBits: 15,
  19356. memLevel: 8,
  19357. strategy: Z_DEFAULT_STRATEGY,
  19358. to: ''
  19359. }, options || {});
  19360. var opt = this.options;
  19361. if (opt.raw && (opt.windowBits > 0)) {
  19362. opt.windowBits = -opt.windowBits;
  19363. }
  19364. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19365. opt.windowBits += 16;
  19366. }
  19367. this.err = 0; // error code, if happens (0 = Z_OK)
  19368. this.msg = ''; // error message
  19369. this.ended = false; // used to avoid multiple onEnd() calls
  19370. this.chunks = []; // chunks of compressed data
  19371. this.strm = new zstream();
  19372. this.strm.avail_out = 0;
  19373. var status = zlib_deflate.deflateInit2(
  19374. this.strm,
  19375. opt.level,
  19376. opt.method,
  19377. opt.windowBits,
  19378. opt.memLevel,
  19379. opt.strategy
  19380. );
  19381. if (status !== Z_OK) {
  19382. throw new Error(msg[status]);
  19383. }
  19384. if (opt.header) {
  19385. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19386. }
  19387. };
  19388. /**
  19389. * Deflate#push(data[, mode]) -> Boolean
  19390. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19391. * converted to utf8 byte sequence.
  19392. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19393. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19394. *
  19395. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19396. * new compressed chunks. Returns `true` on success. The last data block must have
  19397. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19398. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19399. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19400. *
  19401. * On fail call [[Deflate#onEnd]] with error code and return false.
  19402. *
  19403. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19404. * array format is detected automatically). Also, don't skip last param and always
  19405. * use the same type in your code (boolean or number). That will improve JS speed.
  19406. *
  19407. * For regular `Array`-s make sure all elements are [0..255].
  19408. *
  19409. * ##### Example
  19410. *
  19411. * ```javascript
  19412. * push(chunk, false); // push one of data chunks
  19413. * ...
  19414. * push(chunk, true); // push last chunk
  19415. * ```
  19416. **/
  19417. Deflate.prototype.push = function(data, mode) {
  19418. var strm = this.strm;
  19419. var chunkSize = this.options.chunkSize;
  19420. var status, _mode;
  19421. if (this.ended) { return false; }
  19422. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19423. // Convert data if needed
  19424. if (typeof data === 'string') {
  19425. // If we need to compress text, change encoding to utf8.
  19426. strm.input = strings.string2buf(data);
  19427. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19428. strm.input = new Uint8Array(data);
  19429. } else {
  19430. strm.input = data;
  19431. }
  19432. strm.next_in = 0;
  19433. strm.avail_in = strm.input.length;
  19434. do {
  19435. if (strm.avail_out === 0) {
  19436. strm.output = new utils.Buf8(chunkSize);
  19437. strm.next_out = 0;
  19438. strm.avail_out = chunkSize;
  19439. }
  19440. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19441. if (status !== Z_STREAM_END && status !== Z_OK) {
  19442. this.onEnd(status);
  19443. this.ended = true;
  19444. return false;
  19445. }
  19446. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19447. if (this.options.to === 'string') {
  19448. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19449. } else {
  19450. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19451. }
  19452. }
  19453. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19454. // Finalize on the last chunk.
  19455. if (_mode === Z_FINISH) {
  19456. status = zlib_deflate.deflateEnd(this.strm);
  19457. this.onEnd(status);
  19458. this.ended = true;
  19459. return status === Z_OK;
  19460. }
  19461. // callback interim results if Z_SYNC_FLUSH.
  19462. if (_mode === Z_SYNC_FLUSH) {
  19463. this.onEnd(Z_OK);
  19464. strm.avail_out = 0;
  19465. return true;
  19466. }
  19467. return true;
  19468. };
  19469. /**
  19470. * Deflate#onData(chunk) -> Void
  19471. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19472. * on js engine support. When string output requested, each chunk
  19473. * will be string.
  19474. *
  19475. * By default, stores data blocks in `chunks[]` property and glue
  19476. * those in `onEnd`. Override this handler, if you need another behaviour.
  19477. **/
  19478. Deflate.prototype.onData = function(chunk) {
  19479. this.chunks.push(chunk);
  19480. };
  19481. /**
  19482. * Deflate#onEnd(status) -> Void
  19483. * - status (Number): deflate status. 0 (Z_OK) on success,
  19484. * other if not.
  19485. *
  19486. * Called once after you tell deflate that the input stream is
  19487. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19488. * or if an error happened. By default - join collected chunks,
  19489. * free memory and fill `results` / `err` properties.
  19490. **/
  19491. Deflate.prototype.onEnd = function(status) {
  19492. // On success - join
  19493. if (status === Z_OK) {
  19494. if (this.options.to === 'string') {
  19495. this.result = this.chunks.join('');
  19496. } else {
  19497. this.result = utils.flattenChunks(this.chunks);
  19498. }
  19499. }
  19500. this.chunks = [];
  19501. this.err = status;
  19502. this.msg = this.strm.msg;
  19503. };
  19504. /**
  19505. * deflate(data[, options]) -> Uint8Array|Array|String
  19506. * - data (Uint8Array|Array|String): input data to compress.
  19507. * - options (Object): zlib deflate options.
  19508. *
  19509. * Compress `data` with deflate alrorythm and `options`.
  19510. *
  19511. * Supported options are:
  19512. *
  19513. * - level
  19514. * - windowBits
  19515. * - memLevel
  19516. * - strategy
  19517. *
  19518. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19519. * for more information on these.
  19520. *
  19521. * Sugar (options):
  19522. *
  19523. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19524. * negative windowBits implicitly.
  19525. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19526. * (each char code [0..255])
  19527. *
  19528. * ##### Example:
  19529. *
  19530. * ```javascript
  19531. * var pako = require('pako')
  19532. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19533. *
  19534. * console.log(pako.deflate(data));
  19535. * ```
  19536. **/
  19537. function deflate(input, options) {
  19538. var deflator = new Deflate(options);
  19539. deflator.push(input, true);
  19540. // That will never happens, if you don't cheat with options :)
  19541. if (deflator.err) { throw deflator.msg; }
  19542. return deflator.result;
  19543. }
  19544. /**
  19545. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19546. * - data (Uint8Array|Array|String): input data to compress.
  19547. * - options (Object): zlib deflate options.
  19548. *
  19549. * The same as [[deflate]], but creates raw data, without wrapper
  19550. * (header and adler32 crc).
  19551. **/
  19552. function deflateRaw(input, options) {
  19553. options = options || {};
  19554. options.raw = true;
  19555. return deflate(input, options);
  19556. }
  19557. /**
  19558. * gzip(data[, options]) -> Uint8Array|Array|String
  19559. * - data (Uint8Array|Array|String): input data to compress.
  19560. * - options (Object): zlib deflate options.
  19561. *
  19562. * The same as [[deflate]], but create gzip wrapper instead of
  19563. * deflate one.
  19564. **/
  19565. function gzip(input, options) {
  19566. options = options || {};
  19567. options.gzip = true;
  19568. return deflate(input, options);
  19569. }
  19570. exports.Deflate = Deflate;
  19571. exports.deflate = deflate;
  19572. exports.deflateRaw = deflateRaw;
  19573. exports.gzip = gzip;
  19574. },{"./utils/common":72,"./utils/strings":73,"./zlib/deflate.js":77,"./zlib/messages":82,"./zlib/zstream":84}],71:[function(require,module,exports){
  19575. 'use strict';
  19576. var zlib_inflate = require('./zlib/inflate.js');
  19577. var utils = require('./utils/common');
  19578. var strings = require('./utils/strings');
  19579. var c = require('./zlib/constants');
  19580. var msg = require('./zlib/messages');
  19581. var zstream = require('./zlib/zstream');
  19582. var gzheader = require('./zlib/gzheader');
  19583. var toString = Object.prototype.toString;
  19584. /**
  19585. * class Inflate
  19586. *
  19587. * Generic JS-style wrapper for zlib calls. If you don't need
  19588. * streaming behaviour - use more simple functions: [[inflate]]
  19589. * and [[inflateRaw]].
  19590. **/
  19591. /* internal
  19592. * inflate.chunks -> Array
  19593. *
  19594. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19595. **/
  19596. /**
  19597. * Inflate.result -> Uint8Array|Array|String
  19598. *
  19599. * Uncompressed result, generated by default [[Inflate#onData]]
  19600. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19601. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19602. * push a chunk with explicit flush (call [[Inflate#push]] with
  19603. * `Z_SYNC_FLUSH` param).
  19604. **/
  19605. /**
  19606. * Inflate.err -> Number
  19607. *
  19608. * Error code after inflate finished. 0 (Z_OK) on success.
  19609. * Should be checked if broken data possible.
  19610. **/
  19611. /**
  19612. * Inflate.msg -> String
  19613. *
  19614. * Error message, if [[Inflate.err]] != 0
  19615. **/
  19616. /**
  19617. * new Inflate(options)
  19618. * - options (Object): zlib inflate options.
  19619. *
  19620. * Creates new inflator instance with specified params. Throws exception
  19621. * on bad params. Supported options:
  19622. *
  19623. * - `windowBits`
  19624. *
  19625. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19626. * for more information on these.
  19627. *
  19628. * Additional options, for internal needs:
  19629. *
  19630. * - `chunkSize` - size of generated data chunks (16K by default)
  19631. * - `raw` (Boolean) - do raw inflate
  19632. * - `to` (String) - if equal to 'string', then result will be converted
  19633. * from utf8 to utf16 (javascript) string. When string output requested,
  19634. * chunk length can differ from `chunkSize`, depending on content.
  19635. *
  19636. * By default, when no options set, autodetect deflate/gzip data format via
  19637. * wrapper header.
  19638. *
  19639. * ##### Example:
  19640. *
  19641. * ```javascript
  19642. * var pako = require('pako')
  19643. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19644. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19645. *
  19646. * var inflate = new pako.Inflate({ level: 3});
  19647. *
  19648. * inflate.push(chunk1, false);
  19649. * inflate.push(chunk2, true); // true -> last chunk
  19650. *
  19651. * if (inflate.err) { throw new Error(inflate.err); }
  19652. *
  19653. * console.log(inflate.result);
  19654. * ```
  19655. **/
  19656. var Inflate = function(options) {
  19657. this.options = utils.assign({
  19658. chunkSize: 16384,
  19659. windowBits: 0,
  19660. to: ''
  19661. }, options || {});
  19662. var opt = this.options;
  19663. // Force window size for `raw` data, if not set directly,
  19664. // because we have no header for autodetect.
  19665. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19666. opt.windowBits = -opt.windowBits;
  19667. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19668. }
  19669. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19670. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19671. !(options && options.windowBits)) {
  19672. opt.windowBits += 32;
  19673. }
  19674. // Gzip header has no info about windows size, we can do autodetect only
  19675. // for deflate. So, if window size not set, force it to max when gzip possible
  19676. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19677. // bit 3 (16) -> gzipped data
  19678. // bit 4 (32) -> autodetect gzip/deflate
  19679. if ((opt.windowBits & 15) === 0) {
  19680. opt.windowBits |= 15;
  19681. }
  19682. }
  19683. this.err = 0; // error code, if happens (0 = Z_OK)
  19684. this.msg = ''; // error message
  19685. this.ended = false; // used to avoid multiple onEnd() calls
  19686. this.chunks = []; // chunks of compressed data
  19687. this.strm = new zstream();
  19688. this.strm.avail_out = 0;
  19689. var status = zlib_inflate.inflateInit2(
  19690. this.strm,
  19691. opt.windowBits
  19692. );
  19693. if (status !== c.Z_OK) {
  19694. throw new Error(msg[status]);
  19695. }
  19696. this.header = new gzheader();
  19697. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19698. };
  19699. /**
  19700. * Inflate#push(data[, mode]) -> Boolean
  19701. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19702. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19703. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19704. *
  19705. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19706. * new output chunks. Returns `true` on success. The last data block must have
  19707. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19708. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19709. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  19710. *
  19711. * On fail call [[Inflate#onEnd]] with error code and return false.
  19712. *
  19713. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19714. * format is detected automatically). Also, don't skip last param and always
  19715. * use the same type in your code (boolean or number). That will improve JS speed.
  19716. *
  19717. * For regular `Array`-s make sure all elements are [0..255].
  19718. *
  19719. * ##### Example
  19720. *
  19721. * ```javascript
  19722. * push(chunk, false); // push one of data chunks
  19723. * ...
  19724. * push(chunk, true); // push last chunk
  19725. * ```
  19726. **/
  19727. Inflate.prototype.push = function(data, mode) {
  19728. var strm = this.strm;
  19729. var chunkSize = this.options.chunkSize;
  19730. var status, _mode;
  19731. var next_out_utf8, tail, utf8str;
  19732. if (this.ended) { return false; }
  19733. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19734. // Convert data if needed
  19735. if (typeof data === 'string') {
  19736. // Only binary strings can be decompressed on practice
  19737. strm.input = strings.binstring2buf(data);
  19738. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19739. strm.input = new Uint8Array(data);
  19740. } else {
  19741. strm.input = data;
  19742. }
  19743. strm.next_in = 0;
  19744. strm.avail_in = strm.input.length;
  19745. do {
  19746. if (strm.avail_out === 0) {
  19747. strm.output = new utils.Buf8(chunkSize);
  19748. strm.next_out = 0;
  19749. strm.avail_out = chunkSize;
  19750. }
  19751. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19752. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19753. this.onEnd(status);
  19754. this.ended = true;
  19755. return false;
  19756. }
  19757. if (strm.next_out) {
  19758. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  19759. if (this.options.to === 'string') {
  19760. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19761. tail = strm.next_out - next_out_utf8;
  19762. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19763. // move tail
  19764. strm.next_out = tail;
  19765. strm.avail_out = chunkSize - tail;
  19766. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19767. this.onData(utf8str);
  19768. } else {
  19769. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19770. }
  19771. }
  19772. }
  19773. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19774. if (status === c.Z_STREAM_END) {
  19775. _mode = c.Z_FINISH;
  19776. }
  19777. // Finalize on the last chunk.
  19778. if (_mode === c.Z_FINISH) {
  19779. status = zlib_inflate.inflateEnd(this.strm);
  19780. this.onEnd(status);
  19781. this.ended = true;
  19782. return status === c.Z_OK;
  19783. }
  19784. // callback interim results if Z_SYNC_FLUSH.
  19785. if (_mode === c.Z_SYNC_FLUSH) {
  19786. this.onEnd(c.Z_OK);
  19787. strm.avail_out = 0;
  19788. return true;
  19789. }
  19790. return true;
  19791. };
  19792. /**
  19793. * Inflate#onData(chunk) -> Void
  19794. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19795. * on js engine support. When string output requested, each chunk
  19796. * will be string.
  19797. *
  19798. * By default, stores data blocks in `chunks[]` property and glue
  19799. * those in `onEnd`. Override this handler, if you need another behaviour.
  19800. **/
  19801. Inflate.prototype.onData = function(chunk) {
  19802. this.chunks.push(chunk);
  19803. };
  19804. /**
  19805. * Inflate#onEnd(status) -> Void
  19806. * - status (Number): inflate status. 0 (Z_OK) on success,
  19807. * other if not.
  19808. *
  19809. * Called either after you tell inflate that the input stream is
  19810. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19811. * or if an error happened. By default - join collected chunks,
  19812. * free memory and fill `results` / `err` properties.
  19813. **/
  19814. Inflate.prototype.onEnd = function(status) {
  19815. // On success - join
  19816. if (status === c.Z_OK) {
  19817. if (this.options.to === 'string') {
  19818. // Glue & convert here, until we teach pako to send
  19819. // utf8 alligned strings to onData
  19820. this.result = this.chunks.join('');
  19821. } else {
  19822. this.result = utils.flattenChunks(this.chunks);
  19823. }
  19824. }
  19825. this.chunks = [];
  19826. this.err = status;
  19827. this.msg = this.strm.msg;
  19828. };
  19829. /**
  19830. * inflate(data[, options]) -> Uint8Array|Array|String
  19831. * - data (Uint8Array|Array|String): input data to decompress.
  19832. * - options (Object): zlib inflate options.
  19833. *
  19834. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19835. * format via wrapper header by default. That's why we don't provide
  19836. * separate `ungzip` method.
  19837. *
  19838. * Supported options are:
  19839. *
  19840. * - windowBits
  19841. *
  19842. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19843. * for more information.
  19844. *
  19845. * Sugar (options):
  19846. *
  19847. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19848. * negative windowBits implicitly.
  19849. * - `to` (String) - if equal to 'string', then result will be converted
  19850. * from utf8 to utf16 (javascript) string. When string output requested,
  19851. * chunk length can differ from `chunkSize`, depending on content.
  19852. *
  19853. *
  19854. * ##### Example:
  19855. *
  19856. * ```javascript
  19857. * var pako = require('pako')
  19858. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19859. * , output;
  19860. *
  19861. * try {
  19862. * output = pako.inflate(input);
  19863. * } catch (err)
  19864. * console.log(err);
  19865. * }
  19866. * ```
  19867. **/
  19868. function inflate(input, options) {
  19869. var inflator = new Inflate(options);
  19870. inflator.push(input, true);
  19871. // That will never happens, if you don't cheat with options :)
  19872. if (inflator.err) { throw inflator.msg; }
  19873. return inflator.result;
  19874. }
  19875. /**
  19876. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19877. * - data (Uint8Array|Array|String): input data to decompress.
  19878. * - options (Object): zlib inflate options.
  19879. *
  19880. * The same as [[inflate]], but creates raw data, without wrapper
  19881. * (header and adler32 crc).
  19882. **/
  19883. function inflateRaw(input, options) {
  19884. options = options || {};
  19885. options.raw = true;
  19886. return inflate(input, options);
  19887. }
  19888. /**
  19889. * ungzip(data[, options]) -> Uint8Array|Array|String
  19890. * - data (Uint8Array|Array|String): input data to decompress.
  19891. * - options (Object): zlib inflate options.
  19892. *
  19893. * Just shortcut to [[inflate]], because it autodetects format
  19894. * by header.content. Done for convenience.
  19895. **/
  19896. exports.Inflate = Inflate;
  19897. exports.inflate = inflate;
  19898. exports.inflateRaw = inflateRaw;
  19899. exports.ungzip = inflate;
  19900. },{"./utils/common":72,"./utils/strings":73,"./zlib/constants":75,"./zlib/gzheader":78,"./zlib/inflate.js":80,"./zlib/messages":82,"./zlib/zstream":84}],72:[function(require,module,exports){
  19901. 'use strict';
  19902. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19903. (typeof Uint16Array !== 'undefined') &&
  19904. (typeof Int32Array !== 'undefined');
  19905. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19906. var sources = Array.prototype.slice.call(arguments, 1);
  19907. while (sources.length) {
  19908. var source = sources.shift();
  19909. if (!source) { continue; }
  19910. if (typeof source !== 'object') {
  19911. throw new TypeError(source + 'must be non-object');
  19912. }
  19913. for (var p in source) {
  19914. if (source.hasOwnProperty(p)) {
  19915. obj[p] = source[p];
  19916. }
  19917. }
  19918. }
  19919. return obj;
  19920. };
  19921. // reduce buffer size, avoiding mem copy
  19922. exports.shrinkBuf = function (buf, size) {
  19923. if (buf.length === size) { return buf; }
  19924. if (buf.subarray) { return buf.subarray(0, size); }
  19925. buf.length = size;
  19926. return buf;
  19927. };
  19928. var fnTyped = {
  19929. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19930. if (src.subarray && dest.subarray) {
  19931. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19932. return;
  19933. }
  19934. // Fallback to ordinary array
  19935. for (var i=0; i<len; i++) {
  19936. dest[dest_offs + i] = src[src_offs + i];
  19937. }
  19938. },
  19939. // Join array of chunks to single array.
  19940. flattenChunks: function(chunks) {
  19941. var i, l, len, pos, chunk, result;
  19942. // calculate data length
  19943. len = 0;
  19944. for (i=0, l=chunks.length; i<l; i++) {
  19945. len += chunks[i].length;
  19946. }
  19947. // join chunks
  19948. result = new Uint8Array(len);
  19949. pos = 0;
  19950. for (i=0, l=chunks.length; i<l; i++) {
  19951. chunk = chunks[i];
  19952. result.set(chunk, pos);
  19953. pos += chunk.length;
  19954. }
  19955. return result;
  19956. }
  19957. };
  19958. var fnUntyped = {
  19959. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19960. for (var i=0; i<len; i++) {
  19961. dest[dest_offs + i] = src[src_offs + i];
  19962. }
  19963. },
  19964. // Join array of chunks to single array.
  19965. flattenChunks: function(chunks) {
  19966. return [].concat.apply([], chunks);
  19967. }
  19968. };
  19969. // Enable/Disable typed arrays use, for testing
  19970. //
  19971. exports.setTyped = function (on) {
  19972. if (on) {
  19973. exports.Buf8 = Uint8Array;
  19974. exports.Buf16 = Uint16Array;
  19975. exports.Buf32 = Int32Array;
  19976. exports.assign(exports, fnTyped);
  19977. } else {
  19978. exports.Buf8 = Array;
  19979. exports.Buf16 = Array;
  19980. exports.Buf32 = Array;
  19981. exports.assign(exports, fnUntyped);
  19982. }
  19983. };
  19984. exports.setTyped(TYPED_OK);
  19985. },{}],73:[function(require,module,exports){
  19986. // String encode/decode helpers
  19987. 'use strict';
  19988. var utils = require('./common');
  19989. // Quick check if we can use fast array to bin string conversion
  19990. //
  19991. // - apply(Array) can fail on Android 2.2
  19992. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19993. //
  19994. var STR_APPLY_OK = true;
  19995. var STR_APPLY_UIA_OK = true;
  19996. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19997. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  19998. // Table with utf8 lengths (calculated by first byte of sequence)
  19999. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20000. // because max possible codepoint is 0x10ffff
  20001. var _utf8len = new utils.Buf8(256);
  20002. for (var q=0; q<256; q++) {
  20003. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20004. }
  20005. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20006. // convert string to array (typed, when possible)
  20007. exports.string2buf = function (str) {
  20008. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20009. // count binary size
  20010. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20011. c = str.charCodeAt(m_pos);
  20012. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20013. c2 = str.charCodeAt(m_pos+1);
  20014. if ((c2 & 0xfc00) === 0xdc00) {
  20015. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20016. m_pos++;
  20017. }
  20018. }
  20019. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20020. }
  20021. // allocate buffer
  20022. buf = new utils.Buf8(buf_len);
  20023. // convert
  20024. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20025. c = str.charCodeAt(m_pos);
  20026. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20027. c2 = str.charCodeAt(m_pos+1);
  20028. if ((c2 & 0xfc00) === 0xdc00) {
  20029. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20030. m_pos++;
  20031. }
  20032. }
  20033. if (c < 0x80) {
  20034. /* one byte */
  20035. buf[i++] = c;
  20036. } else if (c < 0x800) {
  20037. /* two bytes */
  20038. buf[i++] = 0xC0 | (c >>> 6);
  20039. buf[i++] = 0x80 | (c & 0x3f);
  20040. } else if (c < 0x10000) {
  20041. /* three bytes */
  20042. buf[i++] = 0xE0 | (c >>> 12);
  20043. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20044. buf[i++] = 0x80 | (c & 0x3f);
  20045. } else {
  20046. /* four bytes */
  20047. buf[i++] = 0xf0 | (c >>> 18);
  20048. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20049. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20050. buf[i++] = 0x80 | (c & 0x3f);
  20051. }
  20052. }
  20053. return buf;
  20054. };
  20055. // Helper (used in 2 places)
  20056. function buf2binstring(buf, len) {
  20057. // use fallback for big arrays to avoid stack overflow
  20058. if (len < 65537) {
  20059. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20060. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20061. }
  20062. }
  20063. var result = '';
  20064. for (var i=0; i < len; i++) {
  20065. result += String.fromCharCode(buf[i]);
  20066. }
  20067. return result;
  20068. }
  20069. // Convert byte array to binary string
  20070. exports.buf2binstring = function(buf) {
  20071. return buf2binstring(buf, buf.length);
  20072. };
  20073. // Convert binary string (typed, when possible)
  20074. exports.binstring2buf = function(str) {
  20075. var buf = new utils.Buf8(str.length);
  20076. for (var i=0, len=buf.length; i < len; i++) {
  20077. buf[i] = str.charCodeAt(i);
  20078. }
  20079. return buf;
  20080. };
  20081. // convert array to string
  20082. exports.buf2string = function (buf, max) {
  20083. var i, out, c, c_len;
  20084. var len = max || buf.length;
  20085. // Reserve max possible length (2 words per char)
  20086. // NB: by unknown reasons, Array is significantly faster for
  20087. // String.fromCharCode.apply than Uint16Array.
  20088. var utf16buf = new Array(len*2);
  20089. for (out=0, i=0; i<len;) {
  20090. c = buf[i++];
  20091. // quick process ascii
  20092. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20093. c_len = _utf8len[c];
  20094. // skip 5 & 6 byte codes
  20095. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20096. // apply mask on first byte
  20097. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20098. // join the rest
  20099. while (c_len > 1 && i < len) {
  20100. c = (c << 6) | (buf[i++] & 0x3f);
  20101. c_len--;
  20102. }
  20103. // terminated by end of string?
  20104. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20105. if (c < 0x10000) {
  20106. utf16buf[out++] = c;
  20107. } else {
  20108. c -= 0x10000;
  20109. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20110. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20111. }
  20112. }
  20113. return buf2binstring(utf16buf, out);
  20114. };
  20115. // Calculate max possible position in utf8 buffer,
  20116. // that will not break sequence. If that's not possible
  20117. // - (very small limits) return max size as is.
  20118. //
  20119. // buf[] - utf8 bytes array
  20120. // max - length limit (mandatory);
  20121. exports.utf8border = function(buf, max) {
  20122. var pos;
  20123. max = max || buf.length;
  20124. if (max > buf.length) { max = buf.length; }
  20125. // go back from last position, until start of sequence found
  20126. pos = max-1;
  20127. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20128. // Fuckup - very small and broken sequence,
  20129. // return max, because we should return something anyway.
  20130. if (pos < 0) { return max; }
  20131. // If we came to start of buffer - that means vuffer is too small,
  20132. // return max too.
  20133. if (pos === 0) { return max; }
  20134. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20135. };
  20136. },{"./common":72}],74:[function(require,module,exports){
  20137. 'use strict';
  20138. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20139. // It doesn't worth to make additional optimizationa as in original.
  20140. // Small size is preferable.
  20141. function adler32(adler, buf, len, pos) {
  20142. var s1 = (adler & 0xffff) |0,
  20143. s2 = ((adler >>> 16) & 0xffff) |0,
  20144. n = 0;
  20145. while (len !== 0) {
  20146. // Set limit ~ twice less than 5552, to keep
  20147. // s2 in 31-bits, because we force signed ints.
  20148. // in other case %= will fail.
  20149. n = len > 2000 ? 2000 : len;
  20150. len -= n;
  20151. do {
  20152. s1 = (s1 + buf[pos++]) |0;
  20153. s2 = (s2 + s1) |0;
  20154. } while (--n);
  20155. s1 %= 65521;
  20156. s2 %= 65521;
  20157. }
  20158. return (s1 | (s2 << 16)) |0;
  20159. }
  20160. module.exports = adler32;
  20161. },{}],75:[function(require,module,exports){
  20162. module.exports = {
  20163. /* Allowed flush values; see deflate() and inflate() below for details */
  20164. Z_NO_FLUSH: 0,
  20165. Z_PARTIAL_FLUSH: 1,
  20166. Z_SYNC_FLUSH: 2,
  20167. Z_FULL_FLUSH: 3,
  20168. Z_FINISH: 4,
  20169. Z_BLOCK: 5,
  20170. Z_TREES: 6,
  20171. /* Return codes for the compression/decompression functions. Negative values
  20172. * are errors, positive values are used for special but normal events.
  20173. */
  20174. Z_OK: 0,
  20175. Z_STREAM_END: 1,
  20176. Z_NEED_DICT: 2,
  20177. Z_ERRNO: -1,
  20178. Z_STREAM_ERROR: -2,
  20179. Z_DATA_ERROR: -3,
  20180. //Z_MEM_ERROR: -4,
  20181. Z_BUF_ERROR: -5,
  20182. //Z_VERSION_ERROR: -6,
  20183. /* compression levels */
  20184. Z_NO_COMPRESSION: 0,
  20185. Z_BEST_SPEED: 1,
  20186. Z_BEST_COMPRESSION: 9,
  20187. Z_DEFAULT_COMPRESSION: -1,
  20188. Z_FILTERED: 1,
  20189. Z_HUFFMAN_ONLY: 2,
  20190. Z_RLE: 3,
  20191. Z_FIXED: 4,
  20192. Z_DEFAULT_STRATEGY: 0,
  20193. /* Possible values of the data_type field (though see inflate()) */
  20194. Z_BINARY: 0,
  20195. Z_TEXT: 1,
  20196. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20197. Z_UNKNOWN: 2,
  20198. /* The deflate compression method */
  20199. Z_DEFLATED: 8
  20200. //Z_NULL: null // Use -1 or null inline, depending on var type
  20201. };
  20202. },{}],76:[function(require,module,exports){
  20203. 'use strict';
  20204. // Note: we can't get significant speed boost here.
  20205. // So write code to minimize size - no pregenerated tables
  20206. // and array tools dependencies.
  20207. // Use ordinary array, since untyped makes no boost here
  20208. function makeTable() {
  20209. var c, table = [];
  20210. for (var n =0; n < 256; n++) {
  20211. c = n;
  20212. for (var k =0; k < 8; k++) {
  20213. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20214. }
  20215. table[n] = c;
  20216. }
  20217. return table;
  20218. }
  20219. // Create table on load. Just 255 signed longs. Not a problem.
  20220. var crcTable = makeTable();
  20221. function crc32(crc, buf, len, pos) {
  20222. var t = crcTable,
  20223. end = pos + len;
  20224. crc = crc ^ (-1);
  20225. for (var i = pos; i < end; i++) {
  20226. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20227. }
  20228. return (crc ^ (-1)); // >>> 0;
  20229. }
  20230. module.exports = crc32;
  20231. },{}],77:[function(require,module,exports){
  20232. 'use strict';
  20233. var utils = require('../utils/common');
  20234. var trees = require('./trees');
  20235. var adler32 = require('./adler32');
  20236. var crc32 = require('./crc32');
  20237. var msg = require('./messages');
  20238. /* Public constants ==========================================================*/
  20239. /* ===========================================================================*/
  20240. /* Allowed flush values; see deflate() and inflate() below for details */
  20241. var Z_NO_FLUSH = 0;
  20242. var Z_PARTIAL_FLUSH = 1;
  20243. //var Z_SYNC_FLUSH = 2;
  20244. var Z_FULL_FLUSH = 3;
  20245. var Z_FINISH = 4;
  20246. var Z_BLOCK = 5;
  20247. //var Z_TREES = 6;
  20248. /* Return codes for the compression/decompression functions. Negative values
  20249. * are errors, positive values are used for special but normal events.
  20250. */
  20251. var Z_OK = 0;
  20252. var Z_STREAM_END = 1;
  20253. //var Z_NEED_DICT = 2;
  20254. //var Z_ERRNO = -1;
  20255. var Z_STREAM_ERROR = -2;
  20256. var Z_DATA_ERROR = -3;
  20257. //var Z_MEM_ERROR = -4;
  20258. var Z_BUF_ERROR = -5;
  20259. //var Z_VERSION_ERROR = -6;
  20260. /* compression levels */
  20261. //var Z_NO_COMPRESSION = 0;
  20262. //var Z_BEST_SPEED = 1;
  20263. //var Z_BEST_COMPRESSION = 9;
  20264. var Z_DEFAULT_COMPRESSION = -1;
  20265. var Z_FILTERED = 1;
  20266. var Z_HUFFMAN_ONLY = 2;
  20267. var Z_RLE = 3;
  20268. var Z_FIXED = 4;
  20269. var Z_DEFAULT_STRATEGY = 0;
  20270. /* Possible values of the data_type field (though see inflate()) */
  20271. //var Z_BINARY = 0;
  20272. //var Z_TEXT = 1;
  20273. //var Z_ASCII = 1; // = Z_TEXT
  20274. var Z_UNKNOWN = 2;
  20275. /* The deflate compression method */
  20276. var Z_DEFLATED = 8;
  20277. /*============================================================================*/
  20278. var MAX_MEM_LEVEL = 9;
  20279. /* Maximum value for memLevel in deflateInit2 */
  20280. var MAX_WBITS = 15;
  20281. /* 32K LZ77 window */
  20282. var DEF_MEM_LEVEL = 8;
  20283. var LENGTH_CODES = 29;
  20284. /* number of length codes, not counting the special END_BLOCK code */
  20285. var LITERALS = 256;
  20286. /* number of literal bytes 0..255 */
  20287. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20288. /* number of Literal or Length codes, including the END_BLOCK code */
  20289. var D_CODES = 30;
  20290. /* number of distance codes */
  20291. var BL_CODES = 19;
  20292. /* number of codes used to transfer the bit lengths */
  20293. var HEAP_SIZE = 2*L_CODES + 1;
  20294. /* maximum heap size */
  20295. var MAX_BITS = 15;
  20296. /* All codes must not exceed MAX_BITS bits */
  20297. var MIN_MATCH = 3;
  20298. var MAX_MATCH = 258;
  20299. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20300. var PRESET_DICT = 0x20;
  20301. var INIT_STATE = 42;
  20302. var EXTRA_STATE = 69;
  20303. var NAME_STATE = 73;
  20304. var COMMENT_STATE = 91;
  20305. var HCRC_STATE = 103;
  20306. var BUSY_STATE = 113;
  20307. var FINISH_STATE = 666;
  20308. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20309. var BS_BLOCK_DONE = 2; /* block flush performed */
  20310. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20311. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20312. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20313. function err(strm, errorCode) {
  20314. strm.msg = msg[errorCode];
  20315. return errorCode;
  20316. }
  20317. function rank(f) {
  20318. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20319. }
  20320. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20321. /* =========================================================================
  20322. * Flush as much pending output as possible. All deflate() output goes
  20323. * through this function so some applications may wish to modify it
  20324. * to avoid allocating a large strm->output buffer and copying into it.
  20325. * (See also read_buf()).
  20326. */
  20327. function flush_pending(strm) {
  20328. var s = strm.state;
  20329. //_tr_flush_bits(s);
  20330. var len = s.pending;
  20331. if (len > strm.avail_out) {
  20332. len = strm.avail_out;
  20333. }
  20334. if (len === 0) { return; }
  20335. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20336. strm.next_out += len;
  20337. s.pending_out += len;
  20338. strm.total_out += len;
  20339. strm.avail_out -= len;
  20340. s.pending -= len;
  20341. if (s.pending === 0) {
  20342. s.pending_out = 0;
  20343. }
  20344. }
  20345. function flush_block_only (s, last) {
  20346. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20347. s.block_start = s.strstart;
  20348. flush_pending(s.strm);
  20349. }
  20350. function put_byte(s, b) {
  20351. s.pending_buf[s.pending++] = b;
  20352. }
  20353. /* =========================================================================
  20354. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20355. * IN assertion: the stream state is correct and there is enough room in
  20356. * pending_buf.
  20357. */
  20358. function putShortMSB(s, b) {
  20359. // put_byte(s, (Byte)(b >> 8));
  20360. // put_byte(s, (Byte)(b & 0xff));
  20361. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20362. s.pending_buf[s.pending++] = b & 0xff;
  20363. }
  20364. /* ===========================================================================
  20365. * Read a new buffer from the current input stream, update the adler32
  20366. * and total number of bytes read. All deflate() input goes through
  20367. * this function so some applications may wish to modify it to avoid
  20368. * allocating a large strm->input buffer and copying from it.
  20369. * (See also flush_pending()).
  20370. */
  20371. function read_buf(strm, buf, start, size) {
  20372. var len = strm.avail_in;
  20373. if (len > size) { len = size; }
  20374. if (len === 0) { return 0; }
  20375. strm.avail_in -= len;
  20376. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20377. if (strm.state.wrap === 1) {
  20378. strm.adler = adler32(strm.adler, buf, len, start);
  20379. }
  20380. else if (strm.state.wrap === 2) {
  20381. strm.adler = crc32(strm.adler, buf, len, start);
  20382. }
  20383. strm.next_in += len;
  20384. strm.total_in += len;
  20385. return len;
  20386. }
  20387. /* ===========================================================================
  20388. * Set match_start to the longest match starting at the given string and
  20389. * return its length. Matches shorter or equal to prev_length are discarded,
  20390. * in which case the result is equal to prev_length and match_start is
  20391. * garbage.
  20392. * IN assertions: cur_match is the head of the hash chain for the current
  20393. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20394. * OUT assertion: the match length is not greater than s->lookahead.
  20395. */
  20396. function longest_match(s, cur_match) {
  20397. var chain_length = s.max_chain_length; /* max hash chain length */
  20398. var scan = s.strstart; /* current string */
  20399. var match; /* matched string */
  20400. var len; /* length of current match */
  20401. var best_len = s.prev_length; /* best match length so far */
  20402. var nice_match = s.nice_match; /* stop if match long enough */
  20403. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20404. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20405. var _win = s.window; // shortcut
  20406. var wmask = s.w_mask;
  20407. var prev = s.prev;
  20408. /* Stop when cur_match becomes <= limit. To simplify the code,
  20409. * we prevent matches with the string of window index 0.
  20410. */
  20411. var strend = s.strstart + MAX_MATCH;
  20412. var scan_end1 = _win[scan + best_len - 1];
  20413. var scan_end = _win[scan + best_len];
  20414. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20415. * It is easy to get rid of this optimization if necessary.
  20416. */
  20417. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20418. /* Do not waste too much time if we already have a good match: */
  20419. if (s.prev_length >= s.good_match) {
  20420. chain_length >>= 2;
  20421. }
  20422. /* Do not look for matches beyond the end of the input. This is necessary
  20423. * to make deflate deterministic.
  20424. */
  20425. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20426. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20427. do {
  20428. // Assert(cur_match < s->strstart, "no future");
  20429. match = cur_match;
  20430. /* Skip to next match if the match length cannot increase
  20431. * or if the match length is less than 2. Note that the checks below
  20432. * for insufficient lookahead only occur occasionally for performance
  20433. * reasons. Therefore uninitialized memory will be accessed, and
  20434. * conditional jumps will be made that depend on those values.
  20435. * However the length of the match is limited to the lookahead, so
  20436. * the output of deflate is not affected by the uninitialized values.
  20437. */
  20438. if (_win[match + best_len] !== scan_end ||
  20439. _win[match + best_len - 1] !== scan_end1 ||
  20440. _win[match] !== _win[scan] ||
  20441. _win[++match] !== _win[scan + 1]) {
  20442. continue;
  20443. }
  20444. /* The check at best_len-1 can be removed because it will be made
  20445. * again later. (This heuristic is not always a win.)
  20446. * It is not necessary to compare scan[2] and match[2] since they
  20447. * are always equal when the other bytes match, given that
  20448. * the hash keys are equal and that HASH_BITS >= 8.
  20449. */
  20450. scan += 2;
  20451. match++;
  20452. // Assert(*scan == *match, "match[2]?");
  20453. /* We check for insufficient lookahead only every 8th comparison;
  20454. * the 256th check will be made at strstart+258.
  20455. */
  20456. do {
  20457. /*jshint noempty:false*/
  20458. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20459. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20460. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20461. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20462. scan < strend);
  20463. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20464. len = MAX_MATCH - (strend - scan);
  20465. scan = strend - MAX_MATCH;
  20466. if (len > best_len) {
  20467. s.match_start = cur_match;
  20468. best_len = len;
  20469. if (len >= nice_match) {
  20470. break;
  20471. }
  20472. scan_end1 = _win[scan + best_len - 1];
  20473. scan_end = _win[scan + best_len];
  20474. }
  20475. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20476. if (best_len <= s.lookahead) {
  20477. return best_len;
  20478. }
  20479. return s.lookahead;
  20480. }
  20481. /* ===========================================================================
  20482. * Fill the window when the lookahead becomes insufficient.
  20483. * Updates strstart and lookahead.
  20484. *
  20485. * IN assertion: lookahead < MIN_LOOKAHEAD
  20486. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20487. * At least one byte has been read, or avail_in == 0; reads are
  20488. * performed for at least two bytes (required for the zip translate_eol
  20489. * option -- not supported here).
  20490. */
  20491. function fill_window(s) {
  20492. var _w_size = s.w_size;
  20493. var p, n, m, more, str;
  20494. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20495. do {
  20496. more = s.window_size - s.lookahead - s.strstart;
  20497. // JS ints have 32 bit, block below not needed
  20498. /* Deal with !@#$% 64K limit: */
  20499. //if (sizeof(int) <= 2) {
  20500. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20501. // more = wsize;
  20502. //
  20503. // } else if (more == (unsigned)(-1)) {
  20504. // /* Very unlikely, but possible on 16 bit machine if
  20505. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20506. // */
  20507. // more--;
  20508. // }
  20509. //}
  20510. /* If the window is almost full and there is insufficient lookahead,
  20511. * move the upper half to the lower one to make room in the upper half.
  20512. */
  20513. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20514. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20515. s.match_start -= _w_size;
  20516. s.strstart -= _w_size;
  20517. /* we now have strstart >= MAX_DIST */
  20518. s.block_start -= _w_size;
  20519. /* Slide the hash table (could be avoided with 32 bit values
  20520. at the expense of memory usage). We slide even when level == 0
  20521. to keep the hash table consistent if we switch back to level > 0
  20522. later. (Using level 0 permanently is not an optimal usage of
  20523. zlib, so we don't care about this pathological case.)
  20524. */
  20525. n = s.hash_size;
  20526. p = n;
  20527. do {
  20528. m = s.head[--p];
  20529. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20530. } while (--n);
  20531. n = _w_size;
  20532. p = n;
  20533. do {
  20534. m = s.prev[--p];
  20535. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20536. /* If n is not on any hash chain, prev[n] is garbage but
  20537. * its value will never be used.
  20538. */
  20539. } while (--n);
  20540. more += _w_size;
  20541. }
  20542. if (s.strm.avail_in === 0) {
  20543. break;
  20544. }
  20545. /* If there was no sliding:
  20546. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20547. * more == window_size - lookahead - strstart
  20548. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20549. * => more >= window_size - 2*WSIZE + 2
  20550. * In the BIG_MEM or MMAP case (not yet supported),
  20551. * window_size == input_size + MIN_LOOKAHEAD &&
  20552. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20553. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20554. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20555. */
  20556. //Assert(more >= 2, "more < 2");
  20557. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20558. s.lookahead += n;
  20559. /* Initialize the hash value now that we have some input: */
  20560. if (s.lookahead + s.insert >= MIN_MATCH) {
  20561. str = s.strstart - s.insert;
  20562. s.ins_h = s.window[str];
  20563. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20564. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20565. //#if MIN_MATCH != 3
  20566. // Call update_hash() MIN_MATCH-3 more times
  20567. //#endif
  20568. while (s.insert) {
  20569. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20570. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20571. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20572. s.head[s.ins_h] = str;
  20573. str++;
  20574. s.insert--;
  20575. if (s.lookahead + s.insert < MIN_MATCH) {
  20576. break;
  20577. }
  20578. }
  20579. }
  20580. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20581. * but this is not important since only literal bytes will be emitted.
  20582. */
  20583. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20584. /* If the WIN_INIT bytes after the end of the current data have never been
  20585. * written, then zero those bytes in order to avoid memory check reports of
  20586. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20587. * the longest match routines. Update the high water mark for the next
  20588. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20589. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20590. */
  20591. // if (s.high_water < s.window_size) {
  20592. // var curr = s.strstart + s.lookahead;
  20593. // var init = 0;
  20594. //
  20595. // if (s.high_water < curr) {
  20596. // /* Previous high water mark below current data -- zero WIN_INIT
  20597. // * bytes or up to end of window, whichever is less.
  20598. // */
  20599. // init = s.window_size - curr;
  20600. // if (init > WIN_INIT)
  20601. // init = WIN_INIT;
  20602. // zmemzero(s->window + curr, (unsigned)init);
  20603. // s->high_water = curr + init;
  20604. // }
  20605. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20606. // /* High water mark at or above current data, but below current data
  20607. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20608. // * to end of window, whichever is less.
  20609. // */
  20610. // init = (ulg)curr + WIN_INIT - s->high_water;
  20611. // if (init > s->window_size - s->high_water)
  20612. // init = s->window_size - s->high_water;
  20613. // zmemzero(s->window + s->high_water, (unsigned)init);
  20614. // s->high_water += init;
  20615. // }
  20616. // }
  20617. //
  20618. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20619. // "not enough room for search");
  20620. }
  20621. /* ===========================================================================
  20622. * Copy without compression as much as possible from the input stream, return
  20623. * the current block state.
  20624. * This function does not insert new strings in the dictionary since
  20625. * uncompressible data is probably not useful. This function is used
  20626. * only for the level=0 compression option.
  20627. * NOTE: this function should be optimized to avoid extra copying from
  20628. * window to pending_buf.
  20629. */
  20630. function deflate_stored(s, flush) {
  20631. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20632. * to pending_buf_size, and each stored block has a 5 byte header:
  20633. */
  20634. var max_block_size = 0xffff;
  20635. if (max_block_size > s.pending_buf_size - 5) {
  20636. max_block_size = s.pending_buf_size - 5;
  20637. }
  20638. /* Copy as much as possible from input to output: */
  20639. for (;;) {
  20640. /* Fill the window as much as possible: */
  20641. if (s.lookahead <= 1) {
  20642. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20643. // s->block_start >= (long)s->w_size, "slide too late");
  20644. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20645. // s.block_start >= s.w_size)) {
  20646. // throw new Error("slide too late");
  20647. // }
  20648. fill_window(s);
  20649. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20650. return BS_NEED_MORE;
  20651. }
  20652. if (s.lookahead === 0) {
  20653. break;
  20654. }
  20655. /* flush the current block */
  20656. }
  20657. //Assert(s->block_start >= 0L, "block gone");
  20658. // if (s.block_start < 0) throw new Error("block gone");
  20659. s.strstart += s.lookahead;
  20660. s.lookahead = 0;
  20661. /* Emit a stored block if pending_buf will be full: */
  20662. var max_start = s.block_start + max_block_size;
  20663. if (s.strstart === 0 || s.strstart >= max_start) {
  20664. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20665. s.lookahead = s.strstart - max_start;
  20666. s.strstart = max_start;
  20667. /*** FLUSH_BLOCK(s, 0); ***/
  20668. flush_block_only(s, false);
  20669. if (s.strm.avail_out === 0) {
  20670. return BS_NEED_MORE;
  20671. }
  20672. /***/
  20673. }
  20674. /* Flush if we may have to slide, otherwise block_start may become
  20675. * negative and the data will be gone:
  20676. */
  20677. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20678. /*** FLUSH_BLOCK(s, 0); ***/
  20679. flush_block_only(s, false);
  20680. if (s.strm.avail_out === 0) {
  20681. return BS_NEED_MORE;
  20682. }
  20683. /***/
  20684. }
  20685. }
  20686. s.insert = 0;
  20687. if (flush === Z_FINISH) {
  20688. /*** FLUSH_BLOCK(s, 1); ***/
  20689. flush_block_only(s, true);
  20690. if (s.strm.avail_out === 0) {
  20691. return BS_FINISH_STARTED;
  20692. }
  20693. /***/
  20694. return BS_FINISH_DONE;
  20695. }
  20696. if (s.strstart > s.block_start) {
  20697. /*** FLUSH_BLOCK(s, 0); ***/
  20698. flush_block_only(s, false);
  20699. if (s.strm.avail_out === 0) {
  20700. return BS_NEED_MORE;
  20701. }
  20702. /***/
  20703. }
  20704. return BS_NEED_MORE;
  20705. }
  20706. /* ===========================================================================
  20707. * Compress as much as possible from the input stream, return the current
  20708. * block state.
  20709. * This function does not perform lazy evaluation of matches and inserts
  20710. * new strings in the dictionary only for unmatched strings or for short
  20711. * matches. It is used only for the fast compression options.
  20712. */
  20713. function deflate_fast(s, flush) {
  20714. var hash_head; /* head of the hash chain */
  20715. var bflush; /* set if current block must be flushed */
  20716. for (;;) {
  20717. /* Make sure that we always have enough lookahead, except
  20718. * at the end of the input file. We need MAX_MATCH bytes
  20719. * for the next match, plus MIN_MATCH bytes to insert the
  20720. * string following the next match.
  20721. */
  20722. if (s.lookahead < MIN_LOOKAHEAD) {
  20723. fill_window(s);
  20724. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20725. return BS_NEED_MORE;
  20726. }
  20727. if (s.lookahead === 0) {
  20728. break; /* flush the current block */
  20729. }
  20730. }
  20731. /* Insert the string window[strstart .. strstart+2] in the
  20732. * dictionary, and set hash_head to the head of the hash chain:
  20733. */
  20734. hash_head = 0/*NIL*/;
  20735. if (s.lookahead >= MIN_MATCH) {
  20736. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20737. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20738. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20739. s.head[s.ins_h] = s.strstart;
  20740. /***/
  20741. }
  20742. /* Find the longest match, discarding those <= prev_length.
  20743. * At this point we have always match_length < MIN_MATCH
  20744. */
  20745. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20746. /* To simplify the code, we prevent matches with the string
  20747. * of window index 0 (in particular we have to avoid a match
  20748. * of the string with itself at the start of the input file).
  20749. */
  20750. s.match_length = longest_match(s, hash_head);
  20751. /* longest_match() sets match_start */
  20752. }
  20753. if (s.match_length >= MIN_MATCH) {
  20754. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20755. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20756. s.match_length - MIN_MATCH, bflush); ***/
  20757. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20758. s.lookahead -= s.match_length;
  20759. /* Insert new strings in the hash table only if the match length
  20760. * is not too large. This saves time but degrades compression.
  20761. */
  20762. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20763. s.match_length--; /* string at strstart already in table */
  20764. do {
  20765. s.strstart++;
  20766. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20767. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20768. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20769. s.head[s.ins_h] = s.strstart;
  20770. /***/
  20771. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20772. * always MIN_MATCH bytes ahead.
  20773. */
  20774. } while (--s.match_length !== 0);
  20775. s.strstart++;
  20776. } else
  20777. {
  20778. s.strstart += s.match_length;
  20779. s.match_length = 0;
  20780. s.ins_h = s.window[s.strstart];
  20781. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20782. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20783. //#if MIN_MATCH != 3
  20784. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20785. //#endif
  20786. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20787. * matter since it will be recomputed at next deflate call.
  20788. */
  20789. }
  20790. } else {
  20791. /* No match, output a literal byte */
  20792. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20793. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20794. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20795. s.lookahead--;
  20796. s.strstart++;
  20797. }
  20798. if (bflush) {
  20799. /*** FLUSH_BLOCK(s, 0); ***/
  20800. flush_block_only(s, false);
  20801. if (s.strm.avail_out === 0) {
  20802. return BS_NEED_MORE;
  20803. }
  20804. /***/
  20805. }
  20806. }
  20807. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20808. if (flush === Z_FINISH) {
  20809. /*** FLUSH_BLOCK(s, 1); ***/
  20810. flush_block_only(s, true);
  20811. if (s.strm.avail_out === 0) {
  20812. return BS_FINISH_STARTED;
  20813. }
  20814. /***/
  20815. return BS_FINISH_DONE;
  20816. }
  20817. if (s.last_lit) {
  20818. /*** FLUSH_BLOCK(s, 0); ***/
  20819. flush_block_only(s, false);
  20820. if (s.strm.avail_out === 0) {
  20821. return BS_NEED_MORE;
  20822. }
  20823. /***/
  20824. }
  20825. return BS_BLOCK_DONE;
  20826. }
  20827. /* ===========================================================================
  20828. * Same as above, but achieves better compression. We use a lazy
  20829. * evaluation for matches: a match is finally adopted only if there is
  20830. * no better match at the next window position.
  20831. */
  20832. function deflate_slow(s, flush) {
  20833. var hash_head; /* head of hash chain */
  20834. var bflush; /* set if current block must be flushed */
  20835. var max_insert;
  20836. /* Process the input block. */
  20837. for (;;) {
  20838. /* Make sure that we always have enough lookahead, except
  20839. * at the end of the input file. We need MAX_MATCH bytes
  20840. * for the next match, plus MIN_MATCH bytes to insert the
  20841. * string following the next match.
  20842. */
  20843. if (s.lookahead < MIN_LOOKAHEAD) {
  20844. fill_window(s);
  20845. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20846. return BS_NEED_MORE;
  20847. }
  20848. if (s.lookahead === 0) { break; } /* flush the current block */
  20849. }
  20850. /* Insert the string window[strstart .. strstart+2] in the
  20851. * dictionary, and set hash_head to the head of the hash chain:
  20852. */
  20853. hash_head = 0/*NIL*/;
  20854. if (s.lookahead >= MIN_MATCH) {
  20855. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20856. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20857. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20858. s.head[s.ins_h] = s.strstart;
  20859. /***/
  20860. }
  20861. /* Find the longest match, discarding those <= prev_length.
  20862. */
  20863. s.prev_length = s.match_length;
  20864. s.prev_match = s.match_start;
  20865. s.match_length = MIN_MATCH-1;
  20866. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20867. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20868. /* To simplify the code, we prevent matches with the string
  20869. * of window index 0 (in particular we have to avoid a match
  20870. * of the string with itself at the start of the input file).
  20871. */
  20872. s.match_length = longest_match(s, hash_head);
  20873. /* longest_match() sets match_start */
  20874. if (s.match_length <= 5 &&
  20875. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20876. /* If prev_match is also MIN_MATCH, match_start is garbage
  20877. * but we will ignore the current match anyway.
  20878. */
  20879. s.match_length = MIN_MATCH-1;
  20880. }
  20881. }
  20882. /* If there was a match at the previous step and the current
  20883. * match is not better, output the previous match:
  20884. */
  20885. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20886. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20887. /* Do not insert strings in hash table beyond this. */
  20888. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20889. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20890. s.prev_length - MIN_MATCH, bflush);***/
  20891. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20892. /* Insert in hash table all strings up to the end of the match.
  20893. * strstart-1 and strstart are already inserted. If there is not
  20894. * enough lookahead, the last two strings are not inserted in
  20895. * the hash table.
  20896. */
  20897. s.lookahead -= s.prev_length-1;
  20898. s.prev_length -= 2;
  20899. do {
  20900. if (++s.strstart <= max_insert) {
  20901. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20902. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20903. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20904. s.head[s.ins_h] = s.strstart;
  20905. /***/
  20906. }
  20907. } while (--s.prev_length !== 0);
  20908. s.match_available = 0;
  20909. s.match_length = MIN_MATCH-1;
  20910. s.strstart++;
  20911. if (bflush) {
  20912. /*** FLUSH_BLOCK(s, 0); ***/
  20913. flush_block_only(s, false);
  20914. if (s.strm.avail_out === 0) {
  20915. return BS_NEED_MORE;
  20916. }
  20917. /***/
  20918. }
  20919. } else if (s.match_available) {
  20920. /* If there was no match at the previous position, output a
  20921. * single literal. If there was a match but the current match
  20922. * is longer, truncate the previous match to a single literal.
  20923. */
  20924. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20925. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20926. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20927. if (bflush) {
  20928. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20929. flush_block_only(s, false);
  20930. /***/
  20931. }
  20932. s.strstart++;
  20933. s.lookahead--;
  20934. if (s.strm.avail_out === 0) {
  20935. return BS_NEED_MORE;
  20936. }
  20937. } else {
  20938. /* There is no previous match to compare with, wait for
  20939. * the next step to decide.
  20940. */
  20941. s.match_available = 1;
  20942. s.strstart++;
  20943. s.lookahead--;
  20944. }
  20945. }
  20946. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20947. if (s.match_available) {
  20948. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20949. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20950. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20951. s.match_available = 0;
  20952. }
  20953. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20954. if (flush === Z_FINISH) {
  20955. /*** FLUSH_BLOCK(s, 1); ***/
  20956. flush_block_only(s, true);
  20957. if (s.strm.avail_out === 0) {
  20958. return BS_FINISH_STARTED;
  20959. }
  20960. /***/
  20961. return BS_FINISH_DONE;
  20962. }
  20963. if (s.last_lit) {
  20964. /*** FLUSH_BLOCK(s, 0); ***/
  20965. flush_block_only(s, false);
  20966. if (s.strm.avail_out === 0) {
  20967. return BS_NEED_MORE;
  20968. }
  20969. /***/
  20970. }
  20971. return BS_BLOCK_DONE;
  20972. }
  20973. /* ===========================================================================
  20974. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20975. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20976. * deflate switches away from Z_RLE.)
  20977. */
  20978. function deflate_rle(s, flush) {
  20979. var bflush; /* set if current block must be flushed */
  20980. var prev; /* byte at distance one to match */
  20981. var scan, strend; /* scan goes up to strend for length of run */
  20982. var _win = s.window;
  20983. for (;;) {
  20984. /* Make sure that we always have enough lookahead, except
  20985. * at the end of the input file. We need MAX_MATCH bytes
  20986. * for the longest run, plus one for the unrolled loop.
  20987. */
  20988. if (s.lookahead <= MAX_MATCH) {
  20989. fill_window(s);
  20990. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20991. return BS_NEED_MORE;
  20992. }
  20993. if (s.lookahead === 0) { break; } /* flush the current block */
  20994. }
  20995. /* See how many times the previous byte repeats */
  20996. s.match_length = 0;
  20997. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  20998. scan = s.strstart - 1;
  20999. prev = _win[scan];
  21000. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21001. strend = s.strstart + MAX_MATCH;
  21002. do {
  21003. /*jshint noempty:false*/
  21004. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21005. prev === _win[++scan] && prev === _win[++scan] &&
  21006. prev === _win[++scan] && prev === _win[++scan] &&
  21007. prev === _win[++scan] && prev === _win[++scan] &&
  21008. scan < strend);
  21009. s.match_length = MAX_MATCH - (strend - scan);
  21010. if (s.match_length > s.lookahead) {
  21011. s.match_length = s.lookahead;
  21012. }
  21013. }
  21014. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21015. }
  21016. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21017. if (s.match_length >= MIN_MATCH) {
  21018. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21019. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21020. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21021. s.lookahead -= s.match_length;
  21022. s.strstart += s.match_length;
  21023. s.match_length = 0;
  21024. } else {
  21025. /* No match, output a literal byte */
  21026. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21027. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21028. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21029. s.lookahead--;
  21030. s.strstart++;
  21031. }
  21032. if (bflush) {
  21033. /*** FLUSH_BLOCK(s, 0); ***/
  21034. flush_block_only(s, false);
  21035. if (s.strm.avail_out === 0) {
  21036. return BS_NEED_MORE;
  21037. }
  21038. /***/
  21039. }
  21040. }
  21041. s.insert = 0;
  21042. if (flush === Z_FINISH) {
  21043. /*** FLUSH_BLOCK(s, 1); ***/
  21044. flush_block_only(s, true);
  21045. if (s.strm.avail_out === 0) {
  21046. return BS_FINISH_STARTED;
  21047. }
  21048. /***/
  21049. return BS_FINISH_DONE;
  21050. }
  21051. if (s.last_lit) {
  21052. /*** FLUSH_BLOCK(s, 0); ***/
  21053. flush_block_only(s, false);
  21054. if (s.strm.avail_out === 0) {
  21055. return BS_NEED_MORE;
  21056. }
  21057. /***/
  21058. }
  21059. return BS_BLOCK_DONE;
  21060. }
  21061. /* ===========================================================================
  21062. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21063. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21064. */
  21065. function deflate_huff(s, flush) {
  21066. var bflush; /* set if current block must be flushed */
  21067. for (;;) {
  21068. /* Make sure that we have a literal to write. */
  21069. if (s.lookahead === 0) {
  21070. fill_window(s);
  21071. if (s.lookahead === 0) {
  21072. if (flush === Z_NO_FLUSH) {
  21073. return BS_NEED_MORE;
  21074. }
  21075. break; /* flush the current block */
  21076. }
  21077. }
  21078. /* Output a literal byte */
  21079. s.match_length = 0;
  21080. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21081. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21082. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21083. s.lookahead--;
  21084. s.strstart++;
  21085. if (bflush) {
  21086. /*** FLUSH_BLOCK(s, 0); ***/
  21087. flush_block_only(s, false);
  21088. if (s.strm.avail_out === 0) {
  21089. return BS_NEED_MORE;
  21090. }
  21091. /***/
  21092. }
  21093. }
  21094. s.insert = 0;
  21095. if (flush === Z_FINISH) {
  21096. /*** FLUSH_BLOCK(s, 1); ***/
  21097. flush_block_only(s, true);
  21098. if (s.strm.avail_out === 0) {
  21099. return BS_FINISH_STARTED;
  21100. }
  21101. /***/
  21102. return BS_FINISH_DONE;
  21103. }
  21104. if (s.last_lit) {
  21105. /*** FLUSH_BLOCK(s, 0); ***/
  21106. flush_block_only(s, false);
  21107. if (s.strm.avail_out === 0) {
  21108. return BS_NEED_MORE;
  21109. }
  21110. /***/
  21111. }
  21112. return BS_BLOCK_DONE;
  21113. }
  21114. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21115. * the desired pack level (0..9). The values given below have been tuned to
  21116. * exclude worst case performance for pathological files. Better values may be
  21117. * found for specific files.
  21118. */
  21119. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21120. this.good_length = good_length;
  21121. this.max_lazy = max_lazy;
  21122. this.nice_length = nice_length;
  21123. this.max_chain = max_chain;
  21124. this.func = func;
  21125. };
  21126. var configuration_table;
  21127. configuration_table = [
  21128. /* good lazy nice chain */
  21129. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21130. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21131. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21132. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21133. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21134. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21135. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21136. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21137. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21138. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21139. ];
  21140. /* ===========================================================================
  21141. * Initialize the "longest match" routines for a new zlib stream
  21142. */
  21143. function lm_init(s) {
  21144. s.window_size = 2 * s.w_size;
  21145. /*** CLEAR_HASH(s); ***/
  21146. zero(s.head); // Fill with NIL (= 0);
  21147. /* Set the default configuration parameters:
  21148. */
  21149. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21150. s.good_match = configuration_table[s.level].good_length;
  21151. s.nice_match = configuration_table[s.level].nice_length;
  21152. s.max_chain_length = configuration_table[s.level].max_chain;
  21153. s.strstart = 0;
  21154. s.block_start = 0;
  21155. s.lookahead = 0;
  21156. s.insert = 0;
  21157. s.match_length = s.prev_length = MIN_MATCH - 1;
  21158. s.match_available = 0;
  21159. s.ins_h = 0;
  21160. }
  21161. function DeflateState() {
  21162. this.strm = null; /* pointer back to this zlib stream */
  21163. this.status = 0; /* as the name implies */
  21164. this.pending_buf = null; /* output still pending */
  21165. this.pending_buf_size = 0; /* size of pending_buf */
  21166. this.pending_out = 0; /* next pending byte to output to the stream */
  21167. this.pending = 0; /* nb of bytes in the pending buffer */
  21168. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21169. this.gzhead = null; /* gzip header information to write */
  21170. this.gzindex = 0; /* where in extra, name, or comment */
  21171. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21172. this.last_flush = -1; /* value of flush param for previous deflate call */
  21173. this.w_size = 0; /* LZ77 window size (32K by default) */
  21174. this.w_bits = 0; /* log2(w_size) (8..16) */
  21175. this.w_mask = 0; /* w_size - 1 */
  21176. this.window = null;
  21177. /* Sliding window. Input bytes are read into the second half of the window,
  21178. * and move to the first half later to keep a dictionary of at least wSize
  21179. * bytes. With this organization, matches are limited to a distance of
  21180. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21181. * performed with a length multiple of the block size.
  21182. */
  21183. this.window_size = 0;
  21184. /* Actual size of window: 2*wSize, except when the user input buffer
  21185. * is directly used as sliding window.
  21186. */
  21187. this.prev = null;
  21188. /* Link to older string with same hash index. To limit the size of this
  21189. * array to 64K, this link is maintained only for the last 32K strings.
  21190. * An index in this array is thus a window index modulo 32K.
  21191. */
  21192. this.head = null; /* Heads of the hash chains or NIL. */
  21193. this.ins_h = 0; /* hash index of string to be inserted */
  21194. this.hash_size = 0; /* number of elements in hash table */
  21195. this.hash_bits = 0; /* log2(hash_size) */
  21196. this.hash_mask = 0; /* hash_size-1 */
  21197. this.hash_shift = 0;
  21198. /* Number of bits by which ins_h must be shifted at each input
  21199. * step. It must be such that after MIN_MATCH steps, the oldest
  21200. * byte no longer takes part in the hash key, that is:
  21201. * hash_shift * MIN_MATCH >= hash_bits
  21202. */
  21203. this.block_start = 0;
  21204. /* Window position at the beginning of the current output block. Gets
  21205. * negative when the window is moved backwards.
  21206. */
  21207. this.match_length = 0; /* length of best match */
  21208. this.prev_match = 0; /* previous match */
  21209. this.match_available = 0; /* set if previous match exists */
  21210. this.strstart = 0; /* start of string to insert */
  21211. this.match_start = 0; /* start of matching string */
  21212. this.lookahead = 0; /* number of valid bytes ahead in window */
  21213. this.prev_length = 0;
  21214. /* Length of the best match at previous step. Matches not greater than this
  21215. * are discarded. This is used in the lazy match evaluation.
  21216. */
  21217. this.max_chain_length = 0;
  21218. /* To speed up deflation, hash chains are never searched beyond this
  21219. * length. A higher limit improves compression ratio but degrades the
  21220. * speed.
  21221. */
  21222. this.max_lazy_match = 0;
  21223. /* Attempt to find a better match only when the current match is strictly
  21224. * smaller than this value. This mechanism is used only for compression
  21225. * levels >= 4.
  21226. */
  21227. // That's alias to max_lazy_match, don't use directly
  21228. //this.max_insert_length = 0;
  21229. /* Insert new strings in the hash table only if the match length is not
  21230. * greater than this length. This saves time but degrades compression.
  21231. * max_insert_length is used only for compression levels <= 3.
  21232. */
  21233. this.level = 0; /* compression level (1..9) */
  21234. this.strategy = 0; /* favor or force Huffman coding*/
  21235. this.good_match = 0;
  21236. /* Use a faster search when the previous match is longer than this */
  21237. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21238. /* used by trees.c: */
  21239. /* Didn't use ct_data typedef below to suppress compiler warning */
  21240. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21241. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21242. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21243. // Use flat array of DOUBLE size, with interleaved fata,
  21244. // because JS does not support effective
  21245. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21246. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21247. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21248. zero(this.dyn_ltree);
  21249. zero(this.dyn_dtree);
  21250. zero(this.bl_tree);
  21251. this.l_desc = null; /* desc. for literal tree */
  21252. this.d_desc = null; /* desc. for distance tree */
  21253. this.bl_desc = null; /* desc. for bit length tree */
  21254. //ush bl_count[MAX_BITS+1];
  21255. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21256. /* number of codes at each bit length for an optimal tree */
  21257. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21258. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21259. zero(this.heap);
  21260. this.heap_len = 0; /* number of elements in the heap */
  21261. this.heap_max = 0; /* element of largest frequency */
  21262. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21263. * The same heap array is used to build all trees.
  21264. */
  21265. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21266. zero(this.depth);
  21267. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21268. */
  21269. this.l_buf = 0; /* buffer index for literals or lengths */
  21270. this.lit_bufsize = 0;
  21271. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21272. * limiting lit_bufsize to 64K:
  21273. * - frequencies can be kept in 16 bit counters
  21274. * - if compression is not successful for the first block, all input
  21275. * data is still in the window so we can still emit a stored block even
  21276. * when input comes from standard input. (This can also be done for
  21277. * all blocks if lit_bufsize is not greater than 32K.)
  21278. * - if compression is not successful for a file smaller than 64K, we can
  21279. * even emit a stored file instead of a stored block (saving 5 bytes).
  21280. * This is applicable only for zip (not gzip or zlib).
  21281. * - creating new Huffman trees less frequently may not provide fast
  21282. * adaptation to changes in the input data statistics. (Take for
  21283. * example a binary file with poorly compressible code followed by
  21284. * a highly compressible string table.) Smaller buffer sizes give
  21285. * fast adaptation but have of course the overhead of transmitting
  21286. * trees more frequently.
  21287. * - I can't count above 4
  21288. */
  21289. this.last_lit = 0; /* running index in l_buf */
  21290. this.d_buf = 0;
  21291. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21292. * the same number of elements. To use different lengths, an extra flag
  21293. * array would be necessary.
  21294. */
  21295. this.opt_len = 0; /* bit length of current block with optimal trees */
  21296. this.static_len = 0; /* bit length of current block with static trees */
  21297. this.matches = 0; /* number of string matches in current block */
  21298. this.insert = 0; /* bytes at end of window left to insert */
  21299. this.bi_buf = 0;
  21300. /* Output buffer. bits are inserted starting at the bottom (least
  21301. * significant bits).
  21302. */
  21303. this.bi_valid = 0;
  21304. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21305. * are always zero.
  21306. */
  21307. // Used for window memory init. We safely ignore it for JS. That makes
  21308. // sense only for pointers and memory check tools.
  21309. //this.high_water = 0;
  21310. /* High water mark offset in window for initialized bytes -- bytes above
  21311. * this are set to zero in order to avoid memory check warnings when
  21312. * longest match routines access bytes past the input. This is then
  21313. * updated to the new high water mark.
  21314. */
  21315. }
  21316. function deflateResetKeep(strm) {
  21317. var s;
  21318. if (!strm || !strm.state) {
  21319. return err(strm, Z_STREAM_ERROR);
  21320. }
  21321. strm.total_in = strm.total_out = 0;
  21322. strm.data_type = Z_UNKNOWN;
  21323. s = strm.state;
  21324. s.pending = 0;
  21325. s.pending_out = 0;
  21326. if (s.wrap < 0) {
  21327. s.wrap = -s.wrap;
  21328. /* was made negative by deflate(..., Z_FINISH); */
  21329. }
  21330. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21331. strm.adler = (s.wrap === 2) ?
  21332. 0 // crc32(0, Z_NULL, 0)
  21333. :
  21334. 1; // adler32(0, Z_NULL, 0)
  21335. s.last_flush = Z_NO_FLUSH;
  21336. trees._tr_init(s);
  21337. return Z_OK;
  21338. }
  21339. function deflateReset(strm) {
  21340. var ret = deflateResetKeep(strm);
  21341. if (ret === Z_OK) {
  21342. lm_init(strm.state);
  21343. }
  21344. return ret;
  21345. }
  21346. function deflateSetHeader(strm, head) {
  21347. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21348. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21349. strm.state.gzhead = head;
  21350. return Z_OK;
  21351. }
  21352. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21353. if (!strm) { // === Z_NULL
  21354. return Z_STREAM_ERROR;
  21355. }
  21356. var wrap = 1;
  21357. if (level === Z_DEFAULT_COMPRESSION) {
  21358. level = 6;
  21359. }
  21360. if (windowBits < 0) { /* suppress zlib wrapper */
  21361. wrap = 0;
  21362. windowBits = -windowBits;
  21363. }
  21364. else if (windowBits > 15) {
  21365. wrap = 2; /* write gzip wrapper instead */
  21366. windowBits -= 16;
  21367. }
  21368. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21369. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21370. strategy < 0 || strategy > Z_FIXED) {
  21371. return err(strm, Z_STREAM_ERROR);
  21372. }
  21373. if (windowBits === 8) {
  21374. windowBits = 9;
  21375. }
  21376. /* until 256-byte window bug fixed */
  21377. var s = new DeflateState();
  21378. strm.state = s;
  21379. s.strm = strm;
  21380. s.wrap = wrap;
  21381. s.gzhead = null;
  21382. s.w_bits = windowBits;
  21383. s.w_size = 1 << s.w_bits;
  21384. s.w_mask = s.w_size - 1;
  21385. s.hash_bits = memLevel + 7;
  21386. s.hash_size = 1 << s.hash_bits;
  21387. s.hash_mask = s.hash_size - 1;
  21388. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21389. s.window = new utils.Buf8(s.w_size * 2);
  21390. s.head = new utils.Buf16(s.hash_size);
  21391. s.prev = new utils.Buf16(s.w_size);
  21392. // Don't need mem init magic for JS.
  21393. //s.high_water = 0; /* nothing written to s->window yet */
  21394. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21395. s.pending_buf_size = s.lit_bufsize * 4;
  21396. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21397. s.d_buf = s.lit_bufsize >> 1;
  21398. s.l_buf = (1 + 2) * s.lit_bufsize;
  21399. s.level = level;
  21400. s.strategy = strategy;
  21401. s.method = method;
  21402. return deflateReset(strm);
  21403. }
  21404. function deflateInit(strm, level) {
  21405. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21406. }
  21407. function deflate(strm, flush) {
  21408. var old_flush, s;
  21409. var beg, val; // for gzip header write only
  21410. if (!strm || !strm.state ||
  21411. flush > Z_BLOCK || flush < 0) {
  21412. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21413. }
  21414. s = strm.state;
  21415. if (!strm.output ||
  21416. (!strm.input && strm.avail_in !== 0) ||
  21417. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21418. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21419. }
  21420. s.strm = strm; /* just in case */
  21421. old_flush = s.last_flush;
  21422. s.last_flush = flush;
  21423. /* Write the header */
  21424. if (s.status === INIT_STATE) {
  21425. if (s.wrap === 2) { // GZIP header
  21426. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21427. put_byte(s, 31);
  21428. put_byte(s, 139);
  21429. put_byte(s, 8);
  21430. if (!s.gzhead) { // s->gzhead == Z_NULL
  21431. put_byte(s, 0);
  21432. put_byte(s, 0);
  21433. put_byte(s, 0);
  21434. put_byte(s, 0);
  21435. put_byte(s, 0);
  21436. put_byte(s, s.level === 9 ? 2 :
  21437. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21438. 4 : 0));
  21439. put_byte(s, OS_CODE);
  21440. s.status = BUSY_STATE;
  21441. }
  21442. else {
  21443. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21444. (s.gzhead.hcrc ? 2 : 0) +
  21445. (!s.gzhead.extra ? 0 : 4) +
  21446. (!s.gzhead.name ? 0 : 8) +
  21447. (!s.gzhead.comment ? 0 : 16)
  21448. );
  21449. put_byte(s, s.gzhead.time & 0xff);
  21450. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21451. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21452. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21453. put_byte(s, s.level === 9 ? 2 :
  21454. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21455. 4 : 0));
  21456. put_byte(s, s.gzhead.os & 0xff);
  21457. if (s.gzhead.extra && s.gzhead.extra.length) {
  21458. put_byte(s, s.gzhead.extra.length & 0xff);
  21459. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21460. }
  21461. if (s.gzhead.hcrc) {
  21462. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21463. }
  21464. s.gzindex = 0;
  21465. s.status = EXTRA_STATE;
  21466. }
  21467. }
  21468. else // DEFLATE header
  21469. {
  21470. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21471. var level_flags = -1;
  21472. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21473. level_flags = 0;
  21474. } else if (s.level < 6) {
  21475. level_flags = 1;
  21476. } else if (s.level === 6) {
  21477. level_flags = 2;
  21478. } else {
  21479. level_flags = 3;
  21480. }
  21481. header |= (level_flags << 6);
  21482. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21483. header += 31 - (header % 31);
  21484. s.status = BUSY_STATE;
  21485. putShortMSB(s, header);
  21486. /* Save the adler32 of the preset dictionary: */
  21487. if (s.strstart !== 0) {
  21488. putShortMSB(s, strm.adler >>> 16);
  21489. putShortMSB(s, strm.adler & 0xffff);
  21490. }
  21491. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21492. }
  21493. }
  21494. //#ifdef GZIP
  21495. if (s.status === EXTRA_STATE) {
  21496. if (s.gzhead.extra/* != Z_NULL*/) {
  21497. beg = s.pending; /* start of bytes to update crc */
  21498. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21499. if (s.pending === s.pending_buf_size) {
  21500. if (s.gzhead.hcrc && s.pending > beg) {
  21501. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21502. }
  21503. flush_pending(strm);
  21504. beg = s.pending;
  21505. if (s.pending === s.pending_buf_size) {
  21506. break;
  21507. }
  21508. }
  21509. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21510. s.gzindex++;
  21511. }
  21512. if (s.gzhead.hcrc && s.pending > beg) {
  21513. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21514. }
  21515. if (s.gzindex === s.gzhead.extra.length) {
  21516. s.gzindex = 0;
  21517. s.status = NAME_STATE;
  21518. }
  21519. }
  21520. else {
  21521. s.status = NAME_STATE;
  21522. }
  21523. }
  21524. if (s.status === NAME_STATE) {
  21525. if (s.gzhead.name/* != Z_NULL*/) {
  21526. beg = s.pending; /* start of bytes to update crc */
  21527. //int val;
  21528. do {
  21529. if (s.pending === s.pending_buf_size) {
  21530. if (s.gzhead.hcrc && s.pending > beg) {
  21531. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21532. }
  21533. flush_pending(strm);
  21534. beg = s.pending;
  21535. if (s.pending === s.pending_buf_size) {
  21536. val = 1;
  21537. break;
  21538. }
  21539. }
  21540. // JS specific: little magic to add zero terminator to end of string
  21541. if (s.gzindex < s.gzhead.name.length) {
  21542. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21543. } else {
  21544. val = 0;
  21545. }
  21546. put_byte(s, val);
  21547. } while (val !== 0);
  21548. if (s.gzhead.hcrc && s.pending > beg) {
  21549. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21550. }
  21551. if (val === 0) {
  21552. s.gzindex = 0;
  21553. s.status = COMMENT_STATE;
  21554. }
  21555. }
  21556. else {
  21557. s.status = COMMENT_STATE;
  21558. }
  21559. }
  21560. if (s.status === COMMENT_STATE) {
  21561. if (s.gzhead.comment/* != Z_NULL*/) {
  21562. beg = s.pending; /* start of bytes to update crc */
  21563. //int val;
  21564. do {
  21565. if (s.pending === s.pending_buf_size) {
  21566. if (s.gzhead.hcrc && s.pending > beg) {
  21567. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21568. }
  21569. flush_pending(strm);
  21570. beg = s.pending;
  21571. if (s.pending === s.pending_buf_size) {
  21572. val = 1;
  21573. break;
  21574. }
  21575. }
  21576. // JS specific: little magic to add zero terminator to end of string
  21577. if (s.gzindex < s.gzhead.comment.length) {
  21578. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21579. } else {
  21580. val = 0;
  21581. }
  21582. put_byte(s, val);
  21583. } while (val !== 0);
  21584. if (s.gzhead.hcrc && s.pending > beg) {
  21585. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21586. }
  21587. if (val === 0) {
  21588. s.status = HCRC_STATE;
  21589. }
  21590. }
  21591. else {
  21592. s.status = HCRC_STATE;
  21593. }
  21594. }
  21595. if (s.status === HCRC_STATE) {
  21596. if (s.gzhead.hcrc) {
  21597. if (s.pending + 2 > s.pending_buf_size) {
  21598. flush_pending(strm);
  21599. }
  21600. if (s.pending + 2 <= s.pending_buf_size) {
  21601. put_byte(s, strm.adler & 0xff);
  21602. put_byte(s, (strm.adler >> 8) & 0xff);
  21603. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21604. s.status = BUSY_STATE;
  21605. }
  21606. }
  21607. else {
  21608. s.status = BUSY_STATE;
  21609. }
  21610. }
  21611. //#endif
  21612. /* Flush as much pending output as possible */
  21613. if (s.pending !== 0) {
  21614. flush_pending(strm);
  21615. if (strm.avail_out === 0) {
  21616. /* Since avail_out is 0, deflate will be called again with
  21617. * more output space, but possibly with both pending and
  21618. * avail_in equal to zero. There won't be anything to do,
  21619. * but this is not an error situation so make sure we
  21620. * return OK instead of BUF_ERROR at next call of deflate:
  21621. */
  21622. s.last_flush = -1;
  21623. return Z_OK;
  21624. }
  21625. /* Make sure there is something to do and avoid duplicate consecutive
  21626. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21627. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21628. */
  21629. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21630. flush !== Z_FINISH) {
  21631. return err(strm, Z_BUF_ERROR);
  21632. }
  21633. /* User must not provide more input after the first FINISH: */
  21634. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21635. return err(strm, Z_BUF_ERROR);
  21636. }
  21637. /* Start a new block or continue the current one.
  21638. */
  21639. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21640. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21641. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21642. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21643. configuration_table[s.level].func(s, flush));
  21644. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21645. s.status = FINISH_STATE;
  21646. }
  21647. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21648. if (strm.avail_out === 0) {
  21649. s.last_flush = -1;
  21650. /* avoid BUF_ERROR next call, see above */
  21651. }
  21652. return Z_OK;
  21653. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21654. * of deflate should use the same flush parameter to make sure
  21655. * that the flush is complete. So we don't have to output an
  21656. * empty block here, this will be done at next call. This also
  21657. * ensures that for a very small output buffer, we emit at most
  21658. * one empty block.
  21659. */
  21660. }
  21661. if (bstate === BS_BLOCK_DONE) {
  21662. if (flush === Z_PARTIAL_FLUSH) {
  21663. trees._tr_align(s);
  21664. }
  21665. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21666. trees._tr_stored_block(s, 0, 0, false);
  21667. /* For a full flush, this empty block will be recognized
  21668. * as a special marker by inflate_sync().
  21669. */
  21670. if (flush === Z_FULL_FLUSH) {
  21671. /*** CLEAR_HASH(s); ***/ /* forget history */
  21672. zero(s.head); // Fill with NIL (= 0);
  21673. if (s.lookahead === 0) {
  21674. s.strstart = 0;
  21675. s.block_start = 0;
  21676. s.insert = 0;
  21677. }
  21678. }
  21679. }
  21680. flush_pending(strm);
  21681. if (strm.avail_out === 0) {
  21682. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21683. return Z_OK;
  21684. }
  21685. }
  21686. }
  21687. //Assert(strm->avail_out > 0, "bug2");
  21688. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21689. if (flush !== Z_FINISH) { return Z_OK; }
  21690. if (s.wrap <= 0) { return Z_STREAM_END; }
  21691. /* Write the trailer */
  21692. if (s.wrap === 2) {
  21693. put_byte(s, strm.adler & 0xff);
  21694. put_byte(s, (strm.adler >> 8) & 0xff);
  21695. put_byte(s, (strm.adler >> 16) & 0xff);
  21696. put_byte(s, (strm.adler >> 24) & 0xff);
  21697. put_byte(s, strm.total_in & 0xff);
  21698. put_byte(s, (strm.total_in >> 8) & 0xff);
  21699. put_byte(s, (strm.total_in >> 16) & 0xff);
  21700. put_byte(s, (strm.total_in >> 24) & 0xff);
  21701. }
  21702. else
  21703. {
  21704. putShortMSB(s, strm.adler >>> 16);
  21705. putShortMSB(s, strm.adler & 0xffff);
  21706. }
  21707. flush_pending(strm);
  21708. /* If avail_out is zero, the application will call deflate again
  21709. * to flush the rest.
  21710. */
  21711. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21712. /* write the trailer only once! */
  21713. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21714. }
  21715. function deflateEnd(strm) {
  21716. var status;
  21717. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21718. return Z_STREAM_ERROR;
  21719. }
  21720. status = strm.state.status;
  21721. if (status !== INIT_STATE &&
  21722. status !== EXTRA_STATE &&
  21723. status !== NAME_STATE &&
  21724. status !== COMMENT_STATE &&
  21725. status !== HCRC_STATE &&
  21726. status !== BUSY_STATE &&
  21727. status !== FINISH_STATE
  21728. ) {
  21729. return err(strm, Z_STREAM_ERROR);
  21730. }
  21731. strm.state = null;
  21732. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21733. }
  21734. /* =========================================================================
  21735. * Copy the source state to the destination state
  21736. */
  21737. //function deflateCopy(dest, source) {
  21738. //
  21739. //}
  21740. exports.deflateInit = deflateInit;
  21741. exports.deflateInit2 = deflateInit2;
  21742. exports.deflateReset = deflateReset;
  21743. exports.deflateResetKeep = deflateResetKeep;
  21744. exports.deflateSetHeader = deflateSetHeader;
  21745. exports.deflate = deflate;
  21746. exports.deflateEnd = deflateEnd;
  21747. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21748. /* Not implemented
  21749. exports.deflateBound = deflateBound;
  21750. exports.deflateCopy = deflateCopy;
  21751. exports.deflateSetDictionary = deflateSetDictionary;
  21752. exports.deflateParams = deflateParams;
  21753. exports.deflatePending = deflatePending;
  21754. exports.deflatePrime = deflatePrime;
  21755. exports.deflateTune = deflateTune;
  21756. */
  21757. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./messages":82,"./trees":83}],78:[function(require,module,exports){
  21758. 'use strict';
  21759. function GZheader() {
  21760. /* true if compressed data believed to be text */
  21761. this.text = 0;
  21762. /* modification time */
  21763. this.time = 0;
  21764. /* extra flags (not used when writing a gzip file) */
  21765. this.xflags = 0;
  21766. /* operating system */
  21767. this.os = 0;
  21768. /* pointer to extra field or Z_NULL if none */
  21769. this.extra = null;
  21770. /* extra field length (valid if extra != Z_NULL) */
  21771. this.extra_len = 0; // Actually, we don't need it in JS,
  21772. // but leave for few code modifications
  21773. //
  21774. // Setup limits is not necessary because in js we should not preallocate memory
  21775. // for inflate use constant limit in 65536 bytes
  21776. //
  21777. /* space at extra (only when reading header) */
  21778. // this.extra_max = 0;
  21779. /* pointer to zero-terminated file name or Z_NULL */
  21780. this.name = '';
  21781. /* space at name (only when reading header) */
  21782. // this.name_max = 0;
  21783. /* pointer to zero-terminated comment or Z_NULL */
  21784. this.comment = '';
  21785. /* space at comment (only when reading header) */
  21786. // this.comm_max = 0;
  21787. /* true if there was or will be a header crc */
  21788. this.hcrc = 0;
  21789. /* true when done reading gzip header (not used when writing a gzip file) */
  21790. this.done = false;
  21791. }
  21792. module.exports = GZheader;
  21793. },{}],79:[function(require,module,exports){
  21794. 'use strict';
  21795. // See state defs from inflate.js
  21796. var BAD = 30; /* got a data error -- remain here until reset */
  21797. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21798. /*
  21799. Decode literal, length, and distance codes and write out the resulting
  21800. literal and match bytes until either not enough input or output is
  21801. available, an end-of-block is encountered, or a data error is encountered.
  21802. When large enough input and output buffers are supplied to inflate(), for
  21803. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21804. inflate execution time is spent in this routine.
  21805. Entry assumptions:
  21806. state.mode === LEN
  21807. strm.avail_in >= 6
  21808. strm.avail_out >= 258
  21809. start >= strm.avail_out
  21810. state.bits < 8
  21811. On return, state.mode is one of:
  21812. LEN -- ran out of enough output space or enough available input
  21813. TYPE -- reached end of block code, inflate() to interpret next block
  21814. BAD -- error in block data
  21815. Notes:
  21816. - The maximum input bits used by a length/distance pair is 15 bits for the
  21817. length code, 5 bits for the length extra, 15 bits for the distance code,
  21818. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21819. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21820. checking for available input while decoding.
  21821. - The maximum bytes that a single length/distance pair can output is 258
  21822. bytes, which is the maximum length that can be coded. inflate_fast()
  21823. requires strm.avail_out >= 258 for each loop to avoid checking for
  21824. output space.
  21825. */
  21826. module.exports = function inflate_fast(strm, start) {
  21827. var state;
  21828. var _in; /* local strm.input */
  21829. var last; /* have enough input while in < last */
  21830. var _out; /* local strm.output */
  21831. var beg; /* inflate()'s initial strm.output */
  21832. var end; /* while out < end, enough space available */
  21833. //#ifdef INFLATE_STRICT
  21834. var dmax; /* maximum distance from zlib header */
  21835. //#endif
  21836. var wsize; /* window size or zero if not using window */
  21837. var whave; /* valid bytes in the window */
  21838. var wnext; /* window write index */
  21839. var window; /* allocated sliding window, if wsize != 0 */
  21840. var hold; /* local strm.hold */
  21841. var bits; /* local strm.bits */
  21842. var lcode; /* local strm.lencode */
  21843. var dcode; /* local strm.distcode */
  21844. var lmask; /* mask for first level of length codes */
  21845. var dmask; /* mask for first level of distance codes */
  21846. var here; /* retrieved table entry */
  21847. var op; /* code bits, operation, extra bits, or */
  21848. /* window position, window bytes to copy */
  21849. var len; /* match length, unused bytes */
  21850. var dist; /* match distance */
  21851. var from; /* where to copy match from */
  21852. var from_source;
  21853. var input, output; // JS specific, because we have no pointers
  21854. /* copy state to local variables */
  21855. state = strm.state;
  21856. //here = state.here;
  21857. _in = strm.next_in;
  21858. input = strm.input;
  21859. last = _in + (strm.avail_in - 5);
  21860. _out = strm.next_out;
  21861. output = strm.output;
  21862. beg = _out - (start - strm.avail_out);
  21863. end = _out + (strm.avail_out - 257);
  21864. //#ifdef INFLATE_STRICT
  21865. dmax = state.dmax;
  21866. //#endif
  21867. wsize = state.wsize;
  21868. whave = state.whave;
  21869. wnext = state.wnext;
  21870. window = state.window;
  21871. hold = state.hold;
  21872. bits = state.bits;
  21873. lcode = state.lencode;
  21874. dcode = state.distcode;
  21875. lmask = (1 << state.lenbits) - 1;
  21876. dmask = (1 << state.distbits) - 1;
  21877. /* decode literals and length/distances until end-of-block or not enough
  21878. input data or output space */
  21879. top:
  21880. do {
  21881. if (bits < 15) {
  21882. hold += input[_in++] << bits;
  21883. bits += 8;
  21884. hold += input[_in++] << bits;
  21885. bits += 8;
  21886. }
  21887. here = lcode[hold & lmask];
  21888. dolen:
  21889. for (;;) { // Goto emulation
  21890. op = here >>> 24/*here.bits*/;
  21891. hold >>>= op;
  21892. bits -= op;
  21893. op = (here >>> 16) & 0xff/*here.op*/;
  21894. if (op === 0) { /* literal */
  21895. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21896. // "inflate: literal '%c'\n" :
  21897. // "inflate: literal 0x%02x\n", here.val));
  21898. output[_out++] = here & 0xffff/*here.val*/;
  21899. }
  21900. else if (op & 16) { /* length base */
  21901. len = here & 0xffff/*here.val*/;
  21902. op &= 15; /* number of extra bits */
  21903. if (op) {
  21904. if (bits < op) {
  21905. hold += input[_in++] << bits;
  21906. bits += 8;
  21907. }
  21908. len += hold & ((1 << op) - 1);
  21909. hold >>>= op;
  21910. bits -= op;
  21911. }
  21912. //Tracevv((stderr, "inflate: length %u\n", len));
  21913. if (bits < 15) {
  21914. hold += input[_in++] << bits;
  21915. bits += 8;
  21916. hold += input[_in++] << bits;
  21917. bits += 8;
  21918. }
  21919. here = dcode[hold & dmask];
  21920. dodist:
  21921. for (;;) { // goto emulation
  21922. op = here >>> 24/*here.bits*/;
  21923. hold >>>= op;
  21924. bits -= op;
  21925. op = (here >>> 16) & 0xff/*here.op*/;
  21926. if (op & 16) { /* distance base */
  21927. dist = here & 0xffff/*here.val*/;
  21928. op &= 15; /* number of extra bits */
  21929. if (bits < op) {
  21930. hold += input[_in++] << bits;
  21931. bits += 8;
  21932. if (bits < op) {
  21933. hold += input[_in++] << bits;
  21934. bits += 8;
  21935. }
  21936. }
  21937. dist += hold & ((1 << op) - 1);
  21938. //#ifdef INFLATE_STRICT
  21939. if (dist > dmax) {
  21940. strm.msg = 'invalid distance too far back';
  21941. state.mode = BAD;
  21942. break top;
  21943. }
  21944. //#endif
  21945. hold >>>= op;
  21946. bits -= op;
  21947. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21948. op = _out - beg; /* max distance in output */
  21949. if (dist > op) { /* see if copy from window */
  21950. op = dist - op; /* distance back in window */
  21951. if (op > whave) {
  21952. if (state.sane) {
  21953. strm.msg = 'invalid distance too far back';
  21954. state.mode = BAD;
  21955. break top;
  21956. }
  21957. // (!) This block is disabled in zlib defailts,
  21958. // don't enable it for binary compatibility
  21959. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21960. // if (len <= op - whave) {
  21961. // do {
  21962. // output[_out++] = 0;
  21963. // } while (--len);
  21964. // continue top;
  21965. // }
  21966. // len -= op - whave;
  21967. // do {
  21968. // output[_out++] = 0;
  21969. // } while (--op > whave);
  21970. // if (op === 0) {
  21971. // from = _out - dist;
  21972. // do {
  21973. // output[_out++] = output[from++];
  21974. // } while (--len);
  21975. // continue top;
  21976. // }
  21977. //#endif
  21978. }
  21979. from = 0; // window index
  21980. from_source = window;
  21981. if (wnext === 0) { /* very common case */
  21982. from += wsize - op;
  21983. if (op < len) { /* some from window */
  21984. len -= op;
  21985. do {
  21986. output[_out++] = window[from++];
  21987. } while (--op);
  21988. from = _out - dist; /* rest from output */
  21989. from_source = output;
  21990. }
  21991. }
  21992. else if (wnext < op) { /* wrap around window */
  21993. from += wsize + wnext - op;
  21994. op -= wnext;
  21995. if (op < len) { /* some from end of window */
  21996. len -= op;
  21997. do {
  21998. output[_out++] = window[from++];
  21999. } while (--op);
  22000. from = 0;
  22001. if (wnext < len) { /* some from start of window */
  22002. op = wnext;
  22003. len -= op;
  22004. do {
  22005. output[_out++] = window[from++];
  22006. } while (--op);
  22007. from = _out - dist; /* rest from output */
  22008. from_source = output;
  22009. }
  22010. }
  22011. }
  22012. else { /* contiguous in window */
  22013. from += wnext - op;
  22014. if (op < len) { /* some from window */
  22015. len -= op;
  22016. do {
  22017. output[_out++] = window[from++];
  22018. } while (--op);
  22019. from = _out - dist; /* rest from output */
  22020. from_source = output;
  22021. }
  22022. }
  22023. while (len > 2) {
  22024. output[_out++] = from_source[from++];
  22025. output[_out++] = from_source[from++];
  22026. output[_out++] = from_source[from++];
  22027. len -= 3;
  22028. }
  22029. if (len) {
  22030. output[_out++] = from_source[from++];
  22031. if (len > 1) {
  22032. output[_out++] = from_source[from++];
  22033. }
  22034. }
  22035. }
  22036. else {
  22037. from = _out - dist; /* copy direct from output */
  22038. do { /* minimum length is three */
  22039. output[_out++] = output[from++];
  22040. output[_out++] = output[from++];
  22041. output[_out++] = output[from++];
  22042. len -= 3;
  22043. } while (len > 2);
  22044. if (len) {
  22045. output[_out++] = output[from++];
  22046. if (len > 1) {
  22047. output[_out++] = output[from++];
  22048. }
  22049. }
  22050. }
  22051. }
  22052. else if ((op & 64) === 0) { /* 2nd level distance code */
  22053. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22054. continue dodist;
  22055. }
  22056. else {
  22057. strm.msg = 'invalid distance code';
  22058. state.mode = BAD;
  22059. break top;
  22060. }
  22061. break; // need to emulate goto via "continue"
  22062. }
  22063. }
  22064. else if ((op & 64) === 0) { /* 2nd level length code */
  22065. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22066. continue dolen;
  22067. }
  22068. else if (op & 32) { /* end-of-block */
  22069. //Tracevv((stderr, "inflate: end of block\n"));
  22070. state.mode = TYPE;
  22071. break top;
  22072. }
  22073. else {
  22074. strm.msg = 'invalid literal/length code';
  22075. state.mode = BAD;
  22076. break top;
  22077. }
  22078. break; // need to emulate goto via "continue"
  22079. }
  22080. } while (_in < last && _out < end);
  22081. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22082. len = bits >> 3;
  22083. _in -= len;
  22084. bits -= len << 3;
  22085. hold &= (1 << bits) - 1;
  22086. /* update state and return */
  22087. strm.next_in = _in;
  22088. strm.next_out = _out;
  22089. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22090. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22091. state.hold = hold;
  22092. state.bits = bits;
  22093. return;
  22094. };
  22095. },{}],80:[function(require,module,exports){
  22096. 'use strict';
  22097. var utils = require('../utils/common');
  22098. var adler32 = require('./adler32');
  22099. var crc32 = require('./crc32');
  22100. var inflate_fast = require('./inffast');
  22101. var inflate_table = require('./inftrees');
  22102. var CODES = 0;
  22103. var LENS = 1;
  22104. var DISTS = 2;
  22105. /* Public constants ==========================================================*/
  22106. /* ===========================================================================*/
  22107. /* Allowed flush values; see deflate() and inflate() below for details */
  22108. //var Z_NO_FLUSH = 0;
  22109. //var Z_PARTIAL_FLUSH = 1;
  22110. //var Z_SYNC_FLUSH = 2;
  22111. //var Z_FULL_FLUSH = 3;
  22112. var Z_FINISH = 4;
  22113. var Z_BLOCK = 5;
  22114. var Z_TREES = 6;
  22115. /* Return codes for the compression/decompression functions. Negative values
  22116. * are errors, positive values are used for special but normal events.
  22117. */
  22118. var Z_OK = 0;
  22119. var Z_STREAM_END = 1;
  22120. var Z_NEED_DICT = 2;
  22121. //var Z_ERRNO = -1;
  22122. var Z_STREAM_ERROR = -2;
  22123. var Z_DATA_ERROR = -3;
  22124. var Z_MEM_ERROR = -4;
  22125. var Z_BUF_ERROR = -5;
  22126. //var Z_VERSION_ERROR = -6;
  22127. /* The deflate compression method */
  22128. var Z_DEFLATED = 8;
  22129. /* STATES ====================================================================*/
  22130. /* ===========================================================================*/
  22131. var HEAD = 1; /* i: waiting for magic header */
  22132. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22133. var TIME = 3; /* i: waiting for modification time (gzip) */
  22134. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22135. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22136. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22137. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22138. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22139. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22140. var DICTID = 10; /* i: waiting for dictionary check value */
  22141. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22142. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22143. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22144. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22145. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22146. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22147. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22148. var LENLENS = 18; /* i: waiting for code length code lengths */
  22149. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22150. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22151. var LEN = 21; /* i: waiting for length/lit/eob code */
  22152. var LENEXT = 22; /* i: waiting for length extra bits */
  22153. var DIST = 23; /* i: waiting for distance code */
  22154. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22155. var MATCH = 25; /* o: waiting for output space to copy string */
  22156. var LIT = 26; /* o: waiting for output space to write literal */
  22157. var CHECK = 27; /* i: waiting for 32-bit check value */
  22158. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22159. var DONE = 29; /* finished check, done -- remain here until reset */
  22160. var BAD = 30; /* got a data error -- remain here until reset */
  22161. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22162. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22163. /* ===========================================================================*/
  22164. var ENOUGH_LENS = 852;
  22165. var ENOUGH_DISTS = 592;
  22166. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22167. var MAX_WBITS = 15;
  22168. /* 32K LZ77 window */
  22169. var DEF_WBITS = MAX_WBITS;
  22170. function ZSWAP32(q) {
  22171. return (((q >>> 24) & 0xff) +
  22172. ((q >>> 8) & 0xff00) +
  22173. ((q & 0xff00) << 8) +
  22174. ((q & 0xff) << 24));
  22175. }
  22176. function InflateState() {
  22177. this.mode = 0; /* current inflate mode */
  22178. this.last = false; /* true if processing last block */
  22179. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22180. this.havedict = false; /* true if dictionary provided */
  22181. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22182. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22183. this.check = 0; /* protected copy of check value */
  22184. this.total = 0; /* protected copy of output count */
  22185. // TODO: may be {}
  22186. this.head = null; /* where to save gzip header information */
  22187. /* sliding window */
  22188. this.wbits = 0; /* log base 2 of requested window size */
  22189. this.wsize = 0; /* window size or zero if not using window */
  22190. this.whave = 0; /* valid bytes in the window */
  22191. this.wnext = 0; /* window write index */
  22192. this.window = null; /* allocated sliding window, if needed */
  22193. /* bit accumulator */
  22194. this.hold = 0; /* input bit accumulator */
  22195. this.bits = 0; /* number of bits in "in" */
  22196. /* for string and stored block copying */
  22197. this.length = 0; /* literal or length of data to copy */
  22198. this.offset = 0; /* distance back to copy string from */
  22199. /* for table and code decoding */
  22200. this.extra = 0; /* extra bits needed */
  22201. /* fixed and dynamic code tables */
  22202. this.lencode = null; /* starting table for length/literal codes */
  22203. this.distcode = null; /* starting table for distance codes */
  22204. this.lenbits = 0; /* index bits for lencode */
  22205. this.distbits = 0; /* index bits for distcode */
  22206. /* dynamic table building */
  22207. this.ncode = 0; /* number of code length code lengths */
  22208. this.nlen = 0; /* number of length code lengths */
  22209. this.ndist = 0; /* number of distance code lengths */
  22210. this.have = 0; /* number of code lengths in lens[] */
  22211. this.next = null; /* next available space in codes[] */
  22212. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22213. this.work = new utils.Buf16(288); /* work area for code table building */
  22214. /*
  22215. because we don't have pointers in js, we use lencode and distcode directly
  22216. as buffers so we don't need codes
  22217. */
  22218. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22219. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22220. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22221. this.sane = 0; /* if false, allow invalid distance too far */
  22222. this.back = 0; /* bits back of last unprocessed length/lit */
  22223. this.was = 0; /* initial length of match */
  22224. }
  22225. function inflateResetKeep(strm) {
  22226. var state;
  22227. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22228. state = strm.state;
  22229. strm.total_in = strm.total_out = state.total = 0;
  22230. strm.msg = ''; /*Z_NULL*/
  22231. if (state.wrap) { /* to support ill-conceived Java test suite */
  22232. strm.adler = state.wrap & 1;
  22233. }
  22234. state.mode = HEAD;
  22235. state.last = 0;
  22236. state.havedict = 0;
  22237. state.dmax = 32768;
  22238. state.head = null/*Z_NULL*/;
  22239. state.hold = 0;
  22240. state.bits = 0;
  22241. //state.lencode = state.distcode = state.next = state.codes;
  22242. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22243. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22244. state.sane = 1;
  22245. state.back = -1;
  22246. //Tracev((stderr, "inflate: reset\n"));
  22247. return Z_OK;
  22248. }
  22249. function inflateReset(strm) {
  22250. var state;
  22251. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22252. state = strm.state;
  22253. state.wsize = 0;
  22254. state.whave = 0;
  22255. state.wnext = 0;
  22256. return inflateResetKeep(strm);
  22257. }
  22258. function inflateReset2(strm, windowBits) {
  22259. var wrap;
  22260. var state;
  22261. /* get the state */
  22262. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22263. state = strm.state;
  22264. /* extract wrap request from windowBits parameter */
  22265. if (windowBits < 0) {
  22266. wrap = 0;
  22267. windowBits = -windowBits;
  22268. }
  22269. else {
  22270. wrap = (windowBits >> 4) + 1;
  22271. if (windowBits < 48) {
  22272. windowBits &= 15;
  22273. }
  22274. }
  22275. /* set number of window bits, free window if different */
  22276. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22277. return Z_STREAM_ERROR;
  22278. }
  22279. if (state.window !== null && state.wbits !== windowBits) {
  22280. state.window = null;
  22281. }
  22282. /* update state and reset the rest of it */
  22283. state.wrap = wrap;
  22284. state.wbits = windowBits;
  22285. return inflateReset(strm);
  22286. }
  22287. function inflateInit2(strm, windowBits) {
  22288. var ret;
  22289. var state;
  22290. if (!strm) { return Z_STREAM_ERROR; }
  22291. //strm.msg = Z_NULL; /* in case we return an error */
  22292. state = new InflateState();
  22293. //if (state === Z_NULL) return Z_MEM_ERROR;
  22294. //Tracev((stderr, "inflate: allocated\n"));
  22295. strm.state = state;
  22296. state.window = null/*Z_NULL*/;
  22297. ret = inflateReset2(strm, windowBits);
  22298. if (ret !== Z_OK) {
  22299. strm.state = null/*Z_NULL*/;
  22300. }
  22301. return ret;
  22302. }
  22303. function inflateInit(strm) {
  22304. return inflateInit2(strm, DEF_WBITS);
  22305. }
  22306. /*
  22307. Return state with length and distance decoding tables and index sizes set to
  22308. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22309. If BUILDFIXED is defined, then instead this routine builds the tables the
  22310. first time it's called, and returns those tables the first time and
  22311. thereafter. This reduces the size of the code by about 2K bytes, in
  22312. exchange for a little execution time. However, BUILDFIXED should not be
  22313. used for threaded applications, since the rewriting of the tables and virgin
  22314. may not be thread-safe.
  22315. */
  22316. var virgin = true;
  22317. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22318. function fixedtables(state) {
  22319. /* build fixed huffman tables if first call (may not be thread safe) */
  22320. if (virgin) {
  22321. var sym;
  22322. lenfix = new utils.Buf32(512);
  22323. distfix = new utils.Buf32(32);
  22324. /* literal/length table */
  22325. sym = 0;
  22326. while (sym < 144) { state.lens[sym++] = 8; }
  22327. while (sym < 256) { state.lens[sym++] = 9; }
  22328. while (sym < 280) { state.lens[sym++] = 7; }
  22329. while (sym < 288) { state.lens[sym++] = 8; }
  22330. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22331. /* distance table */
  22332. sym = 0;
  22333. while (sym < 32) { state.lens[sym++] = 5; }
  22334. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22335. /* do this just once */
  22336. virgin = false;
  22337. }
  22338. state.lencode = lenfix;
  22339. state.lenbits = 9;
  22340. state.distcode = distfix;
  22341. state.distbits = 5;
  22342. }
  22343. /*
  22344. Update the window with the last wsize (normally 32K) bytes written before
  22345. returning. If window does not exist yet, create it. This is only called
  22346. when a window is already in use, or when output has been written during this
  22347. inflate call, but the end of the deflate stream has not been reached yet.
  22348. It is also called to create a window for dictionary data when a dictionary
  22349. is loaded.
  22350. Providing output buffers larger than 32K to inflate() should provide a speed
  22351. advantage, since only the last 32K of output is copied to the sliding window
  22352. upon return from inflate(), and since all distances after the first 32K of
  22353. output will fall in the output data, making match copies simpler and faster.
  22354. The advantage may be dependent on the size of the processor's data caches.
  22355. */
  22356. function updatewindow(strm, src, end, copy) {
  22357. var dist;
  22358. var state = strm.state;
  22359. /* if it hasn't been done already, allocate space for the window */
  22360. if (state.window === null) {
  22361. state.wsize = 1 << state.wbits;
  22362. state.wnext = 0;
  22363. state.whave = 0;
  22364. state.window = new utils.Buf8(state.wsize);
  22365. }
  22366. /* copy state->wsize or less output bytes into the circular window */
  22367. if (copy >= state.wsize) {
  22368. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22369. state.wnext = 0;
  22370. state.whave = state.wsize;
  22371. }
  22372. else {
  22373. dist = state.wsize - state.wnext;
  22374. if (dist > copy) {
  22375. dist = copy;
  22376. }
  22377. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22378. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22379. copy -= dist;
  22380. if (copy) {
  22381. //zmemcpy(state->window, end - copy, copy);
  22382. utils.arraySet(state.window,src, end - copy, copy, 0);
  22383. state.wnext = copy;
  22384. state.whave = state.wsize;
  22385. }
  22386. else {
  22387. state.wnext += dist;
  22388. if (state.wnext === state.wsize) { state.wnext = 0; }
  22389. if (state.whave < state.wsize) { state.whave += dist; }
  22390. }
  22391. }
  22392. return 0;
  22393. }
  22394. function inflate(strm, flush) {
  22395. var state;
  22396. var input, output; // input/output buffers
  22397. var next; /* next input INDEX */
  22398. var put; /* next output INDEX */
  22399. var have, left; /* available input and output */
  22400. var hold; /* bit buffer */
  22401. var bits; /* bits in bit buffer */
  22402. var _in, _out; /* save starting available input and output */
  22403. var copy; /* number of stored or match bytes to copy */
  22404. var from; /* where to copy match bytes from */
  22405. var from_source;
  22406. var here = 0; /* current decoding table entry */
  22407. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22408. //var last; /* parent table entry */
  22409. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22410. var len; /* length to copy for repeats, bits to drop */
  22411. var ret; /* return code */
  22412. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22413. var opts;
  22414. var n; // temporary var for NEED_BITS
  22415. var order = /* permutation of code lengths */
  22416. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22417. if (!strm || !strm.state || !strm.output ||
  22418. (!strm.input && strm.avail_in !== 0)) {
  22419. return Z_STREAM_ERROR;
  22420. }
  22421. state = strm.state;
  22422. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22423. //--- LOAD() ---
  22424. put = strm.next_out;
  22425. output = strm.output;
  22426. left = strm.avail_out;
  22427. next = strm.next_in;
  22428. input = strm.input;
  22429. have = strm.avail_in;
  22430. hold = state.hold;
  22431. bits = state.bits;
  22432. //---
  22433. _in = have;
  22434. _out = left;
  22435. ret = Z_OK;
  22436. inf_leave: // goto emulation
  22437. for (;;) {
  22438. switch (state.mode) {
  22439. case HEAD:
  22440. if (state.wrap === 0) {
  22441. state.mode = TYPEDO;
  22442. break;
  22443. }
  22444. //=== NEEDBITS(16);
  22445. while (bits < 16) {
  22446. if (have === 0) { break inf_leave; }
  22447. have--;
  22448. hold += input[next++] << bits;
  22449. bits += 8;
  22450. }
  22451. //===//
  22452. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22453. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22454. //=== CRC2(state.check, hold);
  22455. hbuf[0] = hold & 0xff;
  22456. hbuf[1] = (hold >>> 8) & 0xff;
  22457. state.check = crc32(state.check, hbuf, 2, 0);
  22458. //===//
  22459. //=== INITBITS();
  22460. hold = 0;
  22461. bits = 0;
  22462. //===//
  22463. state.mode = FLAGS;
  22464. break;
  22465. }
  22466. state.flags = 0; /* expect zlib header */
  22467. if (state.head) {
  22468. state.head.done = false;
  22469. }
  22470. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22471. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22472. strm.msg = 'incorrect header check';
  22473. state.mode = BAD;
  22474. break;
  22475. }
  22476. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22477. strm.msg = 'unknown compression method';
  22478. state.mode = BAD;
  22479. break;
  22480. }
  22481. //--- DROPBITS(4) ---//
  22482. hold >>>= 4;
  22483. bits -= 4;
  22484. //---//
  22485. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22486. if (state.wbits === 0) {
  22487. state.wbits = len;
  22488. }
  22489. else if (len > state.wbits) {
  22490. strm.msg = 'invalid window size';
  22491. state.mode = BAD;
  22492. break;
  22493. }
  22494. state.dmax = 1 << len;
  22495. //Tracev((stderr, "inflate: zlib header ok\n"));
  22496. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22497. state.mode = hold & 0x200 ? DICTID : TYPE;
  22498. //=== INITBITS();
  22499. hold = 0;
  22500. bits = 0;
  22501. //===//
  22502. break;
  22503. case FLAGS:
  22504. //=== NEEDBITS(16); */
  22505. while (bits < 16) {
  22506. if (have === 0) { break inf_leave; }
  22507. have--;
  22508. hold += input[next++] << bits;
  22509. bits += 8;
  22510. }
  22511. //===//
  22512. state.flags = hold;
  22513. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22514. strm.msg = 'unknown compression method';
  22515. state.mode = BAD;
  22516. break;
  22517. }
  22518. if (state.flags & 0xe000) {
  22519. strm.msg = 'unknown header flags set';
  22520. state.mode = BAD;
  22521. break;
  22522. }
  22523. if (state.head) {
  22524. state.head.text = ((hold >> 8) & 1);
  22525. }
  22526. if (state.flags & 0x0200) {
  22527. //=== CRC2(state.check, hold);
  22528. hbuf[0] = hold & 0xff;
  22529. hbuf[1] = (hold >>> 8) & 0xff;
  22530. state.check = crc32(state.check, hbuf, 2, 0);
  22531. //===//
  22532. }
  22533. //=== INITBITS();
  22534. hold = 0;
  22535. bits = 0;
  22536. //===//
  22537. state.mode = TIME;
  22538. /* falls through */
  22539. case TIME:
  22540. //=== NEEDBITS(32); */
  22541. while (bits < 32) {
  22542. if (have === 0) { break inf_leave; }
  22543. have--;
  22544. hold += input[next++] << bits;
  22545. bits += 8;
  22546. }
  22547. //===//
  22548. if (state.head) {
  22549. state.head.time = hold;
  22550. }
  22551. if (state.flags & 0x0200) {
  22552. //=== CRC4(state.check, hold)
  22553. hbuf[0] = hold & 0xff;
  22554. hbuf[1] = (hold >>> 8) & 0xff;
  22555. hbuf[2] = (hold >>> 16) & 0xff;
  22556. hbuf[3] = (hold >>> 24) & 0xff;
  22557. state.check = crc32(state.check, hbuf, 4, 0);
  22558. //===
  22559. }
  22560. //=== INITBITS();
  22561. hold = 0;
  22562. bits = 0;
  22563. //===//
  22564. state.mode = OS;
  22565. /* falls through */
  22566. case OS:
  22567. //=== NEEDBITS(16); */
  22568. while (bits < 16) {
  22569. if (have === 0) { break inf_leave; }
  22570. have--;
  22571. hold += input[next++] << bits;
  22572. bits += 8;
  22573. }
  22574. //===//
  22575. if (state.head) {
  22576. state.head.xflags = (hold & 0xff);
  22577. state.head.os = (hold >> 8);
  22578. }
  22579. if (state.flags & 0x0200) {
  22580. //=== CRC2(state.check, hold);
  22581. hbuf[0] = hold & 0xff;
  22582. hbuf[1] = (hold >>> 8) & 0xff;
  22583. state.check = crc32(state.check, hbuf, 2, 0);
  22584. //===//
  22585. }
  22586. //=== INITBITS();
  22587. hold = 0;
  22588. bits = 0;
  22589. //===//
  22590. state.mode = EXLEN;
  22591. /* falls through */
  22592. case EXLEN:
  22593. if (state.flags & 0x0400) {
  22594. //=== NEEDBITS(16); */
  22595. while (bits < 16) {
  22596. if (have === 0) { break inf_leave; }
  22597. have--;
  22598. hold += input[next++] << bits;
  22599. bits += 8;
  22600. }
  22601. //===//
  22602. state.length = hold;
  22603. if (state.head) {
  22604. state.head.extra_len = hold;
  22605. }
  22606. if (state.flags & 0x0200) {
  22607. //=== CRC2(state.check, hold);
  22608. hbuf[0] = hold & 0xff;
  22609. hbuf[1] = (hold >>> 8) & 0xff;
  22610. state.check = crc32(state.check, hbuf, 2, 0);
  22611. //===//
  22612. }
  22613. //=== INITBITS();
  22614. hold = 0;
  22615. bits = 0;
  22616. //===//
  22617. }
  22618. else if (state.head) {
  22619. state.head.extra = null/*Z_NULL*/;
  22620. }
  22621. state.mode = EXTRA;
  22622. /* falls through */
  22623. case EXTRA:
  22624. if (state.flags & 0x0400) {
  22625. copy = state.length;
  22626. if (copy > have) { copy = have; }
  22627. if (copy) {
  22628. if (state.head) {
  22629. len = state.head.extra_len - state.length;
  22630. if (!state.head.extra) {
  22631. // Use untyped array for more conveniend processing later
  22632. state.head.extra = new Array(state.head.extra_len);
  22633. }
  22634. utils.arraySet(
  22635. state.head.extra,
  22636. input,
  22637. next,
  22638. // extra field is limited to 65536 bytes
  22639. // - no need for additional size check
  22640. copy,
  22641. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22642. len
  22643. );
  22644. //zmemcpy(state.head.extra + len, next,
  22645. // len + copy > state.head.extra_max ?
  22646. // state.head.extra_max - len : copy);
  22647. }
  22648. if (state.flags & 0x0200) {
  22649. state.check = crc32(state.check, input, copy, next);
  22650. }
  22651. have -= copy;
  22652. next += copy;
  22653. state.length -= copy;
  22654. }
  22655. if (state.length) { break inf_leave; }
  22656. }
  22657. state.length = 0;
  22658. state.mode = NAME;
  22659. /* falls through */
  22660. case NAME:
  22661. if (state.flags & 0x0800) {
  22662. if (have === 0) { break inf_leave; }
  22663. copy = 0;
  22664. do {
  22665. // TODO: 2 or 1 bytes?
  22666. len = input[next + copy++];
  22667. /* use constant limit because in js we should not preallocate memory */
  22668. if (state.head && len &&
  22669. (state.length < 65536 /*state.head.name_max*/)) {
  22670. state.head.name += String.fromCharCode(len);
  22671. }
  22672. } while (len && copy < have);
  22673. if (state.flags & 0x0200) {
  22674. state.check = crc32(state.check, input, copy, next);
  22675. }
  22676. have -= copy;
  22677. next += copy;
  22678. if (len) { break inf_leave; }
  22679. }
  22680. else if (state.head) {
  22681. state.head.name = null;
  22682. }
  22683. state.length = 0;
  22684. state.mode = COMMENT;
  22685. /* falls through */
  22686. case COMMENT:
  22687. if (state.flags & 0x1000) {
  22688. if (have === 0) { break inf_leave; }
  22689. copy = 0;
  22690. do {
  22691. len = input[next + copy++];
  22692. /* use constant limit because in js we should not preallocate memory */
  22693. if (state.head && len &&
  22694. (state.length < 65536 /*state.head.comm_max*/)) {
  22695. state.head.comment += String.fromCharCode(len);
  22696. }
  22697. } while (len && copy < have);
  22698. if (state.flags & 0x0200) {
  22699. state.check = crc32(state.check, input, copy, next);
  22700. }
  22701. have -= copy;
  22702. next += copy;
  22703. if (len) { break inf_leave; }
  22704. }
  22705. else if (state.head) {
  22706. state.head.comment = null;
  22707. }
  22708. state.mode = HCRC;
  22709. /* falls through */
  22710. case HCRC:
  22711. if (state.flags & 0x0200) {
  22712. //=== NEEDBITS(16); */
  22713. while (bits < 16) {
  22714. if (have === 0) { break inf_leave; }
  22715. have--;
  22716. hold += input[next++] << bits;
  22717. bits += 8;
  22718. }
  22719. //===//
  22720. if (hold !== (state.check & 0xffff)) {
  22721. strm.msg = 'header crc mismatch';
  22722. state.mode = BAD;
  22723. break;
  22724. }
  22725. //=== INITBITS();
  22726. hold = 0;
  22727. bits = 0;
  22728. //===//
  22729. }
  22730. if (state.head) {
  22731. state.head.hcrc = ((state.flags >> 9) & 1);
  22732. state.head.done = true;
  22733. }
  22734. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22735. state.mode = TYPE;
  22736. break;
  22737. case DICTID:
  22738. //=== NEEDBITS(32); */
  22739. while (bits < 32) {
  22740. if (have === 0) { break inf_leave; }
  22741. have--;
  22742. hold += input[next++] << bits;
  22743. bits += 8;
  22744. }
  22745. //===//
  22746. strm.adler = state.check = ZSWAP32(hold);
  22747. //=== INITBITS();
  22748. hold = 0;
  22749. bits = 0;
  22750. //===//
  22751. state.mode = DICT;
  22752. /* falls through */
  22753. case DICT:
  22754. if (state.havedict === 0) {
  22755. //--- RESTORE() ---
  22756. strm.next_out = put;
  22757. strm.avail_out = left;
  22758. strm.next_in = next;
  22759. strm.avail_in = have;
  22760. state.hold = hold;
  22761. state.bits = bits;
  22762. //---
  22763. return Z_NEED_DICT;
  22764. }
  22765. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22766. state.mode = TYPE;
  22767. /* falls through */
  22768. case TYPE:
  22769. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22770. /* falls through */
  22771. case TYPEDO:
  22772. if (state.last) {
  22773. //--- BYTEBITS() ---//
  22774. hold >>>= bits & 7;
  22775. bits -= bits & 7;
  22776. //---//
  22777. state.mode = CHECK;
  22778. break;
  22779. }
  22780. //=== NEEDBITS(3); */
  22781. while (bits < 3) {
  22782. if (have === 0) { break inf_leave; }
  22783. have--;
  22784. hold += input[next++] << bits;
  22785. bits += 8;
  22786. }
  22787. //===//
  22788. state.last = (hold & 0x01)/*BITS(1)*/;
  22789. //--- DROPBITS(1) ---//
  22790. hold >>>= 1;
  22791. bits -= 1;
  22792. //---//
  22793. switch ((hold & 0x03)/*BITS(2)*/) {
  22794. case 0: /* stored block */
  22795. //Tracev((stderr, "inflate: stored block%s\n",
  22796. // state.last ? " (last)" : ""));
  22797. state.mode = STORED;
  22798. break;
  22799. case 1: /* fixed block */
  22800. fixedtables(state);
  22801. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22802. // state.last ? " (last)" : ""));
  22803. state.mode = LEN_; /* decode codes */
  22804. if (flush === Z_TREES) {
  22805. //--- DROPBITS(2) ---//
  22806. hold >>>= 2;
  22807. bits -= 2;
  22808. //---//
  22809. break inf_leave;
  22810. }
  22811. break;
  22812. case 2: /* dynamic block */
  22813. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22814. // state.last ? " (last)" : ""));
  22815. state.mode = TABLE;
  22816. break;
  22817. case 3:
  22818. strm.msg = 'invalid block type';
  22819. state.mode = BAD;
  22820. }
  22821. //--- DROPBITS(2) ---//
  22822. hold >>>= 2;
  22823. bits -= 2;
  22824. //---//
  22825. break;
  22826. case STORED:
  22827. //--- BYTEBITS() ---// /* go to byte boundary */
  22828. hold >>>= bits & 7;
  22829. bits -= bits & 7;
  22830. //---//
  22831. //=== NEEDBITS(32); */
  22832. while (bits < 32) {
  22833. if (have === 0) { break inf_leave; }
  22834. have--;
  22835. hold += input[next++] << bits;
  22836. bits += 8;
  22837. }
  22838. //===//
  22839. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22840. strm.msg = 'invalid stored block lengths';
  22841. state.mode = BAD;
  22842. break;
  22843. }
  22844. state.length = hold & 0xffff;
  22845. //Tracev((stderr, "inflate: stored length %u\n",
  22846. // state.length));
  22847. //=== INITBITS();
  22848. hold = 0;
  22849. bits = 0;
  22850. //===//
  22851. state.mode = COPY_;
  22852. if (flush === Z_TREES) { break inf_leave; }
  22853. /* falls through */
  22854. case COPY_:
  22855. state.mode = COPY;
  22856. /* falls through */
  22857. case COPY:
  22858. copy = state.length;
  22859. if (copy) {
  22860. if (copy > have) { copy = have; }
  22861. if (copy > left) { copy = left; }
  22862. if (copy === 0) { break inf_leave; }
  22863. //--- zmemcpy(put, next, copy); ---
  22864. utils.arraySet(output, input, next, copy, put);
  22865. //---//
  22866. have -= copy;
  22867. next += copy;
  22868. left -= copy;
  22869. put += copy;
  22870. state.length -= copy;
  22871. break;
  22872. }
  22873. //Tracev((stderr, "inflate: stored end\n"));
  22874. state.mode = TYPE;
  22875. break;
  22876. case TABLE:
  22877. //=== NEEDBITS(14); */
  22878. while (bits < 14) {
  22879. if (have === 0) { break inf_leave; }
  22880. have--;
  22881. hold += input[next++] << bits;
  22882. bits += 8;
  22883. }
  22884. //===//
  22885. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22886. //--- DROPBITS(5) ---//
  22887. hold >>>= 5;
  22888. bits -= 5;
  22889. //---//
  22890. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22891. //--- DROPBITS(5) ---//
  22892. hold >>>= 5;
  22893. bits -= 5;
  22894. //---//
  22895. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22896. //--- DROPBITS(4) ---//
  22897. hold >>>= 4;
  22898. bits -= 4;
  22899. //---//
  22900. //#ifndef PKZIP_BUG_WORKAROUND
  22901. if (state.nlen > 286 || state.ndist > 30) {
  22902. strm.msg = 'too many length or distance symbols';
  22903. state.mode = BAD;
  22904. break;
  22905. }
  22906. //#endif
  22907. //Tracev((stderr, "inflate: table sizes ok\n"));
  22908. state.have = 0;
  22909. state.mode = LENLENS;
  22910. /* falls through */
  22911. case LENLENS:
  22912. while (state.have < state.ncode) {
  22913. //=== NEEDBITS(3);
  22914. while (bits < 3) {
  22915. if (have === 0) { break inf_leave; }
  22916. have--;
  22917. hold += input[next++] << bits;
  22918. bits += 8;
  22919. }
  22920. //===//
  22921. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22922. //--- DROPBITS(3) ---//
  22923. hold >>>= 3;
  22924. bits -= 3;
  22925. //---//
  22926. }
  22927. while (state.have < 19) {
  22928. state.lens[order[state.have++]] = 0;
  22929. }
  22930. // We have separate tables & no pointers. 2 commented lines below not needed.
  22931. //state.next = state.codes;
  22932. //state.lencode = state.next;
  22933. // Switch to use dynamic table
  22934. state.lencode = state.lendyn;
  22935. state.lenbits = 7;
  22936. opts = {bits: state.lenbits};
  22937. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22938. state.lenbits = opts.bits;
  22939. if (ret) {
  22940. strm.msg = 'invalid code lengths set';
  22941. state.mode = BAD;
  22942. break;
  22943. }
  22944. //Tracev((stderr, "inflate: code lengths ok\n"));
  22945. state.have = 0;
  22946. state.mode = CODELENS;
  22947. /* falls through */
  22948. case CODELENS:
  22949. while (state.have < state.nlen + state.ndist) {
  22950. for (;;) {
  22951. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22952. here_bits = here >>> 24;
  22953. here_op = (here >>> 16) & 0xff;
  22954. here_val = here & 0xffff;
  22955. if ((here_bits) <= bits) { break; }
  22956. //--- PULLBYTE() ---//
  22957. if (have === 0) { break inf_leave; }
  22958. have--;
  22959. hold += input[next++] << bits;
  22960. bits += 8;
  22961. //---//
  22962. }
  22963. if (here_val < 16) {
  22964. //--- DROPBITS(here.bits) ---//
  22965. hold >>>= here_bits;
  22966. bits -= here_bits;
  22967. //---//
  22968. state.lens[state.have++] = here_val;
  22969. }
  22970. else {
  22971. if (here_val === 16) {
  22972. //=== NEEDBITS(here.bits + 2);
  22973. n = here_bits + 2;
  22974. while (bits < n) {
  22975. if (have === 0) { break inf_leave; }
  22976. have--;
  22977. hold += input[next++] << bits;
  22978. bits += 8;
  22979. }
  22980. //===//
  22981. //--- DROPBITS(here.bits) ---//
  22982. hold >>>= here_bits;
  22983. bits -= here_bits;
  22984. //---//
  22985. if (state.have === 0) {
  22986. strm.msg = 'invalid bit length repeat';
  22987. state.mode = BAD;
  22988. break;
  22989. }
  22990. len = state.lens[state.have - 1];
  22991. copy = 3 + (hold & 0x03);//BITS(2);
  22992. //--- DROPBITS(2) ---//
  22993. hold >>>= 2;
  22994. bits -= 2;
  22995. //---//
  22996. }
  22997. else if (here_val === 17) {
  22998. //=== NEEDBITS(here.bits + 3);
  22999. n = here_bits + 3;
  23000. while (bits < n) {
  23001. if (have === 0) { break inf_leave; }
  23002. have--;
  23003. hold += input[next++] << bits;
  23004. bits += 8;
  23005. }
  23006. //===//
  23007. //--- DROPBITS(here.bits) ---//
  23008. hold >>>= here_bits;
  23009. bits -= here_bits;
  23010. //---//
  23011. len = 0;
  23012. copy = 3 + (hold & 0x07);//BITS(3);
  23013. //--- DROPBITS(3) ---//
  23014. hold >>>= 3;
  23015. bits -= 3;
  23016. //---//
  23017. }
  23018. else {
  23019. //=== NEEDBITS(here.bits + 7);
  23020. n = here_bits + 7;
  23021. while (bits < n) {
  23022. if (have === 0) { break inf_leave; }
  23023. have--;
  23024. hold += input[next++] << bits;
  23025. bits += 8;
  23026. }
  23027. //===//
  23028. //--- DROPBITS(here.bits) ---//
  23029. hold >>>= here_bits;
  23030. bits -= here_bits;
  23031. //---//
  23032. len = 0;
  23033. copy = 11 + (hold & 0x7f);//BITS(7);
  23034. //--- DROPBITS(7) ---//
  23035. hold >>>= 7;
  23036. bits -= 7;
  23037. //---//
  23038. }
  23039. if (state.have + copy > state.nlen + state.ndist) {
  23040. strm.msg = 'invalid bit length repeat';
  23041. state.mode = BAD;
  23042. break;
  23043. }
  23044. while (copy--) {
  23045. state.lens[state.have++] = len;
  23046. }
  23047. }
  23048. }
  23049. /* handle error breaks in while */
  23050. if (state.mode === BAD) { break; }
  23051. /* check for end-of-block code (better have one) */
  23052. if (state.lens[256] === 0) {
  23053. strm.msg = 'invalid code -- missing end-of-block';
  23054. state.mode = BAD;
  23055. break;
  23056. }
  23057. /* build code tables -- note: do not change the lenbits or distbits
  23058. values here (9 and 6) without reading the comments in inftrees.h
  23059. concerning the ENOUGH constants, which depend on those values */
  23060. state.lenbits = 9;
  23061. opts = {bits: state.lenbits};
  23062. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23063. // We have separate tables & no pointers. 2 commented lines below not needed.
  23064. // state.next_index = opts.table_index;
  23065. state.lenbits = opts.bits;
  23066. // state.lencode = state.next;
  23067. if (ret) {
  23068. strm.msg = 'invalid literal/lengths set';
  23069. state.mode = BAD;
  23070. break;
  23071. }
  23072. state.distbits = 6;
  23073. //state.distcode.copy(state.codes);
  23074. // Switch to use dynamic table
  23075. state.distcode = state.distdyn;
  23076. opts = {bits: state.distbits};
  23077. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23078. // We have separate tables & no pointers. 2 commented lines below not needed.
  23079. // state.next_index = opts.table_index;
  23080. state.distbits = opts.bits;
  23081. // state.distcode = state.next;
  23082. if (ret) {
  23083. strm.msg = 'invalid distances set';
  23084. state.mode = BAD;
  23085. break;
  23086. }
  23087. //Tracev((stderr, 'inflate: codes ok\n'));
  23088. state.mode = LEN_;
  23089. if (flush === Z_TREES) { break inf_leave; }
  23090. /* falls through */
  23091. case LEN_:
  23092. state.mode = LEN;
  23093. /* falls through */
  23094. case LEN:
  23095. if (have >= 6 && left >= 258) {
  23096. //--- RESTORE() ---
  23097. strm.next_out = put;
  23098. strm.avail_out = left;
  23099. strm.next_in = next;
  23100. strm.avail_in = have;
  23101. state.hold = hold;
  23102. state.bits = bits;
  23103. //---
  23104. inflate_fast(strm, _out);
  23105. //--- LOAD() ---
  23106. put = strm.next_out;
  23107. output = strm.output;
  23108. left = strm.avail_out;
  23109. next = strm.next_in;
  23110. input = strm.input;
  23111. have = strm.avail_in;
  23112. hold = state.hold;
  23113. bits = state.bits;
  23114. //---
  23115. if (state.mode === TYPE) {
  23116. state.back = -1;
  23117. }
  23118. break;
  23119. }
  23120. state.back = 0;
  23121. for (;;) {
  23122. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23123. here_bits = here >>> 24;
  23124. here_op = (here >>> 16) & 0xff;
  23125. here_val = here & 0xffff;
  23126. if (here_bits <= bits) { break; }
  23127. //--- PULLBYTE() ---//
  23128. if (have === 0) { break inf_leave; }
  23129. have--;
  23130. hold += input[next++] << bits;
  23131. bits += 8;
  23132. //---//
  23133. }
  23134. if (here_op && (here_op & 0xf0) === 0) {
  23135. last_bits = here_bits;
  23136. last_op = here_op;
  23137. last_val = here_val;
  23138. for (;;) {
  23139. here = state.lencode[last_val +
  23140. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23141. here_bits = here >>> 24;
  23142. here_op = (here >>> 16) & 0xff;
  23143. here_val = here & 0xffff;
  23144. if ((last_bits + here_bits) <= bits) { break; }
  23145. //--- PULLBYTE() ---//
  23146. if (have === 0) { break inf_leave; }
  23147. have--;
  23148. hold += input[next++] << bits;
  23149. bits += 8;
  23150. //---//
  23151. }
  23152. //--- DROPBITS(last.bits) ---//
  23153. hold >>>= last_bits;
  23154. bits -= last_bits;
  23155. //---//
  23156. state.back += last_bits;
  23157. }
  23158. //--- DROPBITS(here.bits) ---//
  23159. hold >>>= here_bits;
  23160. bits -= here_bits;
  23161. //---//
  23162. state.back += here_bits;
  23163. state.length = here_val;
  23164. if (here_op === 0) {
  23165. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23166. // "inflate: literal '%c'\n" :
  23167. // "inflate: literal 0x%02x\n", here.val));
  23168. state.mode = LIT;
  23169. break;
  23170. }
  23171. if (here_op & 32) {
  23172. //Tracevv((stderr, "inflate: end of block\n"));
  23173. state.back = -1;
  23174. state.mode = TYPE;
  23175. break;
  23176. }
  23177. if (here_op & 64) {
  23178. strm.msg = 'invalid literal/length code';
  23179. state.mode = BAD;
  23180. break;
  23181. }
  23182. state.extra = here_op & 15;
  23183. state.mode = LENEXT;
  23184. /* falls through */
  23185. case LENEXT:
  23186. if (state.extra) {
  23187. //=== NEEDBITS(state.extra);
  23188. n = state.extra;
  23189. while (bits < n) {
  23190. if (have === 0) { break inf_leave; }
  23191. have--;
  23192. hold += input[next++] << bits;
  23193. bits += 8;
  23194. }
  23195. //===//
  23196. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23197. //--- DROPBITS(state.extra) ---//
  23198. hold >>>= state.extra;
  23199. bits -= state.extra;
  23200. //---//
  23201. state.back += state.extra;
  23202. }
  23203. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23204. state.was = state.length;
  23205. state.mode = DIST;
  23206. /* falls through */
  23207. case DIST:
  23208. for (;;) {
  23209. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23210. here_bits = here >>> 24;
  23211. here_op = (here >>> 16) & 0xff;
  23212. here_val = here & 0xffff;
  23213. if ((here_bits) <= bits) { break; }
  23214. //--- PULLBYTE() ---//
  23215. if (have === 0) { break inf_leave; }
  23216. have--;
  23217. hold += input[next++] << bits;
  23218. bits += 8;
  23219. //---//
  23220. }
  23221. if ((here_op & 0xf0) === 0) {
  23222. last_bits = here_bits;
  23223. last_op = here_op;
  23224. last_val = here_val;
  23225. for (;;) {
  23226. here = state.distcode[last_val +
  23227. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23228. here_bits = here >>> 24;
  23229. here_op = (here >>> 16) & 0xff;
  23230. here_val = here & 0xffff;
  23231. if ((last_bits + here_bits) <= bits) { break; }
  23232. //--- PULLBYTE() ---//
  23233. if (have === 0) { break inf_leave; }
  23234. have--;
  23235. hold += input[next++] << bits;
  23236. bits += 8;
  23237. //---//
  23238. }
  23239. //--- DROPBITS(last.bits) ---//
  23240. hold >>>= last_bits;
  23241. bits -= last_bits;
  23242. //---//
  23243. state.back += last_bits;
  23244. }
  23245. //--- DROPBITS(here.bits) ---//
  23246. hold >>>= here_bits;
  23247. bits -= here_bits;
  23248. //---//
  23249. state.back += here_bits;
  23250. if (here_op & 64) {
  23251. strm.msg = 'invalid distance code';
  23252. state.mode = BAD;
  23253. break;
  23254. }
  23255. state.offset = here_val;
  23256. state.extra = (here_op) & 15;
  23257. state.mode = DISTEXT;
  23258. /* falls through */
  23259. case DISTEXT:
  23260. if (state.extra) {
  23261. //=== NEEDBITS(state.extra);
  23262. n = state.extra;
  23263. while (bits < n) {
  23264. if (have === 0) { break inf_leave; }
  23265. have--;
  23266. hold += input[next++] << bits;
  23267. bits += 8;
  23268. }
  23269. //===//
  23270. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23271. //--- DROPBITS(state.extra) ---//
  23272. hold >>>= state.extra;
  23273. bits -= state.extra;
  23274. //---//
  23275. state.back += state.extra;
  23276. }
  23277. //#ifdef INFLATE_STRICT
  23278. if (state.offset > state.dmax) {
  23279. strm.msg = 'invalid distance too far back';
  23280. state.mode = BAD;
  23281. break;
  23282. }
  23283. //#endif
  23284. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23285. state.mode = MATCH;
  23286. /* falls through */
  23287. case MATCH:
  23288. if (left === 0) { break inf_leave; }
  23289. copy = _out - left;
  23290. if (state.offset > copy) { /* copy from window */
  23291. copy = state.offset - copy;
  23292. if (copy > state.whave) {
  23293. if (state.sane) {
  23294. strm.msg = 'invalid distance too far back';
  23295. state.mode = BAD;
  23296. break;
  23297. }
  23298. // (!) This block is disabled in zlib defailts,
  23299. // don't enable it for binary compatibility
  23300. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23301. // Trace((stderr, "inflate.c too far\n"));
  23302. // copy -= state.whave;
  23303. // if (copy > state.length) { copy = state.length; }
  23304. // if (copy > left) { copy = left; }
  23305. // left -= copy;
  23306. // state.length -= copy;
  23307. // do {
  23308. // output[put++] = 0;
  23309. // } while (--copy);
  23310. // if (state.length === 0) { state.mode = LEN; }
  23311. // break;
  23312. //#endif
  23313. }
  23314. if (copy > state.wnext) {
  23315. copy -= state.wnext;
  23316. from = state.wsize - copy;
  23317. }
  23318. else {
  23319. from = state.wnext - copy;
  23320. }
  23321. if (copy > state.length) { copy = state.length; }
  23322. from_source = state.window;
  23323. }
  23324. else { /* copy from output */
  23325. from_source = output;
  23326. from = put - state.offset;
  23327. copy = state.length;
  23328. }
  23329. if (copy > left) { copy = left; }
  23330. left -= copy;
  23331. state.length -= copy;
  23332. do {
  23333. output[put++] = from_source[from++];
  23334. } while (--copy);
  23335. if (state.length === 0) { state.mode = LEN; }
  23336. break;
  23337. case LIT:
  23338. if (left === 0) { break inf_leave; }
  23339. output[put++] = state.length;
  23340. left--;
  23341. state.mode = LEN;
  23342. break;
  23343. case CHECK:
  23344. if (state.wrap) {
  23345. //=== NEEDBITS(32);
  23346. while (bits < 32) {
  23347. if (have === 0) { break inf_leave; }
  23348. have--;
  23349. // Use '|' insdead of '+' to make sure that result is signed
  23350. hold |= input[next++] << bits;
  23351. bits += 8;
  23352. }
  23353. //===//
  23354. _out -= left;
  23355. strm.total_out += _out;
  23356. state.total += _out;
  23357. if (_out) {
  23358. strm.adler = state.check =
  23359. /*UPDATE(state.check, put - _out, _out);*/
  23360. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23361. }
  23362. _out = left;
  23363. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23364. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23365. strm.msg = 'incorrect data check';
  23366. state.mode = BAD;
  23367. break;
  23368. }
  23369. //=== INITBITS();
  23370. hold = 0;
  23371. bits = 0;
  23372. //===//
  23373. //Tracev((stderr, "inflate: check matches trailer\n"));
  23374. }
  23375. state.mode = LENGTH;
  23376. /* falls through */
  23377. case LENGTH:
  23378. if (state.wrap && state.flags) {
  23379. //=== NEEDBITS(32);
  23380. while (bits < 32) {
  23381. if (have === 0) { break inf_leave; }
  23382. have--;
  23383. hold += input[next++] << bits;
  23384. bits += 8;
  23385. }
  23386. //===//
  23387. if (hold !== (state.total & 0xffffffff)) {
  23388. strm.msg = 'incorrect length check';
  23389. state.mode = BAD;
  23390. break;
  23391. }
  23392. //=== INITBITS();
  23393. hold = 0;
  23394. bits = 0;
  23395. //===//
  23396. //Tracev((stderr, "inflate: length matches trailer\n"));
  23397. }
  23398. state.mode = DONE;
  23399. /* falls through */
  23400. case DONE:
  23401. ret = Z_STREAM_END;
  23402. break inf_leave;
  23403. case BAD:
  23404. ret = Z_DATA_ERROR;
  23405. break inf_leave;
  23406. case MEM:
  23407. return Z_MEM_ERROR;
  23408. case SYNC:
  23409. /* falls through */
  23410. default:
  23411. return Z_STREAM_ERROR;
  23412. }
  23413. }
  23414. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23415. /*
  23416. Return from inflate(), updating the total counts and the check value.
  23417. If there was no progress during the inflate() call, return a buffer
  23418. error. Call updatewindow() to create and/or update the window state.
  23419. Note: a memory error from inflate() is non-recoverable.
  23420. */
  23421. //--- RESTORE() ---
  23422. strm.next_out = put;
  23423. strm.avail_out = left;
  23424. strm.next_in = next;
  23425. strm.avail_in = have;
  23426. state.hold = hold;
  23427. state.bits = bits;
  23428. //---
  23429. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23430. (state.mode < CHECK || flush !== Z_FINISH))) {
  23431. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23432. state.mode = MEM;
  23433. return Z_MEM_ERROR;
  23434. }
  23435. }
  23436. _in -= strm.avail_in;
  23437. _out -= strm.avail_out;
  23438. strm.total_in += _in;
  23439. strm.total_out += _out;
  23440. state.total += _out;
  23441. if (state.wrap && _out) {
  23442. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23443. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23444. }
  23445. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23446. (state.mode === TYPE ? 128 : 0) +
  23447. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23448. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23449. ret = Z_BUF_ERROR;
  23450. }
  23451. return ret;
  23452. }
  23453. function inflateEnd(strm) {
  23454. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23455. return Z_STREAM_ERROR;
  23456. }
  23457. var state = strm.state;
  23458. if (state.window) {
  23459. state.window = null;
  23460. }
  23461. strm.state = null;
  23462. return Z_OK;
  23463. }
  23464. function inflateGetHeader(strm, head) {
  23465. var state;
  23466. /* check state */
  23467. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23468. state = strm.state;
  23469. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23470. /* save header structure */
  23471. state.head = head;
  23472. head.done = false;
  23473. return Z_OK;
  23474. }
  23475. exports.inflateReset = inflateReset;
  23476. exports.inflateReset2 = inflateReset2;
  23477. exports.inflateResetKeep = inflateResetKeep;
  23478. exports.inflateInit = inflateInit;
  23479. exports.inflateInit2 = inflateInit2;
  23480. exports.inflate = inflate;
  23481. exports.inflateEnd = inflateEnd;
  23482. exports.inflateGetHeader = inflateGetHeader;
  23483. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23484. /* Not implemented
  23485. exports.inflateCopy = inflateCopy;
  23486. exports.inflateGetDictionary = inflateGetDictionary;
  23487. exports.inflateMark = inflateMark;
  23488. exports.inflatePrime = inflatePrime;
  23489. exports.inflateSetDictionary = inflateSetDictionary;
  23490. exports.inflateSync = inflateSync;
  23491. exports.inflateSyncPoint = inflateSyncPoint;
  23492. exports.inflateUndermine = inflateUndermine;
  23493. */
  23494. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./inffast":79,"./inftrees":81}],81:[function(require,module,exports){
  23495. 'use strict';
  23496. var utils = require('../utils/common');
  23497. var MAXBITS = 15;
  23498. var ENOUGH_LENS = 852;
  23499. var ENOUGH_DISTS = 592;
  23500. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23501. var CODES = 0;
  23502. var LENS = 1;
  23503. var DISTS = 2;
  23504. var lbase = [ /* Length codes 257..285 base */
  23505. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23506. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23507. ];
  23508. var lext = [ /* Length codes 257..285 extra */
  23509. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23510. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23511. ];
  23512. var dbase = [ /* Distance codes 0..29 base */
  23513. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23514. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23515. 8193, 12289, 16385, 24577, 0, 0
  23516. ];
  23517. var dext = [ /* Distance codes 0..29 extra */
  23518. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23519. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23520. 28, 28, 29, 29, 64, 64
  23521. ];
  23522. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23523. {
  23524. var bits = opts.bits;
  23525. //here = opts.here; /* table entry for duplication */
  23526. var len = 0; /* a code's length in bits */
  23527. var sym = 0; /* index of code symbols */
  23528. var min = 0, max = 0; /* minimum and maximum code lengths */
  23529. var root = 0; /* number of index bits for root table */
  23530. var curr = 0; /* number of index bits for current table */
  23531. var drop = 0; /* code bits to drop for sub-table */
  23532. var left = 0; /* number of prefix codes available */
  23533. var used = 0; /* code entries in table used */
  23534. var huff = 0; /* Huffman code */
  23535. var incr; /* for incrementing code, index */
  23536. var fill; /* index for replicating entries */
  23537. var low; /* low bits for current root entry */
  23538. var mask; /* mask for low root bits */
  23539. var next; /* next available space in table */
  23540. var base = null; /* base value table to use */
  23541. var base_index = 0;
  23542. // var shoextra; /* extra bits table to use */
  23543. var end; /* use base and extra for symbol > end */
  23544. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23545. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23546. var extra = null;
  23547. var extra_index = 0;
  23548. var here_bits, here_op, here_val;
  23549. /*
  23550. Process a set of code lengths to create a canonical Huffman code. The
  23551. code lengths are lens[0..codes-1]. Each length corresponds to the
  23552. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23553. symbols by length from short to long, and retaining the symbol order
  23554. for codes with equal lengths. Then the code starts with all zero bits
  23555. for the first code of the shortest length, and the codes are integer
  23556. increments for the same length, and zeros are appended as the length
  23557. increases. For the deflate format, these bits are stored backwards
  23558. from their more natural integer increment ordering, and so when the
  23559. decoding tables are built in the large loop below, the integer codes
  23560. are incremented backwards.
  23561. This routine assumes, but does not check, that all of the entries in
  23562. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23563. 1..MAXBITS is interpreted as that code length. zero means that that
  23564. symbol does not occur in this code.
  23565. The codes are sorted by computing a count of codes for each length,
  23566. creating from that a table of starting indices for each length in the
  23567. sorted table, and then entering the symbols in order in the sorted
  23568. table. The sorted table is work[], with that space being provided by
  23569. the caller.
  23570. The length counts are used for other purposes as well, i.e. finding
  23571. the minimum and maximum length codes, determining if there are any
  23572. codes at all, checking for a valid set of lengths, and looking ahead
  23573. at length counts to determine sub-table sizes when building the
  23574. decoding tables.
  23575. */
  23576. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23577. for (len = 0; len <= MAXBITS; len++) {
  23578. count[len] = 0;
  23579. }
  23580. for (sym = 0; sym < codes; sym++) {
  23581. count[lens[lens_index + sym]]++;
  23582. }
  23583. /* bound code lengths, force root to be within code lengths */
  23584. root = bits;
  23585. for (max = MAXBITS; max >= 1; max--) {
  23586. if (count[max] !== 0) { break; }
  23587. }
  23588. if (root > max) {
  23589. root = max;
  23590. }
  23591. if (max === 0) { /* no symbols to code at all */
  23592. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23593. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23594. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23595. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23596. //table.op[opts.table_index] = 64;
  23597. //table.bits[opts.table_index] = 1;
  23598. //table.val[opts.table_index++] = 0;
  23599. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23600. opts.bits = 1;
  23601. return 0; /* no symbols, but wait for decoding to report error */
  23602. }
  23603. for (min = 1; min < max; min++) {
  23604. if (count[min] !== 0) { break; }
  23605. }
  23606. if (root < min) {
  23607. root = min;
  23608. }
  23609. /* check for an over-subscribed or incomplete set of lengths */
  23610. left = 1;
  23611. for (len = 1; len <= MAXBITS; len++) {
  23612. left <<= 1;
  23613. left -= count[len];
  23614. if (left < 0) {
  23615. return -1;
  23616. } /* over-subscribed */
  23617. }
  23618. if (left > 0 && (type === CODES || max !== 1)) {
  23619. return -1; /* incomplete set */
  23620. }
  23621. /* generate offsets into symbol table for each length for sorting */
  23622. offs[1] = 0;
  23623. for (len = 1; len < MAXBITS; len++) {
  23624. offs[len + 1] = offs[len] + count[len];
  23625. }
  23626. /* sort symbols by length, by symbol order within each length */
  23627. for (sym = 0; sym < codes; sym++) {
  23628. if (lens[lens_index + sym] !== 0) {
  23629. work[offs[lens[lens_index + sym]]++] = sym;
  23630. }
  23631. }
  23632. /*
  23633. Create and fill in decoding tables. In this loop, the table being
  23634. filled is at next and has curr index bits. The code being used is huff
  23635. with length len. That code is converted to an index by dropping drop
  23636. bits off of the bottom. For codes where len is less than drop + curr,
  23637. those top drop + curr - len bits are incremented through all values to
  23638. fill the table with replicated entries.
  23639. root is the number of index bits for the root table. When len exceeds
  23640. root, sub-tables are created pointed to by the root entry with an index
  23641. of the low root bits of huff. This is saved in low to check for when a
  23642. new sub-table should be started. drop is zero when the root table is
  23643. being filled, and drop is root when sub-tables are being filled.
  23644. When a new sub-table is needed, it is necessary to look ahead in the
  23645. code lengths to determine what size sub-table is needed. The length
  23646. counts are used for this, and so count[] is decremented as codes are
  23647. entered in the tables.
  23648. used keeps track of how many table entries have been allocated from the
  23649. provided *table space. It is checked for LENS and DIST tables against
  23650. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23651. the initial root table size constants. See the comments in inftrees.h
  23652. for more information.
  23653. sym increments through all symbols, and the loop terminates when
  23654. all codes of length max, i.e. all codes, have been processed. This
  23655. routine permits incomplete codes, so another loop after this one fills
  23656. in the rest of the decoding tables with invalid code markers.
  23657. */
  23658. /* set up for code type */
  23659. // poor man optimization - use if-else instead of switch,
  23660. // to avoid deopts in old v8
  23661. if (type === CODES) {
  23662. base = extra = work; /* dummy value--not used */
  23663. end = 19;
  23664. } else if (type === LENS) {
  23665. base = lbase;
  23666. base_index -= 257;
  23667. extra = lext;
  23668. extra_index -= 257;
  23669. end = 256;
  23670. } else { /* DISTS */
  23671. base = dbase;
  23672. extra = dext;
  23673. end = -1;
  23674. }
  23675. /* initialize opts for loop */
  23676. huff = 0; /* starting code */
  23677. sym = 0; /* starting code symbol */
  23678. len = min; /* starting code length */
  23679. next = table_index; /* current table to fill in */
  23680. curr = root; /* current table index bits */
  23681. drop = 0; /* current bits to drop from code for index */
  23682. low = -1; /* trigger new sub-table when len > root */
  23683. used = 1 << root; /* use root table entries */
  23684. mask = used - 1; /* mask for comparing low */
  23685. /* check available table space */
  23686. if ((type === LENS && used > ENOUGH_LENS) ||
  23687. (type === DISTS && used > ENOUGH_DISTS)) {
  23688. return 1;
  23689. }
  23690. var i=0;
  23691. /* process all codes and make table entries */
  23692. for (;;) {
  23693. i++;
  23694. /* create table entry */
  23695. here_bits = len - drop;
  23696. if (work[sym] < end) {
  23697. here_op = 0;
  23698. here_val = work[sym];
  23699. }
  23700. else if (work[sym] > end) {
  23701. here_op = extra[extra_index + work[sym]];
  23702. here_val = base[base_index + work[sym]];
  23703. }
  23704. else {
  23705. here_op = 32 + 64; /* end of block */
  23706. here_val = 0;
  23707. }
  23708. /* replicate for those indices with low len bits equal to huff */
  23709. incr = 1 << (len - drop);
  23710. fill = 1 << curr;
  23711. min = fill; /* save offset to next table */
  23712. do {
  23713. fill -= incr;
  23714. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23715. } while (fill !== 0);
  23716. /* backwards increment the len-bit code huff */
  23717. incr = 1 << (len - 1);
  23718. while (huff & incr) {
  23719. incr >>= 1;
  23720. }
  23721. if (incr !== 0) {
  23722. huff &= incr - 1;
  23723. huff += incr;
  23724. } else {
  23725. huff = 0;
  23726. }
  23727. /* go to next symbol, update count, len */
  23728. sym++;
  23729. if (--count[len] === 0) {
  23730. if (len === max) { break; }
  23731. len = lens[lens_index + work[sym]];
  23732. }
  23733. /* create new sub-table if needed */
  23734. if (len > root && (huff & mask) !== low) {
  23735. /* if first time, transition to sub-tables */
  23736. if (drop === 0) {
  23737. drop = root;
  23738. }
  23739. /* increment past last table */
  23740. next += min; /* here min is 1 << curr */
  23741. /* determine length of next table */
  23742. curr = len - drop;
  23743. left = 1 << curr;
  23744. while (curr + drop < max) {
  23745. left -= count[curr + drop];
  23746. if (left <= 0) { break; }
  23747. curr++;
  23748. left <<= 1;
  23749. }
  23750. /* check for enough space */
  23751. used += 1 << curr;
  23752. if ((type === LENS && used > ENOUGH_LENS) ||
  23753. (type === DISTS && used > ENOUGH_DISTS)) {
  23754. return 1;
  23755. }
  23756. /* point entry in root table to sub-table */
  23757. low = huff & mask;
  23758. /*table.op[low] = curr;
  23759. table.bits[low] = root;
  23760. table.val[low] = next - opts.table_index;*/
  23761. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23762. }
  23763. }
  23764. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23765. at most one remaining entry, since if the code is incomplete, the
  23766. maximum code length that was allowed to get this far is one bit) */
  23767. if (huff !== 0) {
  23768. //table.op[next + huff] = 64; /* invalid code marker */
  23769. //table.bits[next + huff] = len - drop;
  23770. //table.val[next + huff] = 0;
  23771. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23772. }
  23773. /* set return parameters */
  23774. //opts.table_index += used;
  23775. opts.bits = root;
  23776. return 0;
  23777. };
  23778. },{"../utils/common":72}],82:[function(require,module,exports){
  23779. 'use strict';
  23780. module.exports = {
  23781. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23782. '1': 'stream end', /* Z_STREAM_END 1 */
  23783. '0': '', /* Z_OK 0 */
  23784. '-1': 'file error', /* Z_ERRNO (-1) */
  23785. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23786. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23787. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23788. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23789. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23790. };
  23791. },{}],83:[function(require,module,exports){
  23792. 'use strict';
  23793. var utils = require('../utils/common');
  23794. /* Public constants ==========================================================*/
  23795. /* ===========================================================================*/
  23796. //var Z_FILTERED = 1;
  23797. //var Z_HUFFMAN_ONLY = 2;
  23798. //var Z_RLE = 3;
  23799. var Z_FIXED = 4;
  23800. //var Z_DEFAULT_STRATEGY = 0;
  23801. /* Possible values of the data_type field (though see inflate()) */
  23802. var Z_BINARY = 0;
  23803. var Z_TEXT = 1;
  23804. //var Z_ASCII = 1; // = Z_TEXT
  23805. var Z_UNKNOWN = 2;
  23806. /*============================================================================*/
  23807. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23808. // From zutil.h
  23809. var STORED_BLOCK = 0;
  23810. var STATIC_TREES = 1;
  23811. var DYN_TREES = 2;
  23812. /* The three kinds of block type */
  23813. var MIN_MATCH = 3;
  23814. var MAX_MATCH = 258;
  23815. /* The minimum and maximum match lengths */
  23816. // From deflate.h
  23817. /* ===========================================================================
  23818. * Internal compression state.
  23819. */
  23820. var LENGTH_CODES = 29;
  23821. /* number of length codes, not counting the special END_BLOCK code */
  23822. var LITERALS = 256;
  23823. /* number of literal bytes 0..255 */
  23824. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23825. /* number of Literal or Length codes, including the END_BLOCK code */
  23826. var D_CODES = 30;
  23827. /* number of distance codes */
  23828. var BL_CODES = 19;
  23829. /* number of codes used to transfer the bit lengths */
  23830. var HEAP_SIZE = 2*L_CODES + 1;
  23831. /* maximum heap size */
  23832. var MAX_BITS = 15;
  23833. /* All codes must not exceed MAX_BITS bits */
  23834. var Buf_size = 16;
  23835. /* size of bit buffer in bi_buf */
  23836. /* ===========================================================================
  23837. * Constants
  23838. */
  23839. var MAX_BL_BITS = 7;
  23840. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23841. var END_BLOCK = 256;
  23842. /* end of block literal code */
  23843. var REP_3_6 = 16;
  23844. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23845. var REPZ_3_10 = 17;
  23846. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23847. var REPZ_11_138 = 18;
  23848. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23849. var extra_lbits = /* extra bits for each length code */
  23850. [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];
  23851. var extra_dbits = /* extra bits for each distance code */
  23852. [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];
  23853. var extra_blbits = /* extra bits for each bit length code */
  23854. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23855. var bl_order =
  23856. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23857. /* The lengths of the bit length codes are sent in order of decreasing
  23858. * probability, to avoid transmitting the lengths for unused bit length codes.
  23859. */
  23860. /* ===========================================================================
  23861. * Local data. These are initialized only once.
  23862. */
  23863. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23864. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23865. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23866. var static_ltree = new Array((L_CODES+2) * 2);
  23867. zero(static_ltree);
  23868. /* The static literal tree. Since the bit lengths are imposed, there is no
  23869. * need for the L_CODES extra codes used during heap construction. However
  23870. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23871. * below).
  23872. */
  23873. var static_dtree = new Array(D_CODES * 2);
  23874. zero(static_dtree);
  23875. /* The static distance tree. (Actually a trivial tree since all codes use
  23876. * 5 bits.)
  23877. */
  23878. var _dist_code = new Array(DIST_CODE_LEN);
  23879. zero(_dist_code);
  23880. /* Distance codes. The first 256 values correspond to the distances
  23881. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23882. * the 15 bit distances.
  23883. */
  23884. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23885. zero(_length_code);
  23886. /* length code for each normalized match length (0 == MIN_MATCH) */
  23887. var base_length = new Array(LENGTH_CODES);
  23888. zero(base_length);
  23889. /* First normalized length for each code (0 = MIN_MATCH) */
  23890. var base_dist = new Array(D_CODES);
  23891. zero(base_dist);
  23892. /* First normalized distance for each code (0 = distance of 1) */
  23893. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23894. this.static_tree = static_tree; /* static tree or NULL */
  23895. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23896. this.extra_base = extra_base; /* base index for extra_bits */
  23897. this.elems = elems; /* max number of elements in the tree */
  23898. this.max_length = max_length; /* max bit length for the codes */
  23899. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23900. this.has_stree = static_tree && static_tree.length;
  23901. };
  23902. var static_l_desc;
  23903. var static_d_desc;
  23904. var static_bl_desc;
  23905. var TreeDesc = function(dyn_tree, stat_desc) {
  23906. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23907. this.max_code = 0; /* largest code with non zero frequency */
  23908. this.stat_desc = stat_desc; /* the corresponding static tree */
  23909. };
  23910. function d_code(dist) {
  23911. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23912. }
  23913. /* ===========================================================================
  23914. * Output a short LSB first on the stream.
  23915. * IN assertion: there is enough room in pendingBuf.
  23916. */
  23917. function put_short (s, w) {
  23918. // put_byte(s, (uch)((w) & 0xff));
  23919. // put_byte(s, (uch)((ush)(w) >> 8));
  23920. s.pending_buf[s.pending++] = (w) & 0xff;
  23921. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23922. }
  23923. /* ===========================================================================
  23924. * Send a value on a given number of bits.
  23925. * IN assertion: length <= 16 and value fits in length bits.
  23926. */
  23927. function send_bits(s, value, length) {
  23928. if (s.bi_valid > (Buf_size - length)) {
  23929. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23930. put_short(s, s.bi_buf);
  23931. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23932. s.bi_valid += length - Buf_size;
  23933. } else {
  23934. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23935. s.bi_valid += length;
  23936. }
  23937. }
  23938. function send_code(s, c, tree) {
  23939. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23940. }
  23941. /* ===========================================================================
  23942. * Reverse the first len bits of a code, using straightforward code (a faster
  23943. * method would use a table)
  23944. * IN assertion: 1 <= len <= 15
  23945. */
  23946. function bi_reverse(code, len) {
  23947. var res = 0;
  23948. do {
  23949. res |= code & 1;
  23950. code >>>= 1;
  23951. res <<= 1;
  23952. } while (--len > 0);
  23953. return res >>> 1;
  23954. }
  23955. /* ===========================================================================
  23956. * Flush the bit buffer, keeping at most 7 bits in it.
  23957. */
  23958. function bi_flush(s) {
  23959. if (s.bi_valid === 16) {
  23960. put_short(s, s.bi_buf);
  23961. s.bi_buf = 0;
  23962. s.bi_valid = 0;
  23963. } else if (s.bi_valid >= 8) {
  23964. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23965. s.bi_buf >>= 8;
  23966. s.bi_valid -= 8;
  23967. }
  23968. }
  23969. /* ===========================================================================
  23970. * Compute the optimal bit lengths for a tree and update the total bit length
  23971. * for the current block.
  23972. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23973. * above are the tree nodes sorted by increasing frequency.
  23974. * OUT assertions: the field len is set to the optimal bit length, the
  23975. * array bl_count contains the frequencies for each bit length.
  23976. * The length opt_len is updated; static_len is also updated if stree is
  23977. * not null.
  23978. */
  23979. function gen_bitlen(s, desc)
  23980. // deflate_state *s;
  23981. // tree_desc *desc; /* the tree descriptor */
  23982. {
  23983. var tree = desc.dyn_tree;
  23984. var max_code = desc.max_code;
  23985. var stree = desc.stat_desc.static_tree;
  23986. var has_stree = desc.stat_desc.has_stree;
  23987. var extra = desc.stat_desc.extra_bits;
  23988. var base = desc.stat_desc.extra_base;
  23989. var max_length = desc.stat_desc.max_length;
  23990. var h; /* heap index */
  23991. var n, m; /* iterate over the tree elements */
  23992. var bits; /* bit length */
  23993. var xbits; /* extra bits */
  23994. var f; /* frequency */
  23995. var overflow = 0; /* number of elements with bit length too large */
  23996. for (bits = 0; bits <= MAX_BITS; bits++) {
  23997. s.bl_count[bits] = 0;
  23998. }
  23999. /* In a first pass, compute the optimal bit lengths (which may
  24000. * overflow in the case of the bit length tree).
  24001. */
  24002. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24003. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24004. n = s.heap[h];
  24005. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24006. if (bits > max_length) {
  24007. bits = max_length;
  24008. overflow++;
  24009. }
  24010. tree[n*2 + 1]/*.Len*/ = bits;
  24011. /* We overwrite tree[n].Dad which is no longer needed */
  24012. if (n > max_code) { continue; } /* not a leaf node */
  24013. s.bl_count[bits]++;
  24014. xbits = 0;
  24015. if (n >= base) {
  24016. xbits = extra[n-base];
  24017. }
  24018. f = tree[n * 2]/*.Freq*/;
  24019. s.opt_len += f * (bits + xbits);
  24020. if (has_stree) {
  24021. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24022. }
  24023. }
  24024. if (overflow === 0) { return; }
  24025. // Trace((stderr,"\nbit length overflow\n"));
  24026. /* This happens for example on obj2 and pic of the Calgary corpus */
  24027. /* Find the first bit length which could increase: */
  24028. do {
  24029. bits = max_length-1;
  24030. while (s.bl_count[bits] === 0) { bits--; }
  24031. s.bl_count[bits]--; /* move one leaf down the tree */
  24032. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24033. s.bl_count[max_length]--;
  24034. /* The brother of the overflow item also moves one step up,
  24035. * but this does not affect bl_count[max_length]
  24036. */
  24037. overflow -= 2;
  24038. } while (overflow > 0);
  24039. /* Now recompute all bit lengths, scanning in increasing frequency.
  24040. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24041. * lengths instead of fixing only the wrong ones. This idea is taken
  24042. * from 'ar' written by Haruhiko Okumura.)
  24043. */
  24044. for (bits = max_length; bits !== 0; bits--) {
  24045. n = s.bl_count[bits];
  24046. while (n !== 0) {
  24047. m = s.heap[--h];
  24048. if (m > max_code) { continue; }
  24049. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24050. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24051. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24052. tree[m*2 + 1]/*.Len*/ = bits;
  24053. }
  24054. n--;
  24055. }
  24056. }
  24057. }
  24058. /* ===========================================================================
  24059. * Generate the codes for a given tree and bit counts (which need not be
  24060. * optimal).
  24061. * IN assertion: the array bl_count contains the bit length statistics for
  24062. * the given tree and the field len is set for all tree elements.
  24063. * OUT assertion: the field code is set for all tree elements of non
  24064. * zero code length.
  24065. */
  24066. function gen_codes(tree, max_code, bl_count)
  24067. // ct_data *tree; /* the tree to decorate */
  24068. // int max_code; /* largest code with non zero frequency */
  24069. // ushf *bl_count; /* number of codes at each bit length */
  24070. {
  24071. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24072. var code = 0; /* running code value */
  24073. var bits; /* bit index */
  24074. var n; /* code index */
  24075. /* The distribution counts are first used to generate the code values
  24076. * without bit reversal.
  24077. */
  24078. for (bits = 1; bits <= MAX_BITS; bits++) {
  24079. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24080. }
  24081. /* Check that the bit counts in bl_count are consistent. The last code
  24082. * must be all ones.
  24083. */
  24084. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24085. // "inconsistent bit counts");
  24086. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24087. for (n = 0; n <= max_code; n++) {
  24088. var len = tree[n*2 + 1]/*.Len*/;
  24089. if (len === 0) { continue; }
  24090. /* Now reverse the bits */
  24091. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24092. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24093. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24094. }
  24095. }
  24096. /* ===========================================================================
  24097. * Initialize the various 'constant' tables.
  24098. */
  24099. function tr_static_init() {
  24100. var n; /* iterates over tree elements */
  24101. var bits; /* bit counter */
  24102. var length; /* length value */
  24103. var code; /* code value */
  24104. var dist; /* distance index */
  24105. var bl_count = new Array(MAX_BITS+1);
  24106. /* number of codes at each bit length for an optimal tree */
  24107. // do check in _tr_init()
  24108. //if (static_init_done) return;
  24109. /* For some embedded targets, global variables are not initialized: */
  24110. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24111. static_l_desc.static_tree = static_ltree;
  24112. static_l_desc.extra_bits = extra_lbits;
  24113. static_d_desc.static_tree = static_dtree;
  24114. static_d_desc.extra_bits = extra_dbits;
  24115. static_bl_desc.extra_bits = extra_blbits;
  24116. #endif*/
  24117. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24118. length = 0;
  24119. for (code = 0; code < LENGTH_CODES-1; code++) {
  24120. base_length[code] = length;
  24121. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24122. _length_code[length++] = code;
  24123. }
  24124. }
  24125. //Assert (length == 256, "tr_static_init: length != 256");
  24126. /* Note that the length 255 (match length 258) can be represented
  24127. * in two different ways: code 284 + 5 bits or code 285, so we
  24128. * overwrite length_code[255] to use the best encoding:
  24129. */
  24130. _length_code[length-1] = code;
  24131. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24132. dist = 0;
  24133. for (code = 0 ; code < 16; code++) {
  24134. base_dist[code] = dist;
  24135. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24136. _dist_code[dist++] = code;
  24137. }
  24138. }
  24139. //Assert (dist == 256, "tr_static_init: dist != 256");
  24140. dist >>= 7; /* from now on, all distances are divided by 128 */
  24141. for (; code < D_CODES; code++) {
  24142. base_dist[code] = dist << 7;
  24143. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24144. _dist_code[256 + dist++] = code;
  24145. }
  24146. }
  24147. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24148. /* Construct the codes of the static literal tree */
  24149. for (bits = 0; bits <= MAX_BITS; bits++) {
  24150. bl_count[bits] = 0;
  24151. }
  24152. n = 0;
  24153. while (n <= 143) {
  24154. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24155. n++;
  24156. bl_count[8]++;
  24157. }
  24158. while (n <= 255) {
  24159. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24160. n++;
  24161. bl_count[9]++;
  24162. }
  24163. while (n <= 279) {
  24164. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24165. n++;
  24166. bl_count[7]++;
  24167. }
  24168. while (n <= 287) {
  24169. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24170. n++;
  24171. bl_count[8]++;
  24172. }
  24173. /* Codes 286 and 287 do not exist, but we must include them in the
  24174. * tree construction to get a canonical Huffman tree (longest code
  24175. * all ones)
  24176. */
  24177. gen_codes(static_ltree, L_CODES+1, bl_count);
  24178. /* The static distance tree is trivial: */
  24179. for (n = 0; n < D_CODES; n++) {
  24180. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24181. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24182. }
  24183. // Now data ready and we can init static trees
  24184. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24185. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24186. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24187. //static_init_done = true;
  24188. }
  24189. /* ===========================================================================
  24190. * Initialize a new block.
  24191. */
  24192. function init_block(s) {
  24193. var n; /* iterates over tree elements */
  24194. /* Initialize the trees. */
  24195. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24196. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24197. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24198. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24199. s.opt_len = s.static_len = 0;
  24200. s.last_lit = s.matches = 0;
  24201. }
  24202. /* ===========================================================================
  24203. * Flush the bit buffer and align the output on a byte boundary
  24204. */
  24205. function bi_windup(s)
  24206. {
  24207. if (s.bi_valid > 8) {
  24208. put_short(s, s.bi_buf);
  24209. } else if (s.bi_valid > 0) {
  24210. //put_byte(s, (Byte)s->bi_buf);
  24211. s.pending_buf[s.pending++] = s.bi_buf;
  24212. }
  24213. s.bi_buf = 0;
  24214. s.bi_valid = 0;
  24215. }
  24216. /* ===========================================================================
  24217. * Copy a stored block, storing first the length and its
  24218. * one's complement if requested.
  24219. */
  24220. function copy_block(s, buf, len, header)
  24221. //DeflateState *s;
  24222. //charf *buf; /* the input data */
  24223. //unsigned len; /* its length */
  24224. //int header; /* true if block header must be written */
  24225. {
  24226. bi_windup(s); /* align on byte boundary */
  24227. if (header) {
  24228. put_short(s, len);
  24229. put_short(s, ~len);
  24230. }
  24231. // while (len--) {
  24232. // put_byte(s, *buf++);
  24233. // }
  24234. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24235. s.pending += len;
  24236. }
  24237. /* ===========================================================================
  24238. * Compares to subtrees, using the tree depth as tie breaker when
  24239. * the subtrees have equal frequency. This minimizes the worst case length.
  24240. */
  24241. function smaller(tree, n, m, depth) {
  24242. var _n2 = n*2;
  24243. var _m2 = m*2;
  24244. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24245. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24246. }
  24247. /* ===========================================================================
  24248. * Restore the heap property by moving down the tree starting at node k,
  24249. * exchanging a node with the smallest of its two sons if necessary, stopping
  24250. * when the heap property is re-established (each father smaller than its
  24251. * two sons).
  24252. */
  24253. function pqdownheap(s, tree, k)
  24254. // deflate_state *s;
  24255. // ct_data *tree; /* the tree to restore */
  24256. // int k; /* node to move down */
  24257. {
  24258. var v = s.heap[k];
  24259. var j = k << 1; /* left son of k */
  24260. while (j <= s.heap_len) {
  24261. /* Set j to the smallest of the two sons: */
  24262. if (j < s.heap_len &&
  24263. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24264. j++;
  24265. }
  24266. /* Exit if v is smaller than both sons */
  24267. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24268. /* Exchange v with the smallest son */
  24269. s.heap[k] = s.heap[j];
  24270. k = j;
  24271. /* And continue down the tree, setting j to the left son of k */
  24272. j <<= 1;
  24273. }
  24274. s.heap[k] = v;
  24275. }
  24276. // inlined manually
  24277. // var SMALLEST = 1;
  24278. /* ===========================================================================
  24279. * Send the block data compressed using the given Huffman trees
  24280. */
  24281. function compress_block(s, ltree, dtree)
  24282. // deflate_state *s;
  24283. // const ct_data *ltree; /* literal tree */
  24284. // const ct_data *dtree; /* distance tree */
  24285. {
  24286. var dist; /* distance of matched string */
  24287. var lc; /* match length or unmatched char (if dist == 0) */
  24288. var lx = 0; /* running index in l_buf */
  24289. var code; /* the code to send */
  24290. var extra; /* number of extra bits to send */
  24291. if (s.last_lit !== 0) {
  24292. do {
  24293. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24294. lc = s.pending_buf[s.l_buf + lx];
  24295. lx++;
  24296. if (dist === 0) {
  24297. send_code(s, lc, ltree); /* send a literal byte */
  24298. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24299. } else {
  24300. /* Here, lc is the match length - MIN_MATCH */
  24301. code = _length_code[lc];
  24302. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24303. extra = extra_lbits[code];
  24304. if (extra !== 0) {
  24305. lc -= base_length[code];
  24306. send_bits(s, lc, extra); /* send the extra length bits */
  24307. }
  24308. dist--; /* dist is now the match distance - 1 */
  24309. code = d_code(dist);
  24310. //Assert (code < D_CODES, "bad d_code");
  24311. send_code(s, code, dtree); /* send the distance code */
  24312. extra = extra_dbits[code];
  24313. if (extra !== 0) {
  24314. dist -= base_dist[code];
  24315. send_bits(s, dist, extra); /* send the extra distance bits */
  24316. }
  24317. } /* literal or match pair ? */
  24318. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24319. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24320. // "pendingBuf overflow");
  24321. } while (lx < s.last_lit);
  24322. }
  24323. send_code(s, END_BLOCK, ltree);
  24324. }
  24325. /* ===========================================================================
  24326. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24327. * Update the total bit length for the current block.
  24328. * IN assertion: the field freq is set for all tree elements.
  24329. * OUT assertions: the fields len and code are set to the optimal bit length
  24330. * and corresponding code. The length opt_len is updated; static_len is
  24331. * also updated if stree is not null. The field max_code is set.
  24332. */
  24333. function build_tree(s, desc)
  24334. // deflate_state *s;
  24335. // tree_desc *desc; /* the tree descriptor */
  24336. {
  24337. var tree = desc.dyn_tree;
  24338. var stree = desc.stat_desc.static_tree;
  24339. var has_stree = desc.stat_desc.has_stree;
  24340. var elems = desc.stat_desc.elems;
  24341. var n, m; /* iterate over heap elements */
  24342. var max_code = -1; /* largest code with non zero frequency */
  24343. var node; /* new node being created */
  24344. /* Construct the initial heap, with least frequent element in
  24345. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24346. * heap[0] is not used.
  24347. */
  24348. s.heap_len = 0;
  24349. s.heap_max = HEAP_SIZE;
  24350. for (n = 0; n < elems; n++) {
  24351. if (tree[n * 2]/*.Freq*/ !== 0) {
  24352. s.heap[++s.heap_len] = max_code = n;
  24353. s.depth[n] = 0;
  24354. } else {
  24355. tree[n*2 + 1]/*.Len*/ = 0;
  24356. }
  24357. }
  24358. /* The pkzip format requires that at least one distance code exists,
  24359. * and that at least one bit should be sent even if there is only one
  24360. * possible code. So to avoid special checks later on we force at least
  24361. * two codes of non zero frequency.
  24362. */
  24363. while (s.heap_len < 2) {
  24364. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24365. tree[node * 2]/*.Freq*/ = 1;
  24366. s.depth[node] = 0;
  24367. s.opt_len--;
  24368. if (has_stree) {
  24369. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24370. }
  24371. /* node is 0 or 1 so it does not have extra bits */
  24372. }
  24373. desc.max_code = max_code;
  24374. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24375. * establish sub-heaps of increasing lengths:
  24376. */
  24377. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24378. /* Construct the Huffman tree by repeatedly combining the least two
  24379. * frequent nodes.
  24380. */
  24381. node = elems; /* next internal node of the tree */
  24382. do {
  24383. //pqremove(s, tree, n); /* n = node of least frequency */
  24384. /*** pqremove ***/
  24385. n = s.heap[1/*SMALLEST*/];
  24386. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24387. pqdownheap(s, tree, 1/*SMALLEST*/);
  24388. /***/
  24389. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24390. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24391. s.heap[--s.heap_max] = m;
  24392. /* Create a new node father of n and m */
  24393. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24394. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24395. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24396. /* and insert the new node in the heap */
  24397. s.heap[1/*SMALLEST*/] = node++;
  24398. pqdownheap(s, tree, 1/*SMALLEST*/);
  24399. } while (s.heap_len >= 2);
  24400. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24401. /* At this point, the fields freq and dad are set. We can now
  24402. * generate the bit lengths.
  24403. */
  24404. gen_bitlen(s, desc);
  24405. /* The field len is now set, we can generate the bit codes */
  24406. gen_codes(tree, max_code, s.bl_count);
  24407. }
  24408. /* ===========================================================================
  24409. * Scan a literal or distance tree to determine the frequencies of the codes
  24410. * in the bit length tree.
  24411. */
  24412. function scan_tree(s, tree, max_code)
  24413. // deflate_state *s;
  24414. // ct_data *tree; /* the tree to be scanned */
  24415. // int max_code; /* and its largest code of non zero frequency */
  24416. {
  24417. var n; /* iterates over all tree elements */
  24418. var prevlen = -1; /* last emitted length */
  24419. var curlen; /* length of current code */
  24420. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24421. var count = 0; /* repeat count of the current code */
  24422. var max_count = 7; /* max repeat count */
  24423. var min_count = 4; /* min repeat count */
  24424. if (nextlen === 0) {
  24425. max_count = 138;
  24426. min_count = 3;
  24427. }
  24428. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24429. for (n = 0; n <= max_code; n++) {
  24430. curlen = nextlen;
  24431. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24432. if (++count < max_count && curlen === nextlen) {
  24433. continue;
  24434. } else if (count < min_count) {
  24435. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24436. } else if (curlen !== 0) {
  24437. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24438. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24439. } else if (count <= 10) {
  24440. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24441. } else {
  24442. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24443. }
  24444. count = 0;
  24445. prevlen = curlen;
  24446. if (nextlen === 0) {
  24447. max_count = 138;
  24448. min_count = 3;
  24449. } else if (curlen === nextlen) {
  24450. max_count = 6;
  24451. min_count = 3;
  24452. } else {
  24453. max_count = 7;
  24454. min_count = 4;
  24455. }
  24456. }
  24457. }
  24458. /* ===========================================================================
  24459. * Send a literal or distance tree in compressed form, using the codes in
  24460. * bl_tree.
  24461. */
  24462. function send_tree(s, tree, max_code)
  24463. // deflate_state *s;
  24464. // ct_data *tree; /* the tree to be scanned */
  24465. // int max_code; /* and its largest code of non zero frequency */
  24466. {
  24467. var n; /* iterates over all tree elements */
  24468. var prevlen = -1; /* last emitted length */
  24469. var curlen; /* length of current code */
  24470. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24471. var count = 0; /* repeat count of the current code */
  24472. var max_count = 7; /* max repeat count */
  24473. var min_count = 4; /* min repeat count */
  24474. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24475. if (nextlen === 0) {
  24476. max_count = 138;
  24477. min_count = 3;
  24478. }
  24479. for (n = 0; n <= max_code; n++) {
  24480. curlen = nextlen;
  24481. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24482. if (++count < max_count && curlen === nextlen) {
  24483. continue;
  24484. } else if (count < min_count) {
  24485. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24486. } else if (curlen !== 0) {
  24487. if (curlen !== prevlen) {
  24488. send_code(s, curlen, s.bl_tree);
  24489. count--;
  24490. }
  24491. //Assert(count >= 3 && count <= 6, " 3_6?");
  24492. send_code(s, REP_3_6, s.bl_tree);
  24493. send_bits(s, count-3, 2);
  24494. } else if (count <= 10) {
  24495. send_code(s, REPZ_3_10, s.bl_tree);
  24496. send_bits(s, count-3, 3);
  24497. } else {
  24498. send_code(s, REPZ_11_138, s.bl_tree);
  24499. send_bits(s, count-11, 7);
  24500. }
  24501. count = 0;
  24502. prevlen = curlen;
  24503. if (nextlen === 0) {
  24504. max_count = 138;
  24505. min_count = 3;
  24506. } else if (curlen === nextlen) {
  24507. max_count = 6;
  24508. min_count = 3;
  24509. } else {
  24510. max_count = 7;
  24511. min_count = 4;
  24512. }
  24513. }
  24514. }
  24515. /* ===========================================================================
  24516. * Construct the Huffman tree for the bit lengths and return the index in
  24517. * bl_order of the last bit length code to send.
  24518. */
  24519. function build_bl_tree(s) {
  24520. var max_blindex; /* index of last bit length code of non zero freq */
  24521. /* Determine the bit length frequencies for literal and distance trees */
  24522. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24523. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24524. /* Build the bit length tree: */
  24525. build_tree(s, s.bl_desc);
  24526. /* opt_len now includes the length of the tree representations, except
  24527. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24528. */
  24529. /* Determine the number of bit length codes to send. The pkzip format
  24530. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24531. * 3 but the actual value used is 4.)
  24532. */
  24533. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24534. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24535. break;
  24536. }
  24537. }
  24538. /* Update opt_len to include the bit length tree and counts */
  24539. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24540. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24541. // s->opt_len, s->static_len));
  24542. return max_blindex;
  24543. }
  24544. /* ===========================================================================
  24545. * Send the header for a block using dynamic Huffman trees: the counts, the
  24546. * lengths of the bit length codes, the literal tree and the distance tree.
  24547. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24548. */
  24549. function send_all_trees(s, lcodes, dcodes, blcodes)
  24550. // deflate_state *s;
  24551. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24552. {
  24553. var rank; /* index in bl_order */
  24554. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24555. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24556. // "too many codes");
  24557. //Tracev((stderr, "\nbl counts: "));
  24558. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24559. send_bits(s, dcodes-1, 5);
  24560. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24561. for (rank = 0; rank < blcodes; rank++) {
  24562. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24563. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24564. }
  24565. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24566. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24567. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24568. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24569. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24570. }
  24571. /* ===========================================================================
  24572. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24573. * - TEXT if the two conditions below are satisfied:
  24574. * a) There are no non-portable control characters belonging to the
  24575. * "black list" (0..6, 14..25, 28..31).
  24576. * b) There is at least one printable character belonging to the
  24577. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24578. * - BINARY otherwise.
  24579. * - The following partially-portable control characters form a
  24580. * "gray list" that is ignored in this detection algorithm:
  24581. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24582. * IN assertion: the fields Freq of dyn_ltree are set.
  24583. */
  24584. function detect_data_type(s) {
  24585. /* black_mask is the bit mask of black-listed bytes
  24586. * set bits 0..6, 14..25, and 28..31
  24587. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24588. */
  24589. var black_mask = 0xf3ffc07f;
  24590. var n;
  24591. /* Check for non-textual ("black-listed") bytes. */
  24592. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24593. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24594. return Z_BINARY;
  24595. }
  24596. }
  24597. /* Check for textual ("white-listed") bytes. */
  24598. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24599. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24600. return Z_TEXT;
  24601. }
  24602. for (n = 32; n < LITERALS; n++) {
  24603. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24604. return Z_TEXT;
  24605. }
  24606. }
  24607. /* There are no "black-listed" or "white-listed" bytes:
  24608. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24609. */
  24610. return Z_BINARY;
  24611. }
  24612. var static_init_done = false;
  24613. /* ===========================================================================
  24614. * Initialize the tree data structures for a new zlib stream.
  24615. */
  24616. function _tr_init(s)
  24617. {
  24618. if (!static_init_done) {
  24619. tr_static_init();
  24620. static_init_done = true;
  24621. }
  24622. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24623. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24624. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24625. s.bi_buf = 0;
  24626. s.bi_valid = 0;
  24627. /* Initialize the first block of the first file: */
  24628. init_block(s);
  24629. }
  24630. /* ===========================================================================
  24631. * Send a stored block
  24632. */
  24633. function _tr_stored_block(s, buf, stored_len, last)
  24634. //DeflateState *s;
  24635. //charf *buf; /* input block */
  24636. //ulg stored_len; /* length of input block */
  24637. //int last; /* one if this is the last block for a file */
  24638. {
  24639. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24640. copy_block(s, buf, stored_len, true); /* with header */
  24641. }
  24642. /* ===========================================================================
  24643. * Send one empty static block to give enough lookahead for inflate.
  24644. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24645. */
  24646. function _tr_align(s) {
  24647. send_bits(s, STATIC_TREES<<1, 3);
  24648. send_code(s, END_BLOCK, static_ltree);
  24649. bi_flush(s);
  24650. }
  24651. /* ===========================================================================
  24652. * Determine the best encoding for the current block: dynamic trees, static
  24653. * trees or store, and output the encoded block to the zip file.
  24654. */
  24655. function _tr_flush_block(s, buf, stored_len, last)
  24656. //DeflateState *s;
  24657. //charf *buf; /* input block, or NULL if too old */
  24658. //ulg stored_len; /* length of input block */
  24659. //int last; /* one if this is the last block for a file */
  24660. {
  24661. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24662. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24663. /* Build the Huffman trees unless a stored block is forced */
  24664. if (s.level > 0) {
  24665. /* Check if the file is binary or text */
  24666. if (s.strm.data_type === Z_UNKNOWN) {
  24667. s.strm.data_type = detect_data_type(s);
  24668. }
  24669. /* Construct the literal and distance trees */
  24670. build_tree(s, s.l_desc);
  24671. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24672. // s->static_len));
  24673. build_tree(s, s.d_desc);
  24674. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24675. // s->static_len));
  24676. /* At this point, opt_len and static_len are the total bit lengths of
  24677. * the compressed block data, excluding the tree representations.
  24678. */
  24679. /* Build the bit length tree for the above two trees, and get the index
  24680. * in bl_order of the last bit length code to send.
  24681. */
  24682. max_blindex = build_bl_tree(s);
  24683. /* Determine the best encoding. Compute the block lengths in bytes. */
  24684. opt_lenb = (s.opt_len+3+7) >>> 3;
  24685. static_lenb = (s.static_len+3+7) >>> 3;
  24686. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24687. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24688. // s->last_lit));
  24689. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24690. } else {
  24691. // Assert(buf != (char*)0, "lost buf");
  24692. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24693. }
  24694. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24695. /* 4: two words for the lengths */
  24696. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24697. * Otherwise we can't have processed more than WSIZE input bytes since
  24698. * the last block flush, because compression would have been
  24699. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24700. * transform a block into a stored block.
  24701. */
  24702. _tr_stored_block(s, buf, stored_len, last);
  24703. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24704. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24705. compress_block(s, static_ltree, static_dtree);
  24706. } else {
  24707. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24708. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24709. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24710. }
  24711. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24712. /* The above check is made mod 2^32, for files larger than 512 MB
  24713. * and uLong implemented on 32 bits.
  24714. */
  24715. init_block(s);
  24716. if (last) {
  24717. bi_windup(s);
  24718. }
  24719. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24720. // s->compressed_len-7*last));
  24721. }
  24722. /* ===========================================================================
  24723. * Save the match info and tally the frequency counts. Return true if
  24724. * the current block must be flushed.
  24725. */
  24726. function _tr_tally(s, dist, lc)
  24727. // deflate_state *s;
  24728. // unsigned dist; /* distance of matched string */
  24729. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24730. {
  24731. //var out_length, in_length, dcode;
  24732. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24733. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24734. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24735. s.last_lit++;
  24736. if (dist === 0) {
  24737. /* lc is the unmatched char */
  24738. s.dyn_ltree[lc*2]/*.Freq*/++;
  24739. } else {
  24740. s.matches++;
  24741. /* Here, lc is the match length - MIN_MATCH */
  24742. dist--; /* dist = match distance - 1 */
  24743. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24744. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24745. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24746. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24747. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24748. }
  24749. // (!) This block is disabled in zlib defailts,
  24750. // don't enable it for binary compatibility
  24751. //#ifdef TRUNCATE_BLOCK
  24752. // /* Try to guess if it is profitable to stop the current block here */
  24753. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24754. // /* Compute an upper bound for the compressed length */
  24755. // out_length = s.last_lit*8;
  24756. // in_length = s.strstart - s.block_start;
  24757. //
  24758. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24759. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24760. // }
  24761. // out_length >>>= 3;
  24762. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24763. // // s->last_lit, in_length, out_length,
  24764. // // 100L - out_length*100L/in_length));
  24765. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24766. // return true;
  24767. // }
  24768. // }
  24769. //#endif
  24770. return (s.last_lit === s.lit_bufsize-1);
  24771. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24772. * on 16 bit machines and because stored blocks are restricted to
  24773. * 64K-1 bytes.
  24774. */
  24775. }
  24776. exports._tr_init = _tr_init;
  24777. exports._tr_stored_block = _tr_stored_block;
  24778. exports._tr_flush_block = _tr_flush_block;
  24779. exports._tr_tally = _tr_tally;
  24780. exports._tr_align = _tr_align;
  24781. },{"../utils/common":72}],84:[function(require,module,exports){
  24782. 'use strict';
  24783. function ZStream() {
  24784. /* next input byte */
  24785. this.input = null; // JS specific, because we have no pointers
  24786. this.next_in = 0;
  24787. /* number of bytes available at input */
  24788. this.avail_in = 0;
  24789. /* total number of input bytes read so far */
  24790. this.total_in = 0;
  24791. /* next output byte should be put there */
  24792. this.output = null; // JS specific, because we have no pointers
  24793. this.next_out = 0;
  24794. /* remaining free space at output */
  24795. this.avail_out = 0;
  24796. /* total number of bytes output so far */
  24797. this.total_out = 0;
  24798. /* last error message, NULL if no error */
  24799. this.msg = ''/*Z_NULL*/;
  24800. /* not visible by applications */
  24801. this.state = null;
  24802. /* best guess about the data type: binary or text */
  24803. this.data_type = 2/*Z_UNKNOWN*/;
  24804. /* adler32 value of the uncompressed data */
  24805. this.adler = 0;
  24806. }
  24807. module.exports = ZStream;
  24808. },{}],85:[function(require,module,exports){
  24809. module.exports = require('./lib/retry');
  24810. },{"./lib/retry":86}],86:[function(require,module,exports){
  24811. var RetryOperation = require('./retry_operation');
  24812. exports.operation = function(options) {
  24813. var timeouts = exports.timeouts(options);
  24814. return new RetryOperation(timeouts);
  24815. };
  24816. exports.timeouts = function(options) {
  24817. if (options instanceof Array) {
  24818. return [].concat(options);
  24819. }
  24820. var opts = {
  24821. retries: 10,
  24822. factor: 2,
  24823. minTimeout: 1 * 1000,
  24824. maxTimeout: Infinity,
  24825. randomize: false
  24826. };
  24827. for (var key in options) {
  24828. opts[key] = options[key];
  24829. }
  24830. if (opts.minTimeout > opts.maxTimeout) {
  24831. throw new Error('minTimeout is greater than maxTimeout');
  24832. }
  24833. var timeouts = [];
  24834. for (var i = 0; i < opts.retries; i++) {
  24835. timeouts.push(this._createTimeout(i, opts));
  24836. }
  24837. // sort the array numerically ascending
  24838. timeouts.sort(function(a,b) {
  24839. return a - b;
  24840. });
  24841. return timeouts;
  24842. };
  24843. exports._createTimeout = function(attempt, opts) {
  24844. var random = (opts.randomize)
  24845. ? (Math.random() + 1)
  24846. : 1;
  24847. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  24848. timeout = Math.min(timeout, opts.maxTimeout);
  24849. return timeout;
  24850. };
  24851. },{"./retry_operation":87}],87:[function(require,module,exports){
  24852. function RetryOperation(timeouts) {
  24853. this._timeouts = timeouts;
  24854. this._fn = null;
  24855. this._errors = [];
  24856. this._attempts = 1;
  24857. this._operationTimeout = null;
  24858. this._operationTimeoutCb = null;
  24859. this._timeout = null;
  24860. }
  24861. module.exports = RetryOperation;
  24862. RetryOperation.prototype.retry = function(err) {
  24863. if (this._timeout) {
  24864. clearTimeout(this._timeout);
  24865. }
  24866. if (!err) {
  24867. return false;
  24868. }
  24869. this._errors.push(err);
  24870. var timeout = this._timeouts.shift();
  24871. if (timeout === undefined) {
  24872. return false;
  24873. }
  24874. this._attempts++;
  24875. var self = this;
  24876. setTimeout(function() {
  24877. self._fn(self._attempts);
  24878. if (self._operationTimeoutCb) {
  24879. self._timeout = setTimeout(function() {
  24880. self._operationTimeoutCb(self._attempts);
  24881. }, self._operationTimeout);
  24882. }
  24883. }, timeout);
  24884. return true;
  24885. };
  24886. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  24887. this._fn = fn;
  24888. if (timeoutOps) {
  24889. if (timeoutOps.timeout) {
  24890. this._operationTimeout = timeoutOps.timeout;
  24891. }
  24892. if (timeoutOps.cb) {
  24893. this._operationTimeoutCb = timeoutOps.cb;
  24894. }
  24895. }
  24896. this._fn(this._attempts);
  24897. var self = this;
  24898. if (this._operationTimeoutCb) {
  24899. this._timeout = setTimeout(function() {
  24900. self._operationTimeoutCb();
  24901. }, self._operationTimeout);
  24902. }
  24903. };
  24904. RetryOperation.prototype.try = function(fn) {
  24905. console.log('Using RetryOperation.try() is deprecated');
  24906. this.attempt(fn);
  24907. };
  24908. RetryOperation.prototype.start = function(fn) {
  24909. console.log('Using RetryOperation.start() is deprecated');
  24910. this.attempt(fn);
  24911. };
  24912. RetryOperation.prototype.start = RetryOperation.prototype.try;
  24913. RetryOperation.prototype.errors = function() {
  24914. return this._errors;
  24915. };
  24916. RetryOperation.prototype.attempts = function() {
  24917. return this._attempts;
  24918. };
  24919. RetryOperation.prototype.mainError = function() {
  24920. if (this._errors.length === 0) {
  24921. return null;
  24922. }
  24923. var counts = {};
  24924. var mainError = null;
  24925. var mainErrorCount = 0;
  24926. for (var i = 0; i < this._errors.length; i++) {
  24927. var error = this._errors[i];
  24928. var message = error.message;
  24929. var count = (counts[message] || 0) + 1;
  24930. counts[message] = count;
  24931. if (count >= mainErrorCount) {
  24932. mainError = error;
  24933. mainErrorCount = count;
  24934. }
  24935. }
  24936. return mainError;
  24937. };
  24938. },{}],88:[function(require,module,exports){
  24939. module.exports = function arrayEquals(array) {
  24940. // if the other array is a falsy value, return
  24941. if (!array)
  24942. return false;
  24943. // compare lengths - can save a lot of time
  24944. if (this.length != array.length)
  24945. return false;
  24946. for (var i = 0, l = this.length; i < l; i++) {
  24947. // Check if we have nested arrays
  24948. if (this[i] instanceof Array && array[i] instanceof Array) {
  24949. // recurse into the nested arrays
  24950. if (!arrayEquals.apply(this[i], [array[i]]))
  24951. return false;
  24952. } else if (this[i] != array[i]) {
  24953. // Warning - two different object instances will never be equal:
  24954. // {x:20} != {x:20}
  24955. return false;
  24956. }
  24957. }
  24958. return true;
  24959. }
  24960. },{}],89:[function(require,module,exports){
  24961. exports.Interop = require('./interop');
  24962. },{"./interop":90}],90:[function(require,module,exports){
  24963. "use strict";
  24964. var transform = require('./transform');
  24965. var arrayEquals = require('./array-equals');
  24966. function Interop() {
  24967. /**
  24968. * This map holds the most recent Unified Plan offer/answer SDP that was
  24969. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  24970. * the SDP string as values.
  24971. *
  24972. * @type {{}}
  24973. */
  24974. this.cache = {};
  24975. }
  24976. module.exports = Interop;
  24977. /**
  24978. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  24979. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  24980. * application.
  24981. *
  24982. * @param desc
  24983. * @returns {*}
  24984. */
  24985. Interop.prototype.toPlanB = function(desc) {
  24986. //#region Preliminary input validation.
  24987. if (typeof desc !== 'object' || desc === null ||
  24988. typeof desc.sdp !== 'string') {
  24989. console.warn('An empty description was passed as an argument.');
  24990. return desc;
  24991. }
  24992. // Objectify the SDP for easier manipulation.
  24993. var session = transform.parse(desc.sdp);
  24994. // If the SDP contains no media, there's nothing to transform.
  24995. if (typeof session.media === 'undefined' ||
  24996. !Array.isArray(session.media) || session.media.length === 0) {
  24997. console.warn('The description has no media.');
  24998. return desc;
  24999. }
  25000. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25001. // SDP has a video, an audio and a data "channel" at most.
  25002. if (session.media.length <= 3 && session.media.every(function(m) {
  25003. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25004. })) {
  25005. console.warn('This description does not look like Unified Plan.');
  25006. return desc;
  25007. }
  25008. //#endregion
  25009. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25010. // -> Unified Plan transformation.
  25011. this.cache[desc.type] = desc.sdp;
  25012. //#region Convert from Unified Plan to Plan B.
  25013. // We rebuild the session.media array.
  25014. var media = session.media;
  25015. session.media = [];
  25016. // Associative array that maps channel types to channel objects for fast
  25017. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25018. // obj.
  25019. var type2bl = {};
  25020. // Used to build the group:BUNDLE value after the channels construction
  25021. // loop.
  25022. var types = [];
  25023. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25024. media.forEach(function(unifiedLine) {
  25025. // rtcp-mux is required in the Plan B SDP.
  25026. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25027. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25028. unifiedLine.direction !== 'inactive') {
  25029. throw new Error('Cannot convert to Plan B because m-lines ' +
  25030. 'without the rtcp-mux attribute were found.');
  25031. }
  25032. if (unifiedLine.type === 'application') {
  25033. session.media.push(unifiedLine);
  25034. types.push(unifiedLine.mid);
  25035. return;
  25036. }
  25037. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25038. // as the channel basis.
  25039. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25040. type2bl[unifiedLine.type] = unifiedLine;
  25041. }
  25042. // Add sources to the channel and handle a=msid.
  25043. if (typeof unifiedLine.sources === 'object') {
  25044. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25045. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25046. type2bl[unifiedLine.type].sources = {};
  25047. // Assign the sources to the channel.
  25048. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25049. if (typeof unifiedLine.msid !== 'undefined') {
  25050. // In Plan B the msid is an SSRC attribute. Also, we don't
  25051. // care about the obsolete label and mslabel attributes.
  25052. //
  25053. // Note that it is not guaranteed that the unifiedLine will have
  25054. // an msid. recvonly channels in particular don't have one.
  25055. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25056. }
  25057. // NOTE ssrcs in ssrc groups will share msids, as
  25058. // draft-uberti-rtcweb-plan-00 mandates.
  25059. });
  25060. }
  25061. // Add ssrc groups to the channel.
  25062. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25063. Array.isArray(unifiedLine.ssrcGroups)) {
  25064. // Create the ssrcGroups array, if it's not defined.
  25065. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25066. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25067. type2bl[unifiedLine.type].ssrcGroups = [];
  25068. }
  25069. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25070. }
  25071. if (type2bl[unifiedLine.type] === unifiedLine) {
  25072. // Copy ICE related stuff from the principal media line.
  25073. unifiedLine.candidates = media[0].candidates;
  25074. unifiedLine.iceUfrag = media[0].iceUfrag;
  25075. unifiedLine.icePwd = media[0].icePwd;
  25076. unifiedLine.fingerprint = media[0].fingerprint;
  25077. // Plan B mids are in ['audio', 'video', 'data']
  25078. unifiedLine.mid = unifiedLine.type;
  25079. // Plan B doesn't support/need the bundle-only attribute.
  25080. delete unifiedLine.bundleOnly;
  25081. // In Plan B the msid is an SSRC attribute.
  25082. delete unifiedLine.msid;
  25083. // Used to build the group:BUNDLE value after this loop.
  25084. types.push(unifiedLine.type);
  25085. // Add the channel to the new media array.
  25086. session.media.push(unifiedLine);
  25087. }
  25088. });
  25089. // We regenerate the BUNDLE group with the new mids.
  25090. session.groups.some(function(group) {
  25091. if (group.type === 'BUNDLE') {
  25092. group.mids = types.join(' ');
  25093. return true;
  25094. }
  25095. });
  25096. // msid semantic
  25097. session.msidSemantic = {
  25098. semantic: 'WMS',
  25099. token: '*'
  25100. };
  25101. var resStr = transform.write(session);
  25102. return new RTCSessionDescription({
  25103. type: desc.type,
  25104. sdp: resStr
  25105. });
  25106. //#endregion
  25107. };
  25108. /**
  25109. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25110. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25111. * to FF.
  25112. *
  25113. * @param desc
  25114. * @returns {*}
  25115. */
  25116. Interop.prototype.toUnifiedPlan = function(desc) {
  25117. //#region Preliminary input validation.
  25118. if (typeof desc !== 'object' || desc === null ||
  25119. typeof desc.sdp !== 'string') {
  25120. console.warn('An empty description was passed as an argument.');
  25121. return desc;
  25122. }
  25123. var session = transform.parse(desc.sdp);
  25124. // If the SDP contains no media, there's nothing to transform.
  25125. if (typeof session.media === 'undefined' ||
  25126. !Array.isArray(session.media) || session.media.length === 0) {
  25127. console.warn('The description has no media.');
  25128. return desc;
  25129. }
  25130. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25131. // a video, an audio and a data "channel" at most.
  25132. if (session.media.length > 3 || !session.media.every(function(m) {
  25133. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25134. })) {
  25135. console.warn('This description does not look like Plan B.');
  25136. return desc;
  25137. }
  25138. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25139. var mids = [];
  25140. session.media.forEach(function(m) {
  25141. mids.push(m.mid);
  25142. });
  25143. var hasBundle = false;
  25144. if (typeof session.groups !== 'undefined' &&
  25145. Array.isArray(session.groups)) {
  25146. hasBundle = session.groups.every(function(g) {
  25147. return g.type !== 'BUNDLE' ||
  25148. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25149. });
  25150. }
  25151. if (!hasBundle) {
  25152. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25153. " are not bundled were found.");
  25154. }
  25155. //#endregion
  25156. //#region Convert from Plan B to Unified Plan.
  25157. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25158. // rebuild an equivalent Unified Plan offer/answer.
  25159. //
  25160. // For example, if this is a local answer (in Unified Plan style) that we
  25161. // convert to Plan B prior to handing it over to the application (the
  25162. // PeerConnection wrapper called us, for instance, after a successful
  25163. // createAnswer), we want to remember the m-line at which we've seen the
  25164. // (local) SSRC. That's because when the application wants to do call the
  25165. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25166. // Unified Plan), we need to know to which m-line to assign the (local)
  25167. // SSRC. We also need to know all the other m-lines that the original
  25168. // answer had and include them in the transformed answer as well.
  25169. //
  25170. // Another example is if this is a remote offer that we convert to Plan B
  25171. // prior to giving it to the application, we want to remember the mid at
  25172. // which we've seen the (remote) SSRC.
  25173. //
  25174. // In the iteration that follows, we use the cached Unified Plan (if it
  25175. // exists) to assign mids to ssrcs.
  25176. var cached;
  25177. if (typeof this.cache[desc.type] !== 'undefined') {
  25178. cached = transform.parse(this.cache[desc.type]);
  25179. }
  25180. // A helper map that sends mids to m-line objects. We use it later to
  25181. // rebuild the Unified Plan style session.media array.
  25182. var mid2ul = {};
  25183. session.media.forEach(function(bLine) {
  25184. if ((typeof bLine.rtcpMux !== 'string' ||
  25185. bLine.rtcpMux !== 'rtcp-mux') &&
  25186. bLine.direction !== 'inactive') {
  25187. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25188. "without the rtcp-mux attribute were found.");
  25189. }
  25190. if (bLine.type === 'application') {
  25191. mid2ul[bLine.mid] = bLine;
  25192. return;
  25193. }
  25194. // With rtcp-mux and bundle all the channels should have the same ICE
  25195. // stuff.
  25196. var sources = bLine.sources;
  25197. var ssrcGroups = bLine.ssrcGroups;
  25198. var candidates = bLine.candidates;
  25199. var iceUfrag = bLine.iceUfrag;
  25200. var icePwd = bLine.icePwd;
  25201. var fingerprint = bLine.fingerprint;
  25202. var port = bLine.port;
  25203. // We'll use the "bLine" object as a prototype for each new "mLine"
  25204. // that we create, but first we need to clean it up a bit.
  25205. delete bLine.sources;
  25206. delete bLine.ssrcGroups;
  25207. delete bLine.candidates;
  25208. delete bLine.iceUfrag;
  25209. delete bLine.icePwd;
  25210. delete bLine.fingerprint;
  25211. delete bLine.port;
  25212. delete bLine.mid;
  25213. // inverted ssrc group map
  25214. var ssrc2group = {};
  25215. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25216. ssrcGroups.forEach(function (ssrcGroup) {
  25217. // TODO(gp) find out how to receive simulcast with FF. For the
  25218. // time being, hide it.
  25219. if (ssrcGroup.semantics === 'SIM') {
  25220. return;
  25221. }
  25222. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25223. Array.isArray(ssrcGroup.ssrcs)) {
  25224. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25225. if (typeof ssrc2group[ssrc] === 'undefined') {
  25226. ssrc2group[ssrc] = [];
  25227. }
  25228. ssrc2group[ssrc].push(ssrcGroup);
  25229. });
  25230. }
  25231. });
  25232. }
  25233. // ssrc to m-line index.
  25234. var ssrc2ml = {};
  25235. if (typeof sources === 'object') {
  25236. // Explode the Plan B channel sources with one m-line per source.
  25237. Object.keys(sources).forEach(function(ssrc) {
  25238. // The (unified) m-line for this SSRC. We either create it from
  25239. // scratch or, if it's a grouped SSRC, we re-use a related
  25240. // mline. In other words, if the source is grouped with another
  25241. // source, put the two together in the same m-line.
  25242. var unifiedLine;
  25243. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25244. Array.isArray(ssrc2group[ssrc])) {
  25245. ssrc2group[ssrc].some(function (ssrcGroup) {
  25246. // ssrcGroup.ssrcs *is* an Array, no need to check
  25247. // again here.
  25248. return ssrcGroup.ssrcs.some(function (related) {
  25249. if (typeof ssrc2ml[related] === 'object') {
  25250. unifiedLine = ssrc2ml[related];
  25251. return true;
  25252. }
  25253. });
  25254. });
  25255. }
  25256. if (typeof unifiedLine === 'object') {
  25257. // the m-line already exists. Just add the source.
  25258. unifiedLine.sources[ssrc] = sources[ssrc];
  25259. delete sources[ssrc].msid;
  25260. } else {
  25261. // Use the "bLine" as a prototype for the "unifiedLine".
  25262. unifiedLine = Object.create(bLine);
  25263. ssrc2ml[ssrc] = unifiedLine;
  25264. if (typeof sources[ssrc].msid !== 'undefined') {
  25265. // Assign the msid of the source to the m-line. Note
  25266. // that it is not guaranteed that the source will have
  25267. // msid. In particular "recvonly" sources don't have an
  25268. // msid. Note that "recvonly" is a term only defined
  25269. // for m-lines.
  25270. unifiedLine.msid = sources[ssrc].msid;
  25271. delete sources[ssrc].msid;
  25272. }
  25273. // We assign one SSRC per media line.
  25274. unifiedLine.sources = {};
  25275. unifiedLine.sources[ssrc] = sources[ssrc];
  25276. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25277. // Use the cached Unified Plan SDP (if it exists) to assign
  25278. // SSRCs to mids.
  25279. if (typeof cached !== 'undefined' &&
  25280. typeof cached.media !== 'undefined' &&
  25281. Array.isArray(cached.media)) {
  25282. cached.media.forEach(function (m) {
  25283. if (typeof m.sources === 'object') {
  25284. Object.keys(m.sources).forEach(function (s) {
  25285. if (s === ssrc) {
  25286. unifiedLine.mid = m.mid;
  25287. }
  25288. });
  25289. }
  25290. });
  25291. }
  25292. if (typeof unifiedLine.mid === 'undefined') {
  25293. // If this is an SSRC that we see for the first time
  25294. // assign it a new mid. This is typically the case when
  25295. // this method is called to transform a remote
  25296. // description for the first time or when there is a
  25297. // new SSRC in the remote description because a new
  25298. // peer has joined the conference. Local SSRCs should
  25299. // have already been added to the map in the toPlanB
  25300. // method.
  25301. //
  25302. // Because FF generates answers in Unified Plan style,
  25303. // we MUST already have a cached answer with all the
  25304. // local SSRCs mapped to some m-line/mid.
  25305. if (desc.type === 'answer') {
  25306. throw new Error("An unmapped SSRC was found.");
  25307. }
  25308. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25309. }
  25310. // Include the candidates in the 1st media line.
  25311. unifiedLine.candidates = candidates;
  25312. unifiedLine.iceUfrag = iceUfrag;
  25313. unifiedLine.icePwd = icePwd;
  25314. unifiedLine.fingerprint = fingerprint;
  25315. unifiedLine.port = port;
  25316. mid2ul[unifiedLine.mid] = unifiedLine;
  25317. }
  25318. });
  25319. }
  25320. });
  25321. // Rebuild the media array in the right order and add the missing mLines
  25322. // (missing from the Plan B SDP).
  25323. session.media = [];
  25324. mids = []; // reuse
  25325. if (desc.type === 'answer') {
  25326. // The media lines in the answer must match the media lines in the
  25327. // offer. The order is important too. Here we assume that Firefox is the
  25328. // answerer, so we merely have to use the reconstructed (unified) answer
  25329. // to update the cached (unified) answer accordingly.
  25330. //
  25331. // In the general case, one would have to use the cached (unified) offer
  25332. // to find the m-lines that are missing from the reconstructed answer,
  25333. // potentially grabbing them from the cached (unified) answer. One has
  25334. // to be carefull with this approach because inactive m-lines do not
  25335. // always have an mid, making it tricky (impossible?) to find where
  25336. // exactly and which m-lines are missing from the reconstructed answer.
  25337. for (var i = 0; i < cached.media.length; i++) {
  25338. var unifiedLine = cached.media[i];
  25339. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25340. // The mid isn't in the reconstructed (unified) answer.
  25341. // This is either a (unified) m-line containing a remote
  25342. // track only, or a (unified) m-line containing a remote
  25343. // track and a local track that has been removed.
  25344. // In either case, it MUST exist in the cached
  25345. // (unified) answer.
  25346. //
  25347. // In case this is a removed local track, clean-up
  25348. // the (unified) m-line and make sure it's 'recvonly' or
  25349. // 'inactive'.
  25350. delete unifiedLine.msid;
  25351. delete unifiedLine.sources;
  25352. delete unifiedLine.ssrcGroups;
  25353. if (!unifiedLine.direction
  25354. || unifiedLine.direction === 'sendrecv')
  25355. unifiedLine.direction = 'recvonly';
  25356. if (!unifiedLine.direction
  25357. || unifiedLine.direction === 'sendonly')
  25358. unifiedLine.direction = 'inactive';
  25359. } else {
  25360. // This is an (unified) m-line/channel that contains a local
  25361. // track (sendrecv or sendonly channel) or it's a unified
  25362. // recvonly m-line/channel. In either case, since we're
  25363. // going from PlanB -> Unified Plan this m-line MUST
  25364. // exist in the cached answer.
  25365. }
  25366. session.media.push(unifiedLine);
  25367. if (typeof unifiedLine.mid === 'string') {
  25368. // inactive lines don't/may not have an mid.
  25369. mids.push(unifiedLine.mid);
  25370. }
  25371. }
  25372. } else {
  25373. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25374. // under any circumstances. If we are no longer interested in sending a
  25375. // track, we just remove the msid and ssrc attributes and set it to
  25376. // either a=recvonly (as the reofferer, we must use recvonly if the
  25377. // other side was previously sending on the m-section, but we can also
  25378. // leave the possibility open if it wasn't previously in use), or
  25379. // a=inacive.
  25380. if (typeof cached !== 'undefined' &&
  25381. typeof cached.media !== 'undefined' &&
  25382. Array.isArray(cached.media)) {
  25383. cached.media.forEach(function(unifiedLine) {
  25384. mids.push(unifiedLine.mid);
  25385. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25386. session.media.push(mid2ul[unifiedLine.mid]);
  25387. } else {
  25388. delete unifiedLine.msid;
  25389. delete unifiedLine.sources;
  25390. delete unifiedLine.ssrcGroups;
  25391. if (!unifiedLine.direction
  25392. || unifiedLine.direction === 'sendrecv')
  25393. unifiedLine.direction = 'recvonly';
  25394. if (!unifiedLine.direction
  25395. || unifiedLine.direction === 'sendonly')
  25396. unifiedLine.direction = 'inactive';
  25397. session.media.push(unifiedLine);
  25398. }
  25399. });
  25400. }
  25401. // Add all the remaining (new) m-lines of the transformed SDP.
  25402. Object.keys(mid2ul).forEach(function(mid) {
  25403. if (mids.indexOf(mid) === -1) {
  25404. mids.push(mid);
  25405. if (typeof mid2ul[mid].direction === 'recvonly') {
  25406. // This is a remote recvonly channel. Add its SSRC to the
  25407. // appropriate sendrecv or sendonly channel.
  25408. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25409. session.media.some(function (unifiedLine) {
  25410. if ((unifiedLine.direction === 'sendrecv' ||
  25411. unifiedLine.direction === 'sendonly') &&
  25412. unifiedLine.type === mid2ul[mid].type) {
  25413. // mid2ul[mid] shouldn't have any ssrc-groups
  25414. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25415. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25416. });
  25417. return true;
  25418. }
  25419. });
  25420. } else {
  25421. session.media.push(mid2ul[mid]);
  25422. }
  25423. }
  25424. });
  25425. }
  25426. // We regenerate the BUNDLE group (since we regenerated the mids)
  25427. session.groups.some(function(group) {
  25428. if (group.type === 'BUNDLE') {
  25429. group.mids = mids.join(' ');
  25430. return true;
  25431. }
  25432. });
  25433. // msid semantic
  25434. session.msidSemantic = {
  25435. semantic: 'WMS',
  25436. token: '*'
  25437. };
  25438. var resStr = transform.write(session);
  25439. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25440. // function.
  25441. this.cache[desc.type] = resStr;
  25442. return new RTCSessionDescription({
  25443. type: desc.type,
  25444. sdp: resStr
  25445. });
  25446. //#endregion
  25447. };
  25448. },{"./array-equals":88,"./transform":91}],91:[function(require,module,exports){
  25449. var transform = require('sdp-transform');
  25450. exports.write = function(session, opts) {
  25451. if (typeof session !== 'undefined' &&
  25452. typeof session.media !== 'undefined' &&
  25453. Array.isArray(session.media)) {
  25454. session.media.forEach(function (mLine) {
  25455. // expand sources to ssrcs
  25456. if (typeof mLine.sources !== 'undefined' &&
  25457. Object.keys(mLine.sources).length !== 0) {
  25458. mLine.ssrcs = [];
  25459. Object.keys(mLine.sources).forEach(function (ssrc) {
  25460. var source = mLine.sources[ssrc];
  25461. Object.keys(source).forEach(function (attribute) {
  25462. mLine.ssrcs.push({
  25463. id: ssrc,
  25464. attribute: attribute,
  25465. value: source[attribute]
  25466. });
  25467. });
  25468. });
  25469. delete mLine.sources;
  25470. }
  25471. // join ssrcs in ssrc groups
  25472. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25473. Array.isArray(mLine.ssrcGroups)) {
  25474. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25475. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25476. Array.isArray(ssrcGroup.ssrcs)) {
  25477. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25478. }
  25479. });
  25480. }
  25481. });
  25482. }
  25483. // join group mids
  25484. if (typeof session !== 'undefined' &&
  25485. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25486. session.groups.forEach(function (g) {
  25487. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25488. g.mids = g.mids.join(' ');
  25489. }
  25490. });
  25491. }
  25492. return transform.write(session, opts);
  25493. };
  25494. exports.parse = function(sdp) {
  25495. var session = transform.parse(sdp);
  25496. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25497. Array.isArray(session.media)) {
  25498. session.media.forEach(function (mLine) {
  25499. // group sources attributes by ssrc
  25500. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25501. mLine.sources = {};
  25502. mLine.ssrcs.forEach(function (ssrc) {
  25503. if (!mLine.sources[ssrc.id])
  25504. mLine.sources[ssrc.id] = {};
  25505. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25506. });
  25507. delete mLine.ssrcs;
  25508. }
  25509. // split ssrcs in ssrc groups
  25510. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25511. Array.isArray(mLine.ssrcGroups)) {
  25512. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25513. if (typeof ssrcGroup.ssrcs === 'string') {
  25514. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25515. }
  25516. });
  25517. }
  25518. });
  25519. }
  25520. // split group mids
  25521. if (typeof session !== 'undefined' &&
  25522. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25523. session.groups.forEach(function (g) {
  25524. if (typeof g.mids === 'string') {
  25525. g.mids = g.mids.split(' ');
  25526. }
  25527. });
  25528. }
  25529. return session;
  25530. };
  25531. },{"sdp-transform":93}],92:[function(require,module,exports){
  25532. var grammar = module.exports = {
  25533. v: [{
  25534. name: 'version',
  25535. reg: /^(\d*)$/
  25536. }],
  25537. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25538. // NB: sessionId will be a String in most cases because it is huge
  25539. name: 'origin',
  25540. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25541. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25542. format: "%s %s %d %s IP%d %s"
  25543. }],
  25544. // default parsing of these only (though some of these feel outdated)
  25545. s: [{ name: 'name' }],
  25546. i: [{ name: 'description' }],
  25547. u: [{ name: 'uri' }],
  25548. e: [{ name: 'email' }],
  25549. p: [{ name: 'phone' }],
  25550. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25551. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25552. //k: [{}], // outdated thing ignored
  25553. t: [{ //t=0 0
  25554. name: 'timing',
  25555. reg: /^(\d*) (\d*)/,
  25556. names: ['start', 'stop'],
  25557. format: "%d %d"
  25558. }],
  25559. c: [{ //c=IN IP4 10.47.197.26
  25560. name: 'connection',
  25561. reg: /^IN IP(\d) (\S*)/,
  25562. names: ['version', 'ip'],
  25563. format: "IN IP%d %s"
  25564. }],
  25565. b: [{ //b=AS:4000
  25566. push: 'bandwidth',
  25567. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25568. names: ['type', 'limit'],
  25569. format: "%s:%s"
  25570. }],
  25571. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25572. // NB: special - pushes to session
  25573. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25574. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25575. names: ['type', 'port', 'protocol', 'payloads'],
  25576. format: "%s %d %s %s"
  25577. }],
  25578. a: [
  25579. { //a=rtpmap:110 opus/48000/2
  25580. push: 'rtp',
  25581. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25582. names: ['payload', 'codec', 'rate', 'encoding'],
  25583. format: function (o) {
  25584. return (o.encoding) ?
  25585. "rtpmap:%d %s/%s/%s":
  25586. "rtpmap:%d %s/%s";
  25587. }
  25588. },
  25589. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25590. push: 'fmtp',
  25591. reg: /^fmtp:(\d*) (\S*)/,
  25592. names: ['payload', 'config'],
  25593. format: "fmtp:%d %s"
  25594. },
  25595. { //a=control:streamid=0
  25596. name: 'control',
  25597. reg: /^control:(.*)/,
  25598. format: "control:%s"
  25599. },
  25600. { //a=rtcp:65179 IN IP4 193.84.77.194
  25601. name: 'rtcp',
  25602. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25603. names: ['port', 'netType', 'ipVer', 'address'],
  25604. format: function (o) {
  25605. return (o.address != null) ?
  25606. "rtcp:%d %s IP%d %s":
  25607. "rtcp:%d";
  25608. }
  25609. },
  25610. { //a=rtcp-fb:98 trr-int 100
  25611. push: 'rtcpFbTrrInt',
  25612. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25613. names: ['payload', 'value'],
  25614. format: "rtcp-fb:%d trr-int %d"
  25615. },
  25616. { //a=rtcp-fb:98 nack rpsi
  25617. push: 'rtcpFb',
  25618. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25619. names: ['payload', 'type', 'subtype'],
  25620. format: function (o) {
  25621. return (o.subtype != null) ?
  25622. "rtcp-fb:%s %s %s":
  25623. "rtcp-fb:%s %s";
  25624. }
  25625. },
  25626. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25627. //a=extmap:1/recvonly URI-gps-string
  25628. push: 'ext',
  25629. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25630. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25631. format: function (o) {
  25632. return (o.config != null) ?
  25633. "extmap:%s %s %s":
  25634. "extmap:%s %s";
  25635. }
  25636. },
  25637. {
  25638. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25639. push: 'crypto',
  25640. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25641. names: ['id', 'suite', 'config', 'sessionConfig'],
  25642. format: function (o) {
  25643. return (o.sessionConfig != null) ?
  25644. "crypto:%d %s %s %s":
  25645. "crypto:%d %s %s";
  25646. }
  25647. },
  25648. { //a=setup:actpass
  25649. name: 'setup',
  25650. reg: /^setup:(\w*)/,
  25651. format: "setup:%s"
  25652. },
  25653. { //a=mid:1
  25654. name: 'mid',
  25655. reg: /^mid:([^\s]*)/,
  25656. format: "mid:%s"
  25657. },
  25658. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25659. name: 'msid',
  25660. reg: /^msid:(.*)/,
  25661. format: "msid:%s"
  25662. },
  25663. { //a=ptime:20
  25664. name: 'ptime',
  25665. reg: /^ptime:(\d*)/,
  25666. format: "ptime:%d"
  25667. },
  25668. { //a=maxptime:60
  25669. name: 'maxptime',
  25670. reg: /^maxptime:(\d*)/,
  25671. format: "maxptime:%d"
  25672. },
  25673. { //a=sendrecv
  25674. name: 'direction',
  25675. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25676. },
  25677. { //a=ice-lite
  25678. name: 'icelite',
  25679. reg: /^(ice-lite)/
  25680. },
  25681. { //a=ice-ufrag:F7gI
  25682. name: 'iceUfrag',
  25683. reg: /^ice-ufrag:(\S*)/,
  25684. format: "ice-ufrag:%s"
  25685. },
  25686. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25687. name: 'icePwd',
  25688. reg: /^ice-pwd:(\S*)/,
  25689. format: "ice-pwd:%s"
  25690. },
  25691. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25692. name: 'fingerprint',
  25693. reg: /^fingerprint:(\S*) (\S*)/,
  25694. names: ['type', 'hash'],
  25695. format: "fingerprint:%s %s"
  25696. },
  25697. {
  25698. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25699. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25700. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25701. push:'candidates',
  25702. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  25703. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  25704. format: function (o) {
  25705. var str = "candidate:%s %d %s %d %s %d typ %s";
  25706. // NB: candidate has two optional chunks, so %void middle one if it's missing
  25707. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25708. if (o.generation != null) {
  25709. str += " generation %d";
  25710. }
  25711. return str;
  25712. }
  25713. },
  25714. { //a=end-of-candidates (keep after the candidates line for readability)
  25715. name: 'endOfCandidates',
  25716. reg: /^(end-of-candidates)/
  25717. },
  25718. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25719. name: 'remoteCandidates',
  25720. reg: /^remote-candidates:(.*)/,
  25721. format: "remote-candidates:%s"
  25722. },
  25723. { //a=ice-options:google-ice
  25724. name: 'iceOptions',
  25725. reg: /^ice-options:(\S*)/,
  25726. format: "ice-options:%s"
  25727. },
  25728. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25729. push: "ssrcs",
  25730. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25731. names: ['id', 'attribute', 'value'],
  25732. format: "ssrc:%d %s:%s"
  25733. },
  25734. { //a=ssrc-group:FEC 1 2
  25735. push: "ssrcGroups",
  25736. reg: /^ssrc-group:(\w*) (.*)/,
  25737. names: ['semantics', 'ssrcs'],
  25738. format: "ssrc-group:%s %s"
  25739. },
  25740. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25741. name: "msidSemantic",
  25742. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25743. names: ['semantic', 'token'],
  25744. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25745. },
  25746. { //a=group:BUNDLE audio video
  25747. push: 'groups',
  25748. reg: /^group:(\w*) (.*)/,
  25749. names: ['type', 'mids'],
  25750. format: "group:%s %s"
  25751. },
  25752. { //a=rtcp-mux
  25753. name: 'rtcpMux',
  25754. reg: /^(rtcp-mux)/
  25755. },
  25756. { //a=rtcp-rsize
  25757. name: 'rtcpRsize',
  25758. reg: /^(rtcp-rsize)/
  25759. },
  25760. { // any a= that we don't understand is kepts verbatim on media.invalid
  25761. push: 'invalid',
  25762. names: ["value"]
  25763. }
  25764. ]
  25765. };
  25766. // set sensible defaults to avoid polluting the grammar with boring details
  25767. Object.keys(grammar).forEach(function (key) {
  25768. var objs = grammar[key];
  25769. objs.forEach(function (obj) {
  25770. if (!obj.reg) {
  25771. obj.reg = /(.*)/;
  25772. }
  25773. if (!obj.format) {
  25774. obj.format = "%s";
  25775. }
  25776. });
  25777. });
  25778. },{}],93:[function(require,module,exports){
  25779. var parser = require('./parser');
  25780. var writer = require('./writer');
  25781. exports.write = writer;
  25782. exports.parse = parser.parse;
  25783. exports.parseFmtpConfig = parser.parseFmtpConfig;
  25784. exports.parsePayloads = parser.parsePayloads;
  25785. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  25786. },{"./parser":94,"./writer":95}],94:[function(require,module,exports){
  25787. var toIntIfInt = function (v) {
  25788. return String(Number(v)) === v ? Number(v) : v;
  25789. };
  25790. var attachProperties = function (match, location, names, rawName) {
  25791. if (rawName && !names) {
  25792. location[rawName] = toIntIfInt(match[1]);
  25793. }
  25794. else {
  25795. for (var i = 0; i < names.length; i += 1) {
  25796. if (match[i+1] != null) {
  25797. location[names[i]] = toIntIfInt(match[i+1]);
  25798. }
  25799. }
  25800. }
  25801. };
  25802. var parseReg = function (obj, location, content) {
  25803. var needsBlank = obj.name && obj.names;
  25804. if (obj.push && !location[obj.push]) {
  25805. location[obj.push] = [];
  25806. }
  25807. else if (needsBlank && !location[obj.name]) {
  25808. location[obj.name] = {};
  25809. }
  25810. var keyLocation = obj.push ?
  25811. {} : // blank object that will be pushed
  25812. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  25813. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  25814. if (obj.push) {
  25815. location[obj.push].push(keyLocation);
  25816. }
  25817. };
  25818. var grammar = require('./grammar');
  25819. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  25820. exports.parse = function (sdp) {
  25821. var session = {}
  25822. , media = []
  25823. , location = session; // points at where properties go under (one of the above)
  25824. // parse lines we understand
  25825. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  25826. var type = l[0];
  25827. var content = l.slice(2);
  25828. if (type === 'm') {
  25829. media.push({rtp: [], fmtp: []});
  25830. location = media[media.length-1]; // point at latest media line
  25831. }
  25832. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  25833. var obj = grammar[type][j];
  25834. if (obj.reg.test(content)) {
  25835. return parseReg(obj, location, content);
  25836. }
  25837. }
  25838. });
  25839. session.media = media; // link it up
  25840. return session;
  25841. };
  25842. var fmtpReducer = function (acc, expr) {
  25843. var s = expr.split('=');
  25844. if (s.length === 2) {
  25845. acc[s[0]] = toIntIfInt(s[1]);
  25846. }
  25847. return acc;
  25848. };
  25849. exports.parseFmtpConfig = function (str) {
  25850. return str.split(';').reduce(fmtpReducer, {});
  25851. };
  25852. exports.parsePayloads = function (str) {
  25853. return str.split(' ').map(Number);
  25854. };
  25855. exports.parseRemoteCandidates = function (str) {
  25856. var candidates = [];
  25857. var parts = str.split(' ').map(toIntIfInt);
  25858. for (var i = 0; i < parts.length; i += 3) {
  25859. candidates.push({
  25860. component: parts[i],
  25861. ip: parts[i + 1],
  25862. port: parts[i + 2]
  25863. });
  25864. }
  25865. return candidates;
  25866. };
  25867. },{"./grammar":92}],95:[function(require,module,exports){
  25868. var grammar = require('./grammar');
  25869. // customized util.format - discards excess arguments and can void middle ones
  25870. var formatRegExp = /%[sdv%]/g;
  25871. var format = function (formatStr) {
  25872. var i = 1;
  25873. var args = arguments;
  25874. var len = args.length;
  25875. return formatStr.replace(formatRegExp, function (x) {
  25876. if (i >= len) {
  25877. return x; // missing argument
  25878. }
  25879. var arg = args[i];
  25880. i += 1;
  25881. switch (x) {
  25882. case '%%':
  25883. return '%';
  25884. case '%s':
  25885. return String(arg);
  25886. case '%d':
  25887. return Number(arg);
  25888. case '%v':
  25889. return '';
  25890. }
  25891. });
  25892. // NB: we discard excess arguments - they are typically undefined from makeLine
  25893. };
  25894. var makeLine = function (type, obj, location) {
  25895. var str = obj.format instanceof Function ?
  25896. (obj.format(obj.push ? location : location[obj.name])) :
  25897. obj.format;
  25898. var args = [type + '=' + str];
  25899. if (obj.names) {
  25900. for (var i = 0; i < obj.names.length; i += 1) {
  25901. var n = obj.names[i];
  25902. if (obj.name) {
  25903. args.push(location[obj.name][n]);
  25904. }
  25905. else { // for mLine and push attributes
  25906. args.push(location[obj.names[i]]);
  25907. }
  25908. }
  25909. }
  25910. else {
  25911. args.push(location[obj.name]);
  25912. }
  25913. return format.apply(null, args);
  25914. };
  25915. // RFC specified order
  25916. // TODO: extend this with all the rest
  25917. var defaultOuterOrder = [
  25918. 'v', 'o', 's', 'i',
  25919. 'u', 'e', 'p', 'c',
  25920. 'b', 't', 'r', 'z', 'a'
  25921. ];
  25922. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  25923. module.exports = function (session, opts) {
  25924. opts = opts || {};
  25925. // ensure certain properties exist
  25926. if (session.version == null) {
  25927. session.version = 0; // "v=0" must be there (only defined version atm)
  25928. }
  25929. if (session.name == null) {
  25930. session.name = " "; // "s= " must be there if no meaningful name set
  25931. }
  25932. session.media.forEach(function (mLine) {
  25933. if (mLine.payloads == null) {
  25934. mLine.payloads = "";
  25935. }
  25936. });
  25937. var outerOrder = opts.outerOrder || defaultOuterOrder;
  25938. var innerOrder = opts.innerOrder || defaultInnerOrder;
  25939. var sdp = [];
  25940. // loop through outerOrder for matching properties on session
  25941. outerOrder.forEach(function (type) {
  25942. grammar[type].forEach(function (obj) {
  25943. if (obj.name in session && session[obj.name] != null) {
  25944. sdp.push(makeLine(type, obj, session));
  25945. }
  25946. else if (obj.push in session && session[obj.push] != null) {
  25947. session[obj.push].forEach(function (el) {
  25948. sdp.push(makeLine(type, obj, el));
  25949. });
  25950. }
  25951. });
  25952. });
  25953. // then for each media line, follow the innerOrder
  25954. session.media.forEach(function (mLine) {
  25955. sdp.push(makeLine('m', grammar.m[0], mLine));
  25956. innerOrder.forEach(function (type) {
  25957. grammar[type].forEach(function (obj) {
  25958. if (obj.name in mLine && mLine[obj.name] != null) {
  25959. sdp.push(makeLine(type, obj, mLine));
  25960. }
  25961. else if (obj.push in mLine && mLine[obj.push] != null) {
  25962. mLine[obj.push].forEach(function (el) {
  25963. sdp.push(makeLine(type, obj, el));
  25964. });
  25965. }
  25966. });
  25967. });
  25968. });
  25969. return sdp.join('\r\n') + '\r\n';
  25970. };
  25971. },{"./grammar":92}],96:[function(require,module,exports){
  25972. var transform = require('sdp-transform');
  25973. var transformUtils = require('./transform-utils');
  25974. var parseSsrcs = transformUtils.parseSsrcs;
  25975. var writeSsrcs = transformUtils.writeSsrcs;
  25976. //region Constants
  25977. var DEFAULT_NUM_OF_LAYERS = 3;
  25978. //endregion
  25979. //region Ctor
  25980. function Simulcast(options) {
  25981. this.options = options ? options : {};
  25982. if (!this.options.numOfLayers) {
  25983. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  25984. }
  25985. this.layers = [];
  25986. }
  25987. //endregion
  25988. //region Stateless private utility functions
  25989. /**
  25990. * Returns a random integer between min (included) and max (excluded)
  25991. * Using Math.round() gives a non-uniform distribution!
  25992. * @returns {number}
  25993. */
  25994. function generateSSRC() {
  25995. var min = 0, max = 0xffffffff;
  25996. return Math.floor(Math.random() * (max - min)) + min;
  25997. };
  25998. function processVideo(session, action) {
  25999. if (session == null || !Array.isArray(session.media)) {
  26000. return;
  26001. }
  26002. session.media.forEach(function (mLine) {
  26003. if (mLine.type === 'video') {
  26004. action(mLine);
  26005. }
  26006. });
  26007. }
  26008. function validateDescription(desc)
  26009. {
  26010. return desc && desc != null
  26011. && desc.type && desc.type != ''
  26012. && desc.sdp && desc.sdp != '';
  26013. }
  26014. function explodeRemoteSimulcast(mLine) {
  26015. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26016. return;
  26017. }
  26018. var sources = parseSsrcs(mLine);
  26019. var order = [];
  26020. // Find the SIM group and explode its sources.
  26021. var j = mLine.ssrcGroups.length;
  26022. while (j--) {
  26023. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26024. continue;
  26025. }
  26026. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26027. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26028. var ssrc = simulcastSsrcs[i];
  26029. order.push(ssrc);
  26030. var parts = sources[ssrc].msid.split(' ');
  26031. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26032. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26033. // Remove all the groups that this SSRC participates in.
  26034. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26035. if (relatedGroup.semantics === 'SIM') {
  26036. return;
  26037. }
  26038. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26039. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26040. return;
  26041. }
  26042. // Nuke all the related SSRCs.
  26043. relatedSsrcs.forEach(function (relatedSSRC) {
  26044. sources[relatedSSRC].msid = sources[ssrc].msid;
  26045. sources[relatedSSRC].cname = sources[ssrc].cname;
  26046. if (relatedSSRC !== ssrc) {
  26047. order.push(relatedSSRC);
  26048. }
  26049. });
  26050. // Schedule the related group for nuking.
  26051. })
  26052. }
  26053. mLine.ssrcs = writeSsrcs(sources, order);
  26054. mLine.ssrcGroups.splice(j, 1);
  26055. };
  26056. }
  26057. function squeezeRemoteSimulcast(mLine) {
  26058. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26059. return;
  26060. }
  26061. var sources = parseSsrcs(mLine);
  26062. // Find the SIM group and nuke it.
  26063. mLine.ssrcGroups.some(function (simulcastGroup) {
  26064. if (simulcastGroup.semantics !== 'SIM') {
  26065. return false;
  26066. }
  26067. // Schedule the SIM group for nuking.
  26068. simulcastGroup.nuke = true;
  26069. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26070. // Nuke all the higher layer SSRCs.
  26071. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26072. var ssrc = simulcastSsrcs[i];
  26073. delete sources[ssrc];
  26074. // Remove all the groups that this SSRC participates in.
  26075. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26076. if (relatedGroup.semantics === 'SIM') {
  26077. return;
  26078. }
  26079. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26080. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26081. return;
  26082. }
  26083. // Nuke all the related SSRCs.
  26084. relatedSsrcs.forEach(function (relatedSSRC) {
  26085. delete sources[relatedSSRC];
  26086. });
  26087. // Schedule the related group for nuking.
  26088. relatedGroup.nuke = true;
  26089. })
  26090. }
  26091. return true;
  26092. });
  26093. mLine.ssrcs = writeSsrcs(sources);
  26094. // Nuke all the scheduled groups.
  26095. var i = mLine.ssrcGroups.length;
  26096. while (i--) {
  26097. if (mLine.ssrcGroups[i].nuke) {
  26098. mLine.ssrcGroups.splice(i, 1);
  26099. }
  26100. }
  26101. }
  26102. function removeGoogConference(mLine) {
  26103. if (!mLine || !Array.isArray(mLine.invalid)) {
  26104. return;
  26105. }
  26106. var i = mLine.invalid.length;
  26107. while (i--) {
  26108. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26109. mLine.invalid.splice(i, 1);
  26110. }
  26111. }
  26112. }
  26113. function assertGoogConference(mLine) {
  26114. if (!mLine) {
  26115. return;
  26116. }
  26117. if (!Array.isArray(mLine.invalid)) {
  26118. mLine.invalid = [];
  26119. }
  26120. if (!mLine.invalid.some(
  26121. function (i) { return i.value === 'x-google-flag:conference' })) {
  26122. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26123. }
  26124. }
  26125. //endregion
  26126. //region "Private" functions
  26127. /**
  26128. *
  26129. * @param mLine
  26130. * @private
  26131. */
  26132. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26133. if (!mLine || mLine.type !== 'video') {
  26134. return;
  26135. }
  26136. var sources = parseSsrcs(mLine);
  26137. if (Object.keys(sources).length === 0) {
  26138. // no sources, disable simulcast.
  26139. if (this.layers.length !== 0) {
  26140. this.layers = [];
  26141. }
  26142. return;
  26143. }
  26144. // find the base layer (we'll reuse its msid and cname).
  26145. var baseLayerSSRC = Object.keys(sources)[0];
  26146. var baseLayer = sources[baseLayerSSRC];
  26147. // todo(gp) handle screen sharing.
  26148. // check if base CNAME has changed and reinitialise layers.
  26149. if (this.layers.length > 0
  26150. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26151. this.layers = [];
  26152. }
  26153. // (re)initialise layers
  26154. if (this.layers.length < 1) {
  26155. // first push the base layer.
  26156. this.layers.push({
  26157. ssrc: baseLayerSSRC,
  26158. msid: baseLayer.msid,
  26159. cname: baseLayer.cname
  26160. });
  26161. var rtx = false; // RFC 4588
  26162. if (Array.isArray(mLine.rtp)) {
  26163. rtx = mLine.rtp.some(
  26164. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26165. }
  26166. if (rtx) {
  26167. this.layers[0].rtx = generateSSRC();
  26168. }
  26169. // now push additional layers.
  26170. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26171. var layer = { ssrc: generateSSRC() };
  26172. if (rtx) {
  26173. layer.rtx = generateSSRC();
  26174. }
  26175. this.layers.push(layer);
  26176. }
  26177. }
  26178. };
  26179. /**
  26180. *
  26181. * @param mLine
  26182. * @private
  26183. */
  26184. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26185. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26186. var sources = {};
  26187. var msid = this.layers[0].msid;
  26188. var cname = this.layers[0].cname;
  26189. var simulcastSsrcs = [];
  26190. var ssrcGroups = [];
  26191. for (var i = 0; i < this.layers.length; i++) {
  26192. var layer = this.layers[i];
  26193. sources[layer.ssrc] = { msid: msid, cname: cname };
  26194. simulcastSsrcs.push(layer.ssrc);
  26195. if (layer.rtx) {
  26196. sources[layer.rtx] = {
  26197. msid: msid,
  26198. cname: cname
  26199. }
  26200. ssrcGroups.push({
  26201. semantics: 'FID',
  26202. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26203. });
  26204. }
  26205. }
  26206. ssrcGroups.push({
  26207. semantics: 'SIM',
  26208. ssrcs: simulcastSsrcs.join(' ')
  26209. });
  26210. mLine.ssrcGroups = ssrcGroups;
  26211. mLine.ssrcs = writeSsrcs(sources);
  26212. }
  26213. }
  26214. //endregion
  26215. //region "Public" functions
  26216. Simulcast.prototype.isSupported = function () {
  26217. return window.chrome;
  26218. // TODO this needs improvements. For example I doubt that Chrome in Android
  26219. // has simulcast support. Also, only recent versions of Chromium have native
  26220. // simulcast support.
  26221. }
  26222. /**
  26223. *
  26224. * @param desc
  26225. * @returns {RTCSessionDescription}
  26226. */
  26227. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26228. if (!validateDescription(desc)) {
  26229. return desc;
  26230. }
  26231. var session = transform.parse(desc.sdp);
  26232. var self = this;
  26233. processVideo(session, function (mLine) {
  26234. // Handle simulcast reception.
  26235. if (self.options.explodeRemoteSimulcast) {
  26236. explodeRemoteSimulcast(mLine);
  26237. } else {
  26238. squeezeRemoteSimulcast(mLine);
  26239. }
  26240. // If native simulcast is enabled, we must append the x-goog-conference
  26241. // attribute to the SDP.
  26242. if (self.layers.length < 1) {
  26243. removeGoogConference(mLine);
  26244. } else {
  26245. assertGoogConference(mLine);
  26246. }
  26247. });
  26248. return new RTCSessionDescription({
  26249. type: desc.type,
  26250. sdp: transform.write(session)
  26251. });
  26252. };
  26253. /**
  26254. *
  26255. * @param desc
  26256. * @returns {RTCSessionDescription}
  26257. */
  26258. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26259. if (!validateDescription(desc) || !this.isSupported()) {
  26260. return desc;
  26261. }
  26262. var session = transform.parse(desc.sdp);
  26263. var self = this;
  26264. processVideo(session, function (mLine) {
  26265. // Initialize native simulcast layers, if not already done.
  26266. self._maybeInitializeLayers(mLine);
  26267. // Update the SDP with the simulcast layers.
  26268. self._restoreSimulcastView(mLine);
  26269. });
  26270. return new RTCSessionDescription({
  26271. type: desc.type,
  26272. sdp: transform.write(session)
  26273. });
  26274. };
  26275. //endregion
  26276. module.exports = Simulcast;
  26277. },{"./transform-utils":97,"sdp-transform":99}],97:[function(require,module,exports){
  26278. exports.writeSsrcs = function(sources, order) {
  26279. var ssrcs = [];
  26280. // expand sources to ssrcs
  26281. if (typeof sources !== 'undefined' &&
  26282. Object.keys(sources).length !== 0) {
  26283. if (Array.isArray(order)) {
  26284. for (var i = 0; i < order.length; i++) {
  26285. var ssrc = order[i];
  26286. var source = sources[ssrc];
  26287. Object.keys(source).forEach(function (attribute) {
  26288. ssrcs.push({
  26289. id: ssrc,
  26290. attribute: attribute,
  26291. value: source[attribute]
  26292. });
  26293. });
  26294. }
  26295. } else {
  26296. Object.keys(sources).forEach(function (ssrc) {
  26297. var source = sources[ssrc];
  26298. Object.keys(source).forEach(function (attribute) {
  26299. ssrcs.push({
  26300. id: ssrc,
  26301. attribute: attribute,
  26302. value: source[attribute]
  26303. });
  26304. });
  26305. });
  26306. }
  26307. }
  26308. return ssrcs;
  26309. };
  26310. exports.parseSsrcs = function (mLine) {
  26311. var sources = {};
  26312. // group sources attributes by ssrc.
  26313. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26314. mLine.ssrcs.forEach(function (ssrc) {
  26315. if (!sources[ssrc.id])
  26316. sources[ssrc.id] = {};
  26317. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26318. });
  26319. }
  26320. return sources;
  26321. };
  26322. },{}],98:[function(require,module,exports){
  26323. arguments[4][92][0].apply(exports,arguments)
  26324. },{"dup":92}],99:[function(require,module,exports){
  26325. arguments[4][93][0].apply(exports,arguments)
  26326. },{"./parser":100,"./writer":101,"dup":93}],100:[function(require,module,exports){
  26327. arguments[4][94][0].apply(exports,arguments)
  26328. },{"./grammar":98,"dup":94}],101:[function(require,module,exports){
  26329. arguments[4][95][0].apply(exports,arguments)
  26330. },{"./grammar":98,"dup":95}],102:[function(require,module,exports){
  26331. arguments[4][92][0].apply(exports,arguments)
  26332. },{"dup":92}],103:[function(require,module,exports){
  26333. arguments[4][93][0].apply(exports,arguments)
  26334. },{"./parser":104,"./writer":105,"dup":93}],104:[function(require,module,exports){
  26335. arguments[4][94][0].apply(exports,arguments)
  26336. },{"./grammar":102,"dup":94}],105:[function(require,module,exports){
  26337. arguments[4][95][0].apply(exports,arguments)
  26338. },{"./grammar":102,"dup":95}],106:[function(require,module,exports){
  26339. var MediaStreamType = {
  26340. VIDEO_TYPE: "Video",
  26341. AUDIO_TYPE: "Audio"
  26342. };
  26343. module.exports = MediaStreamType;
  26344. },{}],107:[function(require,module,exports){
  26345. var RTCEvents = {
  26346. RTC_READY: "rtc.ready",
  26347. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  26348. LASTN_CHANGED: "rtc.lastn_changed",
  26349. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26350. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26351. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26352. AUDIO_MUTE: "rtc.audio_mute",
  26353. VIDEO_MUTE: "rtc.video_mute"
  26354. };
  26355. module.exports = RTCEvents;
  26356. },{}],108:[function(require,module,exports){
  26357. var Resolutions = {
  26358. "1080": {
  26359. width: 1920,
  26360. height: 1080,
  26361. order: 7
  26362. },
  26363. "fullhd": {
  26364. width: 1920,
  26365. height: 1080,
  26366. order: 7
  26367. },
  26368. "720": {
  26369. width: 1280,
  26370. height: 720,
  26371. order: 6
  26372. },
  26373. "hd": {
  26374. width: 1280,
  26375. height: 720,
  26376. order: 6
  26377. },
  26378. "960": {
  26379. width: 960,
  26380. height: 720,
  26381. order: 5
  26382. },
  26383. "640": {
  26384. width: 640,
  26385. height: 480,
  26386. order: 4
  26387. },
  26388. "vga": {
  26389. width: 640,
  26390. height: 480,
  26391. order: 4
  26392. },
  26393. "360": {
  26394. width: 640,
  26395. height: 360,
  26396. order: 3
  26397. },
  26398. "320": {
  26399. width: 320,
  26400. height: 240,
  26401. order: 2
  26402. },
  26403. "180": {
  26404. width: 320,
  26405. height: 180,
  26406. order: 1
  26407. }
  26408. };
  26409. module.exports = Resolutions;
  26410. },{}],109:[function(require,module,exports){
  26411. var StreamEventTypes = {
  26412. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26413. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26414. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26415. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26416. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  26417. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  26418. };
  26419. module.exports = StreamEventTypes;
  26420. },{}],110:[function(require,module,exports){
  26421. var UIEvents = {
  26422. NICKNAME_CHANGED: "UI.nickname_changed",
  26423. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26424. PINNED_ENDPOINT: "UI.pinned_endpoint",
  26425. LARGEVIDEO_INIT: "UI.largevideo_init"
  26426. };
  26427. module.exports = UIEvents;
  26428. },{}],111:[function(require,module,exports){
  26429. var AuthenticationEvents = {
  26430. /**
  26431. * Event callback arguments:
  26432. * function(authenticationEnabled, userIdentity)
  26433. * authenticationEnabled - indicates whether authentication has been enabled
  26434. * in this session
  26435. * userIdentity - if user has been logged in then it contains user name. If
  26436. * contains 'null' or 'undefined' then user is not logged in.
  26437. */
  26438. IDENTITY_UPDATED: "authentication.identity_updated"
  26439. };
  26440. module.exports = AuthenticationEvents;
  26441. },{}],112:[function(require,module,exports){
  26442. var CQEvents = {
  26443. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26444. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26445. STOP: "cq.stop"
  26446. };
  26447. module.exports = CQEvents;
  26448. },{}],113:[function(require,module,exports){
  26449. var DesktopSharingEventTypes = {
  26450. INIT: "ds.init",
  26451. SWITCHING_DONE: "ds.switching_done",
  26452. NEW_STREAM_CREATED: "ds.new_stream_created"
  26453. };
  26454. module.exports = DesktopSharingEventTypes;
  26455. },{}],114:[function(require,module,exports){
  26456. var Events = {
  26457. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26458. };
  26459. module.exports = Events;
  26460. },{}],115:[function(require,module,exports){
  26461. module.exports = {
  26462. getLanguages : function () {
  26463. var languages = [];
  26464. for(var lang in this)
  26465. {
  26466. if(typeof this[lang] === "string")
  26467. languages.push(this[lang]);
  26468. }
  26469. return languages;
  26470. },
  26471. EN: "en",
  26472. BG: "bg",
  26473. DE: "de",
  26474. TR: "tr",
  26475. FR: "fr"
  26476. }
  26477. },{}],116:[function(require,module,exports){
  26478. var XMPPEvents = {
  26479. CONNECTION_FAILED: "xmpp.connection.failed",
  26480. // Indicates an interrupted connection event.
  26481. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  26482. // Indicates a restored connection event.
  26483. CONNECTION_RESTORED: "xmpp.connection.restored",
  26484. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26485. CALL_INCOMING: "xmpp.callincoming.jingle",
  26486. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26487. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26488. KICKED: "xmpp.kicked",
  26489. BRIDGE_DOWN: "xmpp.bridge_down",
  26490. USER_ID_CHANGED: "xmpp.user_id_changed",
  26491. // We joined the MUC
  26492. MUC_JOINED: "xmpp.muc_joined",
  26493. // A member joined the MUC
  26494. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26495. // A member left the MUC
  26496. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26497. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26498. MUC_DESTROYED: "xmpp.muc_destroyed",
  26499. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26500. REMOTE_STATS: "xmpp.remote_stats",
  26501. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26502. PRESENCE_STATUS: "xmpp.presence_status",
  26503. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26504. SUBJECT_CHANGED: "xmpp.subject_changed",
  26505. MESSAGE_RECEIVED: "xmpp.message_received",
  26506. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26507. PASSWORD_REQUIRED: "xmpp.password_required",
  26508. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26509. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26510. ETHERPAD: "xmpp.etherpad",
  26511. DEVICE_AVAILABLE: "xmpp.device_available",
  26512. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  26513. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  26514. AUDIO_MUTED: "xmpp.audio_muted",
  26515. VIDEO_MUTED: "xmpp.video_muted",
  26516. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  26517. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  26518. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  26519. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  26520. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  26521. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  26522. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  26523. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  26524. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  26525. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  26526. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  26527. // xmpp is connected and obtained user media
  26528. READY_TO_JOIN: 'xmpp.ready_to_join'
  26529. };
  26530. module.exports = XMPPEvents;
  26531. },{}],117:[function(require,module,exports){
  26532. // Copyright Joyent, Inc. and other Node contributors.
  26533. //
  26534. // Permission is hereby granted, free of charge, to any person obtaining a
  26535. // copy of this software and associated documentation files (the
  26536. // "Software"), to deal in the Software without restriction, including
  26537. // without limitation the rights to use, copy, modify, merge, publish,
  26538. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26539. // persons to whom the Software is furnished to do so, subject to the
  26540. // following conditions:
  26541. //
  26542. // The above copyright notice and this permission notice shall be included
  26543. // in all copies or substantial portions of the Software.
  26544. //
  26545. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26546. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26547. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26548. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26549. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26550. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26551. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26552. function EventEmitter() {
  26553. this._events = this._events || {};
  26554. this._maxListeners = this._maxListeners || undefined;
  26555. }
  26556. module.exports = EventEmitter;
  26557. // Backwards-compat with node 0.10.x
  26558. EventEmitter.EventEmitter = EventEmitter;
  26559. EventEmitter.prototype._events = undefined;
  26560. EventEmitter.prototype._maxListeners = undefined;
  26561. // By default EventEmitters will print a warning if more than 10 listeners are
  26562. // added to it. This is a useful default which helps finding memory leaks.
  26563. EventEmitter.defaultMaxListeners = 10;
  26564. // Obviously not all Emitters should be limited to 10. This function allows
  26565. // that to be increased. Set to zero for unlimited.
  26566. EventEmitter.prototype.setMaxListeners = function(n) {
  26567. if (!isNumber(n) || n < 0 || isNaN(n))
  26568. throw TypeError('n must be a positive number');
  26569. this._maxListeners = n;
  26570. return this;
  26571. };
  26572. EventEmitter.prototype.emit = function(type) {
  26573. var er, handler, len, args, i, listeners;
  26574. if (!this._events)
  26575. this._events = {};
  26576. // If there is no 'error' event listener then throw.
  26577. if (type === 'error') {
  26578. if (!this._events.error ||
  26579. (isObject(this._events.error) && !this._events.error.length)) {
  26580. er = arguments[1];
  26581. if (er instanceof Error) {
  26582. throw er; // Unhandled 'error' event
  26583. }
  26584. throw TypeError('Uncaught, unspecified "error" event.');
  26585. }
  26586. }
  26587. handler = this._events[type];
  26588. if (isUndefined(handler))
  26589. return false;
  26590. if (isFunction(handler)) {
  26591. switch (arguments.length) {
  26592. // fast cases
  26593. case 1:
  26594. handler.call(this);
  26595. break;
  26596. case 2:
  26597. handler.call(this, arguments[1]);
  26598. break;
  26599. case 3:
  26600. handler.call(this, arguments[1], arguments[2]);
  26601. break;
  26602. // slower
  26603. default:
  26604. len = arguments.length;
  26605. args = new Array(len - 1);
  26606. for (i = 1; i < len; i++)
  26607. args[i - 1] = arguments[i];
  26608. handler.apply(this, args);
  26609. }
  26610. } else if (isObject(handler)) {
  26611. len = arguments.length;
  26612. args = new Array(len - 1);
  26613. for (i = 1; i < len; i++)
  26614. args[i - 1] = arguments[i];
  26615. listeners = handler.slice();
  26616. len = listeners.length;
  26617. for (i = 0; i < len; i++)
  26618. listeners[i].apply(this, args);
  26619. }
  26620. return true;
  26621. };
  26622. EventEmitter.prototype.addListener = function(type, listener) {
  26623. var m;
  26624. if (!isFunction(listener))
  26625. throw TypeError('listener must be a function');
  26626. if (!this._events)
  26627. this._events = {};
  26628. // To avoid recursion in the case that type === "newListener"! Before
  26629. // adding it to the listeners, first emit "newListener".
  26630. if (this._events.newListener)
  26631. this.emit('newListener', type,
  26632. isFunction(listener.listener) ?
  26633. listener.listener : listener);
  26634. if (!this._events[type])
  26635. // Optimize the case of one listener. Don't need the extra array object.
  26636. this._events[type] = listener;
  26637. else if (isObject(this._events[type]))
  26638. // If we've already got an array, just append.
  26639. this._events[type].push(listener);
  26640. else
  26641. // Adding the second element, need to change to array.
  26642. this._events[type] = [this._events[type], listener];
  26643. // Check for listener leak
  26644. if (isObject(this._events[type]) && !this._events[type].warned) {
  26645. var m;
  26646. if (!isUndefined(this._maxListeners)) {
  26647. m = this._maxListeners;
  26648. } else {
  26649. m = EventEmitter.defaultMaxListeners;
  26650. }
  26651. if (m && m > 0 && this._events[type].length > m) {
  26652. this._events[type].warned = true;
  26653. console.error('(node) warning: possible EventEmitter memory ' +
  26654. 'leak detected. %d listeners added. ' +
  26655. 'Use emitter.setMaxListeners() to increase limit.',
  26656. this._events[type].length);
  26657. if (typeof console.trace === 'function') {
  26658. // not supported in IE 10
  26659. console.trace();
  26660. }
  26661. }
  26662. }
  26663. return this;
  26664. };
  26665. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  26666. EventEmitter.prototype.once = function(type, listener) {
  26667. if (!isFunction(listener))
  26668. throw TypeError('listener must be a function');
  26669. var fired = false;
  26670. function g() {
  26671. this.removeListener(type, g);
  26672. if (!fired) {
  26673. fired = true;
  26674. listener.apply(this, arguments);
  26675. }
  26676. }
  26677. g.listener = listener;
  26678. this.on(type, g);
  26679. return this;
  26680. };
  26681. // emits a 'removeListener' event iff the listener was removed
  26682. EventEmitter.prototype.removeListener = function(type, listener) {
  26683. var list, position, length, i;
  26684. if (!isFunction(listener))
  26685. throw TypeError('listener must be a function');
  26686. if (!this._events || !this._events[type])
  26687. return this;
  26688. list = this._events[type];
  26689. length = list.length;
  26690. position = -1;
  26691. if (list === listener ||
  26692. (isFunction(list.listener) && list.listener === listener)) {
  26693. delete this._events[type];
  26694. if (this._events.removeListener)
  26695. this.emit('removeListener', type, listener);
  26696. } else if (isObject(list)) {
  26697. for (i = length; i-- > 0;) {
  26698. if (list[i] === listener ||
  26699. (list[i].listener && list[i].listener === listener)) {
  26700. position = i;
  26701. break;
  26702. }
  26703. }
  26704. if (position < 0)
  26705. return this;
  26706. if (list.length === 1) {
  26707. list.length = 0;
  26708. delete this._events[type];
  26709. } else {
  26710. list.splice(position, 1);
  26711. }
  26712. if (this._events.removeListener)
  26713. this.emit('removeListener', type, listener);
  26714. }
  26715. return this;
  26716. };
  26717. EventEmitter.prototype.removeAllListeners = function(type) {
  26718. var key, listeners;
  26719. if (!this._events)
  26720. return this;
  26721. // not listening for removeListener, no need to emit
  26722. if (!this._events.removeListener) {
  26723. if (arguments.length === 0)
  26724. this._events = {};
  26725. else if (this._events[type])
  26726. delete this._events[type];
  26727. return this;
  26728. }
  26729. // emit removeListener for all listeners on all events
  26730. if (arguments.length === 0) {
  26731. for (key in this._events) {
  26732. if (key === 'removeListener') continue;
  26733. this.removeAllListeners(key);
  26734. }
  26735. this.removeAllListeners('removeListener');
  26736. this._events = {};
  26737. return this;
  26738. }
  26739. listeners = this._events[type];
  26740. if (isFunction(listeners)) {
  26741. this.removeListener(type, listeners);
  26742. } else {
  26743. // LIFO order
  26744. while (listeners.length)
  26745. this.removeListener(type, listeners[listeners.length - 1]);
  26746. }
  26747. delete this._events[type];
  26748. return this;
  26749. };
  26750. EventEmitter.prototype.listeners = function(type) {
  26751. var ret;
  26752. if (!this._events || !this._events[type])
  26753. ret = [];
  26754. else if (isFunction(this._events[type]))
  26755. ret = [this._events[type]];
  26756. else
  26757. ret = this._events[type].slice();
  26758. return ret;
  26759. };
  26760. EventEmitter.listenerCount = function(emitter, type) {
  26761. var ret;
  26762. if (!emitter._events || !emitter._events[type])
  26763. ret = 0;
  26764. else if (isFunction(emitter._events[type]))
  26765. ret = 1;
  26766. else
  26767. ret = emitter._events[type].length;
  26768. return ret;
  26769. };
  26770. function isFunction(arg) {
  26771. return typeof arg === 'function';
  26772. }
  26773. function isNumber(arg) {
  26774. return typeof arg === 'number';
  26775. }
  26776. function isObject(arg) {
  26777. return typeof arg === 'object' && arg !== null;
  26778. }
  26779. function isUndefined(arg) {
  26780. return arg === void 0;
  26781. }
  26782. },{}],118:[function(require,module,exports){
  26783. // shim for using process in browser
  26784. var process = module.exports = {};
  26785. var queue = [];
  26786. var draining = false;
  26787. var currentQueue;
  26788. var queueIndex = -1;
  26789. function cleanUpNextTick() {
  26790. draining = false;
  26791. if (currentQueue.length) {
  26792. queue = currentQueue.concat(queue);
  26793. } else {
  26794. queueIndex = -1;
  26795. }
  26796. if (queue.length) {
  26797. drainQueue();
  26798. }
  26799. }
  26800. function drainQueue() {
  26801. if (draining) {
  26802. return;
  26803. }
  26804. var timeout = setTimeout(cleanUpNextTick);
  26805. draining = true;
  26806. var len = queue.length;
  26807. while(len) {
  26808. currentQueue = queue;
  26809. queue = [];
  26810. while (++queueIndex < len) {
  26811. currentQueue[queueIndex].run();
  26812. }
  26813. queueIndex = -1;
  26814. len = queue.length;
  26815. }
  26816. currentQueue = null;
  26817. draining = false;
  26818. clearTimeout(timeout);
  26819. }
  26820. process.nextTick = function (fun) {
  26821. var args = new Array(arguments.length - 1);
  26822. if (arguments.length > 1) {
  26823. for (var i = 1; i < arguments.length; i++) {
  26824. args[i - 1] = arguments[i];
  26825. }
  26826. }
  26827. queue.push(new Item(fun, args));
  26828. if (queue.length === 1 && !draining) {
  26829. setTimeout(drainQueue, 0);
  26830. }
  26831. };
  26832. // v8 likes predictible objects
  26833. function Item(fun, array) {
  26834. this.fun = fun;
  26835. this.array = array;
  26836. }
  26837. Item.prototype.run = function () {
  26838. this.fun.apply(null, this.array);
  26839. };
  26840. process.title = 'browser';
  26841. process.browser = true;
  26842. process.env = {};
  26843. process.argv = [];
  26844. process.version = ''; // empty string to avoid regexp issues
  26845. process.versions = {};
  26846. function noop() {}
  26847. process.on = noop;
  26848. process.addListener = noop;
  26849. process.once = noop;
  26850. process.off = noop;
  26851. process.removeListener = noop;
  26852. process.removeAllListeners = noop;
  26853. process.emit = noop;
  26854. process.binding = function (name) {
  26855. throw new Error('process.binding is not supported');
  26856. };
  26857. // TODO(shtylman)
  26858. process.cwd = function () { return '/' };
  26859. process.chdir = function (dir) {
  26860. throw new Error('process.chdir is not supported');
  26861. };
  26862. process.umask = function() { return 0; };
  26863. },{}]},{},[1])(1)
  26864. });