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

app.bundle.js 1015KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815
  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":67}],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. * toggleAudio: toggleAudio,
  57. * toggleVideo: 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. toggleAudio: APP.UI.toggleAudio,
  68. toggleVideo: 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":117}],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":108}],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":108,"../../service/RTC/StreamEventTypes.js":110}],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":107}],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" : "camera");
  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. setVideoMute: function (mute, callback, options) {
  809. if (!this.localVideo)
  810. return;
  811. if (mute == APP.RTC.localVideo.isMuted())
  812. {
  813. APP.xmpp.sendVideoInfoPresence(mute);
  814. if (callback)
  815. callback(mute);
  816. }
  817. else
  818. {
  819. APP.RTC.localVideo.setMute(mute);
  820. APP.xmpp.setVideoMute(
  821. mute,
  822. callback,
  823. options);
  824. }
  825. },
  826. setDeviceAvailability: function (devices) {
  827. if(!devices)
  828. return;
  829. if(devices.audio === true || devices.audio === false)
  830. this.devices.audio = devices.audio;
  831. if(devices.video === true || devices.video === false)
  832. this.devices.video = devices.video;
  833. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  834. }
  835. };
  836. module.exports = RTC;
  837. },{"../../service/RTC/MediaStreamTypes":107,"../../service/RTC/RTCEvents.js":108,"../../service/RTC/StreamEventTypes.js":110,"../../service/UI/UIEvents":111,"../../service/desktopsharing/DesktopSharingEventTypes":114,"../../service/xmpp/XMPPEvents":117,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":118}],8:[function(require,module,exports){
  838. var currentBrowser;
  839. var browserVersion;
  840. var RTCBrowserType = {
  841. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  842. RTC_BROWSER_OPERA: "rtc_browser.opera",
  843. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  844. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  845. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  846. getBrowserType: function () {
  847. return currentBrowser;
  848. },
  849. isChrome: function () {
  850. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  851. },
  852. isOpera: function () {
  853. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  854. },
  855. isFirefox: function () {
  856. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  857. },
  858. isIExplorer: function () {
  859. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  860. },
  861. isSafari: function () {
  862. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  863. },
  864. isTemasysPluginUsed: function () {
  865. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  866. },
  867. getFirefoxVersion: function () {
  868. return RTCBrowserType.isFirefox() ? browserVersion : null;
  869. },
  870. getChromeVersion: function () {
  871. return RTCBrowserType.isChrome() ? browserVersion : null;
  872. },
  873. usesPlanB: function() {
  874. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  875. RTCBrowserType.isTemasysPluginUsed();
  876. },
  877. usesUnifiedPlan: function() {
  878. return RTCBrowserType.isFirefox();
  879. }
  880. // Add version getters for other browsers when needed
  881. };
  882. // detectOpera() must be called before detectChrome() !!!
  883. // otherwise Opera wil be detected as Chrome
  884. function detectChrome() {
  885. if (navigator.webkitGetUserMedia) {
  886. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  887. var userAgent = navigator.userAgent.toLowerCase();
  888. // We can assume that user agent is chrome, because it's
  889. // enforced when 'ext' streaming method is set
  890. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  891. console.log("This appears to be Chrome, ver: " + ver);
  892. return ver;
  893. }
  894. return null;
  895. }
  896. function detectOpera() {
  897. var userAgent = navigator.userAgent;
  898. if (userAgent.match(/Opera|OPR/)) {
  899. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  900. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  901. console.info("This appears to be Opera, ver: " + version);
  902. return version;
  903. }
  904. return null;
  905. }
  906. function detectFirefox() {
  907. if (navigator.mozGetUserMedia) {
  908. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  909. var version = parseInt(
  910. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  911. console.log('This appears to be Firefox, ver: ' + version);
  912. return version;
  913. }
  914. return null;
  915. }
  916. function detectSafari() {
  917. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  918. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  919. console.info("This appears to be Safari");
  920. // FIXME detect Safari version when needed
  921. return 1;
  922. }
  923. return null;
  924. }
  925. function detectIE() {
  926. var version;
  927. var ua = window.navigator.userAgent;
  928. var msie = ua.indexOf('MSIE ');
  929. if (msie > 0) {
  930. // IE 10 or older => return version number
  931. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  932. }
  933. var trident = ua.indexOf('Trident/');
  934. if (!version && trident > 0) {
  935. // IE 11 => return version number
  936. var rv = ua.indexOf('rv:');
  937. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  938. }
  939. var edge = ua.indexOf('Edge/');
  940. if (!version && edge > 0) {
  941. // IE 12 => return version number
  942. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  943. }
  944. if (version) {
  945. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  946. console.info("This appears to be IExplorer, ver: " + version);
  947. }
  948. return version;
  949. }
  950. function detectBrowser() {
  951. var version;
  952. var detectors = [
  953. detectOpera,
  954. detectChrome,
  955. detectFirefox,
  956. detectIE,
  957. detectSafari
  958. ];
  959. // Try all browser detectors
  960. for (var i = 0; i < detectors.length; i++) {
  961. version = detectors[i]();
  962. if (version)
  963. return version;
  964. }
  965. console.error("Failed to detect browser type");
  966. return undefined;
  967. }
  968. browserVersion = detectBrowser();
  969. module.exports = RTCBrowserType;
  970. },{}],9:[function(require,module,exports){
  971. /* global config, require, attachMediaStream, getUserMedia */
  972. var RTCBrowserType = require("./RTCBrowserType");
  973. var Resolutions = require("../../service/RTC/Resolutions");
  974. var AdapterJS = require("./adapter.screenshare");
  975. var SDPUtil = require("../xmpp/SDPUtil");
  976. var currentResolution = null;
  977. function getPreviousResolution(resolution) {
  978. if(!Resolutions[resolution])
  979. return null;
  980. var order = Resolutions[resolution].order;
  981. var res = null;
  982. var resName = null;
  983. for(var i in Resolutions) {
  984. var tmp = Resolutions[i];
  985. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  986. resName = i;
  987. res = tmp;
  988. }
  989. }
  990. return resName;
  991. }
  992. function setResolutionConstraints(constraints, resolution, isAndroid) {
  993. if (resolution && !constraints.video || isAndroid) {
  994. // same behaviour as true
  995. constraints.video = { mandatory: {}, optional: [] };
  996. }
  997. if(Resolutions[resolution]) {
  998. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  999. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1000. }
  1001. else {
  1002. if (isAndroid) {
  1003. constraints.video.mandatory.minWidth = 320;
  1004. constraints.video.mandatory.minHeight = 240;
  1005. constraints.video.mandatory.maxFrameRate = 15;
  1006. }
  1007. }
  1008. if (constraints.video.mandatory.minWidth)
  1009. constraints.video.mandatory.maxWidth =
  1010. constraints.video.mandatory.minWidth;
  1011. if (constraints.video.mandatory.minHeight)
  1012. constraints.video.mandatory.maxHeight =
  1013. constraints.video.mandatory.minHeight;
  1014. }
  1015. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1016. {
  1017. var constraints = {audio: false, video: false};
  1018. if (um.indexOf('video') >= 0) {
  1019. // same behaviour as true
  1020. constraints.video = { mandatory: {}, optional: [] };
  1021. }
  1022. if (um.indexOf('audio') >= 0) {
  1023. // same behaviour as true
  1024. constraints.audio = { mandatory: {}, optional: []};
  1025. }
  1026. if (um.indexOf('screen') >= 0) {
  1027. if (RTCBrowserType.isChrome()) {
  1028. constraints.video = {
  1029. mandatory: {
  1030. chromeMediaSource: "screen",
  1031. googLeakyBucket: true,
  1032. maxWidth: window.screen.width,
  1033. maxHeight: window.screen.height,
  1034. maxFrameRate: 3
  1035. },
  1036. optional: []
  1037. };
  1038. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1039. constraints.video = {
  1040. optional: [
  1041. {
  1042. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1043. }
  1044. ]
  1045. };
  1046. } else {
  1047. console.error(
  1048. "'screen' WebRTC media source is supported only in Chrome" +
  1049. " and with Temasys plugin");
  1050. }
  1051. }
  1052. if (um.indexOf('desktop') >= 0) {
  1053. constraints.video = {
  1054. mandatory: {
  1055. chromeMediaSource: "desktop",
  1056. chromeMediaSourceId: desktopStream,
  1057. googLeakyBucket: true,
  1058. maxWidth: window.screen.width,
  1059. maxHeight: window.screen.height,
  1060. maxFrameRate: 3
  1061. },
  1062. optional: []
  1063. };
  1064. }
  1065. if (constraints.audio) {
  1066. // if it is good enough for hangouts...
  1067. constraints.audio.optional.push(
  1068. {googEchoCancellation: true},
  1069. {googAutoGainControl: true},
  1070. {googNoiseSupression: true},
  1071. {googHighpassFilter: true},
  1072. {googNoisesuppression2: true},
  1073. {googEchoCancellation2: true},
  1074. {googAutoGainControl2: true}
  1075. );
  1076. }
  1077. if (constraints.video) {
  1078. if (um.indexOf('video') >= 0) {
  1079. constraints.video.optional.push(
  1080. {googLeakyBucket: true}
  1081. );
  1082. }
  1083. }
  1084. if (um.indexOf('video') >= 0) {
  1085. setResolutionConstraints(constraints, resolution, isAndroid);
  1086. }
  1087. if (bandwidth) {
  1088. if (!constraints.video) {
  1089. //same behaviour as true
  1090. constraints.video = {mandatory: {}, optional: []};
  1091. }
  1092. constraints.video.optional.push({bandwidth: bandwidth});
  1093. }
  1094. if (fps) {
  1095. // for some cameras it might be necessary to request 30fps
  1096. // so they choose 30fps mjpg over 10fps yuy2
  1097. if (!constraints.video) {
  1098. // same behaviour as true;
  1099. constraints.video = {mandatory: {}, optional: []};
  1100. }
  1101. constraints.video.mandatory.minFrameRate = fps;
  1102. }
  1103. return constraints;
  1104. }
  1105. function RTCUtils(RTCService, onTemasysPluginReady)
  1106. {
  1107. var self = this;
  1108. this.service = RTCService;
  1109. if (RTCBrowserType.isFirefox()) {
  1110. var FFversion = RTCBrowserType.getFirefoxVersion();
  1111. if (FFversion >= 40) {
  1112. this.peerconnection = mozRTCPeerConnection;
  1113. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1114. this.pc_constraints = {};
  1115. this.attachMediaStream = function (element, stream) {
  1116. // srcObject is being standardized and FF will eventually
  1117. // support that unprefixed. FF also supports the
  1118. // "element.src = URL.createObjectURL(...)" combo, but that
  1119. // will be deprecated in favour of srcObject.
  1120. //
  1121. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1122. // https://github.com/webrtc/samples/issues/302
  1123. if(!element[0])
  1124. return;
  1125. element[0].mozSrcObject = stream;
  1126. element[0].play();
  1127. };
  1128. this.getStreamID = function (stream) {
  1129. var id = stream.id;
  1130. if (!id) {
  1131. var tracks = stream.getVideoTracks();
  1132. if (!tracks || tracks.length === 0) {
  1133. tracks = stream.getAudioTracks();
  1134. }
  1135. id = tracks[0].id;
  1136. }
  1137. return SDPUtil.filter_special_chars(id);
  1138. };
  1139. this.getVideoSrc = function (element) {
  1140. if(!element)
  1141. return null;
  1142. return element.mozSrcObject;
  1143. };
  1144. this.setVideoSrc = function (element, src) {
  1145. if(element)
  1146. element.mozSrcObject = src;
  1147. };
  1148. RTCSessionDescription = mozRTCSessionDescription;
  1149. RTCIceCandidate = mozRTCIceCandidate;
  1150. } else {
  1151. console.error(
  1152. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1153. window.location.href = 'unsupported_browser.html';
  1154. return;
  1155. }
  1156. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1157. this.peerconnection = webkitRTCPeerConnection;
  1158. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1159. this.attachMediaStream = function (element, stream) {
  1160. element.attr('src', webkitURL.createObjectURL(stream));
  1161. };
  1162. this.getStreamID = function (stream) {
  1163. // streams from FF endpoints have the characters '{' and '}'
  1164. // that make jQuery choke.
  1165. return SDPUtil.filter_special_chars(stream.id);
  1166. };
  1167. this.getVideoSrc = function (element) {
  1168. if(!element)
  1169. return null;
  1170. return element.getAttribute("src");
  1171. };
  1172. this.setVideoSrc = function (element, src) {
  1173. if(element)
  1174. element.setAttribute("src", src);
  1175. };
  1176. // DTLS should now be enabled by default but..
  1177. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1178. if (navigator.userAgent.indexOf('Android') != -1) {
  1179. this.pc_constraints = {}; // disable DTLS on Android
  1180. }
  1181. if (!webkitMediaStream.prototype.getVideoTracks) {
  1182. webkitMediaStream.prototype.getVideoTracks = function () {
  1183. return this.videoTracks;
  1184. };
  1185. }
  1186. if (!webkitMediaStream.prototype.getAudioTracks) {
  1187. webkitMediaStream.prototype.getAudioTracks = function () {
  1188. return this.audioTracks;
  1189. };
  1190. }
  1191. }
  1192. // Detect IE/Safari
  1193. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1194. //AdapterJS.WebRTCPlugin.setLogLevel(
  1195. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1196. AdapterJS.webRTCReady(function (isPlugin) {
  1197. self.peerconnection = RTCPeerConnection;
  1198. self.getUserMedia = getUserMedia;
  1199. self.attachMediaStream = function (elSel, stream) {
  1200. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1201. return;
  1202. }
  1203. attachMediaStream(elSel[0], stream);
  1204. };
  1205. self.getStreamID = function (stream) {
  1206. var id = SDPUtil.filter_special_chars(stream.label);
  1207. return id;
  1208. };
  1209. self.getVideoSrc = function (element) {
  1210. if (!element) {
  1211. console.warn("Attempt to get video SRC of null element");
  1212. return null;
  1213. }
  1214. var children = element.children;
  1215. for (var i = 0; i !== children.length; ++i) {
  1216. if (children[i].name === 'streamId') {
  1217. return children[i].value;
  1218. }
  1219. }
  1220. //console.info(element.id + " SRC: " + src);
  1221. return null;
  1222. };
  1223. self.setVideoSrc = function (element, src) {
  1224. //console.info("Set video src: ", element, src);
  1225. if (!src) {
  1226. console.warn("Not attaching video stream, 'src' is null");
  1227. return;
  1228. }
  1229. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1230. var stream = AdapterJS.WebRTCPlugin.plugin
  1231. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1232. attachMediaStream(element, stream);
  1233. };
  1234. onTemasysPluginReady(isPlugin);
  1235. });
  1236. } else {
  1237. try {
  1238. console.log('Browser does not appear to be WebRTC-capable');
  1239. } catch (e) { }
  1240. window.location.href = 'unsupported_browser.html';
  1241. }
  1242. }
  1243. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1244. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1245. desktopStream) {
  1246. currentResolution = resolution;
  1247. // Check if we are running on Android device
  1248. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1249. var constraints = getConstraints(
  1250. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1251. console.info("Get media constraints", constraints);
  1252. var self = this;
  1253. try {
  1254. this.getUserMedia(constraints,
  1255. function (stream) {
  1256. console.log('onUserMediaSuccess');
  1257. self.setAvailableDevices(um, true);
  1258. success_callback(stream);
  1259. },
  1260. function (error) {
  1261. self.setAvailableDevices(um, false);
  1262. console.warn('Failed to get access to local media. Error ',
  1263. error, constraints);
  1264. if (failure_callback) {
  1265. failure_callback(error);
  1266. }
  1267. });
  1268. } catch (e) {
  1269. console.error('GUM failed: ', e);
  1270. if(failure_callback) {
  1271. failure_callback(e);
  1272. }
  1273. }
  1274. };
  1275. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1276. var devices = {};
  1277. if(um.indexOf("video") != -1) {
  1278. devices.video = available;
  1279. }
  1280. if(um.indexOf("audio") != -1) {
  1281. devices.audio = available;
  1282. }
  1283. this.service.setDeviceAvailability(devices);
  1284. };
  1285. /**
  1286. * We ask for audio and video combined stream in order to get permissions and
  1287. * not to ask twice.
  1288. */
  1289. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1290. function(devices, callback, usageOptions)
  1291. {
  1292. var self = this;
  1293. // Get AV
  1294. var successCallback = function (stream) {
  1295. if(callback)
  1296. callback(stream, usageOptions);
  1297. else
  1298. self.successCallback(stream, usageOptions);
  1299. };
  1300. if(!devices)
  1301. devices = ['audio', 'video'];
  1302. var newDevices = [];
  1303. if(usageOptions)
  1304. for(var i = 0; i < devices.length; i++) {
  1305. var device = devices[i];
  1306. if(usageOptions[device] === true)
  1307. newDevices.push(device);
  1308. }
  1309. else
  1310. newDevices = devices;
  1311. if(newDevices.length === 0) {
  1312. successCallback();
  1313. return;
  1314. }
  1315. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1316. // With FF/IE we can't split the stream into audio and video because FF
  1317. // doesn't support media stream constructors. So, we need to get the
  1318. // audio stream separately from the video stream using two distinct GUM
  1319. // calls. Not very user friendly :-( but we don't have many other
  1320. // options neither.
  1321. //
  1322. // Note that we pack those 2 streams in a single object and pass it to
  1323. // the successCallback method.
  1324. var obtainVideo = function (audioStream) {
  1325. self.getUserMediaWithConstraints(
  1326. ['video'],
  1327. function (videoStream) {
  1328. return successCallback({
  1329. audioStream: audioStream,
  1330. videoStream: videoStream
  1331. });
  1332. },
  1333. function (error) {
  1334. console.error(
  1335. 'failed to obtain video stream - stop', error);
  1336. self.errorCallback(error);
  1337. },
  1338. config.resolution || '360');
  1339. };
  1340. var obtainAudio = function () {
  1341. self.getUserMediaWithConstraints(
  1342. ['audio'],
  1343. function (audioStream) {
  1344. if (newDevices.indexOf('video') !== -1)
  1345. obtainVideo(audioStream);
  1346. },
  1347. function (error) {
  1348. console.error(
  1349. 'failed to obtain audio stream - stop', error);
  1350. self.errorCallback(error);
  1351. }
  1352. );
  1353. };
  1354. if (newDevices.indexOf('audio') !== -1) {
  1355. obtainAudio();
  1356. } else {
  1357. obtainVideo(null);
  1358. }
  1359. } else {
  1360. this.getUserMediaWithConstraints(
  1361. newDevices,
  1362. function (stream) {
  1363. successCallback(stream);
  1364. },
  1365. function (error) {
  1366. self.errorCallback(error);
  1367. },
  1368. config.resolution || '360');
  1369. }
  1370. };
  1371. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1372. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1373. // it's an object with two properties: audioStream, videoStream.
  1374. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1375. console.log('got', stream, stream.getAudioTracks().length,
  1376. stream.getVideoTracks().length);
  1377. this.handleLocalStream(stream, usageOptions);
  1378. };
  1379. RTCUtils.prototype.errorCallback = function (error) {
  1380. var self = this;
  1381. console.error('failed to obtain audio/video stream - trying audio only', error);
  1382. var resolution = getPreviousResolution(currentResolution);
  1383. if(typeof error == "object" && error.constraintName && error.name
  1384. && (error.name == "ConstraintNotSatisfiedError" ||
  1385. error.name == "OverconstrainedError") &&
  1386. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1387. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1388. && resolution != null)
  1389. {
  1390. self.getUserMediaWithConstraints(['audio', 'video'],
  1391. function (stream) {
  1392. return self.successCallback(stream);
  1393. }, function (error) {
  1394. return self.errorCallback(error);
  1395. }, resolution);
  1396. }
  1397. else {
  1398. self.getUserMediaWithConstraints(
  1399. ['audio'],
  1400. function (stream) {
  1401. return self.successCallback(stream);
  1402. },
  1403. function (error) {
  1404. console.error('failed to obtain audio/video stream - stop',
  1405. error);
  1406. return self.successCallback(null);
  1407. }
  1408. );
  1409. }
  1410. };
  1411. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1412. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1413. // an object with two properties: audioStream, videoStream.
  1414. var audioStream, videoStream;
  1415. if(window.webkitMediaStream)
  1416. {
  1417. audioStream = new webkitMediaStream();
  1418. videoStream = new webkitMediaStream();
  1419. if(stream) {
  1420. var audioTracks = stream.getAudioTracks();
  1421. for (var i = 0; i < audioTracks.length; i++) {
  1422. audioStream.addTrack(audioTracks[i]);
  1423. }
  1424. var videoTracks = stream.getVideoTracks();
  1425. for (i = 0; i < videoTracks.length; i++) {
  1426. videoStream.addTrack(videoTracks[i]);
  1427. }
  1428. }
  1429. }
  1430. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1431. { // Firefox and Temasys plugin
  1432. if (stream && stream.audioStream)
  1433. audioStream = stream.audioStream;
  1434. else
  1435. audioStream = new DummyMediaStream("dummyAudio");
  1436. if (stream && stream.videoStream)
  1437. videoStream = stream.videoStream;
  1438. else
  1439. videoStream = new DummyMediaStream("dummyVideo");
  1440. }
  1441. var audioMuted = (usageOptions && usageOptions.audio === false),
  1442. videoMuted = (usageOptions && usageOptions.video === false);
  1443. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1444. videoGUM = (!usageOptions || usageOptions.video !== false);
  1445. this.service.createLocalStream(audioStream, "audio", null, null,
  1446. audioMuted, audioGUM);
  1447. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1448. videoMuted, videoGUM);
  1449. };
  1450. function DummyMediaStream(id) {
  1451. this.id = id;
  1452. this.label = id;
  1453. this.stop = function() { };
  1454. this.getAudioTracks = function() { return []; };
  1455. this.getVideoTracks = function() { return []; };
  1456. }
  1457. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1458. var newStream = null;
  1459. if (window.webkitMediaStream) {
  1460. newStream = new webkitMediaStream();
  1461. if (newStream) {
  1462. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1463. for (var i = 0; i < tracks.length; i++) {
  1464. newStream.addTrack(tracks[i]);
  1465. }
  1466. }
  1467. }
  1468. else {
  1469. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1470. if (stream) {
  1471. newStream = stream;
  1472. } else {
  1473. newStream =
  1474. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1475. }
  1476. }
  1477. return newStream;
  1478. };
  1479. module.exports = RTCUtils;
  1480. },{"../../service/RTC/Resolutions":109,"../xmpp/SDPUtil":56,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1481. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1482. // Adapter's interface.
  1483. var AdapterJS = AdapterJS || {};
  1484. // Browserify compatibility
  1485. if(typeof exports !== 'undefined') {
  1486. module.exports = AdapterJS;
  1487. }
  1488. AdapterJS.options = AdapterJS.options || {};
  1489. // uncomment to get virtual webcams
  1490. // AdapterJS.options.getAllCams = true;
  1491. // uncomment to prevent the install prompt when the plugin in not yet installed
  1492. // AdapterJS.options.hidePluginInstallPrompt = true;
  1493. // AdapterJS version
  1494. AdapterJS.VERSION = '0.11.0';
  1495. // This function will be called when the WebRTC API is ready to be used
  1496. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1497. // the plugin
  1498. // You may Override this function to synchronise the start of your application
  1499. // with the WebRTC API being ready.
  1500. // If you decide not to override use this synchronisation, it may result in
  1501. // an extensive CPU usage on the plugin start (once per tab loaded)
  1502. // Params:
  1503. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1504. //
  1505. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1506. // The WebRTC API is ready.
  1507. // Override me and do whatever you want here
  1508. };
  1509. // Sets a callback function to be called when the WebRTC interface is ready.
  1510. // The first argument is the function to callback.\
  1511. // Throws an error if the first argument is not a function
  1512. AdapterJS.webRTCReady = function (callback) {
  1513. if (typeof callback !== 'function') {
  1514. throw new Error('Callback provided is not a function');
  1515. }
  1516. if (true === AdapterJS.onwebrtcreadyDone) {
  1517. // All WebRTC interfaces are ready, just call the callback
  1518. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1519. } else {
  1520. // will be triggered automatically when your browser/plugin is ready.
  1521. AdapterJS.onwebrtcready = callback;
  1522. }
  1523. };
  1524. // Plugin namespace
  1525. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1526. // The object to store plugin information
  1527. AdapterJS.WebRTCPlugin.pluginInfo = {
  1528. prefix : 'Tem',
  1529. plugName : 'TemWebRTCPlugin',
  1530. pluginId : 'plugin0',
  1531. type : 'application/x-temwebrtcplugin',
  1532. onload : '__TemWebRTCReady0',
  1533. portalLink : 'http://skylink.io/plugin/',
  1534. downloadLink : null, //set below
  1535. companyName: 'Temasys'
  1536. };
  1537. if(!!navigator.platform.match(/^Mac/i)) {
  1538. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1539. }
  1540. else if(!!navigator.platform.match(/^Win/i)) {
  1541. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1542. }
  1543. // Unique identifier of each opened page
  1544. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1545. // Use this whenever you want to call the plugin.
  1546. AdapterJS.WebRTCPlugin.plugin = null;
  1547. // Set log level for the plugin once it is ready.
  1548. // The different values are
  1549. // This is an asynchronous function that will run when the plugin is ready
  1550. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1551. // Defines webrtc's JS interface according to the plugin's implementation.
  1552. // Define plugin Browsers as WebRTC Interface.
  1553. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1554. // This function detects whether or not a plugin is installed.
  1555. // Checks if Not IE (firefox, for example), else if it's IE,
  1556. // we're running IE and do something. If not it is not supported.
  1557. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1558. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1559. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1560. // Inject the HTML DOM object element into the page.
  1561. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1562. // States of readiness that the plugin goes through when
  1563. // being injected and stated
  1564. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1565. NONE : 0, // no plugin use
  1566. INITIALIZING : 1, // Detected need for plugin
  1567. INJECTING : 2, // Injecting plugin
  1568. INJECTED: 3, // Plugin element injected but not usable yet
  1569. READY: 4 // Plugin ready to be used
  1570. };
  1571. // Current state of the plugin. You cannot use the plugin before this is
  1572. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1573. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1574. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1575. // Used to make sure AdapterJS.onwebrtcready is only called once
  1576. AdapterJS.onwebrtcreadyDone = false;
  1577. // Log levels for the plugin.
  1578. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1579. /*
  1580. Log outputs are prefixed in some cases.
  1581. INFO: Information reported by the plugin.
  1582. ERROR: Errors originating from within the plugin.
  1583. WEBRTC: Error originating from within the libWebRTC library
  1584. */
  1585. // From the least verbose to the most verbose
  1586. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1587. NONE : 'NONE',
  1588. ERROR : 'ERROR',
  1589. WARNING : 'WARNING',
  1590. INFO: 'INFO',
  1591. VERBOSE: 'VERBOSE',
  1592. SENSITIVE: 'SENSITIVE'
  1593. };
  1594. // Does a waiting check before proceeding to load the plugin.
  1595. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1596. // This methid will use an interval to wait for the plugin to be ready.
  1597. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1598. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1599. // This function will be called when plugin is ready. It sends necessary
  1600. // details to the plugin.
  1601. // The function will wait for the document to be ready and the set the
  1602. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1603. // indicating that it can start being requested.
  1604. // This function is not in the IE/Safari condition brackets so that
  1605. // TemPluginLoaded function might be called on Chrome/Firefox.
  1606. // This function is the only private function that is not encapsulated to
  1607. // allow the plugin method to be called.
  1608. __TemWebRTCReady0 = function () {
  1609. if (document.readyState === 'complete') {
  1610. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1611. AdapterJS.maybeThroughWebRTCReady();
  1612. } else {
  1613. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1614. if (document.readyState === 'complete') {
  1615. // TODO: update comments, we wait for the document to be ready
  1616. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1617. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1618. AdapterJS.maybeThroughWebRTCReady();
  1619. }
  1620. }, 100);
  1621. }
  1622. };
  1623. AdapterJS.maybeThroughWebRTCReady = function() {
  1624. if (!AdapterJS.onwebrtcreadyDone) {
  1625. AdapterJS.onwebrtcreadyDone = true;
  1626. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1627. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1628. }
  1629. }
  1630. };
  1631. // Text namespace
  1632. AdapterJS.TEXT = {
  1633. PLUGIN: {
  1634. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1635. 'to work on this browser.',
  1636. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1637. BUTTON: 'Install Now'
  1638. },
  1639. REFRESH: {
  1640. REQUIRE_REFRESH: 'Please refresh page',
  1641. BUTTON: 'Refresh Page'
  1642. }
  1643. };
  1644. // The result of ice connection states.
  1645. // - starting: Ice connection is starting.
  1646. // - checking: Ice connection is checking.
  1647. // - connected Ice connection is connected.
  1648. // - completed Ice connection is connected.
  1649. // - done Ice connection has been completed.
  1650. // - disconnected Ice connection has been disconnected.
  1651. // - failed Ice connection has failed.
  1652. // - closed Ice connection is closed.
  1653. AdapterJS._iceConnectionStates = {
  1654. starting : 'starting',
  1655. checking : 'checking',
  1656. connected : 'connected',
  1657. completed : 'connected',
  1658. done : 'completed',
  1659. disconnected : 'disconnected',
  1660. failed : 'failed',
  1661. closed : 'closed'
  1662. };
  1663. //The IceConnection states that has been fired for each peer.
  1664. AdapterJS._iceConnectionFiredStates = [];
  1665. // Check if WebRTC Interface is defined.
  1666. AdapterJS.isDefined = null;
  1667. // This function helps to retrieve the webrtc detected browser information.
  1668. // This sets:
  1669. // - webrtcDetectedBrowser: The browser agent name.
  1670. // - webrtcDetectedVersion: The browser version.
  1671. // - webrtcDetectedType: The types of webRTC support.
  1672. // - 'moz': Mozilla implementation of webRTC.
  1673. // - 'webkit': WebKit implementation of webRTC.
  1674. // - 'plugin': Using the plugin implementation.
  1675. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1676. var hasMatch, checkMatch = navigator.userAgent.match(
  1677. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1678. if (/trident/i.test(checkMatch[1])) {
  1679. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1680. webrtcDetectedBrowser = 'IE';
  1681. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1682. } else if (checkMatch[1] === 'Chrome') {
  1683. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1684. if (hasMatch !== null) {
  1685. webrtcDetectedBrowser = 'opera';
  1686. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1687. }
  1688. }
  1689. if (navigator.userAgent.indexOf('Safari')) {
  1690. if (typeof InstallTrigger !== 'undefined') {
  1691. webrtcDetectedBrowser = 'firefox';
  1692. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1693. webrtcDetectedBrowser = 'IE';
  1694. } else if (
  1695. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1696. webrtcDetectedBrowser = 'safari';
  1697. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1698. webrtcDetectedBrowser = 'opera';
  1699. } else if (!!window.chrome) {
  1700. webrtcDetectedBrowser = 'chrome';
  1701. }
  1702. }
  1703. if (!webrtcDetectedBrowser) {
  1704. webrtcDetectedVersion = checkMatch[1];
  1705. }
  1706. if (!webrtcDetectedVersion) {
  1707. try {
  1708. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1709. [navigator.appName, navigator.appVersion, '-?'];
  1710. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1711. checkMatch.splice(1, 1, hasMatch[1]);
  1712. }
  1713. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1714. } catch (error) { }
  1715. }
  1716. };
  1717. // To fix configuration as some browsers does not support
  1718. // the 'urls' attribute.
  1719. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1720. if (pcConfig === null) {
  1721. return;
  1722. }
  1723. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1724. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1725. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1726. delete pcConfig.iceServers[i].urls;
  1727. }
  1728. }
  1729. };
  1730. AdapterJS.addEvent = function(elem, evnt, func) {
  1731. if (elem.addEventListener) { // W3C DOM
  1732. elem.addEventListener(evnt, func, false);
  1733. } else if (elem.attachEvent) {// OLD IE DOM
  1734. elem.attachEvent('on'+evnt, func);
  1735. } else { // No much to do
  1736. elem[evnt] = func;
  1737. }
  1738. };
  1739. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1740. // only inject once the page is ready
  1741. if (document.readyState !== 'complete') {
  1742. return;
  1743. }
  1744. var w = window;
  1745. var i = document.createElement('iframe');
  1746. i.style.position = 'fixed';
  1747. i.style.top = '-41px';
  1748. i.style.left = 0;
  1749. i.style.right = 0;
  1750. i.style.width = '100%';
  1751. i.style.height = '40px';
  1752. i.style.backgroundColor = '#ffffe1';
  1753. i.style.border = 'none';
  1754. i.style.borderBottom = '1px solid #888888';
  1755. i.style.zIndex = '9999999';
  1756. if(typeof i.style.webkitTransition === 'string') {
  1757. i.style.webkitTransition = 'all .5s ease-out';
  1758. } else if(typeof i.style.transition === 'string') {
  1759. i.style.transition = 'all .5s ease-out';
  1760. }
  1761. document.body.appendChild(i);
  1762. c = (i.contentWindow) ? i.contentWindow :
  1763. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1764. c.document.open();
  1765. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1766. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1767. 'middle; cursor: default;">' + text + '</span>');
  1768. if(buttonText && buttonLink) {
  1769. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1770. c.document.close();
  1771. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1772. if (!!displayRefreshBar) {
  1773. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1774. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1775. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1776. }
  1777. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1778. e.preventDefault();
  1779. try {
  1780. event.cancelBubble = true;
  1781. } catch(error) { }
  1782. });
  1783. }
  1784. else {
  1785. c.document.close();
  1786. }
  1787. AdapterJS.addEvent(c.document, 'click', function() {
  1788. w.document.body.removeChild(i);
  1789. });
  1790. setTimeout(function() {
  1791. if(typeof i.style.webkitTransform === 'string') {
  1792. i.style.webkitTransform = 'translateY(40px)';
  1793. } else if(typeof i.style.transform === 'string') {
  1794. i.style.transform = 'translateY(40px)';
  1795. } else {
  1796. i.style.top = '0px';
  1797. }
  1798. }, 300);
  1799. };
  1800. // -----------------------------------------------------------
  1801. // Detected webrtc implementation. Types are:
  1802. // - 'moz': Mozilla implementation of webRTC.
  1803. // - 'webkit': WebKit implementation of webRTC.
  1804. // - 'plugin': Using the plugin implementation.
  1805. webrtcDetectedType = null;
  1806. // Detected webrtc datachannel support. Types are:
  1807. // - 'SCTP': SCTP datachannel support.
  1808. // - 'RTP': RTP datachannel support.
  1809. webrtcDetectedDCSupport = null;
  1810. // Set the settings for creating DataChannels, MediaStream for
  1811. // Cross-browser compability.
  1812. // - This is only for SCTP based support browsers.
  1813. // the 'urls' attribute.
  1814. checkMediaDataChannelSettings =
  1815. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1816. if (typeof callback !== 'function') {
  1817. return;
  1818. }
  1819. var beOfferer = true;
  1820. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1821. // Nightly version does not require MozDontOfferDataChannel for interop
  1822. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1823. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1824. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1825. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1826. // Resends an updated version of constraints for MozDataChannel to work
  1827. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1828. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1829. try {
  1830. delete constraints.mandatory.MozDontOfferDataChannel;
  1831. } catch (error) {
  1832. console.error('Failed deleting MozDontOfferDataChannel');
  1833. console.error(error);
  1834. }
  1835. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1836. constraints.mandatory.MozDontOfferDataChannel = true;
  1837. }
  1838. if (!isLocalFirefox) {
  1839. // temporary measure to remove Moz* constraints in non Firefox browsers
  1840. for (var prop in constraints.mandatory) {
  1841. if (constraints.mandatory.hasOwnProperty(prop)) {
  1842. if (prop.indexOf('Moz') !== -1) {
  1843. delete constraints.mandatory[prop];
  1844. }
  1845. }
  1846. }
  1847. }
  1848. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1849. // interopability of the media stream
  1850. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1851. beOfferer = false;
  1852. }
  1853. callback(beOfferer, constraints);
  1854. };
  1855. // Handles the differences for all browsers ice connection state output.
  1856. // - Tested outcomes are:
  1857. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1858. // - Chrome (answerer) : 'checking' > 'connected'
  1859. // - Firefox (offerer) : 'checking' > 'connected'
  1860. // - Firefox (answerer): 'checking' > 'connected'
  1861. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1862. if (typeof callback !== 'function') {
  1863. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1864. return;
  1865. }
  1866. peerId = (peerId) ? peerId : 'peer';
  1867. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1868. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1869. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1870. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1871. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1872. }
  1873. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1874. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1875. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1876. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1877. setTimeout(function () {
  1878. AdapterJS._iceConnectionFiredStates[peerId]
  1879. .push(AdapterJS._iceConnectionStates.done);
  1880. callback(AdapterJS._iceConnectionStates.done);
  1881. }, 1000);
  1882. }
  1883. callback(iceConnectionState);
  1884. }
  1885. return;
  1886. };
  1887. // Firefox:
  1888. // - Creates iceServer from the url for Firefox.
  1889. // - Create iceServer with stun url.
  1890. // - Create iceServer with turn url.
  1891. // - Ignore the transport parameter from TURN url for FF version <=27.
  1892. // - Return null for createIceServer if transport=tcp.
  1893. // - FF 27 and above supports transport parameters in TURN url,
  1894. // - So passing in the full url to create iceServer.
  1895. // Chrome:
  1896. // - Creates iceServer from the url for Chrome M33 and earlier.
  1897. // - Create iceServer with stun url.
  1898. // - Chrome M28 & above uses below TURN format.
  1899. // Plugin:
  1900. // - Creates Ice Server for Plugin Browsers
  1901. // - If Stun - Create iceServer with stun url.
  1902. // - Else - Create iceServer with turn url
  1903. // - This is a WebRTC Function
  1904. createIceServer = null;
  1905. // Firefox:
  1906. // - Creates IceServers for Firefox
  1907. // - Use .url for FireFox.
  1908. // - Multiple Urls support
  1909. // Chrome:
  1910. // - Creates iceServers from the urls for Chrome M34 and above.
  1911. // - .urls is supported since Chrome M34.
  1912. // - Multiple Urls support
  1913. // Plugin:
  1914. // - Creates Ice Servers for Plugin Browsers
  1915. // - Multiple Urls support
  1916. // - This is a WebRTC Function
  1917. createIceServers = null;
  1918. //------------------------------------------------------------
  1919. //The RTCPeerConnection object.
  1920. RTCPeerConnection = null;
  1921. // Creates RTCSessionDescription object for Plugin Browsers
  1922. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  1923. RTCSessionDescription : null;
  1924. // Creates RTCIceCandidate object for Plugin Browsers
  1925. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  1926. RTCIceCandidate : null;
  1927. // Get UserMedia (only difference is the prefix).
  1928. // Code from Adam Barth.
  1929. getUserMedia = null;
  1930. // Attach a media stream to an element.
  1931. attachMediaStream = null;
  1932. // Re-attach a media stream to an element.
  1933. reattachMediaStream = null;
  1934. // Detected browser agent name. Types are:
  1935. // - 'firefox': Firefox browser.
  1936. // - 'chrome': Chrome browser.
  1937. // - 'opera': Opera browser.
  1938. // - 'safari': Safari browser.
  1939. // - 'IE' - Internet Explorer browser.
  1940. webrtcDetectedBrowser = null;
  1941. // Detected browser version.
  1942. webrtcDetectedVersion = null;
  1943. // Check for browser types and react accordingly
  1944. if (navigator.mozGetUserMedia) {
  1945. webrtcDetectedBrowser = 'firefox';
  1946. webrtcDetectedVersion = parseInt(navigator
  1947. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1948. webrtcDetectedType = 'moz';
  1949. webrtcDetectedDCSupport = 'SCTP';
  1950. RTCPeerConnection = function (pcConfig, pcConstraints) {
  1951. AdapterJS.maybeFixConfiguration(pcConfig);
  1952. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  1953. };
  1954. // The RTCSessionDescription object.
  1955. RTCSessionDescription = mozRTCSessionDescription;
  1956. window.RTCSessionDescription = RTCSessionDescription;
  1957. // The RTCIceCandidate object.
  1958. RTCIceCandidate = mozRTCIceCandidate;
  1959. window.RTCIceCandidate = RTCIceCandidate;
  1960. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1961. navigator.getUserMedia = window.getUserMedia;
  1962. // Shim for MediaStreamTrack.getSources.
  1963. MediaStreamTrack.getSources = function(successCb) {
  1964. setTimeout(function() {
  1965. var infos = [
  1966. { kind: 'audio', id: 'default', label:'', facing:'' },
  1967. { kind: 'video', id: 'default', label:'', facing:'' }
  1968. ];
  1969. successCb(infos);
  1970. }, 0);
  1971. };
  1972. createIceServer = function (url, username, password) {
  1973. var iceServer = null;
  1974. var url_parts = url.split(':');
  1975. if (url_parts[0].indexOf('stun') === 0) {
  1976. iceServer = { url : url };
  1977. } else if (url_parts[0].indexOf('turn') === 0) {
  1978. if (webrtcDetectedVersion < 27) {
  1979. var turn_url_parts = url.split('?');
  1980. if (turn_url_parts.length === 1 ||
  1981. turn_url_parts[1].indexOf('transport=udp') === 0) {
  1982. iceServer = {
  1983. url : turn_url_parts[0],
  1984. credential : password,
  1985. username : username
  1986. };
  1987. }
  1988. } else {
  1989. iceServer = {
  1990. url : url,
  1991. credential : password,
  1992. username : username
  1993. };
  1994. }
  1995. }
  1996. return iceServer;
  1997. };
  1998. createIceServers = function (urls, username, password) {
  1999. var iceServers = [];
  2000. for (i = 0; i < urls.length; i++) {
  2001. var iceServer = createIceServer(urls[i], username, password);
  2002. if (iceServer !== null) {
  2003. iceServers.push(iceServer);
  2004. }
  2005. }
  2006. return iceServers;
  2007. };
  2008. attachMediaStream = function (element, stream) {
  2009. element.mozSrcObject = stream;
  2010. if (stream !== null)
  2011. element.play();
  2012. return element;
  2013. };
  2014. reattachMediaStream = function (to, from) {
  2015. to.mozSrcObject = from.mozSrcObject;
  2016. to.play();
  2017. return to;
  2018. };
  2019. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2020. if (!callback) {
  2021. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2022. ': 1 argument required, but only 0 present.');
  2023. }
  2024. return callback([]);
  2025. };
  2026. // Fake get{Video,Audio}Tracks
  2027. if (!MediaStream.prototype.getVideoTracks) {
  2028. MediaStream.prototype.getVideoTracks = function () {
  2029. return [];
  2030. };
  2031. }
  2032. if (!MediaStream.prototype.getAudioTracks) {
  2033. MediaStream.prototype.getAudioTracks = function () {
  2034. return [];
  2035. };
  2036. }
  2037. AdapterJS.maybeThroughWebRTCReady();
  2038. } else if (navigator.webkitGetUserMedia) {
  2039. webrtcDetectedBrowser = 'chrome';
  2040. webrtcDetectedType = 'webkit';
  2041. webrtcDetectedVersion = parseInt(navigator
  2042. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2043. // check if browser is opera 20+
  2044. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2045. if (checkIfOpera !== null) {
  2046. webrtcDetectedBrowser = 'opera';
  2047. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2048. }
  2049. // check browser datachannel support
  2050. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2051. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2052. webrtcDetectedDCSupport = 'SCTP';
  2053. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2054. webrtcDetectedVersion > 24) {
  2055. webrtcDetectedDCSupport = 'RTP';
  2056. } else {
  2057. webrtcDetectedDCSupport = '';
  2058. }
  2059. createIceServer = function (url, username, password) {
  2060. var iceServer = null;
  2061. var url_parts = url.split(':');
  2062. if (url_parts[0].indexOf('stun') === 0) {
  2063. iceServer = { 'url' : url };
  2064. } else if (url_parts[0].indexOf('turn') === 0) {
  2065. iceServer = {
  2066. 'url' : url,
  2067. 'credential' : password,
  2068. 'username' : username
  2069. };
  2070. }
  2071. return iceServer;
  2072. };
  2073. createIceServers = function (urls, username, password) {
  2074. var iceServers = [];
  2075. if (webrtcDetectedVersion >= 34) {
  2076. iceServers = {
  2077. 'urls' : urls,
  2078. 'credential' : password,
  2079. 'username' : username
  2080. };
  2081. } else {
  2082. for (i = 0; i < urls.length; i++) {
  2083. var iceServer = createIceServer(urls[i], username, password);
  2084. if (iceServer !== null) {
  2085. iceServers.push(iceServer);
  2086. }
  2087. }
  2088. }
  2089. return iceServers;
  2090. };
  2091. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2092. if (webrtcDetectedVersion < 34) {
  2093. AdapterJS.maybeFixConfiguration(pcConfig);
  2094. }
  2095. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2096. };
  2097. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2098. navigator.getUserMedia = window.getUserMedia;
  2099. attachMediaStream = function (element, stream) {
  2100. if (typeof element.srcObject !== 'undefined') {
  2101. element.srcObject = stream;
  2102. } else if (typeof element.mozSrcObject !== 'undefined') {
  2103. element.mozSrcObject = stream;
  2104. } else if (typeof element.src !== 'undefined') {
  2105. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2106. } else {
  2107. console.log('Error attaching stream to element.');
  2108. }
  2109. return element;
  2110. };
  2111. reattachMediaStream = function (to, from) {
  2112. to.src = from.src;
  2113. return to;
  2114. };
  2115. AdapterJS.maybeThroughWebRTCReady();
  2116. } else { // TRY TO USE PLUGIN
  2117. // IE 9 is not offering an implementation of console.log until you open a console
  2118. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2119. /* jshint -W020 */
  2120. console = {} || console;
  2121. // Implemented based on console specs from MDN
  2122. // You may override these functions
  2123. console.log = function (arg) {};
  2124. console.info = function (arg) {};
  2125. console.error = function (arg) {};
  2126. console.dir = function (arg) {};
  2127. console.exception = function (arg) {};
  2128. console.trace = function (arg) {};
  2129. console.warn = function (arg) {};
  2130. console.count = function (arg) {};
  2131. console.debug = function (arg) {};
  2132. console.count = function (arg) {};
  2133. console.time = function (arg) {};
  2134. console.timeEnd = function (arg) {};
  2135. console.group = function (arg) {};
  2136. console.groupCollapsed = function (arg) {};
  2137. console.groupEnd = function (arg) {};
  2138. /* jshint +W020 */
  2139. }
  2140. webrtcDetectedType = 'plugin';
  2141. webrtcDetectedDCSupport = 'plugin';
  2142. AdapterJS.parseWebrtcDetectedBrowser();
  2143. isIE = webrtcDetectedBrowser === 'IE';
  2144. /* jshint -W035 */
  2145. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2146. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2147. /* empty because it needs to prevent the function from running. */
  2148. }
  2149. };
  2150. /* jshint +W035 */
  2151. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2152. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2153. // Call immediately if possible
  2154. // Once the plugin is set, the code will always take this path
  2155. callback();
  2156. } else {
  2157. // otherwise start a 100ms interval
  2158. var checkPluginReadyState = setInterval(function () {
  2159. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2160. clearInterval(checkPluginReadyState);
  2161. callback();
  2162. }
  2163. }, 100);
  2164. }
  2165. };
  2166. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2167. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2168. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2169. });
  2170. };
  2171. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2172. // only inject once the page is ready
  2173. if (document.readyState !== 'complete') {
  2174. return;
  2175. }
  2176. // Prevent multiple injections
  2177. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2178. return;
  2179. }
  2180. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2181. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2182. var frag = document.createDocumentFragment();
  2183. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2184. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2185. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2186. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2187. '<param name="pluginId" value="' +
  2188. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2189. '<param name="windowless" value="false" /> ' +
  2190. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2191. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2192. '" />' +
  2193. // uncomment to be able to use virtual cams
  2194. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2195. '</object>';
  2196. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2197. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2198. }
  2199. document.body.appendChild(frag);
  2200. // Need to re-fetch the plugin
  2201. AdapterJS.WebRTCPlugin.plugin =
  2202. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2203. } else {
  2204. // Load Plugin
  2205. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2206. AdapterJS.WebRTCPlugin.plugin.id =
  2207. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2208. // IE will only start the plugin if it's ACTUALLY visible
  2209. if (isIE) {
  2210. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2211. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2212. } else { // The size of the plugin on Safari should be 0x0px
  2213. // so that the autorisation prompt is at the top
  2214. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2215. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2216. }
  2217. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2218. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2219. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2220. '<param name="pluginId" value="' +
  2221. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2222. '<param name="windowless" value="false" /> ' +
  2223. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2224. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2225. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2226. }
  2227. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2228. };
  2229. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2230. function (comName, plugName, installedCb, notInstalledCb) {
  2231. if (!isIE) {
  2232. var pluginArray = navigator.plugins;
  2233. for (var i = 0; i < pluginArray.length; i++) {
  2234. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2235. installedCb();
  2236. return;
  2237. }
  2238. }
  2239. notInstalledCb();
  2240. } else {
  2241. try {
  2242. var axo = new ActiveXObject(comName + '.' + plugName);
  2243. } catch (e) {
  2244. notInstalledCb();
  2245. return;
  2246. }
  2247. installedCb();
  2248. }
  2249. };
  2250. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2251. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2252. AdapterJS.isDefined = function (variable) {
  2253. return variable !== null && variable !== undefined;
  2254. };
  2255. createIceServer = function (url, username, password) {
  2256. var iceServer = null;
  2257. var url_parts = url.split(':');
  2258. if (url_parts[0].indexOf('stun') === 0) {
  2259. iceServer = {
  2260. 'url' : url,
  2261. 'hasCredentials' : false
  2262. };
  2263. } else if (url_parts[0].indexOf('turn') === 0) {
  2264. iceServer = {
  2265. 'url' : url,
  2266. 'hasCredentials' : true,
  2267. 'credential' : password,
  2268. 'username' : username
  2269. };
  2270. }
  2271. return iceServer;
  2272. };
  2273. createIceServers = function (urls, username, password) {
  2274. var iceServers = [];
  2275. for (var i = 0; i < urls.length; ++i) {
  2276. iceServers.push(createIceServer(urls[i], username, password));
  2277. }
  2278. return iceServers;
  2279. };
  2280. RTCSessionDescription = function (info) {
  2281. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2282. return AdapterJS.WebRTCPlugin.plugin.
  2283. ConstructSessionDescription(info.type, info.sdp);
  2284. };
  2285. RTCPeerConnection = function (servers, constraints) {
  2286. var iceServers = null;
  2287. if (servers) {
  2288. iceServers = servers.iceServers;
  2289. for (var i = 0; i < iceServers.length; i++) {
  2290. if (iceServers[i].urls && !iceServers[i].url) {
  2291. iceServers[i].url = iceServers[i].urls;
  2292. }
  2293. iceServers[i].hasCredentials = AdapterJS.
  2294. isDefined(iceServers[i].username) &&
  2295. AdapterJS.isDefined(iceServers[i].credential);
  2296. }
  2297. }
  2298. var mandatory = (constraints && constraints.mandatory) ?
  2299. constraints.mandatory : null;
  2300. var optional = (constraints && constraints.optional) ?
  2301. constraints.optional : null;
  2302. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2303. return AdapterJS.WebRTCPlugin.plugin.
  2304. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2305. iceServers, mandatory, optional);
  2306. };
  2307. MediaStreamTrack = {};
  2308. MediaStreamTrack.getSources = function (callback) {
  2309. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2310. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2311. });
  2312. };
  2313. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2314. constraints.audio = constraints.audio || false;
  2315. constraints.video = constraints.video || false;
  2316. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2317. AdapterJS.WebRTCPlugin.plugin.
  2318. getUserMedia(constraints, successCallback, failureCallback);
  2319. });
  2320. };
  2321. window.navigator.getUserMedia = window.getUserMedia;
  2322. attachMediaStream = function (element, stream) {
  2323. if (!element || !element.parentNode) {
  2324. return;
  2325. }
  2326. var streamId
  2327. if (stream === null) {
  2328. streamId = '';
  2329. }
  2330. else {
  2331. stream.enableSoundTracks(true);
  2332. streamId = stream.id;
  2333. }
  2334. if (element.nodeName.toLowerCase() !== 'audio') {
  2335. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2336. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2337. var frag = document.createDocumentFragment();
  2338. var temp = document.createElement('div');
  2339. var classHTML = '';
  2340. if (element.className) {
  2341. classHTML = 'class="' + element.className + '" ';
  2342. } else if (element.attributes && element.attributes['class']) {
  2343. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2344. }
  2345. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2346. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2347. '<param name="pluginId" value="' + elementId + '" /> ' +
  2348. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2349. '<param name="windowless" value="true" /> ' +
  2350. '<param name="streamId" value="' + streamId + '" /> ' +
  2351. '</object>';
  2352. while (temp.firstChild) {
  2353. frag.appendChild(temp.firstChild);
  2354. }
  2355. var height = '';
  2356. var width = '';
  2357. if (element.getBoundingClientRect) {
  2358. var rectObject = element.getBoundingClientRect();
  2359. width = rectObject.width + 'px';
  2360. height = rectObject.height + 'px';
  2361. }
  2362. else if (element.width) {
  2363. width = element.width;
  2364. height = element.height;
  2365. } else {
  2366. // TODO: What scenario could bring us here?
  2367. }
  2368. element.parentNode.insertBefore(frag, element);
  2369. frag = document.getElementById(elementId);
  2370. frag.width = width;
  2371. frag.height = height;
  2372. element.parentNode.removeChild(element);
  2373. } else {
  2374. var children = element.children;
  2375. for (var i = 0; i !== children.length; ++i) {
  2376. if (children[i].name === 'streamId') {
  2377. children[i].value = streamId;
  2378. break;
  2379. }
  2380. }
  2381. element.setStreamId(streamId);
  2382. }
  2383. var newElement = document.getElementById(elementId);
  2384. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2385. if (isIE) { // on IE the event needs to be plugged manually
  2386. newElement.attachEvent('onplaying', newElement.onplaying);
  2387. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2388. newElement._TemOnClick = function (id) {
  2389. var arg = {
  2390. srcElement : document.getElementById(id)
  2391. };
  2392. newElement.onclick(arg);
  2393. };
  2394. }
  2395. return newElement;
  2396. } else {
  2397. return element;
  2398. }
  2399. };
  2400. reattachMediaStream = function (to, from) {
  2401. var stream = null;
  2402. var children = from.children;
  2403. for (var i = 0; i !== children.length; ++i) {
  2404. if (children[i].name === 'streamId') {
  2405. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2406. stream = AdapterJS.WebRTCPlugin.plugin
  2407. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2408. break;
  2409. }
  2410. }
  2411. if (stream !== null) {
  2412. return attachMediaStream(to, stream);
  2413. } else {
  2414. console.log('Could not find the stream associated with this element');
  2415. }
  2416. };
  2417. RTCIceCandidate = function (candidate) {
  2418. if (!candidate.sdpMid) {
  2419. candidate.sdpMid = '';
  2420. }
  2421. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2422. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2423. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2424. );
  2425. };
  2426. // inject plugin
  2427. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2428. AdapterJS.WebRTCPlugin.injectPlugin();
  2429. };
  2430. // This function will be called if the plugin is needed (browser different
  2431. // from Chrome or Firefox), but the plugin is not installed.
  2432. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2433. function() {
  2434. AdapterJS.addEvent(document,
  2435. 'readystatechange',
  2436. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2437. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2438. };
  2439. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2440. if (AdapterJS.options.hidePluginInstallPrompt) {
  2441. return;
  2442. }
  2443. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2444. if(downloadLink) { // if download link
  2445. var popupString;
  2446. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2447. popupString = 'This website requires you to install the ' +
  2448. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2449. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2450. ' WebRTC Plugin</a>' +
  2451. ' to work on this browser.';
  2452. } else { // no portal link, just print a generic explanation
  2453. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2454. }
  2455. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2456. } else { // no download link, just print a generic explanation
  2457. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2458. }
  2459. };
  2460. // Try to detect the plugin and act accordingly
  2461. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2462. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2463. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2464. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2465. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2466. }
  2467. (function () {
  2468. 'use strict';
  2469. var baseGetUserMedia = null;
  2470. AdapterJS.TEXT.EXTENSION = {
  2471. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2472. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2473. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2474. BUTTON_FF: 'Install Now',
  2475. BUTTON_CHROME: 'Go to Chrome Web Store'
  2476. };
  2477. var clone = function(obj) {
  2478. if (null == obj || "object" != typeof obj) return obj;
  2479. var copy = obj.constructor();
  2480. for (var attr in obj) {
  2481. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2482. }
  2483. return copy;
  2484. };
  2485. if (window.navigator.mozGetUserMedia) {
  2486. baseGetUserMedia = window.navigator.getUserMedia;
  2487. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2488. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2489. // intercepting screensharing requests
  2490. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2491. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2492. }
  2493. var updatedConstraints = clone(constraints);
  2494. //constraints.video.mediaSource = constraints.video.mediaSource;
  2495. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2496. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2497. // strange but this works anyway
  2498. var checkIfReady = setInterval(function () {
  2499. if (document.readyState === 'complete') {
  2500. clearInterval(checkIfReady);
  2501. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2502. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2503. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2504. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2505. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2506. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2507. } else {
  2508. failureCb(error);
  2509. }
  2510. });
  2511. }
  2512. }, 1);
  2513. } else { // regular GetUserMediaRequest
  2514. baseGetUserMedia(constraints, successCb, failureCb);
  2515. }
  2516. };
  2517. getUserMedia = navigator.getUserMedia;
  2518. } else if (window.navigator.webkitGetUserMedia) {
  2519. baseGetUserMedia = window.navigator.getUserMedia;
  2520. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2521. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2522. if (window.webrtcDetectedBrowser !== 'chrome') {
  2523. throw new Error('Current browser does not support screensharing');
  2524. }
  2525. // would be fine since no methods
  2526. var updatedConstraints = clone(constraints);
  2527. var chromeCallback = function(error, sourceId) {
  2528. if(!error) {
  2529. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2530. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2531. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2532. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2533. if (sourceId) {
  2534. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2535. }
  2536. delete updatedConstraints.video.mediaSource;
  2537. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2538. } else {
  2539. if (error === 'permission-denied') {
  2540. throw new Error('Permission denied for screen retrieval');
  2541. } else {
  2542. throw new Error('Failed retrieving selected screen');
  2543. }
  2544. }
  2545. };
  2546. var onIFrameCallback = function (event) {
  2547. if (!event.data) {
  2548. return;
  2549. }
  2550. if (event.data.chromeMediaSourceId) {
  2551. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2552. chromeCallback('permission-denied');
  2553. } else {
  2554. chromeCallback(null, event.data.chromeMediaSourceId);
  2555. }
  2556. }
  2557. if (event.data.chromeExtensionStatus) {
  2558. if (event.data.chromeExtensionStatus === 'not-installed') {
  2559. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2560. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2561. event.data.data, true, true);
  2562. } else {
  2563. chromeCallback(event.data.chromeExtensionStatus, null);
  2564. }
  2565. }
  2566. // this event listener is no more needed
  2567. window.removeEventListener('message', onIFrameCallback);
  2568. };
  2569. window.addEventListener('message', onIFrameCallback);
  2570. postFrameMessage({
  2571. captureSourceId: true
  2572. });
  2573. } else {
  2574. baseGetUserMedia(constraints, successCb, failureCb);
  2575. }
  2576. };
  2577. getUserMedia = navigator.getUserMedia;
  2578. } else {
  2579. baseGetUserMedia = window.navigator.getUserMedia;
  2580. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2581. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2582. // would be fine since no methods
  2583. var updatedConstraints = clone(constraints);
  2584. // wait for plugin to be ready
  2585. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2586. // check if screensharing feature is available
  2587. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2588. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2589. // set the constraints
  2590. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2591. updatedConstraints.video.optional.push({
  2592. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2593. });
  2594. delete updatedConstraints.video.mediaSource;
  2595. } else {
  2596. throw new Error('Your WebRTC plugin does not support screensharing');
  2597. }
  2598. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2599. });
  2600. } else {
  2601. baseGetUserMedia(constraints, successCb, failureCb);
  2602. }
  2603. };
  2604. getUserMedia = window.navigator.getUserMedia;
  2605. }
  2606. if (window.webrtcDetectedBrowser === 'chrome') {
  2607. var iframe = document.createElement('iframe');
  2608. iframe.onload = function() {
  2609. iframe.isLoaded = true;
  2610. };
  2611. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2612. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2613. iframe.style.display = 'none';
  2614. (document.body || document.documentElement).appendChild(iframe);
  2615. var postFrameMessage = function (object) {
  2616. object = object || {};
  2617. if (!iframe.isLoaded) {
  2618. setTimeout(function () {
  2619. iframe.contentWindow.postMessage(object, '*');
  2620. }, 100);
  2621. return;
  2622. }
  2623. iframe.contentWindow.postMessage(object, '*');
  2624. };
  2625. }
  2626. })();
  2627. },{}],11:[function(require,module,exports){
  2628. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2629. var UI = {};
  2630. var VideoLayout = require("./videolayout/VideoLayout.js");
  2631. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2632. var Prezi = require("./prezi/Prezi.js");
  2633. var Etherpad = require("./etherpad/Etherpad.js");
  2634. var Chat = require("./side_pannels/chat/Chat.js");
  2635. var Toolbar = require("./toolbars/Toolbar");
  2636. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2637. var BottomToolbar = require("./toolbars/BottomToolbar");
  2638. var ContactList = require("./side_pannels/contactlist/ContactList");
  2639. var Avatar = require("./avatar/Avatar");
  2640. var EventEmitter = require("events");
  2641. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2642. var Settings = require("./../settings/Settings");
  2643. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2644. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2645. UI.messageHandler = require("./util/MessageHandler");
  2646. var messageHandler = UI.messageHandler;
  2647. var Authentication = require("./authentication/Authentication");
  2648. var UIUtil = require("./util/UIUtil");
  2649. var NicknameHandler = require("./util/NicknameHandler");
  2650. var CQEvents = require("../../service/connectionquality/CQEvents");
  2651. var DesktopSharingEventTypes
  2652. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2653. var RTCEvents = require("../../service/RTC/RTCEvents");
  2654. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2655. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2656. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2657. var UIEvents = require("../../service/UI/UIEvents");
  2658. var MemberEvents = require("../../service/members/Events");
  2659. var eventEmitter = new EventEmitter();
  2660. var roomName = null;
  2661. function promptDisplayName() {
  2662. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2663. message += APP.translation.translateString(
  2664. "dialog.displayNameRequired");
  2665. message += '</h2>' +
  2666. '<input name="displayName" type="text" data-i18n=' +
  2667. '"[placeholder]defaultNickname" placeholder="' +
  2668. APP.translation.translateString(
  2669. "defaultNickname", {name: "Jane Pink"}) +
  2670. '" autofocus>';
  2671. var buttonTxt
  2672. = APP.translation.generateTranslationHTML("dialog.Ok");
  2673. var buttons = [];
  2674. buttons.push({title: buttonTxt, value: "ok"});
  2675. messageHandler.openDialog(null, message,
  2676. true,
  2677. buttons,
  2678. function (e, v, m, f) {
  2679. if (v == "ok") {
  2680. var displayName = f.displayName;
  2681. if (displayName) {
  2682. VideoLayout.inputDisplayNameHandler(displayName);
  2683. return true;
  2684. }
  2685. }
  2686. e.preventDefault();
  2687. },
  2688. function () {
  2689. var form = $.prompt.getPrompt();
  2690. var input = form.find("input[name='displayName']");
  2691. input.focus();
  2692. var button = form.find("button");
  2693. button.attr("disabled", "disabled");
  2694. input.keyup(function () {
  2695. if(!input.val())
  2696. button.attr("disabled", "disabled");
  2697. else
  2698. button.removeAttr("disabled");
  2699. });
  2700. }
  2701. );
  2702. }
  2703. function notifyForInitialMute() {
  2704. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2705. "notify.muted", null, {timeOut: 120000});
  2706. }
  2707. function setupPrezi() {
  2708. $("#reloadPresentationLink").click(function() {
  2709. Prezi.reloadPresentation();
  2710. });
  2711. }
  2712. function setupChat() {
  2713. Chat.init();
  2714. $("#toggle_smileys").click(function() {
  2715. Chat.toggleSmileys();
  2716. });
  2717. }
  2718. function setupToolbars() {
  2719. Toolbar.init(UI);
  2720. Toolbar.setupButtonsFromConfig();
  2721. BottomToolbar.init();
  2722. }
  2723. function streamHandler(stream, isMuted) {
  2724. switch (stream.type) {
  2725. case "audio":
  2726. VideoLayout.changeLocalAudio(stream, isMuted);
  2727. break;
  2728. case "video":
  2729. VideoLayout.changeLocalVideo(stream, isMuted);
  2730. break;
  2731. case "stream":
  2732. VideoLayout.changeLocalStream(stream, isMuted);
  2733. break;
  2734. }
  2735. }
  2736. function onXmppConnectionFailed(stropheErrorMsg) {
  2737. var title = APP.translation.generateTranslationHTML(
  2738. "dialog.error");
  2739. var message;
  2740. if (stropheErrorMsg) {
  2741. message = APP.translation.generateTranslationHTML(
  2742. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2743. } else {
  2744. message = APP.translation.generateTranslationHTML(
  2745. "dialog.connectError");
  2746. }
  2747. messageHandler.openDialog(
  2748. title, message, true, {}, function (e, v, m, f) { return false; });
  2749. }
  2750. function onDisposeConference(unload) {
  2751. Toolbar.showAuthenticateButton(false);
  2752. }
  2753. function onDisplayNameChanged(jid, displayName) {
  2754. ContactList.onDisplayNameChange(jid, displayName);
  2755. SettingsMenu.onDisplayNameChange(jid, displayName);
  2756. VideoLayout.onDisplayNameChanged(jid, displayName);
  2757. }
  2758. function registerListeners() {
  2759. APP.RTC.addStreamListener(streamHandler,
  2760. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2761. APP.RTC.addStreamListener(streamHandler,
  2762. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2763. APP.RTC.addStreamListener(function (stream) {
  2764. VideoLayout.onRemoteStreamAdded(stream);
  2765. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2766. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2767. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  2768. function (resourceJid) {
  2769. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2770. });
  2771. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2772. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2773. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2774. endpointsEnteringLastN, stream);
  2775. });
  2776. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2777. function (devices) {
  2778. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2779. });
  2780. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  2781. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function() {
  2782. // when the data channel becomes available, tell the bridge about video
  2783. // selections so that it can do adaptive simulcast,
  2784. // we want the notification to trigger even if userJid is undefined,
  2785. // or null.
  2786. var userJid = APP.UI.getLargeVideoJid();
  2787. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userJid);
  2788. });
  2789. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  2790. var resourceJid;
  2791. if(jid === APP.statistics.LOCAL_JID) {
  2792. resourceJid = AudioLevels.LOCAL_LEVEL;
  2793. if(APP.RTC.localAudio.isMuted()) {
  2794. audioLevel = 0;
  2795. }
  2796. } else {
  2797. resourceJid = Strophe.getResourceFromJid(jid);
  2798. }
  2799. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2800. UI.getLargeVideoJid());
  2801. });
  2802. APP.desktopsharing.addListener(function () {
  2803. ToolbarToggler.showDesktopSharingButton();
  2804. }, DesktopSharingEventTypes.INIT);
  2805. APP.desktopsharing.addListener(
  2806. Toolbar.changeDesktopSharingButtonState,
  2807. DesktopSharingEventTypes.SWITCHING_DONE);
  2808. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2809. VideoLayout.updateLocalConnectionStats);
  2810. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2811. VideoLayout.updateConnectionStats);
  2812. APP.connectionquality.addListener(CQEvents.STOP,
  2813. VideoLayout.onStatsStop);
  2814. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2815. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2816. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2817. messageHandler.openMessageDialog(
  2818. 'dialog.serviceUnavailable',
  2819. 'dialog.gracefulShutdown'
  2820. );
  2821. });
  2822. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2823. var title = APP.translation.generateTranslationHTML(
  2824. "dialog.reservationError");
  2825. var message = APP.translation.generateTranslationHTML(
  2826. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2827. messageHandler.openDialog(
  2828. title,
  2829. message,
  2830. true, {},
  2831. function (event, value, message, formVals) {
  2832. return false;
  2833. }
  2834. );
  2835. });
  2836. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2837. messageHandler.openMessageDialog("dialog.sessTerminated",
  2838. "dialog.kickMessage");
  2839. });
  2840. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2841. //FIXME: use Session Terminated from translation, but
  2842. // 'reason' text comes from XMPP packet and is not translated
  2843. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2844. messageHandler.openDialog(
  2845. title, reason, true, {},
  2846. function (event, value, message, formVals) {
  2847. return false;
  2848. }
  2849. );
  2850. });
  2851. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2852. messageHandler.showError("dialog.error",
  2853. "dialog.bridgeUnavailable");
  2854. });
  2855. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2856. Avatar.setUserAvatar(from, id);
  2857. });
  2858. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2859. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2860. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2861. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2862. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2863. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2864. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2865. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2866. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2867. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2868. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2869. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2870. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2871. onAuthenticationRequired);
  2872. APP.xmpp.addListener(XMPPEvents.VIDEO_TYPE, onPeerVideoTypeChanged);
  2873. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2874. function (resource, devices) {
  2875. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2876. });
  2877. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  2878. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  2879. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function(doMuteAudio) {
  2880. UI.setAudioMuted(doMuteAudio);
  2881. });
  2882. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2883. onDtmfSupportChanged);
  2884. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  2885. SettingsMenu.setStartMuted(audio, video);
  2886. });
  2887. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  2888. UI.setInitialMuteFromFocus(audio, video);
  2889. });
  2890. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  2891. UI.messageHandler.showError("dialog.sorry",
  2892. "dialog.internalError");
  2893. });
  2894. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function() {
  2895. messageHandler.showError("dialog.error",
  2896. "dialog.SLDFailure");
  2897. });
  2898. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function() {
  2899. messageHandler.showError("dialog.error",
  2900. "dialog.SRDFailure");
  2901. });
  2902. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function() {
  2903. messageHandler.showError();
  2904. });
  2905. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function() {
  2906. // FIXME: re-use LoginDialog which supports retries
  2907. UI.showLoginPopup(connect);
  2908. });
  2909. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function(focusComponent, retrySec) {
  2910. UI.messageHandler.notify(
  2911. null, "notify.focus",
  2912. 'disconnected', "notify.focusFail",
  2913. {component: focusComponent, ms: retrySec});
  2914. });
  2915. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function(pres) {
  2916. UI.messageHandler.openReportDialog(null,
  2917. "dialog.joinError", pres);
  2918. });
  2919. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function(pres) {
  2920. UI.messageHandler.openReportDialog(null,
  2921. "dialog.connectError", pres);
  2922. });
  2923. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function() {
  2924. var roomName = UI.generateRoomName();
  2925. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  2926. });
  2927. //NicknameHandler emits this event
  2928. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  2929. APP.xmpp.addToPresence("displayName", nickname);
  2930. });
  2931. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  2932. AudioLevels.init();
  2933. });
  2934. // Listens for video interruption events.
  2935. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  2936. // Listens for video restores events.
  2937. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  2938. }
  2939. /**
  2940. * Mutes/unmutes the local video.
  2941. *
  2942. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2943. * @param options an object which specifies optional arguments such as the
  2944. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2945. * specifies whether the method was initiated in response to a user command (in
  2946. * contrast to an automatic decision taken by the application logic)
  2947. */
  2948. function setVideoMute(mute, options) {
  2949. APP.RTC.setVideoMute(mute,
  2950. UI.setVideoMuteButtonsState,
  2951. options);
  2952. }
  2953. function onResize() {
  2954. Chat.resizeChat();
  2955. VideoLayout.resizeLargeVideoContainer();
  2956. }
  2957. function bindEvents() {
  2958. /**
  2959. * Resizes and repositions videos in full screen mode.
  2960. */
  2961. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  2962. onResize);
  2963. $(window).resize(onResize);
  2964. }
  2965. UI.start = function (init) {
  2966. document.title = interfaceConfig.APP_NAME;
  2967. var setupWelcomePage = null;
  2968. if(config.enableWelcomePage && window.location.pathname == "/" &&
  2969. (!window.localStorage.welcomePageDisabled ||
  2970. window.localStorage.welcomePageDisabled == "false")) {
  2971. $("#videoconference_page").hide();
  2972. if (!setupWelcomePage)
  2973. setupWelcomePage = require("./welcome_page/WelcomePage");
  2974. setupWelcomePage();
  2975. return;
  2976. }
  2977. $("#welcome_page").hide();
  2978. $("#videospace").mousemove(function () {
  2979. return ToolbarToggler.showToolbar();
  2980. });
  2981. // Set the defaults for prompt dialogs.
  2982. $.prompt.setDefaults({persistent: false});
  2983. registerListeners();
  2984. VideoLayout.init(eventEmitter);
  2985. NicknameHandler.init(eventEmitter);
  2986. bindEvents();
  2987. setupPrezi();
  2988. setupToolbars();
  2989. setupChat();
  2990. document.title = interfaceConfig.APP_NAME;
  2991. $("#downloadlog").click(function (event) {
  2992. dump(event.target);
  2993. });
  2994. if(config.enableWelcomePage && window.location.pathname == "/" &&
  2995. (!window.localStorage.welcomePageDisabled ||
  2996. window.localStorage.welcomePageDisabled == "false")) {
  2997. $("#videoconference_page").hide();
  2998. if (!setupWelcomePage)
  2999. setupWelcomePage = require("./welcome_page/WelcomePage");
  3000. setupWelcomePage();
  3001. return;
  3002. }
  3003. $("#welcome_page").hide();
  3004. // Display notice message at the top of the toolbar
  3005. if (config.noticeMessage) {
  3006. $('#noticeText').text(config.noticeMessage);
  3007. $('#notice').css({display: 'block'});
  3008. }
  3009. if(config.requireDisplayName) {
  3010. var currentSettings = Settings.getSettings();
  3011. if (!currentSettings.displayName) {
  3012. promptDisplayName();
  3013. }
  3014. }
  3015. init();
  3016. toastr.options = {
  3017. "closeButton": true,
  3018. "debug": false,
  3019. "positionClass": "notification-bottom-right",
  3020. "onclick": null,
  3021. "showDuration": "300",
  3022. "hideDuration": "1000",
  3023. "timeOut": "2000",
  3024. "extendedTimeOut": "1000",
  3025. "showEasing": "swing",
  3026. "hideEasing": "linear",
  3027. "showMethod": "fadeIn",
  3028. "hideMethod": "fadeOut",
  3029. "reposition": function() {
  3030. if(PanelToggler.isVisible()) {
  3031. $("#toast-container").addClass("notification-bottom-right-center");
  3032. } else {
  3033. $("#toast-container").removeClass("notification-bottom-right-center");
  3034. }
  3035. },
  3036. "newestOnTop": false
  3037. };
  3038. SettingsMenu.init();
  3039. };
  3040. function chatAddError(errorMessage, originalText) {
  3041. return Chat.chatAddError(errorMessage, originalText);
  3042. }
  3043. function chatSetSubject(text) {
  3044. return Chat.chatSetSubject(text);
  3045. }
  3046. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3047. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3048. }
  3049. function onMucJoined(jid, info) {
  3050. Toolbar.updateRoomUrl(window.location.href);
  3051. var meHTML = APP.translation.generateTranslationHTML("me");
  3052. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3053. var settings = Settings.getSettings();
  3054. // Make sure we configure our avatar id, before creating avatar for us
  3055. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3056. // Add myself to the contact list.
  3057. ContactList.addContact(jid);
  3058. // Once we've joined the muc show the toolbar
  3059. ToolbarToggler.showToolbar();
  3060. var displayName =
  3061. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3062. if (displayName)
  3063. onDisplayNameChanged('localVideoContainer', displayName);
  3064. VideoLayout.mucJoined();
  3065. }
  3066. function initEtherpad(name) {
  3067. Etherpad.init(name);
  3068. }
  3069. function onMucMemberLeft(jid) {
  3070. console.log('left.muc', jid);
  3071. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3072. '>.displayname').html();
  3073. messageHandler.notify(displayName,'notify.somebody',
  3074. 'disconnected',
  3075. 'notify.disconnected');
  3076. if (!config.startAudioMuted ||
  3077. config.startAudioMuted > APP.members.size()) {
  3078. UIUtil.playSoundNotification('userLeft');
  3079. }
  3080. ContactList.removeContact(jid);
  3081. VideoLayout.participantLeft(jid);
  3082. }
  3083. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3084. console.info("My role changed, new role: " + info.role);
  3085. onModeratorStatusChanged(isModerator);
  3086. VideoLayout.showModeratorIndicator();
  3087. SettingsMenu.onRoleChanged();
  3088. if (isModerator) {
  3089. Authentication.closeAuthenticationWindow();
  3090. messageHandler.notify(null, "notify.me",
  3091. 'connected', "notify.moderator");
  3092. }
  3093. }
  3094. function onModeratorStatusChanged(isModerator) {
  3095. Toolbar.showSipCallButton(isModerator);
  3096. Toolbar.showRecordingButton(
  3097. isModerator); //&&
  3098. // FIXME:
  3099. // Recording visible if
  3100. // there are at least 2(+ 1 focus) participants
  3101. //Object.keys(connection.emuc.members).length >= 3);
  3102. }
  3103. function onPasswordRequired(callback) {
  3104. // password is required
  3105. Toolbar.lockLockButton();
  3106. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3107. message += APP.translation.translateString(
  3108. "dialog.passwordRequired");
  3109. message += '</h2>' +
  3110. '<input name="lockKey" type="text" data-i18n=' +
  3111. '"[placeholder]dialog.password" placeholder="' +
  3112. APP.translation.translateString("dialog.password") +
  3113. '" autofocus>';
  3114. messageHandler.openTwoButtonDialog(null, null, null, message,
  3115. true,
  3116. "dialog.Ok",
  3117. function (e, v, m, f) {},
  3118. null,
  3119. function (e, v, m, f) {
  3120. if (v) {
  3121. var lockKey = f.lockKey;
  3122. if (lockKey) {
  3123. Toolbar.setSharedKey(lockKey);
  3124. callback(lockKey);
  3125. }
  3126. }
  3127. },
  3128. ':input:first'
  3129. );
  3130. }
  3131. /**
  3132. * The dialpad button is shown iff there is at least one member that supports
  3133. * DTMF (e.g. jigasi).
  3134. */
  3135. function onDtmfSupportChanged(dtmfSupport) {
  3136. //TODO: enable when the UI is ready
  3137. //Toolbar.showDialPadButton(dtmfSupport);
  3138. }
  3139. function onMucMemberJoined(jid, id, displayName) {
  3140. messageHandler.notify(displayName,'notify.somebody',
  3141. 'connected',
  3142. 'notify.connected');
  3143. if (!config.startAudioMuted ||
  3144. config.startAudioMuted > APP.members.size())
  3145. UIUtil.playSoundNotification('userJoined');
  3146. // Configure avatar
  3147. Avatar.setUserAvatar(jid, id);
  3148. // Add Peer's container
  3149. VideoLayout.ensurePeerContainerExists(jid);
  3150. }
  3151. function onMucPresenceStatus(jid, info) {
  3152. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3153. }
  3154. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3155. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3156. }
  3157. function onMucRoleChanged(role, displayName) {
  3158. VideoLayout.showModeratorIndicator();
  3159. if (role === 'moderator') {
  3160. var messageKey, messageOptions = {};
  3161. if (!displayName) {
  3162. messageKey = "notify.grantedToUnknown";
  3163. }
  3164. else {
  3165. messageKey = "notify.grantedTo";
  3166. messageOptions = {to: displayName};
  3167. }
  3168. messageHandler.notify(
  3169. displayName,'notify.somebody',
  3170. 'connected', messageKey,
  3171. messageOptions);
  3172. }
  3173. }
  3174. function onAuthenticationRequired(intervalCallback) {
  3175. Authentication.openAuthenticationDialog(
  3176. roomName, intervalCallback, function () {
  3177. Toolbar.authenticateClicked();
  3178. });
  3179. }
  3180. function onLastNChanged(oldValue, newValue) {
  3181. if (config.muteLocalVideoIfNotInLastN) {
  3182. setVideoMute(!newValue, { 'byUser': false });
  3183. }
  3184. }
  3185. UI.toggleSmileys = function () {
  3186. Chat.toggleSmileys();
  3187. };
  3188. UI.getSettings = function () {
  3189. return Settings.getSettings();
  3190. };
  3191. UI.toggleFilmStrip = function () {
  3192. return BottomToolbar.toggleFilmStrip();
  3193. };
  3194. UI.toggleChat = function () {
  3195. return BottomToolbar.toggleChat();
  3196. };
  3197. UI.toggleContactList = function () {
  3198. return BottomToolbar.toggleContactList();
  3199. };
  3200. UI.inputDisplayNameHandler = function (value) {
  3201. VideoLayout.inputDisplayNameHandler(value);
  3202. };
  3203. UI.getLargeVideoJid = function() {
  3204. return VideoLayout.getLargeVideoJid();
  3205. };
  3206. UI.generateRoomName = function() {
  3207. if(roomName)
  3208. return roomName;
  3209. var roomnode = null;
  3210. var path = window.location.pathname;
  3211. // determinde the room node from the url
  3212. // TODO: just the roomnode or the whole bare jid?
  3213. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3214. // custom function might be responsible for doing the pushstate
  3215. roomnode = config.getroomnode(path);
  3216. } else {
  3217. /* fall back to default strategy
  3218. * this is making assumptions about how the URL->room mapping happens.
  3219. * It currently assumes deployment at root, with a rewrite like the
  3220. * following one (for nginx):
  3221. location ~ ^/([a-zA-Z0-9]+)$ {
  3222. rewrite ^/(.*)$ / break;
  3223. }
  3224. */
  3225. if (path.length > 1) {
  3226. roomnode = path.substr(1).toLowerCase();
  3227. } else {
  3228. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3229. roomnode = word.toLowerCase();
  3230. window.history.pushState('VideoChat',
  3231. 'Room: ' + word, window.location.pathname + word);
  3232. }
  3233. }
  3234. roomName = roomnode + '@' + config.hosts.muc;
  3235. return roomName;
  3236. };
  3237. UI.connectionIndicatorShowMore = function(jid) {
  3238. return VideoLayout.showMore(jid);
  3239. };
  3240. UI.showLoginPopup = function(callback) {
  3241. console.log('password is required');
  3242. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3243. message += APP.translation.translateString(
  3244. "dialog.passwordRequired");
  3245. message += '</h2>' +
  3246. '<input name="username" type="text" ' +
  3247. 'placeholder="user@domain.net" autofocus>' +
  3248. '<input name="password" ' +
  3249. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3250. ' placeholder="user password">';
  3251. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3252. true,
  3253. "dialog.Ok",
  3254. function (e, v, m, f) {
  3255. if (v) {
  3256. if (f.username !== null && f.password != null) {
  3257. callback(f.username, f.password);
  3258. }
  3259. }
  3260. },
  3261. null, null, ':input:first'
  3262. );
  3263. };
  3264. UI.checkForNicknameAndJoin = function () {
  3265. Authentication.closeAuthenticationDialog();
  3266. Authentication.stopInterval();
  3267. var nick = null;
  3268. if (config.useNicks) {
  3269. nick = window.prompt('Your nickname (optional)');
  3270. }
  3271. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3272. };
  3273. function dump(elem, filename) {
  3274. elem = elem.parentNode;
  3275. elem.download = filename || 'meetlog.json';
  3276. elem.href = 'data:application/json;charset=utf-8,\n';
  3277. var data = APP.xmpp.getJingleLog();
  3278. var metadata = {};
  3279. metadata.time = new Date();
  3280. metadata.url = window.location.href;
  3281. metadata.ua = navigator.userAgent;
  3282. var log = APP.xmpp.getXmppLog();
  3283. if (log) {
  3284. metadata.xmpp = log;
  3285. }
  3286. data.metadata = metadata;
  3287. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3288. return false;
  3289. }
  3290. UI.getRoomName = function () {
  3291. return roomName;
  3292. };
  3293. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3294. if (muteAudio || muteVideo)
  3295. notifyForInitialMute();
  3296. if (muteAudio)
  3297. UI.setAudioMuted(true);
  3298. if (muteVideo)
  3299. UI.setVideoMute(true);
  3300. };
  3301. /**
  3302. * Mutes/unmutes the local video.
  3303. */
  3304. UI.toggleVideo = function () {
  3305. setVideoMute(!APP.RTC.localVideo.isMuted());
  3306. };
  3307. /**
  3308. * Mutes / unmutes audio for the local participant.
  3309. */
  3310. UI.toggleAudio = function() {
  3311. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3312. };
  3313. /**
  3314. * Sets muted audio state for the local participant.
  3315. */
  3316. UI.setAudioMuted = function (mute, earlyMute) {
  3317. var audioMute = null;
  3318. if (earlyMute)
  3319. audioMute = function (mute, cb) {
  3320. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3321. };
  3322. else
  3323. audioMute = function (mute, cb) {
  3324. return APP.xmpp.setAudioMute(mute, cb);
  3325. };
  3326. if (!audioMute(mute, function () {
  3327. VideoLayout.showLocalAudioIndicator(mute);
  3328. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3329. })) {
  3330. // We still click the button.
  3331. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3332. return;
  3333. }
  3334. };
  3335. UI.addListener = function (type, listener) {
  3336. eventEmitter.on(type, listener);
  3337. };
  3338. UI.clickOnVideo = function (videoNumber) {
  3339. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3340. if (remoteVideos.length > videoNumber) {
  3341. remoteVideos[videoNumber].click();
  3342. }
  3343. };
  3344. //Used by torture
  3345. UI.showToolbar = function () {
  3346. return ToolbarToggler.showToolbar();
  3347. };
  3348. //Used by torture
  3349. UI.dockToolbar = function (isDock) {
  3350. return ToolbarToggler.dockToolbar(isDock);
  3351. };
  3352. UI.setVideoMuteButtonsState = function (mute) {
  3353. var video = $('#video');
  3354. var communicativeClass = "icon-camera";
  3355. var muteClass = "icon-camera icon-camera-disabled";
  3356. if (mute) {
  3357. video.removeClass(communicativeClass);
  3358. video.addClass(muteClass);
  3359. } else {
  3360. video.removeClass(muteClass);
  3361. video.addClass(communicativeClass);
  3362. }
  3363. };
  3364. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3365. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3366. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3367. if(resourceJid === APP.xmpp.myResource())
  3368. SettingsMenu.changeAvatar(thumbUrl);
  3369. };
  3370. UI.setVideoMute = setVideoMute;
  3371. module.exports = UI;
  3372. },{"../../service/RTC/RTCEvents":108,"../../service/RTC/StreamEventTypes":110,"../../service/UI/UIEvents":111,"../../service/connectionquality/CQEvents":113,"../../service/desktopsharing/DesktopSharingEventTypes":114,"../../service/members/Events":115,"../../service/xmpp/XMPPEvents":117,"../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":118}],12:[function(require,module,exports){
  3373. /* global APP, interfaceConfig, $, Strophe */
  3374. var CanvasUtil = require("./CanvasUtils");
  3375. var ASDrawContext = null;
  3376. function initActiveSpeakerAudioLevels() {
  3377. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3378. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3379. // Draw a circle.
  3380. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3381. // Add a shadow around the circle
  3382. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3383. ASDrawContext.shadowOffsetX = 0;
  3384. ASDrawContext.shadowOffsetY = 0;
  3385. }
  3386. /**
  3387. * The audio Levels plugin.
  3388. */
  3389. var AudioLevels = (function(my) {
  3390. var audioLevelCanvasCache = {};
  3391. my.LOCAL_LEVEL = 'local';
  3392. my.init = function () {
  3393. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3394. initActiveSpeakerAudioLevels();
  3395. };
  3396. /**
  3397. * Updates the audio level canvas for the given peerJid. If the canvas
  3398. * didn't exist we create it.
  3399. */
  3400. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3401. var resourceJid = null;
  3402. var videoSpanId = null;
  3403. if (!peerJid)
  3404. videoSpanId = 'localVideoContainer';
  3405. else {
  3406. resourceJid = Strophe.getResourceFromJid(peerJid);
  3407. videoSpanId = 'participant_' + resourceJid;
  3408. }
  3409. var videoSpan = document.getElementById(videoSpanId);
  3410. if (!videoSpan) {
  3411. if (resourceJid)
  3412. console.error("No video element for jid", resourceJid);
  3413. else
  3414. console.error("No video element for local video.");
  3415. return;
  3416. }
  3417. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3418. var videoSpaceWidth = $('#remoteVideos').width();
  3419. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3420. var thumbnailWidth = thumbnailSize[0];
  3421. var thumbnailHeight = thumbnailSize[1];
  3422. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3423. audioLevelCanvas = document.createElement('canvas');
  3424. audioLevelCanvas.className = "audiolevel";
  3425. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3426. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3427. resizeAudioLevelCanvas( audioLevelCanvas,
  3428. thumbnailWidth,
  3429. thumbnailHeight);
  3430. videoSpan.appendChild(audioLevelCanvas);
  3431. } else {
  3432. audioLevelCanvas = audioLevelCanvas.get(0);
  3433. resizeAudioLevelCanvas( audioLevelCanvas,
  3434. thumbnailWidth,
  3435. thumbnailHeight);
  3436. }
  3437. };
  3438. /**
  3439. * Updates the audio level UI for the given resourceJid.
  3440. *
  3441. * @param resourceJid the resource jid indicating the video element for
  3442. * which we draw the audio level
  3443. * @param audioLevel the newAudio level to render
  3444. */
  3445. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3446. drawAudioLevelCanvas(resourceJid, audioLevel);
  3447. var videoSpanId = getVideoSpanId(resourceJid);
  3448. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3449. if (!audioLevelCanvas)
  3450. return;
  3451. var drawContext = audioLevelCanvas.getContext('2d');
  3452. var canvasCache = audioLevelCanvasCache[resourceJid];
  3453. drawContext.clearRect (0, 0,
  3454. audioLevelCanvas.width, audioLevelCanvas.height);
  3455. drawContext.drawImage(canvasCache, 0, 0);
  3456. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3457. if(!APP.xmpp.myJid()) {
  3458. return;
  3459. }
  3460. resourceJid = APP.xmpp.myResource();
  3461. }
  3462. if(resourceJid === largeVideoResourceJid) {
  3463. window.requestAnimationFrame(function () {
  3464. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3465. });
  3466. }
  3467. };
  3468. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3469. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3470. return;
  3471. ASDrawContext.clearRect(0, 0, 300, 300);
  3472. if(audioLevel == 0)
  3473. return;
  3474. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3475. // Fill the shape.
  3476. ASDrawContext.fill();
  3477. };
  3478. /**
  3479. * Resizes the given audio level canvas to match the given thumbnail size.
  3480. */
  3481. function resizeAudioLevelCanvas(audioLevelCanvas,
  3482. thumbnailWidth,
  3483. thumbnailHeight) {
  3484. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3485. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3486. }
  3487. /**
  3488. * Draws the audio level canvas into the cached canvas object.
  3489. *
  3490. * @param resourceJid the resource jid indicating the video element for
  3491. * which we draw the audio level
  3492. * @param audioLevel the newAudio level to render
  3493. */
  3494. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3495. if (!audioLevelCanvasCache[resourceJid]) {
  3496. var videoSpanId = getVideoSpanId(resourceJid);
  3497. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3498. /*
  3499. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3500. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3501. * error. Since audio levels are frequently updated, the errors have
  3502. * been observed to pile into the console, strain the CPU.
  3503. */
  3504. if (audioLevelCanvasOrig) {
  3505. audioLevelCanvasCache[resourceJid] =
  3506. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3507. }
  3508. }
  3509. var canvas = audioLevelCanvasCache[resourceJid];
  3510. if (!canvas)
  3511. return;
  3512. var drawContext = canvas.getContext('2d');
  3513. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3514. var shadowLevel = getShadowLevel(audioLevel);
  3515. if (shadowLevel > 0) {
  3516. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3517. CanvasUtil.drawRoundRectGlow(drawContext,
  3518. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3519. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3520. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3521. interfaceConfig.CANVAS_RADIUS,
  3522. interfaceConfig.SHADOW_COLOR,
  3523. shadowLevel);
  3524. }
  3525. }
  3526. /**
  3527. * Returns the shadow/glow level for the given audio level.
  3528. *
  3529. * @param audioLevel the audio level from which we determine the shadow
  3530. * level
  3531. */
  3532. function getShadowLevel (audioLevel) {
  3533. var shadowLevel = 0;
  3534. if (audioLevel <= 0.3) {
  3535. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3536. }
  3537. else if (audioLevel <= 0.6) {
  3538. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3539. }
  3540. else {
  3541. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3542. }
  3543. return shadowLevel;
  3544. }
  3545. /**
  3546. * Returns the video span id corresponding to the given resourceJid or local
  3547. * user.
  3548. */
  3549. function getVideoSpanId(resourceJid) {
  3550. var videoSpanId = null;
  3551. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3552. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3553. videoSpanId = 'localVideoContainer';
  3554. else
  3555. videoSpanId = 'participant_' + resourceJid;
  3556. return videoSpanId;
  3557. }
  3558. /**
  3559. * Indicates that the remote video has been resized.
  3560. */
  3561. $(document).bind('remotevideo.resized', function (event, width, height) {
  3562. var resized = false;
  3563. $('#remoteVideos>span>canvas').each(function() {
  3564. var canvas = $(this).get(0);
  3565. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3566. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3567. resized = true;
  3568. }
  3569. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3570. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3571. resized = true;
  3572. }
  3573. });
  3574. if (resized)
  3575. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3576. audioLevelCanvasCache[resourceJid].width =
  3577. width + interfaceConfig.CANVAS_EXTRA;
  3578. audioLevelCanvasCache[resourceJid].height =
  3579. height + interfaceConfig.CANVAS_EXTRA;
  3580. });
  3581. });
  3582. return my;
  3583. })(AudioLevels || {});
  3584. module.exports = AudioLevels;
  3585. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3586. /**
  3587. * Utility class for drawing canvas shapes.
  3588. */
  3589. var CanvasUtil = (function(my) {
  3590. /**
  3591. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3592. * of the glow.
  3593. *
  3594. * @param drawContext the context of the canvas to draw to
  3595. * @param x the x coordinate of the round rectangle
  3596. * @param y the y coordinate of the round rectangle
  3597. * @param w the width of the round rectangle
  3598. * @param h the height of the round rectangle
  3599. * @param glowColor the color of the glow
  3600. * @param glowWidth the width of the glow
  3601. */
  3602. my.drawRoundRectGlow
  3603. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3604. // Save the previous state of the context.
  3605. drawContext.save();
  3606. if (w < 2 * r) r = w / 2;
  3607. if (h < 2 * r) r = h / 2;
  3608. // Draw a round rectangle.
  3609. drawContext.beginPath();
  3610. drawContext.moveTo(x+r, y);
  3611. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3612. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3613. drawContext.arcTo(x, y+h, x, y, r);
  3614. drawContext.arcTo(x, y, x+w, y, r);
  3615. drawContext.closePath();
  3616. // Add a shadow around the rectangle
  3617. drawContext.shadowColor = glowColor;
  3618. drawContext.shadowBlur = glowWidth;
  3619. drawContext.shadowOffsetX = 0;
  3620. drawContext.shadowOffsetY = 0;
  3621. // Fill the shape.
  3622. drawContext.fill();
  3623. drawContext.save();
  3624. drawContext.restore();
  3625. // 1) Uncomment this line to use Composite Operation, which is doing the
  3626. // same as the clip function below and is also antialiasing the round
  3627. // border, but is said to be less fast performance wise.
  3628. // drawContext.globalCompositeOperation='destination-out';
  3629. drawContext.beginPath();
  3630. drawContext.moveTo(x+r, y);
  3631. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3632. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3633. drawContext.arcTo(x, y+h, x, y, r);
  3634. drawContext.arcTo(x, y, x+w, y, r);
  3635. drawContext.closePath();
  3636. // 2) Uncomment this line to use Composite Operation, which is doing the
  3637. // same as the clip function below and is also antialiasing the round
  3638. // border, but is said to be less fast performance wise.
  3639. // drawContext.fill();
  3640. // Comment these two lines if choosing to do the same with composite
  3641. // operation above 1 and 2.
  3642. drawContext.clip();
  3643. drawContext.clearRect(0, 0, 277, 200);
  3644. // Restore the previous context state.
  3645. drawContext.restore();
  3646. };
  3647. /**
  3648. * Clones the given canvas.
  3649. *
  3650. * @return the new cloned canvas.
  3651. */
  3652. my.cloneCanvas = function (oldCanvas) {
  3653. /*
  3654. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3655. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3656. * levels are frequently updated, the errors have been observed to pile
  3657. * into the console, strain the CPU.
  3658. */
  3659. if (!oldCanvas)
  3660. return oldCanvas;
  3661. //create a new canvas
  3662. var newCanvas = document.createElement('canvas');
  3663. var context = newCanvas.getContext('2d');
  3664. //set dimensions
  3665. newCanvas.width = oldCanvas.width;
  3666. newCanvas.height = oldCanvas.height;
  3667. //apply the old canvas to the new one
  3668. context.drawImage(oldCanvas, 0, 0);
  3669. //return the new canvas
  3670. return newCanvas;
  3671. };
  3672. return my;
  3673. })(CanvasUtil || {});
  3674. module.exports = CanvasUtil;
  3675. },{}],14:[function(require,module,exports){
  3676. /* global $, APP*/
  3677. var LoginDialog = require('./LoginDialog');
  3678. var Moderator = require('../../xmpp/moderator');
  3679. /* Initial "authentication required" dialog */
  3680. var authDialog = null;
  3681. /* Loop retry ID that wits for other user to create the room */
  3682. var authRetryId = null;
  3683. var authenticationWindow = null;
  3684. var Authentication = {
  3685. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3686. // This is the loop that will wait for the room to be created by
  3687. // someone else. 'auth_required.moderator' will bring us back here.
  3688. authRetryId = window.setTimeout(intervalCallback, 5000);
  3689. // Show prompt only if it's not open
  3690. if (authDialog !== null) {
  3691. return;
  3692. }
  3693. // extract room name from 'room@muc.server.net'
  3694. var room = roomName.substr(0, roomName.indexOf('@'));
  3695. var title
  3696. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3697. var msg
  3698. = APP.translation.generateTranslationHTML(
  3699. "dialog.WaitForHostMsg", {room: room});
  3700. var buttonTxt
  3701. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3702. var buttons = [];
  3703. buttons.push({title: buttonTxt, value: "authNow"});
  3704. authDialog = APP.UI.messageHandler.openDialog(
  3705. title,
  3706. msg,
  3707. true,
  3708. buttons,
  3709. function (onSubmitEvent, submitValue) {
  3710. // Do not close the dialog yet
  3711. onSubmitEvent.preventDefault();
  3712. // Open login popup
  3713. if (submitValue === 'authNow') {
  3714. callback();
  3715. }
  3716. }
  3717. );
  3718. },
  3719. closeAuthenticationWindow: function () {
  3720. if (authenticationWindow) {
  3721. authenticationWindow.close();
  3722. authenticationWindow = null;
  3723. }
  3724. },
  3725. xmppAuthenticate: function () {
  3726. var loginDialog = LoginDialog.show(
  3727. function (connection, state) {
  3728. if (!state) {
  3729. // User cancelled
  3730. loginDialog.close();
  3731. return;
  3732. } else if (state == APP.xmpp.Status.CONNECTED) {
  3733. loginDialog.close();
  3734. Authentication.stopInterval();
  3735. Authentication.closeAuthenticationDialog();
  3736. // Close the connection as anonymous one will be used
  3737. // to create the conference. Session-id will authorize
  3738. // the request.
  3739. connection.disconnect();
  3740. var roomName = APP.UI.generateRoomName();
  3741. Moderator.allocateConferenceFocus(roomName, function () {
  3742. // If it's not "on the fly" authentication now join
  3743. // the conference room
  3744. if (!APP.xmpp.isMUCJoined()) {
  3745. APP.UI.checkForNicknameAndJoin();
  3746. }
  3747. });
  3748. }
  3749. }, true);
  3750. },
  3751. focusAuthenticationWindow: function () {
  3752. // If auth window exists just bring it to the front
  3753. if (authenticationWindow) {
  3754. authenticationWindow.focus();
  3755. return;
  3756. }
  3757. },
  3758. closeAuthenticationDialog: function () {
  3759. // Close authentication dialog if opened
  3760. if (authDialog) {
  3761. authDialog.close();
  3762. authDialog = null;
  3763. }
  3764. },
  3765. createAuthenticationWindow: function (callback, url) {
  3766. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3767. url, 910, 660,
  3768. // On closed
  3769. function () {
  3770. // Close authentication dialog if opened
  3771. Authentication.closeAuthenticationDialog();
  3772. callback();
  3773. authenticationWindow = null;
  3774. });
  3775. return authenticationWindow;
  3776. },
  3777. stopInterval: function () {
  3778. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3779. if (authRetryId) {
  3780. window.clearTimeout(authRetryId);
  3781. authRetryId = null;
  3782. }
  3783. }
  3784. };
  3785. module.exports = Authentication;
  3786. },{"../../xmpp/moderator":59,"./LoginDialog":15}],15:[function(require,module,exports){
  3787. /* global $, APP, config*/
  3788. var XMPP = require('../../xmpp/xmpp');
  3789. var Moderator = require('../../xmpp/moderator');
  3790. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3791. // anonymous domain is not enabled
  3792. /**
  3793. * Creates new <tt>Dialog</tt> instance.
  3794. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3795. * when we either fail to connect or succeed(check Strophe.Status).
  3796. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3797. * in order to create session-id after the connection is established.
  3798. * @constructor
  3799. */
  3800. function Dialog(callback, obtainSession) {
  3801. var self = this;
  3802. var stop = false;
  3803. var connection = APP.xmpp.createConnection();
  3804. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3805. message += APP.translation.translateString("dialog.passwordRequired");
  3806. message += '</h2>' +
  3807. '<input name="username" type="text" ' +
  3808. 'placeholder="user@domain.net" autofocus>' +
  3809. '<input name="password" ' +
  3810. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3811. ' placeholder="user password">';
  3812. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3813. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3814. var states = {
  3815. login: {
  3816. html: message,
  3817. buttons: [
  3818. { title: okButton, value: true},
  3819. { title: cancelButton, value: false}
  3820. ],
  3821. focus: ':input:first',
  3822. submit: function (e, v, m, f) {
  3823. e.preventDefault();
  3824. if (v) {
  3825. var jid = f.username;
  3826. var password = f.password;
  3827. if (jid && password) {
  3828. stop = false;
  3829. connection.reset();
  3830. connDialog.goToState('connecting');
  3831. connection.connect(jid, password, stateHandler);
  3832. }
  3833. } else {
  3834. // User cancelled
  3835. stop = true;
  3836. callback();
  3837. }
  3838. }
  3839. },
  3840. connecting: {
  3841. title: APP.translation.translateString('dialog.connecting'),
  3842. html: '<div id="connectionStatus"></div>',
  3843. buttons: [],
  3844. defaultButton: 0
  3845. },
  3846. finished: {
  3847. title: APP.translation.translateString('dialog.error'),
  3848. html: '<div id="errorMessage"></div>',
  3849. buttons: [
  3850. {
  3851. title: APP.translation.translateString('dialog.retry'),
  3852. value: 'retry'
  3853. },
  3854. {
  3855. title: APP.translation.translateString('dialog.Cancel'),
  3856. value: 'cancel'
  3857. },
  3858. ],
  3859. defaultButton: 0,
  3860. submit: function (e, v, m, f) {
  3861. e.preventDefault();
  3862. if (v === 'retry')
  3863. connDialog.goToState('login');
  3864. else
  3865. callback();
  3866. }
  3867. }
  3868. };
  3869. var connDialog
  3870. = APP.UI.messageHandler.openDialogWithStates(states,
  3871. { persistent: true, closeText: '' }, null);
  3872. var stateHandler = function (status, message) {
  3873. if (stop) {
  3874. return;
  3875. }
  3876. var translateKey = "connection." + XMPP.getStatusString(status);
  3877. var statusStr = APP.translation.translateString(translateKey);
  3878. // Display current state
  3879. var connectionStatus =
  3880. connDialog.getState('connecting').find('#connectionStatus');
  3881. connectionStatus.text(statusStr);
  3882. switch (status) {
  3883. case XMPP.Status.CONNECTED:
  3884. stop = true;
  3885. if (!obtainSession) {
  3886. callback(connection, status);
  3887. return;
  3888. }
  3889. // Obtaining session-id status
  3890. connectionStatus.text(
  3891. APP.translation.translateString(
  3892. 'connection.FETCH_SESSION_ID'));
  3893. // Authenticate with Jicofo and obtain session-id
  3894. var roomName = APP.UI.generateRoomName();
  3895. // Jicofo will return new session-id when connected
  3896. // from authenticated domain
  3897. connection.sendIQ(
  3898. Moderator.createConferenceIq(roomName),
  3899. function (result) {
  3900. connectionStatus.text(
  3901. APP.translation.translateString(
  3902. 'connection.GOT_SESSION_ID'));
  3903. stop = true;
  3904. // Parse session-id
  3905. Moderator.parseSessionId(result);
  3906. callback(connection, status);
  3907. },
  3908. function (error) {
  3909. console.error("Auth on the fly failed", error);
  3910. stop = true;
  3911. var errorMsg =
  3912. APP.translation.translateString(
  3913. 'connection.GET_SESSION_ID_ERROR') +
  3914. $(error).find('>error').attr('code');
  3915. self.displayError(errorMsg);
  3916. connection.disconnect();
  3917. });
  3918. break;
  3919. case XMPP.Status.AUTHFAIL:
  3920. case XMPP.Status.CONNFAIL:
  3921. case XMPP.Status.DISCONNECTED:
  3922. stop = true;
  3923. callback(connection, status);
  3924. var errorMessage = statusStr;
  3925. if (message)
  3926. {
  3927. errorMessage += ': ' + message;
  3928. }
  3929. self.displayError(errorMessage);
  3930. break;
  3931. default:
  3932. break;
  3933. }
  3934. };
  3935. /**
  3936. * Displays error message in 'finished' state which allows either to cancel
  3937. * or retry.
  3938. * @param message the final message to be displayed.
  3939. */
  3940. this.displayError = function (message) {
  3941. var finishedState = connDialog.getState('finished');
  3942. var errorMessageElem = finishedState.find('#errorMessage');
  3943. errorMessageElem.text(message);
  3944. connDialog.goToState('finished');
  3945. };
  3946. /**
  3947. * Closes LoginDialog.
  3948. */
  3949. this.close = function () {
  3950. stop = true;
  3951. connDialog.close();
  3952. };
  3953. }
  3954. var LoginDialog = {
  3955. /**
  3956. * Displays login prompt used to establish new XMPP connection. Given
  3957. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  3958. * called when we connect successfully(status === CONNECTED) or when we fail
  3959. * to do so. On connection failure program can call Dialog.close() method in
  3960. * order to cancel or do nothing to let the user retry.
  3961. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  3962. * called when we either fail to connect or succeed(check
  3963. * Strophe.Status).
  3964. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  3965. * Jicofo in order to create session-id after the connection is
  3966. * established.
  3967. * @returns {Dialog}
  3968. */
  3969. show: function (callback, obtainSession) {
  3970. return new Dialog(callback, obtainSession);
  3971. }
  3972. };
  3973. module.exports = LoginDialog;
  3974. },{"../../xmpp/moderator":59,"../../xmpp/xmpp":67}],16:[function(require,module,exports){
  3975. var Settings = require("../../settings/Settings");
  3976. var users = {};
  3977. var Avatar = {
  3978. /**
  3979. * Sets the user's avatar in the settings menu(if local user), contact list
  3980. * and thumbnail
  3981. * @param jid jid of the user
  3982. * @param id email or userID to be used as a hash
  3983. */
  3984. setUserAvatar: function (jid, id) {
  3985. if (id) {
  3986. if (users[jid] === id) {
  3987. return;
  3988. }
  3989. users[jid] = id;
  3990. }
  3991. var thumbUrl = this.getThumbUrl(jid);
  3992. var contactListUrl = this.getContactListUrl(jid);
  3993. var resourceJid = Strophe.getResourceFromJid(jid);
  3994. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  3995. },
  3996. /**
  3997. * Returns image URL for the avatar to be displayed on large video area
  3998. * where current active speaker is presented.
  3999. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4000. */
  4001. getActiveSpeakerUrl: function (jid) {
  4002. return this.getGravatarUrl(jid, 100);
  4003. },
  4004. /**
  4005. * Returns image URL for the avatar to be displayed on small video thumbnail
  4006. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4007. */
  4008. getThumbUrl: function (jid) {
  4009. return this.getGravatarUrl(jid, 100);
  4010. },
  4011. /**
  4012. * Returns the URL for the avatar to be displayed as contactlist item
  4013. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4014. */
  4015. getContactListUrl: function (jid) {
  4016. return this.getGravatarUrl(jid, 30);
  4017. },
  4018. getGravatarUrl: function (jid, size) {
  4019. if (!jid) {
  4020. console.error("Get gravatar - jid is undefined");
  4021. return null;
  4022. }
  4023. var id = users[jid];
  4024. if (!id) {
  4025. console.warn(
  4026. "No avatar stored yet for " + jid + " - using JID as ID");
  4027. id = jid;
  4028. }
  4029. return 'https://www.gravatar.com/avatar/' +
  4030. MD5.hexdigest(id.trim().toLowerCase()) +
  4031. "?d=wavatar&size=" + (size || "30");
  4032. }
  4033. };
  4034. module.exports = Avatar;
  4035. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4036. /* global $, config,
  4037. setLargeVideoVisible, Util */
  4038. var VideoLayout = require("../videolayout/VideoLayout");
  4039. var Prezi = require("../prezi/Prezi");
  4040. var UIUtil = require("../util/UIUtil");
  4041. var etherpadName = null;
  4042. var etherpadIFrame = null;
  4043. var domain = null;
  4044. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4045. /**
  4046. * Resizes the etherpad.
  4047. */
  4048. function resize() {
  4049. if ($('#etherpad>iframe').length) {
  4050. var remoteVideos = $('#remoteVideos');
  4051. var availableHeight
  4052. = window.innerHeight - remoteVideos.outerHeight();
  4053. var availableWidth = UIUtil.getAvailableVideoWidth();
  4054. $('#etherpad>iframe').width(availableWidth);
  4055. $('#etherpad>iframe').height(availableHeight);
  4056. }
  4057. }
  4058. /**
  4059. * Creates the Etherpad button and adds it to the toolbar.
  4060. */
  4061. function enableEtherpadButton() {
  4062. if (!$('#etherpadButton').is(":visible"))
  4063. $('#etherpadButton').css({display: 'inline-block'});
  4064. }
  4065. /**
  4066. * Creates the IFrame for the etherpad.
  4067. */
  4068. function createIFrame() {
  4069. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4070. domain + etherpadName + options, function() {
  4071. document.domain = document.domain;
  4072. bubbleIframeMouseMove(etherpadIFrame);
  4073. setTimeout(function() {
  4074. // the iframes inside of the etherpad are
  4075. // not yet loaded when the etherpad iframe is loaded
  4076. var outer = etherpadIFrame.
  4077. contentDocument.getElementsByName("ace_outer")[0];
  4078. bubbleIframeMouseMove(outer);
  4079. var inner = outer.
  4080. contentDocument.getElementsByName("ace_inner")[0];
  4081. bubbleIframeMouseMove(inner);
  4082. }, 2000);
  4083. });
  4084. }
  4085. function bubbleIframeMouseMove(iframe){
  4086. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4087. iframe.contentWindow.onmousemove = function(e){
  4088. if(existingOnMouseMove) existingOnMouseMove(e);
  4089. var evt = document.createEvent("MouseEvents");
  4090. var boundingClientRect = iframe.getBoundingClientRect();
  4091. evt.initMouseEvent(
  4092. "mousemove",
  4093. true, // bubbles
  4094. false, // not cancelable
  4095. window,
  4096. e.detail,
  4097. e.screenX,
  4098. e.screenY,
  4099. e.clientX + boundingClientRect.left,
  4100. e.clientY + boundingClientRect.top,
  4101. e.ctrlKey,
  4102. e.altKey,
  4103. e.shiftKey,
  4104. e.metaKey,
  4105. e.button,
  4106. null // no related element
  4107. );
  4108. iframe.dispatchEvent(evt);
  4109. };
  4110. }
  4111. var Etherpad = {
  4112. /**
  4113. * Initializes the etherpad.
  4114. */
  4115. init: function (name) {
  4116. if (config.etherpad_base && !etherpadName && name) {
  4117. domain = config.etherpad_base;
  4118. etherpadName = name;
  4119. enableEtherpadButton();
  4120. /**
  4121. * Resizes the etherpad, when the window is resized.
  4122. */
  4123. $(window).resize(function () {
  4124. resize();
  4125. });
  4126. }
  4127. },
  4128. /**
  4129. * Opens/hides the Etherpad.
  4130. */
  4131. toggleEtherpad: function (isPresentation) {
  4132. if (!etherpadIFrame)
  4133. createIFrame();
  4134. if(VideoLayout.getLargeVideoState() === "etherpad")
  4135. {
  4136. VideoLayout.setLargeVideoState("video");
  4137. }
  4138. else
  4139. {
  4140. VideoLayout.setLargeVideoState("etherpad");
  4141. }
  4142. resize();
  4143. }
  4144. };
  4145. module.exports = Etherpad;
  4146. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4147. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4148. var UIUtil = require("../util/UIUtil");
  4149. var VideoLayout = require("../videolayout/VideoLayout");
  4150. var messageHandler = require("../util/MessageHandler");
  4151. var PreziPlayer = require("./PreziPlayer");
  4152. var preziPlayer = null;
  4153. /**
  4154. * Shows/hides a presentation.
  4155. */
  4156. function setPresentationVisible(visible) {
  4157. if (visible) {
  4158. VideoLayout.setLargeVideoState("prezi");
  4159. }
  4160. else {
  4161. VideoLayout.setLargeVideoState("video");
  4162. }
  4163. }
  4164. var Prezi = {
  4165. /**
  4166. * Reloads the current presentation.
  4167. */
  4168. reloadPresentation: function() {
  4169. var iframe = document.getElementById(preziPlayer.options.preziId);
  4170. iframe.src = iframe.src;
  4171. },
  4172. /**
  4173. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4174. * otherwise.
  4175. */
  4176. isPresentationVisible: function () {
  4177. return ($('#presentation>iframe') != null
  4178. && $('#presentation>iframe').css('opacity') == 1);
  4179. },
  4180. /**
  4181. * Opens the Prezi dialog, from which the user could choose a presentation
  4182. * to load.
  4183. */
  4184. openPreziDialog: function() {
  4185. var myprezi = APP.xmpp.getPrezi();
  4186. if (myprezi) {
  4187. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4188. null,
  4189. "dialog.removePreziMsg",
  4190. null,
  4191. false,
  4192. "dialog.Remove",
  4193. function(e,v,m,f) {
  4194. if(v) {
  4195. APP.xmpp.removePreziFromPresence();
  4196. }
  4197. }
  4198. );
  4199. }
  4200. else if (preziPlayer != null) {
  4201. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4202. null, "dialog.sharePreziMsg",
  4203. null,
  4204. false,
  4205. "dialog.Ok",
  4206. function(e,v,m,f) {
  4207. $.prompt.close();
  4208. }
  4209. );
  4210. }
  4211. else {
  4212. var html = APP.translation.generateTranslationHTML(
  4213. "dialog.sharePreziTitle");
  4214. var cancelButton = APP.translation.generateTranslationHTML(
  4215. "dialog.Cancel");
  4216. var shareButton = APP.translation.generateTranslationHTML(
  4217. "dialog.Share");
  4218. var backButton = APP.translation.generateTranslationHTML(
  4219. "dialog.Back");
  4220. var buttons = [];
  4221. var buttons1 = [];
  4222. // Cancel button to both states
  4223. buttons.push({title: cancelButton, value: false});
  4224. buttons1.push({title: cancelButton, value: false});
  4225. // Share button
  4226. buttons.push({title: shareButton, value: true});
  4227. // Back button
  4228. buttons1.push({title: backButton, value: true});
  4229. var linkError = APP.translation.generateTranslationHTML(
  4230. "dialog.preziLinkError");
  4231. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4232. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4233. var openPreziState = {
  4234. state0: {
  4235. html: '<h2>' + html + '</h2>' +
  4236. '<input name="preziUrl" type="text" ' +
  4237. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4238. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4239. '\' placeholder="' + defaultUrl + '" autofocus>',
  4240. persistent: false,
  4241. buttons: buttons,
  4242. focus: ':input:first',
  4243. defaultButton: 0,
  4244. submit: function (e, v, m, f) {
  4245. e.preventDefault();
  4246. if(v)
  4247. {
  4248. var preziUrl = f.preziUrl;
  4249. if (preziUrl)
  4250. {
  4251. var urlValue
  4252. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4253. if (urlValue.indexOf('http://prezi.com/') != 0
  4254. && urlValue.indexOf('https://prezi.com/') != 0)
  4255. {
  4256. $.prompt.goToState('state1');
  4257. return false;
  4258. }
  4259. else {
  4260. var presIdTmp = urlValue.substring(
  4261. urlValue.indexOf("prezi.com/") + 10);
  4262. if (!isAlphanumeric(presIdTmp)
  4263. || presIdTmp.indexOf('/') < 2) {
  4264. $.prompt.goToState('state1');
  4265. return false;
  4266. }
  4267. else {
  4268. APP.xmpp.addToPresence("prezi", urlValue);
  4269. $.prompt.close();
  4270. }
  4271. }
  4272. }
  4273. }
  4274. else
  4275. $.prompt.close();
  4276. }
  4277. },
  4278. state1: {
  4279. html: '<h2>' + html + '</h2>' +
  4280. linkError,
  4281. persistent: false,
  4282. buttons: buttons1,
  4283. focus: ':input:first',
  4284. defaultButton: 1,
  4285. submit: function (e, v, m, f) {
  4286. e.preventDefault();
  4287. if (v === 0)
  4288. $.prompt.close();
  4289. else
  4290. $.prompt.goToState('state0');
  4291. }
  4292. }
  4293. };
  4294. messageHandler.openDialogWithStates(openPreziState);
  4295. }
  4296. }
  4297. };
  4298. /**
  4299. * A new presentation has been added.
  4300. *
  4301. * @param event the event indicating the add of a presentation
  4302. * @param jid the jid from which the presentation was added
  4303. * @param presUrl url of the presentation
  4304. * @param currentSlide the current slide to which we should move
  4305. */
  4306. function presentationAdded(event, jid, presUrl, currentSlide) {
  4307. console.log("presentation added", presUrl);
  4308. var presId = getPresentationId(presUrl);
  4309. var elementId = 'participant_'
  4310. + Strophe.getResourceFromJid(jid)
  4311. + '_' + presId;
  4312. VideoLayout.addPreziContainer(elementId);
  4313. var controlsEnabled = false;
  4314. if (jid === APP.xmpp.myJid())
  4315. controlsEnabled = true;
  4316. setPresentationVisible(true);
  4317. VideoLayout.setLargeVideoHover(
  4318. function (event) {
  4319. if (Prezi.isPresentationVisible()) {
  4320. var reloadButtonRight = window.innerWidth
  4321. - $('#presentation>iframe').offset().left
  4322. - $('#presentation>iframe').width();
  4323. $('#reloadPresentation').css({ right: reloadButtonRight,
  4324. display:'inline-block'});
  4325. }
  4326. },
  4327. function (event) {
  4328. if (!Prezi.isPresentationVisible())
  4329. $('#reloadPresentation').css({display:'none'});
  4330. else {
  4331. var e = event.toElement || event.relatedTarget;
  4332. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4333. $('#reloadPresentation').css({display:'none'});
  4334. }
  4335. });
  4336. preziPlayer = new PreziPlayer(
  4337. 'presentation',
  4338. {preziId: presId,
  4339. width: getPresentationWidth(),
  4340. height: getPresentationHeihgt(),
  4341. controls: controlsEnabled,
  4342. debug: true
  4343. });
  4344. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4345. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4346. console.log("prezi status", event.value);
  4347. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4348. if (jid != APP.xmpp.myJid())
  4349. preziPlayer.flyToStep(currentSlide);
  4350. }
  4351. });
  4352. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4353. console.log("event value", event.value);
  4354. APP.xmpp.addToPresence("preziSlide", event.value);
  4355. });
  4356. $("#" + elementId).css( 'background-image',
  4357. 'url(../images/avatarprezi.png)');
  4358. $("#" + elementId).click(
  4359. function () {
  4360. setPresentationVisible(true);
  4361. }
  4362. );
  4363. };
  4364. /**
  4365. * A presentation has been removed.
  4366. *
  4367. * @param event the event indicating the remove of a presentation
  4368. * @param jid the jid for which the presentation was removed
  4369. * @param the url of the presentation
  4370. */
  4371. function presentationRemoved(event, jid, presUrl) {
  4372. console.log('presentation removed', presUrl);
  4373. var presId = getPresentationId(presUrl);
  4374. setPresentationVisible(false);
  4375. $('#participant_'
  4376. + Strophe.getResourceFromJid(jid)
  4377. + '_' + presId).remove();
  4378. $('#presentation>iframe').remove();
  4379. if (preziPlayer != null) {
  4380. preziPlayer.destroy();
  4381. preziPlayer = null;
  4382. }
  4383. };
  4384. /**
  4385. * Indicates if the given string is an alphanumeric string.
  4386. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4387. * purpose of checking URIs.
  4388. */
  4389. function isAlphanumeric(unsafeText) {
  4390. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4391. return regex.test(unsafeText);
  4392. }
  4393. /**
  4394. * Returns the presentation id from the given url.
  4395. */
  4396. function getPresentationId (presUrl) {
  4397. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4398. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4399. }
  4400. /**
  4401. * Returns the presentation width.
  4402. */
  4403. function getPresentationWidth() {
  4404. var availableWidth = UIUtil.getAvailableVideoWidth();
  4405. var availableHeight = getPresentationHeihgt();
  4406. var aspectRatio = 16.0 / 9.0;
  4407. if (availableHeight < availableWidth / aspectRatio) {
  4408. availableWidth = Math.floor(availableHeight * aspectRatio);
  4409. }
  4410. return availableWidth;
  4411. }
  4412. /**
  4413. * Returns the presentation height.
  4414. */
  4415. function getPresentationHeihgt() {
  4416. var remoteVideos = $('#remoteVideos');
  4417. return window.innerHeight - remoteVideos.outerHeight();
  4418. }
  4419. /**
  4420. * Resizes the presentation iframe.
  4421. */
  4422. function resize() {
  4423. if ($('#presentation>iframe')) {
  4424. $('#presentation>iframe').width(getPresentationWidth());
  4425. $('#presentation>iframe').height(getPresentationHeihgt());
  4426. }
  4427. }
  4428. /**
  4429. * Presentation has been removed.
  4430. */
  4431. $(document).bind('presentationremoved.muc', presentationRemoved);
  4432. /**
  4433. * Presentation has been added.
  4434. */
  4435. $(document).bind('presentationadded.muc', presentationAdded);
  4436. /*
  4437. * Indicates presentation slide change.
  4438. */
  4439. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4440. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4441. preziPlayer.flyToStep(current);
  4442. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4443. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4444. preziPlayer.flyToStep(current, i);
  4445. }
  4446. }
  4447. });
  4448. $(window).resize(function () {
  4449. resize();
  4450. });
  4451. module.exports = Prezi;
  4452. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4453. (function() {
  4454. "use strict";
  4455. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4456. window.PreziPlayer = (function() {
  4457. PreziPlayer.API_VERSION = 1;
  4458. PreziPlayer.CURRENT_STEP = 'currentStep';
  4459. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4460. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4461. PreziPlayer.STATUS_LOADING = 'loading';
  4462. PreziPlayer.STATUS_READY = 'ready';
  4463. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4464. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4465. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4466. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4467. PreziPlayer.EVENT_STATUS = "statusChange";
  4468. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4469. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4470. PreziPlayer.domain = "https://prezi.com";
  4471. PreziPlayer.path = "/player/";
  4472. PreziPlayer.players = {};
  4473. PreziPlayer.binded_methods = ['changesHandler'];
  4474. PreziPlayer.createMultiplePlayers = function(optionArray){
  4475. for(var i=0; i<optionArray.length; i++) {
  4476. var optionSet = optionArray[i];
  4477. new PreziPlayer(optionSet.id, optionSet);
  4478. };
  4479. };
  4480. PreziPlayer.messageReceived = function(event){
  4481. var message, item, player;
  4482. try {
  4483. message = JSON.parse(event.data);
  4484. if (message.id && (player = PreziPlayer.players[message.id])) {
  4485. if (player.options.debug === true) {
  4486. if (console && console.log)
  4487. console.log('received', message);
  4488. }
  4489. if (message.type === "changes") {
  4490. player.changesHandler(message);
  4491. }
  4492. for (var i = 0; i < player.callbacks.length; i++) {
  4493. item = player.callbacks[i];
  4494. if (item && message.type === item.event) {
  4495. item.callback(message);
  4496. }
  4497. }
  4498. }
  4499. } catch (e) { }
  4500. };
  4501. function PreziPlayer(id, options) {
  4502. var params, paramString = "", _this = this;
  4503. if (PreziPlayer.players[id]){
  4504. PreziPlayer.players[id].destroy();
  4505. }
  4506. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4507. var method_name = PreziPlayer.binded_methods[i];
  4508. _this[method_name] = __bind(_this[method_name], _this);
  4509. };
  4510. options = options || {};
  4511. this.options = options;
  4512. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4513. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4514. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4515. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4516. this.callbacks = [];
  4517. this.id = id;
  4518. this.embedTo = document.getElementById(id);
  4519. if (!this.embedTo) {
  4520. throw "The element id is not available.";
  4521. }
  4522. this.iframe = document.createElement('iframe');
  4523. params = [
  4524. { name: 'oid', value: options.preziId },
  4525. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4526. { name: 'controls', value: options.controls ? 1 : 0 }
  4527. ];
  4528. for(var i=0; i<params.length; i++) {
  4529. var param = params[i];
  4530. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4531. };
  4532. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4533. this.iframe.frameBorder = 0;
  4534. this.iframe.scrolling = "no";
  4535. this.iframe.width = options.width || 640;
  4536. this.iframe.height = options.height || 480;
  4537. this.embedTo.innerHTML = '';
  4538. // JITSI: IN CASE SOMETHING GOES WRONG.
  4539. try {
  4540. this.embedTo.appendChild(this.iframe);
  4541. }
  4542. catch (err) {
  4543. console.log("CATCH ERROR");
  4544. }
  4545. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4546. // crashes for us.
  4547. this.initPollInterval = setInterval(function(){
  4548. _this.sendMessage({'action': 'init'});
  4549. }, 500);
  4550. PreziPlayer.players[id] = this;
  4551. }
  4552. PreziPlayer.prototype.changesHandler = function(message) {
  4553. var key, value, j, item;
  4554. if (this.initPollInterval) {
  4555. clearInterval(this.initPollInterval);
  4556. this.initPollInterval = false;
  4557. }
  4558. for (key in message.data) {
  4559. if (message.data.hasOwnProperty(key)){
  4560. value = message.data[key];
  4561. this.values[key] = value;
  4562. for (j=0; j<this.callbacks.length; j++) {
  4563. item = this.callbacks[j];
  4564. if (item && item.event === key + "Change"){
  4565. item.callback({type: item.event, value: value});
  4566. }
  4567. }
  4568. }
  4569. }
  4570. };
  4571. PreziPlayer.prototype.destroy = function() {
  4572. if (this.initPollInterval) {
  4573. clearInterval(this.initPollInterval);
  4574. this.initPollInterval = false;
  4575. }
  4576. this.embedTo.innerHTML = '';
  4577. };
  4578. PreziPlayer.prototype.sendMessage = function(message) {
  4579. if (this.options.debug === true) {
  4580. if (console && console.log) console.log('sent', message);
  4581. }
  4582. message.version = PreziPlayer.API_VERSION;
  4583. message.id = this.id;
  4584. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4585. };
  4586. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4587. PreziPlayer.prototype.flyToNextStep = function() {
  4588. return this.sendMessage({
  4589. 'action': 'present',
  4590. 'data': ['moveToNextStep']
  4591. });
  4592. };
  4593. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4594. PreziPlayer.prototype.flyToPreviousStep = function() {
  4595. return this.sendMessage({
  4596. 'action': 'present',
  4597. 'data': ['moveToPrevStep']
  4598. });
  4599. };
  4600. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4601. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4602. var obj = this;
  4603. // check animation_step
  4604. if (animation_step > 0 &&
  4605. obj.values.animationCountOnSteps &&
  4606. obj.values.animationCountOnSteps[step] <= animation_step) {
  4607. animation_step = obj.values.animationCountOnSteps[step];
  4608. }
  4609. // jump to animation steps by calling flyToNextStep()
  4610. function doAnimationSteps() {
  4611. if (obj.values.isMoving == true) {
  4612. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4613. return;
  4614. }
  4615. while (animation_step-- > 0) {
  4616. obj.flyToNextStep(); // do the animation steps
  4617. }
  4618. }
  4619. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4620. // jump to the step
  4621. return this.sendMessage({
  4622. 'action': 'present',
  4623. 'data': ['moveToStep', step]
  4624. });
  4625. };
  4626. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4627. PreziPlayer.prototype.flyToObject = function(objectId) {
  4628. return this.sendMessage({
  4629. 'action': 'present',
  4630. 'data': ['moveToObject', objectId]
  4631. });
  4632. };
  4633. PreziPlayer.prototype.play = function(defaultDelay) {
  4634. return this.sendMessage({
  4635. 'action': 'present',
  4636. 'data': ['startAutoPlay', defaultDelay]
  4637. });
  4638. };
  4639. PreziPlayer.prototype.stop = function() {
  4640. return this.sendMessage({
  4641. 'action': 'present',
  4642. 'data': ['stopAutoPlay']
  4643. });
  4644. };
  4645. PreziPlayer.prototype.pause = function(defaultDelay) {
  4646. return this.sendMessage({
  4647. 'action': 'present',
  4648. 'data': ['pauseAutoPlay', defaultDelay]
  4649. });
  4650. };
  4651. PreziPlayer.prototype.getCurrentStep = function() {
  4652. return this.values.currentStep;
  4653. };
  4654. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4655. return this.values.currentAnimationStep;
  4656. };
  4657. PreziPlayer.prototype.getCurrentObject = function() {
  4658. return this.values.currentObject;
  4659. };
  4660. PreziPlayer.prototype.getStatus = function() {
  4661. return this.values.status;
  4662. };
  4663. PreziPlayer.prototype.isPlaying = function() {
  4664. return this.values.isAutoPlaying;
  4665. };
  4666. PreziPlayer.prototype.getStepCount = function() {
  4667. return this.values.stepCount;
  4668. };
  4669. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4670. return this.values.animationCountOnSteps;
  4671. };
  4672. PreziPlayer.prototype.getTitle = function() {
  4673. return this.values.title;
  4674. };
  4675. PreziPlayer.prototype.setDimensions = function(dims) {
  4676. for (var parameter in dims) {
  4677. this.iframe[parameter] = dims[parameter];
  4678. }
  4679. }
  4680. PreziPlayer.prototype.getDimensions = function() {
  4681. return {
  4682. width: parseInt(this.iframe.width, 10),
  4683. height: parseInt(this.iframe.height, 10)
  4684. }
  4685. }
  4686. PreziPlayer.prototype.on = function(event, callback) {
  4687. this.callbacks.push({
  4688. event: event,
  4689. callback: callback
  4690. });
  4691. };
  4692. PreziPlayer.prototype.off = function(event, callback) {
  4693. var j, item;
  4694. if (event === undefined) {
  4695. this.callbacks = [];
  4696. }
  4697. j = this.callbacks.length;
  4698. while (j--) {
  4699. item = this.callbacks[j];
  4700. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4701. this.callbacks.splice(j, 1);
  4702. }
  4703. }
  4704. };
  4705. if (window.addEventListener) {
  4706. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4707. } else {
  4708. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4709. }
  4710. return PreziPlayer;
  4711. })();
  4712. })();
  4713. module.exports = PreziPlayer;
  4714. },{}],20:[function(require,module,exports){
  4715. /* global require, $ */
  4716. var Chat = require("./chat/Chat");
  4717. var ContactList = require("./contactlist/ContactList");
  4718. var Settings = require("./../../settings/Settings");
  4719. var SettingsMenu = require("./settings/SettingsMenu");
  4720. var VideoLayout = require("../videolayout/VideoLayout");
  4721. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4722. var UIUtil = require("../util/UIUtil");
  4723. var LargeVideo = require("../videolayout/LargeVideo");
  4724. /**
  4725. * Toggler for the chat, contact list, settings menu, etc..
  4726. */
  4727. var PanelToggler = (function(my) {
  4728. var currentlyOpen = null;
  4729. var buttons = {
  4730. '#chatspace': '#chatBottomButton',
  4731. '#contactlist': '#contactListButton',
  4732. '#settingsmenu': '#settingsButton'
  4733. };
  4734. /**
  4735. * Toggles the windows in the side panel
  4736. * @param object the window that should be shown
  4737. * @param selector the selector for the element containing the panel
  4738. * @param onOpenComplete function to be called when the panel is opened
  4739. * @param onOpen function to be called if the window is going to be opened
  4740. * @param onClose function to be called if the window is going to be closed
  4741. */
  4742. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4743. UIUtil.buttonClick(buttons[selector], "active");
  4744. if (object.isVisible()) {
  4745. $("#toast-container").animate({
  4746. right: '5px'
  4747. },
  4748. {
  4749. queue: false,
  4750. duration: 500
  4751. });
  4752. $(selector).hide("slide", {
  4753. direction: "right",
  4754. queue: false,
  4755. duration: 500
  4756. });
  4757. if(typeof onClose === "function") {
  4758. onClose();
  4759. }
  4760. currentlyOpen = null;
  4761. }
  4762. else {
  4763. // Undock the toolbar when the chat is shown and if we're in a
  4764. // video mode.
  4765. if (LargeVideo.isLargeVideoVisible()) {
  4766. ToolbarToggler.dockToolbar(false);
  4767. }
  4768. if(currentlyOpen) {
  4769. var current = $(currentlyOpen);
  4770. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4771. current.css('z-index', 4);
  4772. setTimeout(function () {
  4773. current.css('display', 'none');
  4774. current.css('z-index', 5);
  4775. }, 500);
  4776. }
  4777. $("#toast-container").animate({
  4778. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4779. },
  4780. {
  4781. queue: false,
  4782. duration: 500
  4783. });
  4784. $(selector).show("slide", {
  4785. direction: "right",
  4786. queue: false,
  4787. duration: 500,
  4788. complete: onOpenComplete
  4789. });
  4790. if(typeof onOpen === "function") {
  4791. onOpen();
  4792. }
  4793. currentlyOpen = selector;
  4794. }
  4795. };
  4796. /**
  4797. * Opens / closes the chat area.
  4798. */
  4799. my.toggleChat = function() {
  4800. var chatCompleteFunction = Chat.isVisible() ?
  4801. function() {} : function () {
  4802. Chat.scrollChatToBottom();
  4803. $('#chatspace').trigger('shown');
  4804. };
  4805. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4806. toggle(Chat,
  4807. '#chatspace',
  4808. function () {
  4809. // Request the focus in the nickname field or the chat input field.
  4810. if ($('#nickname').css('visibility') === 'visible') {
  4811. $('#nickinput').focus();
  4812. } else {
  4813. $('#usermsg').focus();
  4814. }
  4815. },
  4816. null,
  4817. Chat.resizeChat,
  4818. null);
  4819. };
  4820. /**
  4821. * Opens / closes the contact list area.
  4822. */
  4823. my.toggleContactList = function () {
  4824. var completeFunction = ContactList.isVisible() ?
  4825. function() {} : function () { $('#contactlist').trigger('shown');};
  4826. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4827. toggle(ContactList,
  4828. '#contactlist',
  4829. null,
  4830. function() {
  4831. ContactList.setVisualNotification(false);
  4832. },
  4833. null);
  4834. };
  4835. /**
  4836. * Opens / closes the settings menu
  4837. */
  4838. my.toggleSettingsMenu = function() {
  4839. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4840. toggle(SettingsMenu,
  4841. '#settingsmenu',
  4842. null,
  4843. function() {
  4844. var settings = Settings.getSettings();
  4845. $('#setDisplayName').get(0).value = settings.displayName;
  4846. $('#setEmail').get(0).value = settings.email;
  4847. },
  4848. null);
  4849. };
  4850. /**
  4851. * Returns the size of the side panel.
  4852. */
  4853. my.getPanelSize = function () {
  4854. var availableHeight = window.innerHeight;
  4855. var availableWidth = window.innerWidth;
  4856. var panelWidth = 200;
  4857. if (availableWidth * 0.2 < 200) {
  4858. panelWidth = availableWidth * 0.2;
  4859. }
  4860. return [panelWidth, availableHeight];
  4861. };
  4862. my.isVisible = function() {
  4863. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4864. };
  4865. return my;
  4866. }(PanelToggler || {}));
  4867. module.exports = PanelToggler;
  4868. },{"../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){
  4869. /* global APP, $, Util, nickname:true */
  4870. var Replacement = require("./Replacement");
  4871. var CommandsProcessor = require("./Commands");
  4872. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4873. var smileys = require("./smileys.json").smileys;
  4874. var NicknameHandler = require("../../util/NicknameHandler");
  4875. var UIUtil = require("../../util/UIUtil");
  4876. var UIEvents = require("../../../../service/UI/UIEvents");
  4877. var notificationInterval = false;
  4878. var unreadMessages = 0;
  4879. /**
  4880. * Shows/hides a visual notification, indicating that a message has arrived.
  4881. */
  4882. function setVisualNotification(show) {
  4883. var unreadMsgElement = document.getElementById('unreadMessages');
  4884. var unreadMsgBottomElement
  4885. = document.getElementById('bottomUnreadMessages');
  4886. var glower = $('#chatButton');
  4887. var bottomGlower = $('#chatBottomButton');
  4888. if (unreadMessages) {
  4889. unreadMsgElement.innerHTML = unreadMessages.toString();
  4890. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4891. ToolbarToggler.dockToolbar(true);
  4892. var chatButtonElement
  4893. = document.getElementById('chatButton').parentNode;
  4894. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4895. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4896. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4897. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4898. unreadMsgElement.setAttribute(
  4899. 'style',
  4900. 'top:' + topIndent +
  4901. '; left:' + leftIndent + ';');
  4902. var chatBottomButtonElement
  4903. = document.getElementById('chatBottomButton').parentNode;
  4904. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4905. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4906. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4907. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  4908. unreadMsgBottomElement.setAttribute(
  4909. 'style',
  4910. 'top:' + bottomTopIndent +
  4911. '; left:' + bottomLeftIndent + ';');
  4912. if (!glower.hasClass('icon-chat-simple')) {
  4913. glower.removeClass('icon-chat');
  4914. glower.addClass('icon-chat-simple');
  4915. }
  4916. }
  4917. else {
  4918. unreadMsgElement.innerHTML = '';
  4919. unreadMsgBottomElement.innerHTML = '';
  4920. glower.removeClass('icon-chat-simple');
  4921. glower.addClass('icon-chat');
  4922. }
  4923. if (show && !notificationInterval) {
  4924. notificationInterval = window.setInterval(function () {
  4925. glower.toggleClass('active');
  4926. bottomGlower.toggleClass('active glowing');
  4927. }, 800);
  4928. }
  4929. else if (!show && notificationInterval) {
  4930. window.clearInterval(notificationInterval);
  4931. notificationInterval = false;
  4932. glower.removeClass('active');
  4933. bottomGlower.removeClass('glowing');
  4934. bottomGlower.addClass('active');
  4935. }
  4936. }
  4937. /**
  4938. * Returns the current time in the format it is shown to the user
  4939. * @returns {string}
  4940. */
  4941. function getCurrentTime(stamp) {
  4942. var now = (stamp? new Date(stamp): new Date());
  4943. var hour = now.getHours();
  4944. var minute = now.getMinutes();
  4945. var second = now.getSeconds();
  4946. if(hour.toString().length === 1) {
  4947. hour = '0'+hour;
  4948. }
  4949. if(minute.toString().length === 1) {
  4950. minute = '0'+minute;
  4951. }
  4952. if(second.toString().length === 1) {
  4953. second = '0'+second;
  4954. }
  4955. return hour+':'+minute+':'+second;
  4956. }
  4957. function toggleSmileys() {
  4958. var smileys = $('#smileysContainer');
  4959. if(!smileys.is(':visible')) {
  4960. smileys.show("slide", { direction: "down", duration: 300});
  4961. } else {
  4962. smileys.hide("slide", { direction: "down", duration: 300});
  4963. }
  4964. $('#usermsg').focus();
  4965. }
  4966. function addClickFunction(smiley, number) {
  4967. smiley.onclick = function addSmileyToMessage() {
  4968. var usermsg = $('#usermsg');
  4969. var message = usermsg.val();
  4970. message += smileys['smiley' + number];
  4971. usermsg.val(message);
  4972. usermsg.get(0).setSelectionRange(message.length, message.length);
  4973. toggleSmileys();
  4974. usermsg.focus();
  4975. };
  4976. }
  4977. /**
  4978. * Adds the smileys container to the chat
  4979. */
  4980. function addSmileys() {
  4981. var smileysContainer = document.createElement('div');
  4982. smileysContainer.id = 'smileysContainer';
  4983. for(var i = 1; i <= 21; i++) {
  4984. var smileyContainer = document.createElement('div');
  4985. smileyContainer.id = 'smiley' + i;
  4986. smileyContainer.className = 'smileyContainer';
  4987. var smiley = document.createElement('img');
  4988. smiley.src = 'images/smileys/smiley' + i + '.svg';
  4989. smiley.className = 'smiley';
  4990. addClickFunction(smiley, i);
  4991. smileyContainer.appendChild(smiley);
  4992. smileysContainer.appendChild(smileyContainer);
  4993. }
  4994. $("#chatspace").append(smileysContainer);
  4995. }
  4996. /**
  4997. * Resizes the chat conversation.
  4998. */
  4999. function resizeChatConversation() {
  5000. var msgareaHeight = $('#usermsg').outerHeight();
  5001. var chatspace = $('#chatspace');
  5002. var width = chatspace.width();
  5003. var chat = $('#chatconversation');
  5004. var smileys = $('#smileysarea');
  5005. smileys.height(msgareaHeight);
  5006. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5007. $('#smileysContainer').css('bottom', msgareaHeight);
  5008. chat.width(width - 10);
  5009. chat.height(window.innerHeight - 15 - msgareaHeight);
  5010. }
  5011. /**
  5012. * Chat related user interface.
  5013. */
  5014. var Chat = (function (my) {
  5015. /**
  5016. * Initializes chat related interface.
  5017. */
  5018. my.init = function () {
  5019. if(NicknameHandler.getNickname())
  5020. Chat.setChatConversationMode(true);
  5021. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5022. function (nickname) {
  5023. Chat.setChatConversationMode(true);
  5024. });
  5025. $('#nickinput').keydown(function (event) {
  5026. if (event.keyCode === 13) {
  5027. event.preventDefault();
  5028. var val = UIUtil.escapeHtml(this.value);
  5029. this.value = '';
  5030. if (!NicknameHandler.getNickname()) {
  5031. NicknameHandler.setNickname(val);
  5032. return;
  5033. }
  5034. }
  5035. });
  5036. var usermsg = $('#usermsg');
  5037. usermsg.keydown(function (event) {
  5038. if (event.keyCode === 13) {
  5039. event.preventDefault();
  5040. var value = this.value;
  5041. usermsg.val('').trigger('autosize.resize');
  5042. this.focus();
  5043. var command = new CommandsProcessor(value);
  5044. if(command.isCommand()) {
  5045. command.processCommand();
  5046. }
  5047. else {
  5048. var message = UIUtil.escapeHtml(value);
  5049. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5050. }
  5051. }
  5052. });
  5053. var onTextAreaResize = function () {
  5054. resizeChatConversation();
  5055. Chat.scrollChatToBottom();
  5056. };
  5057. usermsg.autosize({callback: onTextAreaResize});
  5058. $("#chatspace").bind("shown",
  5059. function () {
  5060. unreadMessages = 0;
  5061. setVisualNotification(false);
  5062. });
  5063. addSmileys();
  5064. };
  5065. /**
  5066. * Appends the given message to the chat conversation.
  5067. */
  5068. my.updateChatConversation =
  5069. function (from, displayName, message, myjid, stamp) {
  5070. var divClassName = '';
  5071. if (APP.xmpp.myJid() === from) {
  5072. divClassName = "localuser";
  5073. }
  5074. else {
  5075. divClassName = "remoteuser";
  5076. if (!Chat.isVisible()) {
  5077. unreadMessages++;
  5078. UIUtil.playSoundNotification('chatNotification');
  5079. setVisualNotification(true);
  5080. }
  5081. }
  5082. // replace links and smileys
  5083. // Strophe already escapes special symbols on sending,
  5084. // so we escape here only tags to avoid double &amp;
  5085. var escMessage = message.replace(/</g, '&lt;').
  5086. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5087. var escDisplayName = UIUtil.escapeHtml(displayName);
  5088. message = Replacement.processReplacements(escMessage);
  5089. var messageContainer =
  5090. '<div class="chatmessage">'+
  5091. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5092. '<div class="username ' + divClassName +'">' + escDisplayName +
  5093. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5094. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5095. '</div>';
  5096. $('#chatconversation').append(messageContainer);
  5097. $('#chatconversation').animate(
  5098. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5099. };
  5100. /**
  5101. * Appends error message to the conversation
  5102. * @param errorMessage the received error message.
  5103. * @param originalText the original message.
  5104. */
  5105. my.chatAddError = function(errorMessage, originalText) {
  5106. errorMessage = UIUtil.escapeHtml(errorMessage);
  5107. originalText = UIUtil.escapeHtml(originalText);
  5108. $('#chatconversation').append(
  5109. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5110. (originalText? (' \"'+ originalText + '\"') : "") +
  5111. ' was not sent.' +
  5112. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5113. $('#chatconversation').animate(
  5114. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5115. };
  5116. /**
  5117. * Sets the subject to the UI
  5118. * @param subject the subject
  5119. */
  5120. my.chatSetSubject = function(subject) {
  5121. if (subject)
  5122. subject = subject.trim();
  5123. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5124. if(subject === "") {
  5125. $("#subject").css({display: "none"});
  5126. }
  5127. else {
  5128. $("#subject").css({display: "block"});
  5129. }
  5130. };
  5131. /**
  5132. * Sets the chat conversation mode.
  5133. */
  5134. my.setChatConversationMode = function (isConversationMode) {
  5135. if (isConversationMode) {
  5136. $('#nickname').css({visibility: 'hidden'});
  5137. $('#chatconversation').css({visibility: 'visible'});
  5138. $('#usermsg').css({visibility: 'visible'});
  5139. $('#smileysarea').css({visibility: 'visible'});
  5140. $('#usermsg').focus();
  5141. }
  5142. };
  5143. /**
  5144. * Resizes the chat area.
  5145. */
  5146. my.resizeChat = function () {
  5147. var chatSize = require("../SidePanelToggler").getPanelSize();
  5148. $('#chatspace').width(chatSize[0]);
  5149. $('#chatspace').height(chatSize[1]);
  5150. resizeChatConversation();
  5151. };
  5152. /**
  5153. * Indicates if the chat is currently visible.
  5154. */
  5155. my.isVisible = function () {
  5156. return $('#chatspace').is(":visible");
  5157. };
  5158. /**
  5159. * Shows and hides the window with the smileys
  5160. */
  5161. my.toggleSmileys = toggleSmileys;
  5162. /**
  5163. * Scrolls chat to the bottom.
  5164. */
  5165. my.scrollChatToBottom = function() {
  5166. setTimeout(function () {
  5167. $('#chatconversation').scrollTop(
  5168. $('#chatconversation')[0].scrollHeight);
  5169. }, 5);
  5170. };
  5171. return my;
  5172. }(Chat || {}));
  5173. module.exports = Chat;
  5174. },{"../../../../service/UI/UIEvents":111,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5175. /* global APP, require */
  5176. var UIUtil = require("../../util/UIUtil");
  5177. /**
  5178. * List with supported commands. The keys are the names of the commands and
  5179. * the value is the function that processes the message.
  5180. * @type {{String: function}}
  5181. */
  5182. var commands = {
  5183. "topic" : processTopic
  5184. };
  5185. /**
  5186. * Extracts the command from the message.
  5187. * @param message the received message
  5188. * @returns {string} the command
  5189. */
  5190. function getCommand(message) {
  5191. if(message) {
  5192. for(var command in commands) {
  5193. if(message.indexOf("/" + command) == 0)
  5194. return command;
  5195. }
  5196. }
  5197. return "";
  5198. }
  5199. /**
  5200. * Processes the data for topic command.
  5201. * @param commandArguments the arguments of the topic command.
  5202. */
  5203. function processTopic(commandArguments) {
  5204. var topic = UIUtil.escapeHtml(commandArguments);
  5205. APP.xmpp.setSubject(topic);
  5206. }
  5207. /**
  5208. * Constructs a new CommandProccessor instance from a message that
  5209. * handles commands received via chat messages.
  5210. * @param message the message
  5211. * @constructor
  5212. */
  5213. function CommandsProcessor(message) {
  5214. var command = getCommand(message);
  5215. /**
  5216. * Returns the name of the command.
  5217. * @returns {String} the command
  5218. */
  5219. this.getCommand = function() {
  5220. return command;
  5221. };
  5222. var messageArgument = message.substr(command.length + 2);
  5223. /**
  5224. * Returns the arguments of the command.
  5225. * @returns {string}
  5226. */
  5227. this.getArgument = function() {
  5228. return messageArgument;
  5229. };
  5230. }
  5231. /**
  5232. * Checks whether this instance is valid command or not.
  5233. * @returns {boolean}
  5234. */
  5235. CommandsProcessor.prototype.isCommand = function() {
  5236. if (this.getCommand())
  5237. return true;
  5238. return false;
  5239. };
  5240. /**
  5241. * Processes the command.
  5242. */
  5243. CommandsProcessor.prototype.processCommand = function() {
  5244. if(!this.isCommand())
  5245. return;
  5246. commands[this.getCommand()](this.getArgument());
  5247. };
  5248. module.exports = CommandsProcessor;
  5249. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5250. var Smileys = require("./smileys.json");
  5251. /**
  5252. * Processes links and smileys in "body"
  5253. */
  5254. function processReplacements(body)
  5255. {
  5256. //make links clickable
  5257. body = linkify(body);
  5258. //add smileys
  5259. body = smilify(body);
  5260. return body;
  5261. }
  5262. /**
  5263. * Finds and replaces all links in the links in "body"
  5264. * with their <a href=""></a>
  5265. */
  5266. function linkify(inputText)
  5267. {
  5268. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5269. //URLs starting with http://, https://, or ftp://
  5270. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5271. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5272. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5273. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5274. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5275. //Change email addresses to mailto:: links.
  5276. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5277. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5278. return replacedText;
  5279. }
  5280. /**
  5281. * Replaces common smiley strings with images
  5282. */
  5283. function smilify(body)
  5284. {
  5285. if(!body) {
  5286. return body;
  5287. }
  5288. var regexs = Smileys["regexs"];
  5289. for(var smiley in regexs) {
  5290. if(regexs.hasOwnProperty(smiley)) {
  5291. body = body.replace(regexs[smiley],
  5292. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5293. }
  5294. }
  5295. return body;
  5296. }
  5297. module.exports = {
  5298. processReplacements: processReplacements,
  5299. linkify: linkify
  5300. };
  5301. },{"./smileys.json":24}],24:[function(require,module,exports){
  5302. module.exports={
  5303. "smileys": {
  5304. "smiley1": ":)",
  5305. "smiley2": ":(",
  5306. "smiley3": ":D",
  5307. "smiley4": "(y)",
  5308. "smiley5": " :P",
  5309. "smiley6": "(wave)",
  5310. "smiley7": "(blush)",
  5311. "smiley8": "(chuckle)",
  5312. "smiley9": "(shocked)",
  5313. "smiley10": ":*",
  5314. "smiley11": "(n)",
  5315. "smiley12": "(search)",
  5316. "smiley13": " <3",
  5317. "smiley14": "(oops)",
  5318. "smiley15": "(angry)",
  5319. "smiley16": "(angel)",
  5320. "smiley17": "(sick)",
  5321. "smiley18": ";(",
  5322. "smiley19": "(bomb)",
  5323. "smiley20": "(clap)",
  5324. "smiley21": " ;)"
  5325. },
  5326. "regexs": {
  5327. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5328. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5329. "smiley1": /(:-\)|:\))/gi,
  5330. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5331. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5332. "smiley6": /(\(wave\))/gi,
  5333. "smiley7": /(\(blush\))/gi,
  5334. "smiley8": /(\(chuckle\))/gi,
  5335. "smiley9": /(:-0|\(shocked\))/gi,
  5336. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5337. "smiley11": /(\(n\))/gi,
  5338. "smiley12": /(\(search\))/g,
  5339. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5340. "smiley14": /(\(oops\))/gi,
  5341. "smiley15": /(\(angry\))/gi,
  5342. "smiley16": /(\(angel\))/gi,
  5343. "smiley17": /(\(sick\))/gi,
  5344. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5345. "smiley19": /(\(bomb\))/gi,
  5346. "smiley20": /(\(clap\))/gi,
  5347. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5348. }
  5349. }
  5350. },{}],25:[function(require,module,exports){
  5351. /* global $, APP, Strophe */
  5352. var Avatar = require('../../avatar/Avatar');
  5353. var numberOfContacts = 0;
  5354. var notificationInterval;
  5355. /**
  5356. * Updates the number of participants in the contact list button and sets
  5357. * the glow
  5358. * @param delta indicates whether a new user has joined (1) or someone has
  5359. * left(-1)
  5360. */
  5361. function updateNumberOfParticipants(delta) {
  5362. numberOfContacts += delta;
  5363. if (numberOfContacts === 1) {
  5364. // when the user is alone we don't show the number of participants
  5365. $("#numberOfParticipants").text('');
  5366. ContactList.setVisualNotification(false);
  5367. } else if (numberOfContacts > 1) {
  5368. ContactList.setVisualNotification(!ContactList.isVisible());
  5369. $("#numberOfParticipants").text(numberOfContacts);
  5370. } else {
  5371. console.error("Invalid number of participants: " + numberOfContacts);
  5372. }
  5373. }
  5374. /**
  5375. * Creates the avatar element.
  5376. *
  5377. * @return {object} the newly created avatar element
  5378. */
  5379. function createAvatar(jid) {
  5380. var avatar = document.createElement('img');
  5381. avatar.className = "icon-avatar avatar";
  5382. avatar.src = Avatar.getContactListUrl(jid);
  5383. return avatar;
  5384. }
  5385. /**
  5386. * Creates the display name paragraph.
  5387. *
  5388. * @param displayName the display name to set
  5389. */
  5390. function createDisplayNameParagraph(key, displayName) {
  5391. var p = document.createElement('p');
  5392. if(displayName)
  5393. p.innerText = displayName;
  5394. else if(key) {
  5395. p.setAttribute("data-i18n",key);
  5396. p.innerText = APP.translation.translateString(key);
  5397. }
  5398. return p;
  5399. }
  5400. function stopGlowing(glower) {
  5401. window.clearInterval(notificationInterval);
  5402. notificationInterval = false;
  5403. glower.removeClass('glowing');
  5404. if (!ContactList.isVisible()) {
  5405. glower.removeClass('active');
  5406. }
  5407. }
  5408. /**
  5409. * Contact list.
  5410. */
  5411. var ContactList = {
  5412. /**
  5413. * Indicates if the chat is currently visible.
  5414. *
  5415. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5416. * otherwise
  5417. */
  5418. isVisible: function () {
  5419. return $('#contactlist').is(":visible");
  5420. },
  5421. /**
  5422. * Adds a contact for the given peerJid if such doesn't yet exist.
  5423. *
  5424. * @param peerJid the peerJid corresponding to the contact
  5425. */
  5426. ensureAddContact: function (peerJid) {
  5427. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5428. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5429. if (!contact || contact.length <= 0)
  5430. ContactList.addContact(peerJid);
  5431. },
  5432. /**
  5433. * Adds a contact for the given peer jid.
  5434. *
  5435. * @param peerJid the jid of the contact to add
  5436. */
  5437. addContact: function (peerJid) {
  5438. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5439. var contactlist = $('#contacts');
  5440. var newContact = document.createElement('li');
  5441. newContact.id = resourceJid;
  5442. newContact.className = "clickable";
  5443. newContact.onclick = function (event) {
  5444. if (event.currentTarget.className === "clickable") {
  5445. $(ContactList).trigger('contactclicked', [peerJid]);
  5446. }
  5447. };
  5448. newContact.appendChild(createAvatar(peerJid));
  5449. newContact.appendChild(createDisplayNameParagraph("participant"));
  5450. if (resourceJid === APP.xmpp.myResource()) {
  5451. contactlist.prepend(newContact);
  5452. }
  5453. else {
  5454. contactlist.append(newContact);
  5455. }
  5456. updateNumberOfParticipants(1);
  5457. },
  5458. /**
  5459. * Removes a contact for the given peer jid.
  5460. *
  5461. * @param peerJid the peerJid corresponding to the contact to remove
  5462. */
  5463. removeContact: function (peerJid) {
  5464. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5465. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5466. if (contact && contact.length > 0) {
  5467. var contactlist = $('#contactlist>ul');
  5468. contactlist.get(0).removeChild(contact.get(0));
  5469. updateNumberOfParticipants(-1);
  5470. }
  5471. },
  5472. setVisualNotification: function (show, stopGlowingIn) {
  5473. var glower = $('#contactListButton');
  5474. if (show && !notificationInterval) {
  5475. notificationInterval = window.setInterval(function () {
  5476. glower.toggleClass('active glowing');
  5477. }, 800);
  5478. }
  5479. else if (!show && notificationInterval) {
  5480. stopGlowing(glower);
  5481. }
  5482. if (stopGlowingIn) {
  5483. setTimeout(function () {
  5484. stopGlowing(glower);
  5485. }, stopGlowingIn);
  5486. }
  5487. },
  5488. setClickable: function (resourceJid, isClickable) {
  5489. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5490. if (isClickable) {
  5491. contact.addClass('clickable');
  5492. } else {
  5493. contact.removeClass('clickable');
  5494. }
  5495. },
  5496. onDisplayNameChange: function (peerJid, displayName) {
  5497. if (peerJid === 'localVideoContainer')
  5498. peerJid = APP.xmpp.myJid();
  5499. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5500. var contactName = $('#contacts #' + resourceJid + '>p');
  5501. if (contactName && displayName && displayName.length > 0)
  5502. contactName.html(displayName);
  5503. },
  5504. userAvatarChanged: function (resourceJid, contactListUrl) {
  5505. // set the avatar in the contact list
  5506. var contact = $('#' + resourceJid + '>img');
  5507. if (contact && contact.length > 0) {
  5508. contact.get(0).src = contactListUrl;
  5509. }
  5510. }
  5511. };
  5512. module.exports = ContactList;
  5513. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5514. /* global APP, $ */
  5515. var Avatar = require("../../avatar/Avatar");
  5516. var Settings = require("./../../../settings/Settings");
  5517. var UIUtil = require("../../util/UIUtil");
  5518. var languages = require("../../../../service/translation/languages");
  5519. function generateLanguagesSelectBox() {
  5520. var currentLang = APP.translation.getCurrentLanguage();
  5521. var html = "<select id=\"languages_selectbox\">";
  5522. var langArray = languages.getLanguages();
  5523. for(var i = 0; i < langArray.length; i++) {
  5524. var lang = langArray[i];
  5525. html += "<option ";
  5526. if(lang === currentLang)
  5527. html += "selected ";
  5528. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5529. html += "</option>";
  5530. }
  5531. return html + "</select>";
  5532. }
  5533. var SettingsMenu = {
  5534. init: function () {
  5535. var startMutedSelector = $("#startMutedOptions");
  5536. startMutedSelector.before(generateLanguagesSelectBox());
  5537. APP.translation.translateElement($("#languages_selectbox"));
  5538. $('#settingsmenu>input').keyup(function(event){
  5539. if(event.keyCode === 13) {//enter
  5540. SettingsMenu.update();
  5541. }
  5542. });
  5543. if (APP.xmpp.isModerator()) {
  5544. startMutedSelector.css("display", "block");
  5545. }
  5546. else {
  5547. startMutedSelector.css("display", "none");
  5548. }
  5549. $("#updateSettings").click(function () {
  5550. SettingsMenu.update();
  5551. });
  5552. },
  5553. onRoleChanged: function () {
  5554. if(APP.xmpp.isModerator()) {
  5555. $("#startMutedOptions").css("display", "block");
  5556. }
  5557. else {
  5558. $("#startMutedOptions").css("display", "none");
  5559. }
  5560. },
  5561. setStartMuted: function (audio, video) {
  5562. $("#startAudioMuted").attr("checked", audio);
  5563. $("#startVideoMuted").attr("checked", video);
  5564. },
  5565. update: function() {
  5566. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5567. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5568. if(newDisplayName) {
  5569. var displayName = Settings.setDisplayName(newDisplayName);
  5570. APP.xmpp.addToPresence("displayName", displayName, true);
  5571. }
  5572. var language = $("#languages_selectbox").val();
  5573. APP.translation.setLanguage(language);
  5574. Settings.setLanguage(language);
  5575. APP.xmpp.addToPresence("email", newEmail);
  5576. var email = Settings.setEmail(newEmail);
  5577. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5578. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5579. APP.xmpp.addToPresence("startMuted",
  5580. [startAudioMuted, startVideoMuted]);
  5581. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5582. },
  5583. isVisible: function() {
  5584. return $('#settingsmenu').is(':visible');
  5585. },
  5586. setDisplayName: function(newDisplayName) {
  5587. var displayName = Settings.setDisplayName(newDisplayName);
  5588. $('#setDisplayName').get(0).value = displayName;
  5589. },
  5590. onDisplayNameChange: function(peerJid, newDisplayName) {
  5591. if(peerJid === 'localVideoContainer' ||
  5592. peerJid === APP.xmpp.myJid()) {
  5593. this.setDisplayName(newDisplayName);
  5594. }
  5595. },
  5596. changeAvatar: function (thumbUrl) {
  5597. $('#avatar').get(0).src = thumbUrl;
  5598. }
  5599. };
  5600. module.exports = SettingsMenu;
  5601. },{"../../../../service/translation/languages":116,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5602. /* global $ */
  5603. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5604. var buttonHandlers = {
  5605. "bottom_toolbar_contact_list": function () {
  5606. BottomToolbar.toggleContactList();
  5607. },
  5608. "bottom_toolbar_film_strip": function () {
  5609. BottomToolbar.toggleFilmStrip();
  5610. },
  5611. "bottom_toolbar_chat": function () {
  5612. BottomToolbar.toggleChat();
  5613. }
  5614. };
  5615. var BottomToolbar = (function (my) {
  5616. my.init = function () {
  5617. for(var k in buttonHandlers)
  5618. $("#" + k).click(buttonHandlers[k]);
  5619. };
  5620. my.toggleChat = function() {
  5621. PanelToggler.toggleChat();
  5622. };
  5623. my.toggleContactList = function() {
  5624. PanelToggler.toggleContactList();
  5625. };
  5626. my.toggleFilmStrip = function() {
  5627. var filmstrip = $("#remoteVideos");
  5628. filmstrip.toggleClass("hidden");
  5629. };
  5630. $(document).bind("remotevideo.resized", function (event, width, height) {
  5631. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5632. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5633. });
  5634. return my;
  5635. }(BottomToolbar || {}));
  5636. module.exports = BottomToolbar;
  5637. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5638. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5639. Util */
  5640. var messageHandler = require("../util/MessageHandler");
  5641. var BottomToolbar = require("./BottomToolbar");
  5642. var Prezi = require("../prezi/Prezi");
  5643. var Etherpad = require("../etherpad/Etherpad");
  5644. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5645. var Authentication = require("../authentication/Authentication");
  5646. var UIUtil = require("../util/UIUtil");
  5647. var AuthenticationEvents
  5648. = require("../../../service/authentication/AuthenticationEvents");
  5649. var roomUrl = null;
  5650. var sharedKey = '';
  5651. var UI = null;
  5652. var recordingToaster = null;
  5653. var buttonHandlers = {
  5654. "toolbar_button_mute": function () {
  5655. return APP.UI.toggleAudio();
  5656. },
  5657. "toolbar_button_camera": function () {
  5658. return APP.UI.toggleVideo();
  5659. },
  5660. /*"toolbar_button_authentication": function () {
  5661. return Toolbar.authenticateClicked();
  5662. },*/
  5663. "toolbar_button_record": function () {
  5664. return toggleRecording();
  5665. },
  5666. "toolbar_button_security": function () {
  5667. return Toolbar.openLockDialog();
  5668. },
  5669. "toolbar_button_link": function () {
  5670. return Toolbar.openLinkDialog();
  5671. },
  5672. "toolbar_button_chat": function () {
  5673. return BottomToolbar.toggleChat();
  5674. },
  5675. "toolbar_button_prezi": function () {
  5676. return Prezi.openPreziDialog();
  5677. },
  5678. "toolbar_button_etherpad": function () {
  5679. return Etherpad.toggleEtherpad(0);
  5680. },
  5681. "toolbar_button_desktopsharing": function () {
  5682. return APP.desktopsharing.toggleScreenSharing();
  5683. },
  5684. "toolbar_button_fullScreen": function() {
  5685. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  5686. return Toolbar.toggleFullScreen();
  5687. },
  5688. "toolbar_button_sip": function () {
  5689. return callSipButtonClicked();
  5690. },
  5691. "toolbar_button_dialpad": function () {
  5692. return dialpadButtonClicked();
  5693. },
  5694. "toolbar_button_settings": function () {
  5695. PanelToggler.toggleSettingsMenu();
  5696. },
  5697. "toolbar_button_hangup": function () {
  5698. return hangup();
  5699. },
  5700. "toolbar_button_login": function () {
  5701. Toolbar.authenticateClicked();
  5702. },
  5703. "toolbar_button_logout": function () {
  5704. // Ask for confirmation
  5705. messageHandler.openTwoButtonDialog(
  5706. "dialog.logoutTitle",
  5707. null,
  5708. "dialog.logoutQuestion",
  5709. null,
  5710. false,
  5711. "dialog.Yes",
  5712. function (evt, yes) {
  5713. if (yes) {
  5714. APP.xmpp.logout(function (url) {
  5715. if (url) {
  5716. window.location.href = url;
  5717. } else {
  5718. hangup();
  5719. }
  5720. });
  5721. }
  5722. });
  5723. }
  5724. };
  5725. function hangup() {
  5726. APP.xmpp.disposeConference();
  5727. if(config.enableWelcomePage) {
  5728. setTimeout(function() {
  5729. window.localStorage.welcomePageDisabled = false;
  5730. window.location.pathname = "/";
  5731. }, 10000);
  5732. }
  5733. var title = APP.translation.generateTranslationHTML(
  5734. "dialog.sessTerminated");
  5735. var msg = APP.translation.generateTranslationHTML(
  5736. "dialog.hungUp");
  5737. var button = APP.translation.generateTranslationHTML(
  5738. "dialog.joinAgain");
  5739. var buttons = [];
  5740. buttons.push({title: button, value: true});
  5741. UI.messageHandler.openDialog(
  5742. title,
  5743. msg,
  5744. true,
  5745. buttons,
  5746. function(event, value, message, formVals) {
  5747. window.location.reload();
  5748. return false;
  5749. }
  5750. );
  5751. }
  5752. /**
  5753. * Starts or stops the recording for the conference.
  5754. */
  5755. function toggleRecording() {
  5756. APP.xmpp.toggleRecording(function (callback) {
  5757. var msg = APP.translation.generateTranslationHTML(
  5758. "dialog.recordingToken");
  5759. var token = APP.translation.translateString("dialog.token");
  5760. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5761. '<h2>' + msg + '</h2>' +
  5762. '<input name="recordingToken" type="text" ' +
  5763. ' data-i18n="[placeholder]dialog.token" ' +
  5764. 'placeholder="' + token + '" autofocus>',
  5765. false,
  5766. "dialog.Save",
  5767. function (e, v, m, f) {
  5768. if (v) {
  5769. var token = f.recordingToken;
  5770. if (token) {
  5771. callback(UIUtil.escapeHtml(token));
  5772. }
  5773. }
  5774. },
  5775. null,
  5776. function () { },
  5777. ':input:first'
  5778. );
  5779. }, Toolbar.setRecordingButtonState);
  5780. }
  5781. /**
  5782. * Locks / unlocks the room.
  5783. */
  5784. function lockRoom(lock) {
  5785. var currentSharedKey = '';
  5786. if (lock)
  5787. currentSharedKey = sharedKey;
  5788. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5789. // password is required
  5790. if (sharedKey) {
  5791. console.log('set room password');
  5792. Toolbar.lockLockButton();
  5793. }
  5794. else {
  5795. console.log('removed room password');
  5796. Toolbar.unlockLockButton();
  5797. }
  5798. }, function (err) {
  5799. console.warn('setting password failed', err);
  5800. messageHandler.showError("dialog.lockTitle",
  5801. "dialog.lockMessage");
  5802. Toolbar.setSharedKey('');
  5803. }, function () {
  5804. console.warn('room passwords not supported');
  5805. messageHandler.showError("dialog.warning",
  5806. "dialog.passwordNotSupported");
  5807. Toolbar.setSharedKey('');
  5808. });
  5809. }
  5810. /**
  5811. * Invite participants to conference.
  5812. */
  5813. function inviteParticipants() {
  5814. if (roomUrl === null)
  5815. return;
  5816. var sharedKeyText = "";
  5817. if (sharedKey && sharedKey.length > 0) {
  5818. sharedKeyText =
  5819. APP.translation.translateString("email.sharedKey",
  5820. {sharedKey: sharedKey});
  5821. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5822. }
  5823. var supportedBrowsers = "Chromium, Google Chrome " +
  5824. APP.translation.translateString("email.and") + " Opera";
  5825. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5826. var subject = APP.translation.translateString("email.subject",
  5827. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5828. var body = APP.translation.translateString("email.body",
  5829. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5830. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5831. body = body.replace(/\n/g, "%0D%0A");
  5832. if (window.localStorage.displayname) {
  5833. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5834. }
  5835. if (interfaceConfig.INVITATION_POWERED_BY) {
  5836. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5837. }
  5838. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5839. }
  5840. function dialpadButtonClicked() {
  5841. //TODO show the dialpad box
  5842. }
  5843. function callSipButtonClicked() {
  5844. var defaultNumber
  5845. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5846. var sipMsg = APP.translation.generateTranslationHTML(
  5847. "dialog.sipMsg");
  5848. messageHandler.openTwoButtonDialog(null, null, null,
  5849. '<h2>' + sipMsg + '</h2>' +
  5850. '<input name="sipNumber" type="text"' +
  5851. ' value="' + defaultNumber + '" autofocus>',
  5852. false,
  5853. "dialog.Dial",
  5854. function (e, v, m, f) {
  5855. if (v) {
  5856. var numberInput = f.sipNumber;
  5857. if (numberInput) {
  5858. APP.xmpp.dial(
  5859. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5860. }
  5861. }
  5862. },
  5863. null, null, ':input:first'
  5864. );
  5865. }
  5866. var Toolbar = (function (my) {
  5867. my.init = function (ui) {
  5868. for(var k in buttonHandlers)
  5869. $("#" + k).click(buttonHandlers[k]);
  5870. UI = ui;
  5871. // Update login info
  5872. APP.xmpp.addListener(
  5873. AuthenticationEvents.IDENTITY_UPDATED,
  5874. function (authenticationEnabled, userIdentity) {
  5875. var loggedIn = false;
  5876. if (userIdentity) {
  5877. loggedIn = true;
  5878. }
  5879. Toolbar.showAuthenticateButton(authenticationEnabled);
  5880. if (authenticationEnabled) {
  5881. Toolbar.setAuthenticatedIdentity(userIdentity);
  5882. Toolbar.showLoginButton(!loggedIn);
  5883. Toolbar.showLogoutButton(loggedIn);
  5884. }
  5885. }
  5886. );
  5887. };
  5888. /**
  5889. * Sets shared key
  5890. * @param sKey the shared key
  5891. */
  5892. my.setSharedKey = function (sKey) {
  5893. sharedKey = sKey;
  5894. };
  5895. my.authenticateClicked = function () {
  5896. Authentication.focusAuthenticationWindow();
  5897. if (!APP.xmpp.isExternalAuthEnabled()) {
  5898. Authentication.xmppAuthenticate();
  5899. return;
  5900. }
  5901. // Get authentication URL
  5902. if (!APP.xmpp.isMUCJoined()) {
  5903. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  5904. // If conference has not been started yet - redirect to login page
  5905. window.location.href = url;
  5906. });
  5907. } else {
  5908. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  5909. // Otherwise - open popup with authentication URL
  5910. var authenticationWindow = Authentication.createAuthenticationWindow(
  5911. function () {
  5912. // On popup closed - retry room allocation
  5913. APP.xmpp.allocateConferenceFocus(
  5914. APP.UI.getRoomName(),
  5915. function () { console.info("AUTH DONE"); }
  5916. );
  5917. }, url);
  5918. if (!authenticationWindow) {
  5919. messageHandler.openMessageDialog(
  5920. null, "dialog.popupError");
  5921. }
  5922. });
  5923. }
  5924. };
  5925. /**
  5926. * Updates the room invite url.
  5927. */
  5928. my.updateRoomUrl = function (newRoomUrl) {
  5929. roomUrl = newRoomUrl;
  5930. // If the invite dialog has been already opened we update the information.
  5931. var inviteLink = document.getElementById('inviteLinkRef');
  5932. if (inviteLink) {
  5933. inviteLink.value = roomUrl;
  5934. inviteLink.select();
  5935. $('#inviteLinkRef').parent()
  5936. .find('button[value=true]').prop('disabled', false);
  5937. }
  5938. };
  5939. /**
  5940. * Disables and enables some of the buttons.
  5941. */
  5942. my.setupButtonsFromConfig = function () {
  5943. if (config.disablePrezi) {
  5944. $("#prezi_button").css({display: "none"});
  5945. }
  5946. };
  5947. /**
  5948. * Opens the lock room dialog.
  5949. */
  5950. my.openLockDialog = function () {
  5951. // Only the focus is able to set a shared key.
  5952. if (!APP.xmpp.isModerator()) {
  5953. if (sharedKey) {
  5954. messageHandler.openMessageDialog(null,
  5955. "dialog.passwordError");
  5956. } else {
  5957. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  5958. }
  5959. } else {
  5960. if (sharedKey) {
  5961. messageHandler.openTwoButtonDialog(null, null,
  5962. "dialog.passwordCheck",
  5963. null,
  5964. false,
  5965. "dialog.Remove",
  5966. function (e, v) {
  5967. if (v) {
  5968. Toolbar.setSharedKey('');
  5969. lockRoom(false);
  5970. }
  5971. });
  5972. } else {
  5973. var msg = APP.translation.generateTranslationHTML(
  5974. "dialog.passwordMsg");
  5975. var yourPassword = APP.translation.translateString(
  5976. "dialog.yourPassword");
  5977. messageHandler.openTwoButtonDialog(null, null, null,
  5978. '<h2>' + msg + '</h2>' +
  5979. '<input name="lockKey" type="text"' +
  5980. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  5981. 'placeholder="' + yourPassword + '" autofocus>',
  5982. false,
  5983. "dialog.Save",
  5984. function (e, v, m, f) {
  5985. if (v) {
  5986. var lockKey = f.lockKey;
  5987. if (lockKey) {
  5988. Toolbar.setSharedKey(
  5989. UIUtil.escapeHtml(lockKey));
  5990. lockRoom(true);
  5991. }
  5992. }
  5993. },
  5994. null, null, 'input:first'
  5995. );
  5996. }
  5997. }
  5998. };
  5999. /**
  6000. * Opens the invite link dialog.
  6001. */
  6002. my.openLinkDialog = function () {
  6003. var inviteAttreibutes;
  6004. if (roomUrl === null) {
  6005. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6006. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6007. } else {
  6008. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6009. }
  6010. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6011. null, null,
  6012. '<input id="inviteLinkRef" type="text" ' +
  6013. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6014. false,
  6015. "dialog.Invite",
  6016. function (e, v) {
  6017. if (v) {
  6018. if (roomUrl) {
  6019. inviteParticipants();
  6020. }
  6021. }
  6022. },
  6023. function (event) {
  6024. if (roomUrl) {
  6025. document.getElementById('inviteLinkRef').select();
  6026. } else {
  6027. if (event && event.target)
  6028. $(event.target)
  6029. .find('button[value=true]').prop('disabled', true);
  6030. }
  6031. }
  6032. );
  6033. };
  6034. /**
  6035. * Opens the settings dialog.
  6036. * FIXME: not used ?
  6037. */
  6038. my.openSettingsDialog = function () {
  6039. var settings1 = APP.translation.generateTranslationHTML(
  6040. "dialog.settings1");
  6041. var settings2 = APP.translation.generateTranslationHTML(
  6042. "dialog.settings2");
  6043. var settings3 = APP.translation.generateTranslationHTML(
  6044. "dialog.settings3");
  6045. var yourPassword = APP.translation.translateString(
  6046. "dialog.yourPassword");
  6047. messageHandler.openTwoButtonDialog(null,
  6048. '<h2>' + settings1 + '</h2>' +
  6049. '<input type="checkbox" id="initMuted">' +
  6050. settings2 + '<br/>' +
  6051. '<input type="checkbox" id="requireNicknames">' +
  6052. settings3 +
  6053. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6054. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6055. null,
  6056. null,
  6057. false,
  6058. "dialog.Save",
  6059. function () {
  6060. document.getElementById('lockKey').focus();
  6061. },
  6062. function (e, v) {
  6063. if (v) {
  6064. if ($('#initMuted').is(":checked")) {
  6065. // it is checked
  6066. }
  6067. if ($('#requireNicknames').is(":checked")) {
  6068. // it is checked
  6069. }
  6070. /*
  6071. var lockKey = document.getElementById('lockKey');
  6072. if (lockKey.value) {
  6073. setSharedKey(lockKey.value);
  6074. lockRoom(true);
  6075. }
  6076. */
  6077. }
  6078. }
  6079. );
  6080. };
  6081. /**
  6082. * Toggles the application in and out of full screen mode
  6083. * (a.k.a. presentation mode in Chrome).
  6084. */
  6085. my.toggleFullScreen = function () {
  6086. var fsElement = document.documentElement;
  6087. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6088. //Enter Full Screen
  6089. if (fsElement.mozRequestFullScreen) {
  6090. fsElement.mozRequestFullScreen();
  6091. }
  6092. else {
  6093. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6094. }
  6095. } else {
  6096. //Exit Full Screen
  6097. if (document.mozCancelFullScreen) {
  6098. document.mozCancelFullScreen();
  6099. } else {
  6100. document.webkitCancelFullScreen();
  6101. }
  6102. }
  6103. };
  6104. /**
  6105. * Unlocks the lock button state.
  6106. */
  6107. my.unlockLockButton = function () {
  6108. if ($("#lockIcon").hasClass("icon-security-locked"))
  6109. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6110. };
  6111. /**
  6112. * Updates the lock button state to locked.
  6113. */
  6114. my.lockLockButton = function () {
  6115. if ($("#lockIcon").hasClass("icon-security"))
  6116. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6117. };
  6118. /**
  6119. * Shows or hides authentication button
  6120. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6121. */
  6122. my.showAuthenticateButton = function (show) {
  6123. if (show) {
  6124. $('#authentication').css({display: "inline"});
  6125. }
  6126. else {
  6127. $('#authentication').css({display: "none"});
  6128. }
  6129. };
  6130. // Shows or hides the 'recording' button.
  6131. my.showRecordingButton = function (show) {
  6132. if (!config.enableRecording) {
  6133. return;
  6134. }
  6135. if (show) {
  6136. $('#recording').css({display: "inline"});
  6137. }
  6138. else {
  6139. $('#recording').css({display: "none"});
  6140. }
  6141. };
  6142. // Sets the state of the recording button
  6143. my.setRecordingButtonState = function (recordingState) {
  6144. var selector = $('#recordButton');
  6145. if (recordingState === 'on') {
  6146. selector.removeClass("icon-recEnable");
  6147. selector.addClass("icon-recEnable active");
  6148. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6149. var recordOnKey = "recording.on";
  6150. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6151. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6152. setTimeout(function(){
  6153. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6154. $('#videoConnectionMessage').css({display: "none"});
  6155. }, 1500);
  6156. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6157. null, null, {timeOut: 0, closeButton: null});
  6158. } else if (recordingState === 'off') {
  6159. selector.removeClass("icon-recEnable active");
  6160. selector.addClass("icon-recEnable");
  6161. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6162. $('#videoConnectionMessage').css({display: "none"});
  6163. if (recordingToaster)
  6164. messageHandler.remove(recordingToaster);
  6165. } else if (recordingState === 'pending') {
  6166. selector.removeClass("icon-recEnable active");
  6167. selector.addClass("icon-recEnable");
  6168. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6169. var recordPendingKey = "recording.pending";
  6170. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6171. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6172. $('#videoConnectionMessage').css({display: "block"});
  6173. }
  6174. };
  6175. // Shows or hides SIP calls button
  6176. my.showSipCallButton = function (show) {
  6177. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6178. $('#sipCallButton').css({display: "inline-block"});
  6179. } else {
  6180. $('#sipCallButton').css({display: "none"});
  6181. }
  6182. };
  6183. // Shows or hides the dialpad button
  6184. my.showDialPadButton = function (show) {
  6185. if (show) {
  6186. $('#dialPadButton').css({display: "inline-block"});
  6187. } else {
  6188. $('#dialPadButton').css({display: "none"});
  6189. }
  6190. };
  6191. /**
  6192. * Displays user authenticated identity name(login).
  6193. * @param authIdentity identity name to be displayed.
  6194. */
  6195. my.setAuthenticatedIdentity = function (authIdentity) {
  6196. if (authIdentity) {
  6197. var selector = $('#toolbar_auth_identity');
  6198. selector.css({display: "list-item"});
  6199. selector.text(authIdentity);
  6200. } else {
  6201. $('#toolbar_auth_identity').css({display: "none"});
  6202. }
  6203. };
  6204. /**
  6205. * Shows/hides login button.
  6206. * @param show <tt>true</tt> to show
  6207. */
  6208. my.showLoginButton = function (show) {
  6209. if (show) {
  6210. $('#toolbar_button_login').css({display: "list-item"});
  6211. } else {
  6212. $('#toolbar_button_login').css({display: "none"});
  6213. }
  6214. };
  6215. /**
  6216. * Shows/hides logout button.
  6217. * @param show <tt>true</tt> to show
  6218. */
  6219. my.showLogoutButton = function (show) {
  6220. if (show) {
  6221. $('#toolbar_button_logout').css({display: "list-item"});
  6222. } else {
  6223. $('#toolbar_button_logout').css({display: "none"});
  6224. }
  6225. };
  6226. /**
  6227. * Sets the state of the button. The button has blue glow if desktop
  6228. * streaming is active.
  6229. * @param active the state of the desktop streaming.
  6230. */
  6231. my.changeDesktopSharingButtonState = function (active) {
  6232. var button = $("#desktopsharing > a");
  6233. if (active) {
  6234. button.addClass("glow");
  6235. } else {
  6236. button.removeClass("glow");
  6237. }
  6238. };
  6239. return my;
  6240. }(Toolbar || {}));
  6241. module.exports = Toolbar;
  6242. },{"../../../service/authentication/AuthenticationEvents":112,"../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){
  6243. /* global APP, config, $, interfaceConfig, Moderator,
  6244. DesktopStreaming.showDesktopSharingButton */
  6245. var toolbarTimeoutObject,
  6246. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6247. function showDesktopSharingButton() {
  6248. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6249. $('#desktopsharing').css({display: "inline"});
  6250. } else {
  6251. $('#desktopsharing').css({display: "none"});
  6252. }
  6253. }
  6254. /**
  6255. * Hides the toolbar.
  6256. */
  6257. function hideToolbar() {
  6258. if(config.alwaysVisibleToolbar)
  6259. return;
  6260. var header = $("#header"),
  6261. bottomToolbar = $("#bottomToolbar");
  6262. var isToolbarHover = false;
  6263. header.find('*').each(function () {
  6264. var id = $(this).attr('id');
  6265. if ($("#" + id + ":hover").length > 0) {
  6266. isToolbarHover = true;
  6267. }
  6268. });
  6269. if ($("#bottomToolbar:hover").length > 0) {
  6270. isToolbarHover = true;
  6271. }
  6272. clearTimeout(toolbarTimeoutObject);
  6273. toolbarTimeoutObject = null;
  6274. if (!isToolbarHover) {
  6275. header.hide("slide", { direction: "up", duration: 300});
  6276. $('#subject').animate({top: "-=40"}, 300);
  6277. if ($("#remoteVideos").hasClass("hidden")) {
  6278. bottomToolbar.hide(
  6279. "slide", {direction: "right", duration: 300});
  6280. }
  6281. }
  6282. else {
  6283. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6284. }
  6285. }
  6286. var ToolbarToggler = {
  6287. /**
  6288. * Shows the main toolbar.
  6289. */
  6290. showToolbar: function () {
  6291. var header = $("#header"),
  6292. bottomToolbar = $("#bottomToolbar");
  6293. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6294. header.show("slide", { direction: "up", duration: 300});
  6295. $('#subject').animate({top: "+=40"}, 300);
  6296. if (!bottomToolbar.is(":visible")) {
  6297. bottomToolbar.show(
  6298. "slide", {direction: "right", duration: 300});
  6299. }
  6300. if (toolbarTimeoutObject) {
  6301. clearTimeout(toolbarTimeoutObject);
  6302. toolbarTimeoutObject = null;
  6303. }
  6304. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6305. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6306. }
  6307. if (APP.xmpp.isModerator())
  6308. {
  6309. // TODO: Enable settings functionality.
  6310. // Need to uncomment the settings button in index.html.
  6311. // $('#settingsButton').css({visibility:"visible"});
  6312. }
  6313. // Show/hide desktop sharing button
  6314. showDesktopSharingButton();
  6315. },
  6316. /**
  6317. * Docks/undocks the toolbar.
  6318. *
  6319. * @param isDock indicates what operation to perform
  6320. */
  6321. dockToolbar: function (isDock) {
  6322. if (isDock) {
  6323. // First make sure the toolbar is shown.
  6324. if (!$('#header').is(':visible')) {
  6325. this.showToolbar();
  6326. }
  6327. // Then clear the time out, to dock the toolbar.
  6328. if (toolbarTimeoutObject) {
  6329. clearTimeout(toolbarTimeoutObject);
  6330. toolbarTimeoutObject = null;
  6331. }
  6332. }
  6333. else {
  6334. if (!$('#header').is(':visible')) {
  6335. this.showToolbar();
  6336. }
  6337. else {
  6338. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6339. }
  6340. }
  6341. },
  6342. showDesktopSharingButton: showDesktopSharingButton
  6343. };
  6344. module.exports = ToolbarToggler;
  6345. },{}],30:[function(require,module,exports){
  6346. /* global $ */
  6347. var JitsiPopover = (function () {
  6348. /**
  6349. * Constructs new JitsiPopover and attaches it to the element
  6350. * @param element jquery selector
  6351. * @param options the options for the popover.
  6352. * @constructor
  6353. */
  6354. function JitsiPopover(element, options)
  6355. {
  6356. this.options = {
  6357. skin: "white",
  6358. content: ""
  6359. };
  6360. if(options)
  6361. {
  6362. if(options.skin)
  6363. this.options.skin = options.skin;
  6364. if(options.content)
  6365. this.options.content = options.content;
  6366. }
  6367. this.elementIsHovered = false;
  6368. this.popoverIsHovered = false;
  6369. this.popoverShown = false;
  6370. element.data("jitsi_popover", this);
  6371. this.element = element;
  6372. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6373. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6374. '<div class="jitsiPopupmenuPadding"></div></div>';
  6375. var self = this;
  6376. this.element.on("mouseenter", function () {
  6377. self.elementIsHovered = true;
  6378. self.show();
  6379. }).on("mouseleave", function () {
  6380. self.elementIsHovered = false;
  6381. setTimeout(function () {
  6382. self.hide();
  6383. }, 10);
  6384. });
  6385. }
  6386. /**
  6387. * Shows the popover
  6388. */
  6389. JitsiPopover.prototype.show = function () {
  6390. this.createPopover();
  6391. this.popoverShown = true;
  6392. };
  6393. /**
  6394. * Hides the popover
  6395. */
  6396. JitsiPopover.prototype.hide = function () {
  6397. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6398. this.popoverShown) {
  6399. this.forceHide();
  6400. }
  6401. };
  6402. /**
  6403. * Hides the popover.
  6404. */
  6405. JitsiPopover.prototype.forceHide = function () {
  6406. $(".jitsipopover").remove();
  6407. this.popoverShown = false;
  6408. };
  6409. /**
  6410. * Creates the popover html.
  6411. */
  6412. JitsiPopover.prototype.createPopover = function () {
  6413. $("body").append(this.template);
  6414. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6415. var self = this;
  6416. $(".jitsipopover").on("mouseenter", function () {
  6417. self.popoverIsHovered = true;
  6418. }).on("mouseleave", function () {
  6419. self.popoverIsHovered = false;
  6420. self.hide();
  6421. });
  6422. this.refreshPosition();
  6423. };
  6424. /**
  6425. * Refreshes the position of the popover.
  6426. */
  6427. JitsiPopover.prototype.refreshPosition = function () {
  6428. $(".jitsipopover").position({
  6429. my: "bottom",
  6430. at: "top",
  6431. collision: "fit",
  6432. of: this.element,
  6433. using: function (position, elements) {
  6434. var calcLeft = elements.target.left - elements.element.left +
  6435. elements.target.width/2;
  6436. $(".jitsipopover").css(
  6437. {top: position.top, left: position.left, display: "table"});
  6438. $(".jitsipopover > .arrow").css({left: calcLeft});
  6439. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6440. {left: calcLeft - 50});
  6441. }
  6442. });
  6443. };
  6444. /**
  6445. * Updates the content of popover.
  6446. * @param content new content
  6447. */
  6448. JitsiPopover.prototype.updateContent = function (content) {
  6449. this.options.content = content;
  6450. if(!this.popoverShown)
  6451. return;
  6452. $(".jitsipopover").remove();
  6453. this.createPopover();
  6454. };
  6455. return JitsiPopover;
  6456. })();
  6457. module.exports = JitsiPopover;
  6458. },{}],31:[function(require,module,exports){
  6459. /* global $, APP, jQuery, toastr */
  6460. var messageHandler = (function(my) {
  6461. /**
  6462. * Shows a message to the user.
  6463. *
  6464. * @param titleKey the title of the message
  6465. * @param messageKey the text of the message
  6466. */
  6467. my.openMessageDialog = function(titleKey, messageKey) {
  6468. var title = null;
  6469. if(titleKey) {
  6470. title = APP.translation.generateTranslationHTML(titleKey);
  6471. }
  6472. var message = APP.translation.generateTranslationHTML(messageKey);
  6473. $.prompt(message,
  6474. {title: title, persistent: false}
  6475. );
  6476. };
  6477. /**
  6478. * Shows a message to the user with two buttons: first is given as a
  6479. * parameter and the second is Cancel.
  6480. *
  6481. * @param titleString the title of the message
  6482. * @param msgString the text of the message
  6483. * @param persistent boolean value which determines whether the message is
  6484. * persistent or not
  6485. * @param leftButton the fist button's text
  6486. * @param submitFunction function to be called on submit
  6487. * @param loadedFunction function to be called after the prompt is fully
  6488. * loaded
  6489. * @param closeFunction function to be called after the prompt is closed
  6490. * @param focus optional focus selector or button index to be focused after
  6491. * the dialog is opened
  6492. * @param defaultButton index of default button which will be activated when
  6493. * the user press 'enter'. Indexed from 0.
  6494. */
  6495. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6496. persistent, leftButtonKey, submitFunction, loadedFunction,
  6497. closeFunction, focus, defaultButton) {
  6498. var buttons = [];
  6499. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6500. buttons.push({ title: leftButton, value: true});
  6501. var cancelButton
  6502. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6503. buttons.push({title: cancelButton, value: false});
  6504. var message = msgString, title = titleString;
  6505. if (titleKey) {
  6506. title = APP.translation.generateTranslationHTML(titleKey);
  6507. }
  6508. if (msgKey) {
  6509. message = APP.translation.generateTranslationHTML(msgKey);
  6510. }
  6511. $.prompt(message, {
  6512. title: title,
  6513. persistent: false,
  6514. buttons: buttons,
  6515. defaultButton: defaultButton,
  6516. focus: focus,
  6517. loaded: loadedFunction,
  6518. submit: submitFunction,
  6519. close: closeFunction
  6520. });
  6521. };
  6522. /**
  6523. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6524. *
  6525. * @param titleString the title of the message
  6526. * @param msgString the text of the message
  6527. * @param persistent boolean value which determines whether the message is
  6528. * persistent or not
  6529. * @param buttons object with the buttons. The keys must be the name of the
  6530. * button and value is the value that will be passed to
  6531. * submitFunction
  6532. * @param submitFunction function to be called on submit
  6533. * @param loadedFunction function to be called after the prompt is fully
  6534. * loaded
  6535. */
  6536. my.openDialog = function (titleString, msgString, persistent, buttons,
  6537. submitFunction, loadedFunction) {
  6538. var args = {
  6539. title: titleString,
  6540. persistent: persistent,
  6541. buttons: buttons,
  6542. defaultButton: 1,
  6543. loaded: loadedFunction,
  6544. submit: submitFunction
  6545. };
  6546. if (persistent) {
  6547. args.closeText = '';
  6548. }
  6549. return new Impromptu(msgString, args);
  6550. };
  6551. /**
  6552. * Closes currently opened dialog.
  6553. */
  6554. my.closeDialog = function () {
  6555. $.prompt.close();
  6556. };
  6557. /**
  6558. * Shows a dialog with different states to the user.
  6559. *
  6560. * @param statesObject object containing all the states of the dialog.
  6561. */
  6562. my.openDialogWithStates = function (statesObject, options) {
  6563. return new Impromptu(statesObject, options);
  6564. };
  6565. /**
  6566. * Opens new popup window for given <tt>url</tt> centered over current
  6567. * window.
  6568. *
  6569. * @param url the URL to be displayed in the popup window
  6570. * @param w the width of the popup window
  6571. * @param h the height of the popup window
  6572. * @param onPopupClosed optional callback function called when popup window
  6573. * has been closed.
  6574. *
  6575. * @returns {object} popup window object if opened successfully or undefined
  6576. * in case we failed to open it(popup blocked)
  6577. */
  6578. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6579. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6580. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6581. var popup = window.open(
  6582. url, '_blank',
  6583. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6584. if (popup && onPopupClosed) {
  6585. var pollTimer = window.setInterval(function () {
  6586. if (popup.closed !== false) {
  6587. window.clearInterval(pollTimer);
  6588. onPopupClosed();
  6589. }
  6590. }, 200);
  6591. }
  6592. return popup;
  6593. };
  6594. /**
  6595. * Shows a dialog prompting the user to send an error report.
  6596. *
  6597. * @param titleKey the title of the message
  6598. * @param msgKey the text of the message
  6599. * @param error the error that is being reported
  6600. */
  6601. my.openReportDialog = function(titleKey, msgKey, error) {
  6602. my.openMessageDialog(titleKey, msgKey);
  6603. console.log(error);
  6604. //FIXME send the error to the server
  6605. };
  6606. /**
  6607. * Shows an error dialog to the user.
  6608. * @param titleKey the title of the message.
  6609. * @param msgKey the text of the message.
  6610. */
  6611. my.showError = function(titleKey, msgKey) {
  6612. if (!titleKey) {
  6613. titleKey = "dialog.oops";
  6614. }
  6615. if (!msgKey) {
  6616. msgKey = "dialog.defaultError";
  6617. }
  6618. messageHandler.openMessageDialog(titleKey, msgKey);
  6619. };
  6620. my.notify = function(displayName, displayNameKey,
  6621. cls, messageKey, messageArguments, options) {
  6622. var displayNameSpan = '<span class="nickname" ';
  6623. if (displayName) {
  6624. displayNameSpan += ">" + displayName;
  6625. } else {
  6626. displayNameSpan += "data-i18n='" + displayNameKey +
  6627. "'>" + APP.translation.translateString(displayNameKey);
  6628. }
  6629. displayNameSpan += "</span>";
  6630. return toastr.info(
  6631. displayNameSpan + '<br>' +
  6632. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6633. (messageArguments?
  6634. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6635. : "") + ">" +
  6636. APP.translation.translateString(messageKey,
  6637. messageArguments) +
  6638. '</span>', null, options);
  6639. };
  6640. my.remove = function(toasterElement) {
  6641. toasterElement.remove();
  6642. };
  6643. return my;
  6644. }(messageHandler || {}));
  6645. module.exports = messageHandler;
  6646. },{}],32:[function(require,module,exports){
  6647. var UIEvents = require("../../../service/UI/UIEvents");
  6648. var nickname = null;
  6649. var eventEmitter = null;
  6650. var NicknameHandler = {
  6651. init: function (emitter) {
  6652. eventEmitter = emitter;
  6653. var storedDisplayName = window.localStorage.displayname;
  6654. if (storedDisplayName) {
  6655. nickname = storedDisplayName;
  6656. }
  6657. },
  6658. setNickname: function (newNickname) {
  6659. if (!newNickname || nickname === newNickname)
  6660. return;
  6661. nickname = newNickname;
  6662. window.localStorage.displayname = nickname;
  6663. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6664. },
  6665. getNickname: function () {
  6666. return nickname;
  6667. },
  6668. addListener: function (type, listener) {
  6669. eventEmitter.on(type, listener);
  6670. }
  6671. };
  6672. module.exports = NicknameHandler;
  6673. },{"../../../service/UI/UIEvents":111}],33:[function(require,module,exports){
  6674. /* global $ */
  6675. /**
  6676. * Created by hristo on 12/22/14.
  6677. */
  6678. module.exports = {
  6679. /**
  6680. * Returns the available video width.
  6681. */
  6682. getAvailableVideoWidth: function (isVisible) {
  6683. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6684. if(typeof isVisible === "undefined" || isVisible === null)
  6685. isVisible = PanelToggler.isVisible();
  6686. var rightPanelWidth
  6687. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6688. return window.innerWidth - rightPanelWidth;
  6689. },
  6690. /**
  6691. * Changes the style class of the element given by id.
  6692. */
  6693. buttonClick: function(id, classname) {
  6694. $(id).toggleClass(classname); // add the class to the clicked element
  6695. },
  6696. /**
  6697. * Returns the text width for the given element.
  6698. *
  6699. * @param el the element
  6700. */
  6701. getTextWidth: function (el) {
  6702. return (el.clientWidth + 1);
  6703. },
  6704. /**
  6705. * Returns the text height for the given element.
  6706. *
  6707. * @param el the element
  6708. */
  6709. getTextHeight: function (el) {
  6710. return (el.clientHeight + 1);
  6711. },
  6712. /**
  6713. * Plays the sound given by id.
  6714. *
  6715. * @param id the identifier of the audio element.
  6716. */
  6717. playSoundNotification: function (id) {
  6718. document.getElementById(id).play();
  6719. },
  6720. /**
  6721. * Escapes the given text.
  6722. */
  6723. escapeHtml: function (unsafeText) {
  6724. return $('<div/>').text(unsafeText).html();
  6725. },
  6726. imageToGrayScale: function (canvas) {
  6727. var context = canvas.getContext('2d');
  6728. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6729. var pixels = imgData.data;
  6730. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6731. var grayscale
  6732. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  6733. pixels[i ] = grayscale; // red
  6734. pixels[i+1] = grayscale; // green
  6735. pixels[i+2] = grayscale; // blue
  6736. // pixels[i+3] is alpha
  6737. }
  6738. // redraw the image in black & white
  6739. context.putImageData(imgData, 0, 0);
  6740. },
  6741. setTooltip: function (element, key, position) {
  6742. element.setAttribute("data-i18n", "[data-content]" + key);
  6743. element.setAttribute("data-toggle", "popover");
  6744. element.setAttribute("data-placement", position);
  6745. element.setAttribute("data-html", true);
  6746. element.setAttribute("data-container", "body");
  6747. }
  6748. };
  6749. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6750. /* global APP, $ */
  6751. var JitsiPopover = require("../util/JitsiPopover");
  6752. /**
  6753. * Constructs new connection indicator.
  6754. * @param videoContainer the video container associated with the indicator.
  6755. * @constructor
  6756. */
  6757. function ConnectionIndicator(videoContainer, jid) {
  6758. this.videoContainer = videoContainer;
  6759. this.bandwidth = null;
  6760. this.packetLoss = null;
  6761. this.bitrate = null;
  6762. this.showMoreValue = false;
  6763. this.resolution = null;
  6764. this.transport = [];
  6765. this.popover = null;
  6766. this.jid = jid;
  6767. this.create();
  6768. }
  6769. /**
  6770. * Values for the connection quality
  6771. * @type {{98: string,
  6772. * 81: string,
  6773. * 64: string,
  6774. * 47: string,
  6775. * 30: string,
  6776. * 0: string}}
  6777. */
  6778. ConnectionIndicator.connectionQualityValues = {
  6779. 98: "18px", //full
  6780. 81: "15px",//4 bars
  6781. 64: "11px",//3 bars
  6782. 47: "7px",//2 bars
  6783. 30: "3px",//1 bar
  6784. 0: "0px"//empty
  6785. };
  6786. ConnectionIndicator.getIP = function(value) {
  6787. return value.substring(0, value.lastIndexOf(":"));
  6788. };
  6789. ConnectionIndicator.getPort = function(value) {
  6790. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6791. };
  6792. ConnectionIndicator.getStringFromArray = function (array) {
  6793. var res = "";
  6794. for(var i = 0; i < array.length; i++) {
  6795. res += (i === 0? "" : ", ") + array[i];
  6796. }
  6797. return res;
  6798. };
  6799. /**
  6800. * Generates the html content.
  6801. * @returns {string} the html content.
  6802. */
  6803. ConnectionIndicator.prototype.generateText = function () {
  6804. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6805. var translate = APP.translation.translateString;
  6806. if(this.bitrate === null) {
  6807. downloadBitrate = "N/A";
  6808. uploadBitrate = "N/A";
  6809. }
  6810. else {
  6811. downloadBitrate =
  6812. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6813. uploadBitrate =
  6814. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6815. }
  6816. if(this.packetLoss === null) {
  6817. packetLoss = "N/A";
  6818. } else {
  6819. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6820. (this.packetLoss.download !== null ?
  6821. this.packetLoss.download : "N/A") +
  6822. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6823. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  6824. "%";
  6825. }
  6826. var resolutionValue = null;
  6827. if(this.resolution && this.jid != null) {
  6828. var keys = Object.keys(this.resolution);
  6829. for(var ssrc in this.resolution) {
  6830. resolutionValue = this.resolution[ssrc];
  6831. }
  6832. }
  6833. if(this.jid === null) {
  6834. resolution = "";
  6835. if(this.resolution === null || !Object.keys(this.resolution) ||
  6836. Object.keys(this.resolution).length === 0) {
  6837. resolution = "N/A";
  6838. } else {
  6839. for (i in this.resolution) {
  6840. resolutionValue = this.resolution[i];
  6841. if (resolutionValue) {
  6842. if (resolutionValue.height &&
  6843. resolutionValue.width) {
  6844. resolution += (resolution === "" ? "" : ", ") +
  6845. resolutionValue.width + "x" +
  6846. resolutionValue.height;
  6847. }
  6848. }
  6849. }
  6850. }
  6851. } else if(!resolutionValue ||
  6852. !resolutionValue.height ||
  6853. !resolutionValue.width) {
  6854. resolution = "N/A";
  6855. } else {
  6856. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6857. }
  6858. var result = "<table style='width:100%'>" +
  6859. "<tr>" +
  6860. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6861. translate("connectionindicator.bitrate") + "</span></td>" +
  6862. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6863. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6864. uploadBitrate + "</td>" +
  6865. "</tr><tr>" +
  6866. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6867. translate("connectionindicator.packetloss") + "</span></td>" +
  6868. "<td>" + packetLoss + "</td>" +
  6869. "</tr><tr>" +
  6870. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6871. translate("connectionindicator.resolution") + "</span></td>" +
  6872. "<td>" + resolution + "</td></tr></table>";
  6873. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6874. result += "<div class=\"jitsipopover_showmore\" " +
  6875. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6876. // FIXME: we do not know local jid when this text is generated
  6877. //this.jid + "')\" data-i18n='connectionindicator." +
  6878. "local')\" data-i18n='connectionindicator." +
  6879. (this.showMoreValue ? "less" : "more") + "'>" +
  6880. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6881. "</div><br />";
  6882. }
  6883. if (this.showMoreValue) {
  6884. var downloadBandwidth, uploadBandwidth, transport;
  6885. if (this.bandwidth === null) {
  6886. downloadBandwidth = "N/A";
  6887. uploadBandwidth = "N/A";
  6888. } else {
  6889. downloadBandwidth = this.bandwidth.download?
  6890. this.bandwidth.download + " Kbps" :
  6891. "N/A";
  6892. uploadBandwidth = this.bandwidth.upload?
  6893. this.bandwidth.upload + " Kbps" :
  6894. "N/A";
  6895. }
  6896. if (!this.transport || this.transport.length === 0) {
  6897. transport = "<tr>" +
  6898. "<td><span class='jitsipopover_blue' " +
  6899. "data-i18n='connectionindicator.address'>" +
  6900. translate("connectionindicator.address") + "</span></td>" +
  6901. "<td> N/A</td></tr>";
  6902. } else {
  6903. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  6904. for(i = 0; i < this.transport.length; i++) {
  6905. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  6906. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  6907. var localIP =
  6908. ConnectionIndicator.getIP(this.transport[i].localip);
  6909. var localPort =
  6910. ConnectionIndicator.getPort(this.transport[i].localip);
  6911. if(data.remoteIP.indexOf(ip) == -1) {
  6912. data.remoteIP.push(ip);
  6913. }
  6914. if(data.remotePort.indexOf(port) == -1) {
  6915. data.remotePort.push(port);
  6916. }
  6917. if(data.localIP.indexOf(localIP) == -1) {
  6918. data.localIP.push(localIP);
  6919. }
  6920. if(data.localPort.indexOf(localPort) == -1) {
  6921. data.localPort.push(localPort);
  6922. }
  6923. }
  6924. var local_address_key = "connectionindicator.localaddress";
  6925. var remote_address_key = "connectionindicator.remoteaddress";
  6926. var localTransport =
  6927. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6928. local_address_key +"' data-i18n-options='" +
  6929. JSON.stringify({count: data.localIP.length}) + "'>" +
  6930. translate(local_address_key, {count: data.localIP.length}) +
  6931. "</span></td><td> " +
  6932. ConnectionIndicator.getStringFromArray(data.localIP) +
  6933. "</td></tr>";
  6934. transport =
  6935. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6936. remote_address_key + "' data-i18n-options='" +
  6937. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  6938. translate(remote_address_key,
  6939. {count: data.remoteIP.length}) +
  6940. "</span></td><td> " +
  6941. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  6942. "</td></tr>";
  6943. var key_remote = "connectionindicator.remoteport",
  6944. key_local = "connectionindicator.localport";
  6945. transport += "<tr>" +
  6946. "<td>" +
  6947. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  6948. "' data-i18n-options='" +
  6949. JSON.stringify({count: this.transport.length}) + "'>" +
  6950. translate(key_remote, {count: this.transport.length}) +
  6951. "</span></td><td>";
  6952. localTransport += "<tr>" +
  6953. "<td>" +
  6954. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  6955. "' data-i18n-options='" +
  6956. JSON.stringify({count: this.transport.length}) + "'>" +
  6957. translate(key_local, {count: this.transport.length}) +
  6958. "</span></td><td>";
  6959. transport +=
  6960. ConnectionIndicator.getStringFromArray(data.remotePort);
  6961. localTransport +=
  6962. ConnectionIndicator.getStringFromArray(data.localPort);
  6963. transport += "</td></tr>";
  6964. transport += localTransport + "</td></tr>";
  6965. transport +="<tr>" +
  6966. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  6967. translate("connectionindicator.transport") + "</span></td>" +
  6968. "<td>" + this.transport[0].type + "</td></tr>";
  6969. }
  6970. result += "<table style='width:100%'>" +
  6971. "<tr>" +
  6972. "<td>" +
  6973. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  6974. translate("connectionindicator.bandwidth") + "</span>" +
  6975. "</td><td>" +
  6976. "<span class='jitsipopover_green'>&darr;</span>" +
  6977. downloadBandwidth +
  6978. " <span class='jitsipopover_orange'>&uarr;</span>" +
  6979. uploadBandwidth + "</td></tr>";
  6980. result += transport + "</table>";
  6981. }
  6982. return result;
  6983. };
  6984. /**
  6985. * Shows or hide the additional information.
  6986. */
  6987. ConnectionIndicator.prototype.showMore = function () {
  6988. this.showMoreValue = !this.showMoreValue;
  6989. this.updatePopoverData();
  6990. };
  6991. function createIcon(classes) {
  6992. var icon = document.createElement("span");
  6993. for(var i in classes) {
  6994. icon.classList.add(classes[i]);
  6995. }
  6996. icon.appendChild(
  6997. document.createElement("i")).classList.add("icon-connection");
  6998. return icon;
  6999. }
  7000. /**
  7001. * Creates the indicator
  7002. */
  7003. ConnectionIndicator.prototype.create = function () {
  7004. this.connectionIndicatorContainer = document.createElement("div");
  7005. this.connectionIndicatorContainer.className = "connectionindicator";
  7006. this.connectionIndicatorContainer.style.display = "none";
  7007. this.videoContainer.container.appendChild(
  7008. this.connectionIndicatorContainer);
  7009. this.popover = new JitsiPopover(
  7010. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7011. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7012. APP.translation.translateString("connectionindicator.na") + "</div>",
  7013. skin: "black"});
  7014. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7015. createIcon(["connection", "connection_empty"]));
  7016. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7017. createIcon(["connection", "connection_full"]));
  7018. };
  7019. /**
  7020. * Removes the indicator
  7021. */
  7022. ConnectionIndicator.prototype.remove = function() {
  7023. if (this.connectionIndicatorContainer.parentNode) {
  7024. this.connectionIndicatorContainer.parentNode.removeChild(
  7025. this.connectionIndicatorContainer);
  7026. }
  7027. this.popover.forceHide();
  7028. };
  7029. /**
  7030. * Updates the data of the indicator
  7031. * @param percent the percent of connection quality
  7032. * @param object the statistics data.
  7033. */
  7034. ConnectionIndicator.prototype.updateConnectionQuality =
  7035. function (percent, object) {
  7036. if (percent === null) {
  7037. this.connectionIndicatorContainer.style.display = "none";
  7038. this.popover.forceHide();
  7039. return;
  7040. } else {
  7041. if(this.connectionIndicatorContainer.style.display == "none") {
  7042. this.connectionIndicatorContainer.style.display = "block";
  7043. this.videoContainer.updateIconPositions();
  7044. }
  7045. }
  7046. this.bandwidth = object.bandwidth;
  7047. this.bitrate = object.bitrate;
  7048. this.packetLoss = object.packetLoss;
  7049. this.transport = object.transport;
  7050. if (object.resolution) {
  7051. this.resolution = object.resolution;
  7052. }
  7053. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7054. if (percent >= quality) {
  7055. this.fullIcon.style.width =
  7056. ConnectionIndicator.connectionQualityValues[quality];
  7057. }
  7058. }
  7059. this.updatePopoverData();
  7060. };
  7061. /**
  7062. * Updates the resolution
  7063. * @param resolution the new resolution
  7064. */
  7065. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7066. this.resolution = resolution;
  7067. this.updatePopoverData();
  7068. };
  7069. /**
  7070. * Updates the content of the popover
  7071. */
  7072. ConnectionIndicator.prototype.updatePopoverData = function () {
  7073. this.popover.updateContent(
  7074. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7075. APP.translation.translateElement($(".connection_info"));
  7076. };
  7077. /**
  7078. * Hides the popover
  7079. */
  7080. ConnectionIndicator.prototype.hide = function () {
  7081. this.popover.forceHide();
  7082. };
  7083. /**
  7084. * Hides the indicator
  7085. */
  7086. ConnectionIndicator.prototype.hideIndicator = function () {
  7087. this.connectionIndicatorContainer.style.display = "none";
  7088. if(this.popover)
  7089. this.popover.forceHide();
  7090. };
  7091. module.exports = ConnectionIndicator;
  7092. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7093. /* global $, APP, Strophe, interfaceConfig */
  7094. var Avatar = require("../avatar/Avatar");
  7095. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7096. var UIUtil = require("../util/UIUtil");
  7097. var UIEvents = require("../../../service/UI/UIEvents");
  7098. var xmpp = require("../../xmpp/xmpp");
  7099. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7100. // FIXME: With Temasys we have to re-select everytime
  7101. //var video = $('#largeVideo');
  7102. var currentVideoWidth = null;
  7103. var currentVideoHeight = null;
  7104. // By default we use camera
  7105. var getVideoSize = getCameraVideoSize;
  7106. var getVideoPosition = getCameraVideoPosition;
  7107. /**
  7108. * The small video instance that is displayed in the large video
  7109. * @type {SmallVideo}
  7110. */
  7111. var currentSmallVideo = null;
  7112. /**
  7113. * Indicates whether the large video is enabled.
  7114. * @type {boolean}
  7115. */
  7116. var isEnabled = true;
  7117. /**
  7118. * Current large video state.
  7119. * Possible values - video, prezi or etherpad.
  7120. * @type {string}
  7121. */
  7122. var state = "video";
  7123. /**
  7124. * Returns the html element associated with the passed state of large video
  7125. * @param state the state.
  7126. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7127. */
  7128. function getContainerByState(state)
  7129. {
  7130. var selector = null;
  7131. switch (state)
  7132. {
  7133. case "video":
  7134. selector = "#largeVideo";
  7135. break;
  7136. case "etherpad":
  7137. selector = "#etherpad>iframe";
  7138. break;
  7139. case "prezi":
  7140. selector = "#presentation>iframe";
  7141. break;
  7142. }
  7143. return (selector !== null)? $(selector) : null;
  7144. }
  7145. /**
  7146. * Sets the size and position of the given video element.
  7147. *
  7148. * @param video the video element to position
  7149. * @param width the desired video width
  7150. * @param height the desired video height
  7151. * @param horizontalIndent the left and right indent
  7152. * @param verticalIndent the top and bottom indent
  7153. */
  7154. function positionVideo(video,
  7155. width,
  7156. height,
  7157. horizontalIndent,
  7158. verticalIndent,
  7159. animate) {
  7160. if (animate) {
  7161. video.animate({
  7162. width: width,
  7163. height: height,
  7164. top: verticalIndent,
  7165. bottom: verticalIndent,
  7166. left: horizontalIndent,
  7167. right: horizontalIndent
  7168. },
  7169. {
  7170. queue: false,
  7171. duration: 500
  7172. });
  7173. } else {
  7174. video.width(width);
  7175. video.height(height);
  7176. video.css({ top: verticalIndent + 'px',
  7177. bottom: verticalIndent + 'px',
  7178. left: horizontalIndent + 'px',
  7179. right: horizontalIndent + 'px'});
  7180. }
  7181. }
  7182. /**
  7183. * Returns an array of the video dimensions, so that it keeps it's aspect
  7184. * ratio and fits available area with it's larger dimension. This method
  7185. * ensures that whole video will be visible and can leave empty areas.
  7186. *
  7187. * @return an array with 2 elements, the video width and the video height
  7188. */
  7189. function getDesktopVideoSize(videoWidth,
  7190. videoHeight,
  7191. videoSpaceWidth,
  7192. videoSpaceHeight) {
  7193. if (!videoWidth)
  7194. videoWidth = currentVideoWidth;
  7195. if (!videoHeight)
  7196. videoHeight = currentVideoHeight;
  7197. var aspectRatio = videoWidth / videoHeight;
  7198. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7199. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7200. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7201. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7202. {
  7203. availableHeight = videoSpaceHeight;
  7204. availableWidth = availableHeight * aspectRatio;
  7205. }
  7206. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7207. {
  7208. availableWidth = videoSpaceWidth;
  7209. availableHeight = availableWidth / aspectRatio;
  7210. }
  7211. return [availableWidth, availableHeight];
  7212. }
  7213. /**
  7214. * Returns an array of the video horizontal and vertical indents,
  7215. * so that if fits its parent.
  7216. *
  7217. * @return an array with 2 elements, the horizontal indent and the vertical
  7218. * indent
  7219. */
  7220. function getCameraVideoPosition(videoWidth,
  7221. videoHeight,
  7222. videoSpaceWidth,
  7223. videoSpaceHeight) {
  7224. // Parent height isn't completely calculated when we position the video in
  7225. // full screen mode and this is why we use the screen height in this case.
  7226. // Need to think it further at some point and implement it properly.
  7227. var isFullScreen = document.fullScreen ||
  7228. document.mozFullScreen ||
  7229. document.webkitIsFullScreen;
  7230. if (isFullScreen)
  7231. videoSpaceHeight = window.innerHeight;
  7232. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7233. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7234. return [horizontalIndent, verticalIndent];
  7235. }
  7236. /**
  7237. * Returns an array of the video horizontal and vertical indents.
  7238. * Centers horizontally and top aligns vertically.
  7239. *
  7240. * @return an array with 2 elements, the horizontal indent and the vertical
  7241. * indent
  7242. */
  7243. function getDesktopVideoPosition(videoWidth,
  7244. videoHeight,
  7245. videoSpaceWidth,
  7246. videoSpaceHeight) {
  7247. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7248. var verticalIndent = 0;// Top aligned
  7249. return [horizontalIndent, verticalIndent];
  7250. }
  7251. /**
  7252. * Returns an array of the video dimensions, so that it covers the screen.
  7253. * It leaves no empty areas, but some parts of the video might not be visible.
  7254. *
  7255. * @return an array with 2 elements, the video width and the video height
  7256. */
  7257. function getCameraVideoSize(videoWidth,
  7258. videoHeight,
  7259. videoSpaceWidth,
  7260. videoSpaceHeight) {
  7261. if (!videoWidth)
  7262. videoWidth = currentVideoWidth;
  7263. if (!videoHeight)
  7264. videoHeight = currentVideoHeight;
  7265. var aspectRatio = videoWidth / videoHeight;
  7266. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7267. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7268. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7269. availableHeight = videoSpaceHeight;
  7270. availableWidth = availableHeight * aspectRatio;
  7271. }
  7272. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7273. availableWidth = videoSpaceWidth;
  7274. availableHeight = availableWidth / aspectRatio;
  7275. }
  7276. return [availableWidth, availableHeight];
  7277. }
  7278. /**
  7279. * Updates the src of the active speaker avatar
  7280. * @param jid of the current active speaker
  7281. */
  7282. function updateActiveSpeakerAvatarSrc() {
  7283. var avatar = $("#activeSpeakerAvatar")[0];
  7284. var jid = currentSmallVideo.peerJid;
  7285. var url = Avatar.getActiveSpeakerUrl(jid);
  7286. if (avatar.src === url)
  7287. return;
  7288. if (jid) {
  7289. avatar.src = url;
  7290. currentSmallVideo.showAvatar();
  7291. }
  7292. }
  7293. /**
  7294. * Change the video source of the large video.
  7295. * @param isVisible
  7296. */
  7297. function changeVideo(isVisible) {
  7298. if (!currentSmallVideo) {
  7299. console.error("Unable to change large video - no 'currentSmallVideo'");
  7300. return;
  7301. }
  7302. updateActiveSpeakerAvatarSrc();
  7303. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7304. var videoTransform = document.getElementById('largeVideo')
  7305. .style.webkitTransform;
  7306. var flipX = currentSmallVideo.flipX;
  7307. if (flipX && videoTransform !== 'scaleX(-1)') {
  7308. document.getElementById('largeVideo').style.webkitTransform =
  7309. "scaleX(-1)";
  7310. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7311. document.getElementById('largeVideo').style.webkitTransform =
  7312. "none";
  7313. }
  7314. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7315. // Change the way we'll be measuring and positioning large video
  7316. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7317. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7318. getCameraVideoPosition;
  7319. // Only if the large video is currently visible.
  7320. if (isVisible) {
  7321. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7322. $('#largeVideo').fadeIn(300);
  7323. }
  7324. }
  7325. /**
  7326. * Creates the html elements for the large video.
  7327. */
  7328. function createLargeVideoHTML()
  7329. {
  7330. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7331. html += '<div id="presentation"></div>' +
  7332. '<div id="etherpad"></div>' +
  7333. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7334. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7335. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7336. '<span data-i18n="poweredby"></span> jitsi.org' +
  7337. '</a>'+
  7338. '<div id="activeSpeaker">' +
  7339. '<img id="activeSpeakerAvatar" src=""/>' +
  7340. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7341. '</div>' +
  7342. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7343. '<span id="videoConnectionMessage"></span>';
  7344. html += '</div>';
  7345. $(html).prependTo("#videospace");
  7346. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7347. var leftWatermarkDiv
  7348. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7349. leftWatermarkDiv.css({display: 'block'});
  7350. leftWatermarkDiv.parent().get(0).href
  7351. = interfaceConfig.JITSI_WATERMARK_LINK;
  7352. }
  7353. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7354. var rightWatermarkDiv
  7355. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7356. rightWatermarkDiv.css({display: 'block'});
  7357. rightWatermarkDiv.parent().get(0).href
  7358. = interfaceConfig.BRAND_WATERMARK_LINK;
  7359. rightWatermarkDiv.get(0).style.backgroundImage
  7360. = "url(images/rightwatermark.png)";
  7361. }
  7362. if (interfaceConfig.SHOW_POWERED_BY) {
  7363. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7364. }
  7365. if (!RTCBrowserType.isIExplorer()) {
  7366. $('#largeVideo').volume = 0;
  7367. }
  7368. }
  7369. var LargeVideo = {
  7370. init: function (VideoLayout, emitter) {
  7371. if(!isEnabled)
  7372. return;
  7373. createLargeVideoHTML();
  7374. this.VideoLayout = VideoLayout;
  7375. this.eventEmitter = emitter;
  7376. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7377. var self = this;
  7378. // Listen for large video size updates
  7379. var largeVideo = $('#largeVideo')[0];
  7380. var onplaying = function (arg1, arg2, arg3) {
  7381. // re-select
  7382. if (RTCBrowserType.isTemasysPluginUsed())
  7383. largeVideo = $('#largeVideo')[0];
  7384. currentVideoWidth = largeVideo.videoWidth;
  7385. currentVideoHeight = largeVideo.videoHeight;
  7386. self.position(currentVideoWidth, currentVideoHeight);
  7387. };
  7388. largeVideo.onplaying = onplaying;
  7389. },
  7390. /**
  7391. * Indicates if the large video is currently visible.
  7392. *
  7393. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7394. */
  7395. isLargeVideoVisible: function() {
  7396. return $('#largeVideo').is(':visible');
  7397. },
  7398. /**
  7399. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7400. */
  7401. isCurrentlyOnLarge: function (resourceJid) {
  7402. return currentSmallVideo && resourceJid &&
  7403. currentSmallVideo.getResourceJid() === resourceJid;
  7404. },
  7405. /**
  7406. * Updates the large video with the given new video source.
  7407. */
  7408. updateLargeVideo: function (resourceJid, forceUpdate) {
  7409. if(!isEnabled)
  7410. return;
  7411. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7412. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7413. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7414. $('#activeSpeaker').css('visibility', 'hidden');
  7415. var oldSmallVideo = null;
  7416. if (currentSmallVideo) {
  7417. oldSmallVideo = currentSmallVideo;
  7418. }
  7419. currentSmallVideo = newSmallVideo;
  7420. var oldJid = null;
  7421. if (oldSmallVideo)
  7422. oldJid = oldSmallVideo.peerJid;
  7423. if (oldJid !== resourceJid) {
  7424. // we want the notification to trigger even if userJid is undefined,
  7425. // or null.
  7426. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7427. }
  7428. if (RTCBrowserType.isSafari()) {
  7429. // FIXME In Safari fadeOut works only for the first time
  7430. changeVideo(this.isLargeVideoVisible());
  7431. } else {
  7432. $('#largeVideo').fadeOut(300,
  7433. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7434. }
  7435. } else {
  7436. if (currentSmallVideo) {
  7437. currentSmallVideo.showAvatar();
  7438. }
  7439. }
  7440. },
  7441. /**
  7442. * Shows/hides the large video.
  7443. */
  7444. setLargeVideoVisible: function(isVisible) {
  7445. if(!isEnabled)
  7446. return;
  7447. if (isVisible) {
  7448. $('#largeVideo').css({visibility: 'visible'});
  7449. $('.watermark').css({visibility: 'visible'});
  7450. if(currentSmallVideo)
  7451. currentSmallVideo.enableDominantSpeaker(true);
  7452. }
  7453. else {
  7454. $('#largeVideo').css({visibility: 'hidden'});
  7455. $('#activeSpeaker').css('visibility', 'hidden');
  7456. $('.watermark').css({visibility: 'hidden'});
  7457. if(currentSmallVideo)
  7458. currentSmallVideo.enableDominantSpeaker(false);
  7459. }
  7460. },
  7461. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7462. if (!isEnabled)
  7463. return;
  7464. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7465. {
  7466. var isDesktop = newVideoType === 'screen';
  7467. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7468. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7469. : getCameraVideoPosition;
  7470. this.position(null, null);
  7471. }
  7472. },
  7473. /**
  7474. * Positions the large video.
  7475. *
  7476. * @param videoWidth the stream video width
  7477. * @param videoHeight the stream video height
  7478. */
  7479. position: function (videoWidth, videoHeight,
  7480. videoSpaceWidth, videoSpaceHeight, animate) {
  7481. if(!isEnabled)
  7482. return;
  7483. if(!videoSpaceWidth)
  7484. videoSpaceWidth = $('#videospace').width();
  7485. if(!videoSpaceHeight)
  7486. videoSpaceHeight = window.innerHeight;
  7487. var videoSize = getVideoSize(videoWidth,
  7488. videoHeight,
  7489. videoSpaceWidth,
  7490. videoSpaceHeight);
  7491. var largeVideoWidth = videoSize[0];
  7492. var largeVideoHeight = videoSize[1];
  7493. var videoPosition = getVideoPosition(largeVideoWidth,
  7494. largeVideoHeight,
  7495. videoSpaceWidth,
  7496. videoSpaceHeight);
  7497. var horizontalIndent = videoPosition[0];
  7498. var verticalIndent = videoPosition[1];
  7499. positionVideo($('#largeVideo'),
  7500. largeVideoWidth,
  7501. largeVideoHeight,
  7502. horizontalIndent, verticalIndent, animate);
  7503. },
  7504. resize: function (animate, isVisible, completeFunction) {
  7505. if(!isEnabled)
  7506. return;
  7507. var availableHeight = window.innerHeight;
  7508. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7509. if (availableWidth < 0 || availableHeight < 0) return;
  7510. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7511. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7512. $('#activeSpeaker').css('top', top);
  7513. if(animate) {
  7514. $('#videospace').animate({
  7515. right: window.innerWidth - availableWidth,
  7516. width: availableWidth,
  7517. height: availableHeight
  7518. },
  7519. {
  7520. queue: false,
  7521. duration: 500,
  7522. complete: completeFunction
  7523. });
  7524. $('#largeVideoContainer').animate({
  7525. width: availableWidth,
  7526. height: availableHeight
  7527. },
  7528. {
  7529. queue: false,
  7530. duration: 500
  7531. });
  7532. } else {
  7533. $('#videospace').width(availableWidth);
  7534. $('#videospace').height(availableHeight);
  7535. $('#largeVideoContainer').width(availableWidth);
  7536. $('#largeVideoContainer').height(availableHeight);
  7537. }
  7538. return [availableWidth, availableHeight];
  7539. },
  7540. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7541. if(!isEnabled)
  7542. return;
  7543. var size = this.resize(true, isVisible, completeFunction);
  7544. this.position(null, null, size[0], size[1], true);
  7545. },
  7546. getResourceJid: function () {
  7547. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7548. },
  7549. updateAvatar: function (resourceJid) {
  7550. if(!isEnabled)
  7551. return;
  7552. if (resourceJid === this.getResourceJid()) {
  7553. updateActiveSpeakerAvatarSrc();
  7554. }
  7555. },
  7556. showAvatar: function (resourceJid, show) {
  7557. if(!isEnabled)
  7558. return;
  7559. if(this.getResourceJid() === resourceJid && state === "video") {
  7560. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7561. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7562. return true;
  7563. }
  7564. return false;
  7565. },
  7566. /**
  7567. * Disables the large video
  7568. */
  7569. disable: function () {
  7570. isEnabled = false;
  7571. },
  7572. /**
  7573. * Enables the large video
  7574. */
  7575. enable: function () {
  7576. isEnabled = true;
  7577. },
  7578. /**
  7579. * Returns true if the video is enabled.
  7580. */
  7581. isEnabled: function () {
  7582. return isEnabled;
  7583. },
  7584. /**
  7585. * Creates the iframe used by the etherpad
  7586. * @param src the value for src attribute
  7587. * @param onloadHandler handler executed when the iframe loads it content
  7588. * @returns {HTMLElement} the iframe
  7589. */
  7590. createEtherpadIframe: function (src, onloadHandler) {
  7591. if(!isEnabled)
  7592. return;
  7593. var etherpadIFrame = document.createElement('iframe');
  7594. etherpadIFrame.src = src;
  7595. etherpadIFrame.frameBorder = 0;
  7596. etherpadIFrame.scrolling = "no";
  7597. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7598. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7599. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7600. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7601. etherpadIFrame.onload = onloadHandler;
  7602. return etherpadIFrame;
  7603. },
  7604. /**
  7605. * Changes the state of the large video.
  7606. * Possible values - video, prezi, etherpad.
  7607. * @param newState - the new state
  7608. */
  7609. setState: function (newState) {
  7610. if(state === newState)
  7611. return;
  7612. var currentContainer = getContainerByState(state);
  7613. if(!currentContainer)
  7614. return;
  7615. var self = this;
  7616. var oldState = state;
  7617. switch (newState)
  7618. {
  7619. case "etherpad":
  7620. $('#activeSpeaker').css('visibility', 'hidden');
  7621. currentContainer.fadeOut(300, function () {
  7622. if (oldState === "prezi") {
  7623. currentContainer.css({opacity: '0'});
  7624. $('#reloadPresentation').css({display: 'none'});
  7625. }
  7626. else {
  7627. self.setLargeVideoVisible(false);
  7628. }
  7629. });
  7630. $('#etherpad>iframe').fadeIn(300, function () {
  7631. document.body.style.background = '#eeeeee';
  7632. $('#etherpad>iframe').css({visibility: 'visible'});
  7633. $('#etherpad').css({zIndex: 2});
  7634. });
  7635. break;
  7636. case "prezi":
  7637. var prezi = $('#presentation>iframe');
  7638. currentContainer.fadeOut(300, function() {
  7639. document.body.style.background = 'black';
  7640. });
  7641. prezi.fadeIn(300, function() {
  7642. prezi.css({opacity:'1'});
  7643. ToolbarToggler.dockToolbar(true);//fix that
  7644. self.setLargeVideoVisible(false);
  7645. $('#etherpad>iframe').css({visibility: 'hidden'});
  7646. $('#etherpad').css({zIndex: 0});
  7647. });
  7648. $('#activeSpeaker').css('visibility', 'hidden');
  7649. break;
  7650. case "video":
  7651. currentContainer.fadeOut(300, function () {
  7652. $('#presentation>iframe').css({opacity:'0'});
  7653. $('#reloadPresentation').css({display:'none'});
  7654. $('#etherpad>iframe').css({visibility: 'hidden'});
  7655. $('#etherpad').css({zIndex: 0});
  7656. document.body.style.background = 'black';
  7657. ToolbarToggler.dockToolbar(false);//fix that
  7658. });
  7659. $('#largeVideo').fadeIn(300, function () {
  7660. self.setLargeVideoVisible(true);
  7661. });
  7662. break;
  7663. }
  7664. state = newState;
  7665. },
  7666. /**
  7667. * Returns the current state of the large video.
  7668. * @returns {string} the current state - video, prezi or etherpad.
  7669. */
  7670. getState: function () {
  7671. return state;
  7672. },
  7673. /**
  7674. * Sets hover handlers for the large video container div.
  7675. *
  7676. * @param inHandler
  7677. * @param outHandler
  7678. */
  7679. setHover: function(inHandler, outHandler)
  7680. {
  7681. $('#largeVideoContainer').hover(inHandler, outHandler);
  7682. },
  7683. /**
  7684. * Enables/disables the filter indicating a video problem to the user.
  7685. *
  7686. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  7687. */
  7688. enableVideoProblemFilter: function (enable) {
  7689. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  7690. }
  7691. };
  7692. module.exports = LargeVideo;
  7693. },{"../../../service/UI/UIEvents":111,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":67,"../avatar/Avatar":16,"../toolbars/ToolbarToggler":29,"../util/UIUtil":33}],36:[function(require,module,exports){
  7694. /* global $, interfaceConfig, APP */
  7695. var SmallVideo = require("./SmallVideo");
  7696. var ConnectionIndicator = require("./ConnectionIndicator");
  7697. var NicknameHandler = require("../util/NicknameHandler");
  7698. var UIUtil = require("../util/UIUtil");
  7699. var LargeVideo = require("./LargeVideo");
  7700. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7701. function LocalVideo(VideoLayout) {
  7702. this.videoSpanId = "localVideoContainer";
  7703. this.container = $("#localVideoContainer").get(0);
  7704. this.VideoLayout = VideoLayout;
  7705. this.flipX = true;
  7706. this.isLocal = true;
  7707. this.peerJid = null;
  7708. }
  7709. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7710. LocalVideo.prototype.constructor = LocalVideo;
  7711. /**
  7712. * Creates the edit display name button.
  7713. *
  7714. * @returns {object} the edit button
  7715. */
  7716. function createEditDisplayNameButton() {
  7717. var editButton = document.createElement('a');
  7718. editButton.className = 'displayname';
  7719. UIUtil.setTooltip(editButton,
  7720. "videothumbnail.editnickname",
  7721. "top");
  7722. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7723. return editButton;
  7724. }
  7725. /**
  7726. * Sets the display name for the given video span id.
  7727. */
  7728. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7729. if (!this.container) {
  7730. console.warn(
  7731. "Unable to set displayName - " + this.videoSpanId +
  7732. " does not exist");
  7733. return;
  7734. }
  7735. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7736. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7737. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7738. var meHTML;
  7739. // If we already have a display name for this video.
  7740. if (nameSpan.length > 0) {
  7741. if (nameSpan.text() !== displayName) {
  7742. if (displayName && displayName.length > 0) {
  7743. meHTML = APP.translation.generateTranslationHTML("me");
  7744. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7745. } else {
  7746. $('#localDisplayName').html(defaultLocalDisplayName);
  7747. }
  7748. }
  7749. } else {
  7750. var editButton = createEditDisplayNameButton();
  7751. nameSpan = document.createElement('span');
  7752. nameSpan.className = 'displayname';
  7753. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7754. if (displayName && displayName.length > 0) {
  7755. meHTML = APP.translation.generateTranslationHTML("me");
  7756. nameSpan.innerHTML = displayName + meHTML;
  7757. }
  7758. else {
  7759. nameSpan.innerHTML = defaultLocalDisplayName;
  7760. }
  7761. nameSpan.id = 'localDisplayName';
  7762. this.container.appendChild(editButton);
  7763. //translates popover of edit button
  7764. APP.translation.translateElement($("a.displayname"));
  7765. var editableText = document.createElement('input');
  7766. editableText.className = 'displayname';
  7767. editableText.type = 'text';
  7768. editableText.id = 'editDisplayName';
  7769. if (displayName && displayName.length) {
  7770. editableText.value = displayName;
  7771. }
  7772. var defaultNickname = APP.translation.translateString(
  7773. "defaultNickname", {name: "Jane Pink"});
  7774. editableText.setAttribute('style', 'display:none;');
  7775. editableText.setAttribute('data-18n',
  7776. '[placeholder]defaultNickname');
  7777. editableText.setAttribute("data-i18n-options",
  7778. JSON.stringify({name: "Jane Pink"}));
  7779. editableText.setAttribute("placeholder", defaultNickname);
  7780. this.container.appendChild(editableText);
  7781. var self = this;
  7782. $('#localVideoContainer .displayname')
  7783. .bind("click", function (e) {
  7784. var editDisplayName = $('#editDisplayName');
  7785. e.preventDefault();
  7786. e.stopPropagation();
  7787. $('#localDisplayName').hide();
  7788. editDisplayName.show();
  7789. editDisplayName.focus();
  7790. editDisplayName.select();
  7791. editDisplayName.one("focusout", function (e) {
  7792. self.VideoLayout.inputDisplayNameHandler(this.value);
  7793. });
  7794. editDisplayName.on('keydown', function (e) {
  7795. if (e.keyCode === 13) {
  7796. e.preventDefault();
  7797. self.VideoLayout.inputDisplayNameHandler(this.value);
  7798. }
  7799. });
  7800. });
  7801. }
  7802. };
  7803. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7804. NicknameHandler.setNickname(name);
  7805. var localDisplayName = $('#localDisplayName');
  7806. if (!localDisplayName.is(":visible")) {
  7807. if (NicknameHandler.getNickname()) {
  7808. var meHTML = APP.translation.generateTranslationHTML("me");
  7809. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  7810. meHTML + ")");
  7811. } else {
  7812. var defaultHTML = APP.translation.generateTranslationHTML(
  7813. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7814. localDisplayName .html(defaultHTML);
  7815. }
  7816. localDisplayName.show();
  7817. }
  7818. $('#editDisplayName').hide();
  7819. };
  7820. LocalVideo.prototype.createConnectionIndicator = function() {
  7821. if(this.connectionIndicator)
  7822. return;
  7823. this.connectionIndicator = new ConnectionIndicator(this, null);
  7824. };
  7825. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7826. var self = this;
  7827. function localVideoClick(event) {
  7828. // FIXME: with Temasys plugin event arg is not an event, but
  7829. // the clicked object itself, so we have to skip this call
  7830. if (event.stopPropagation) {
  7831. event.stopPropagation();
  7832. }
  7833. self.VideoLayout.handleVideoThumbClicked(
  7834. false,
  7835. APP.xmpp.myResource());
  7836. }
  7837. var localVideoContainerSelector = $('#localVideoContainer');
  7838. localVideoContainerSelector.off('click');
  7839. localVideoContainerSelector.on('click', localVideoClick);
  7840. // Add hover handler
  7841. localVideoContainerSelector.hover(
  7842. function() {
  7843. self.showDisplayName(true);
  7844. },
  7845. function() {
  7846. if (!LargeVideo.isLargeVideoVisible() ||
  7847. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  7848. self.showDisplayName(false);
  7849. }
  7850. }
  7851. );
  7852. if(isMuted) {
  7853. APP.UI.setVideoMute(true);
  7854. return;
  7855. }
  7856. this.flipX = stream.videoType != "screen";
  7857. var localVideo = document.createElement('video');
  7858. localVideo.id = 'localVideo_' +
  7859. APP.RTC.getStreamID(stream.getOriginalStream());
  7860. if (!RTCBrowserType.isIExplorer()) {
  7861. localVideo.autoplay = true;
  7862. localVideo.volume = 0; // is it required if audio is separated ?
  7863. }
  7864. localVideo.oncontextmenu = function () { return false; };
  7865. var localVideoContainer = document.getElementById('localVideoWrapper');
  7866. localVideoContainer.appendChild(localVideo);
  7867. var localVideoSelector = $('#' + localVideo.id);
  7868. // Add click handler to both video and video wrapper elements in case
  7869. // there's no video.
  7870. // onclick has to be used with Temasys plugin
  7871. localVideo.onclick = localVideoClick;
  7872. if (this.flipX) {
  7873. localVideoSelector.addClass("flipVideoX");
  7874. }
  7875. // Attach WebRTC stream
  7876. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7877. // Add stream ended handler
  7878. stream.getOriginalStream().onended = function () {
  7879. // We have to re-select after attach when Temasys plugin is used,
  7880. // because <video> element is replaced with <object>
  7881. localVideo = $('#' + localVideo.id)[0];
  7882. localVideoContainer.removeChild(localVideo);
  7883. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7884. };
  7885. };
  7886. LocalVideo.prototype.joined = function (jid) {
  7887. this.peerJid = jid;
  7888. };
  7889. LocalVideo.prototype.getResourceJid = function () {
  7890. var myResource = APP.xmpp.myResource();
  7891. if (!myResource) {
  7892. console.error("Requested local resource before we're in the MUC");
  7893. }
  7894. return myResource;
  7895. };
  7896. module.exports = LocalVideo;
  7897. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7898. /* global $, APP, require, Strophe, interfaceConfig */
  7899. var ConnectionIndicator = require("./ConnectionIndicator");
  7900. var SmallVideo = require("./SmallVideo");
  7901. var AudioLevels = require("../audio_levels/AudioLevels");
  7902. var LargeVideo = require("./LargeVideo");
  7903. var Avatar = require("../avatar/Avatar");
  7904. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7905. function RemoteVideo(peerJid, VideoLayout) {
  7906. this.peerJid = peerJid;
  7907. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7908. this.videoSpanId = 'participant_' + this.resourceJid;
  7909. this.VideoLayout = VideoLayout;
  7910. this.addRemoteVideoContainer();
  7911. this.connectionIndicator = new ConnectionIndicator(
  7912. this, this.peerJid);
  7913. this.setDisplayName();
  7914. var nickfield = document.createElement('span');
  7915. nickfield.className = "nick";
  7916. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7917. this.container.appendChild(nickfield);
  7918. this.flipX = false;
  7919. this.isLocal = false;
  7920. }
  7921. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7922. RemoteVideo.prototype.constructor = RemoteVideo;
  7923. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7924. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7925. if (APP.xmpp.isModerator())
  7926. this.addRemoteVideoMenu();
  7927. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7928. return this.container;
  7929. };
  7930. /**
  7931. * Adds the remote video menu element for the given <tt>jid</tt> in the
  7932. * given <tt>parentElement</tt>.
  7933. *
  7934. * @param jid the jid indicating the video for which we're adding a menu.
  7935. * @param parentElement the parent element where this menu will be added
  7936. */
  7937. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  7938. var spanElement = document.createElement('span');
  7939. spanElement.className = 'remotevideomenu';
  7940. this.container.appendChild(spanElement);
  7941. var menuElement = document.createElement('i');
  7942. menuElement.className = 'fa fa-angle-down';
  7943. menuElement.title = 'Remote user controls';
  7944. spanElement.appendChild(menuElement);
  7945. var popupmenuElement = document.createElement('ul');
  7946. popupmenuElement.className = 'popupmenu';
  7947. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  7948. spanElement.appendChild(popupmenuElement);
  7949. var muteMenuItem = document.createElement('li');
  7950. var muteLinkItem = document.createElement('a');
  7951. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  7952. if (!this.isMuted) {
  7953. muteLinkItem.innerHTML = mutedIndicator +
  7954. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7955. muteLinkItem.className = 'mutelink';
  7956. }
  7957. else {
  7958. muteLinkItem.innerHTML = mutedIndicator +
  7959. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7960. muteLinkItem.className = 'mutelink disabled';
  7961. }
  7962. var self = this;
  7963. muteLinkItem.onclick = function(){
  7964. if ($(this).attr('disabled') != undefined) {
  7965. event.preventDefault();
  7966. }
  7967. var isMute = self.isMuted == true;
  7968. APP.xmpp.setMute(self.peerJid, !isMute);
  7969. popupmenuElement.setAttribute('style', 'display:none;');
  7970. if (isMute) {
  7971. this.innerHTML = mutedIndicator +
  7972. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7973. this.className = 'mutelink disabled';
  7974. }
  7975. else {
  7976. this.innerHTML = mutedIndicator +
  7977. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7978. this.className = 'mutelink';
  7979. }
  7980. };
  7981. muteMenuItem.appendChild(muteLinkItem);
  7982. popupmenuElement.appendChild(muteMenuItem);
  7983. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  7984. var ejectMenuItem = document.createElement('li');
  7985. var ejectLinkItem = document.createElement('a');
  7986. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  7987. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  7988. ejectLinkItem.onclick = function(){
  7989. APP.xmpp.eject(self.peerJid);
  7990. popupmenuElement.setAttribute('style', 'display:none;');
  7991. };
  7992. ejectMenuItem.appendChild(ejectLinkItem);
  7993. popupmenuElement.appendChild(ejectMenuItem);
  7994. var paddingSpan = document.createElement('span');
  7995. paddingSpan.className = 'popupmenuPadding';
  7996. popupmenuElement.appendChild(paddingSpan);
  7997. APP.translation.translateElement(
  7998. $("#" + popupmenuElement.id + " > li > a > div"));
  7999. };
  8000. /**
  8001. * Removes the remote stream element corresponding to the given stream and
  8002. * parent container.
  8003. *
  8004. * @param stream the stream
  8005. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8006. */
  8007. RemoteVideo.prototype.removeRemoteStreamElement =
  8008. function (stream, isVideo, id) {
  8009. if (!this.container)
  8010. return false;
  8011. var select = null;
  8012. if (isVideo) {
  8013. select = $('#' + id);
  8014. }
  8015. else
  8016. select = $('#' + this.videoSpanId + '>audio');
  8017. select.remove();
  8018. console.info((isVideo ? "Video" : "Audio") +
  8019. " removed " + this.getResourceJid(), select);
  8020. if (isVideo)
  8021. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8022. };
  8023. /**
  8024. * Removes RemoteVideo from the page.
  8025. */
  8026. RemoteVideo.prototype.remove = function () {
  8027. console.log("Remove thumbnail", this.peerJid);
  8028. this.removeConnectionIndicator();
  8029. // Remove whole container
  8030. if (this.container.parentNode)
  8031. this.container.parentNode.removeChild(this.container);
  8032. };
  8033. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8034. var isVideo = stream.getVideoTracks().length > 0;
  8035. if (!isVideo || stream.id === 'mixedmslabel') {
  8036. return;
  8037. }
  8038. var self = this;
  8039. var resourceJid = this.getResourceJid();
  8040. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8041. // when video playback starts
  8042. var onPlayingHandler = function () {
  8043. // FIXME: why do i have to do this for FF?
  8044. if (RTCBrowserType.isFirefox()) {
  8045. APP.RTC.attachMediaStream(sel, stream);
  8046. }
  8047. if (RTCBrowserType.isTemasysPluginUsed()) {
  8048. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8049. }
  8050. self.VideoLayout.videoactive(sel, resourceJid);
  8051. sel[0].onplaying = null;
  8052. if (RTCBrowserType.isTemasysPluginUsed()) {
  8053. // 'currentTime' is used to check if the video has started
  8054. // and the value is not set by the plugin, so we do it
  8055. sel[0].currentTime = 1;
  8056. }
  8057. };
  8058. sel[0].onplaying = onPlayingHandler;
  8059. };
  8060. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8061. if (!this.container)
  8062. return;
  8063. var self = this;
  8064. var isVideo = stream.getVideoTracks().length > 0;
  8065. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8066. var newElementId = streamElement.id;
  8067. this.container.appendChild(streamElement);
  8068. var sel = $('#' + newElementId);
  8069. sel.hide();
  8070. // If the container is currently visible we attach the stream.
  8071. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8072. this.waitForPlayback(sel, stream);
  8073. APP.RTC.attachMediaStream(sel, stream);
  8074. }
  8075. stream.onended = function () {
  8076. console.log('stream ended', this);
  8077. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8078. };
  8079. // Name of video element name is different for IE/Safari
  8080. var videoElem = APP.RTC.getVideoElementName();
  8081. // Add click handler.
  8082. var onClickHandler = function (event) {
  8083. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8084. // On IE we need to populate this handler on video <object>
  8085. // and it does not give event instance as an argument,
  8086. // so we check here for methods.
  8087. if (event.stopPropagation && event.preventDefault) {
  8088. event.stopPropagation();
  8089. event.preventDefault();
  8090. }
  8091. return false;
  8092. };
  8093. this.container.onclick = onClickHandler;
  8094. // reselect
  8095. if (RTCBrowserType.isTemasysPluginUsed())
  8096. sel = $('#' + newElementId);
  8097. sel[0].onclick = onClickHandler;
  8098. //FIXME
  8099. // Add hover handler
  8100. $(this.container).hover(
  8101. function() {
  8102. self.showDisplayName(true);
  8103. },
  8104. function() {
  8105. // If the video has been "pinned" by the user we want to
  8106. // keep the display name on place.
  8107. if (!LargeVideo.isLargeVideoVisible() ||
  8108. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8109. self.showDisplayName(false);
  8110. }
  8111. );
  8112. },
  8113. /**
  8114. * Show/hide peer container for the given resourceJid.
  8115. */
  8116. RemoteVideo.prototype.showPeerContainer = function (state) {
  8117. if (!this.container)
  8118. return;
  8119. var isHide = state === 'hide';
  8120. var resizeThumbnails = false;
  8121. if (!isHide) {
  8122. if (!$(this.container).is(':visible')) {
  8123. resizeThumbnails = true;
  8124. $(this.container).show();
  8125. }
  8126. this.showAvatar(state !== 'show');
  8127. }
  8128. else if ($(this.container).is(':visible') && isHide)
  8129. {
  8130. resizeThumbnails = true;
  8131. $(this.container).hide();
  8132. if(this.connectionIndicator)
  8133. this.connectionIndicator.hide();
  8134. }
  8135. if (resizeThumbnails) {
  8136. this.VideoLayout.resizeThumbnails();
  8137. }
  8138. // We want to be able to pin a participant from the contact list, even
  8139. // if he's not in the lastN set!
  8140. // ContactList.setClickable(resourceJid, !isHide);
  8141. };
  8142. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8143. if (this.connectionIndicator)
  8144. this.connectionIndicator.remove();
  8145. };
  8146. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8147. if (this.connectionIndicator)
  8148. this.connectionIndicator.hide();
  8149. };
  8150. /**
  8151. * Updates the remote video menu.
  8152. *
  8153. * @param jid the jid indicating the video for which we're adding a menu.
  8154. * @param isMuted indicates the current mute state
  8155. */
  8156. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8157. var muteMenuItem
  8158. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8159. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8160. if (muteMenuItem.length) {
  8161. var muteLink = muteMenuItem.get(0);
  8162. if (isMuted === 'true') {
  8163. muteLink.innerHTML = mutedIndicator + ' Muted';
  8164. muteLink.className = 'mutelink disabled';
  8165. }
  8166. else {
  8167. muteLink.innerHTML = mutedIndicator + ' Mute';
  8168. muteLink.className = 'mutelink';
  8169. }
  8170. }
  8171. };
  8172. /**
  8173. * Sets the display name for the given video span id.
  8174. */
  8175. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8176. if (!this.container) {
  8177. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8178. " does not exist");
  8179. return;
  8180. }
  8181. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8182. // If we already have a display name for this video.
  8183. if (nameSpan.length > 0) {
  8184. if (displayName && displayName.length > 0) {
  8185. $('#' + this.videoSpanId + '_name').html(displayName);
  8186. }
  8187. else if (key && key.length > 0) {
  8188. var nameHtml = APP.translation.generateTranslationHTML(key);
  8189. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8190. }
  8191. else
  8192. $('#' + this.videoSpanId + '_name').text(
  8193. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8194. } else {
  8195. nameSpan = document.createElement('span');
  8196. nameSpan.className = 'displayname';
  8197. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8198. if (displayName && displayName.length > 0) {
  8199. nameSpan.innerText = displayName;
  8200. }
  8201. else
  8202. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8203. nameSpan.id = this.videoSpanId + '_name';
  8204. }
  8205. };
  8206. /**
  8207. * Removes remote video menu element from video element identified by
  8208. * given <tt>videoElementId</tt>.
  8209. *
  8210. * @param videoElementId the id of local or remote video element.
  8211. */
  8212. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8213. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8214. if (menuSpan.length) {
  8215. menuSpan.remove();
  8216. }
  8217. };
  8218. RemoteVideo.prototype.getResourceJid = function () {
  8219. if (!this.resourceJid) {
  8220. console.error("Undefined resource jid");
  8221. }
  8222. return this.resourceJid;
  8223. };
  8224. RemoteVideo.createContainer = function (spanId) {
  8225. var container = document.createElement('span');
  8226. container.id = spanId;
  8227. container.className = 'videocontainer';
  8228. var remotes = document.getElementById('remoteVideos');
  8229. return remotes.appendChild(container);
  8230. };
  8231. module.exports = RemoteVideo;
  8232. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8233. /* global $, APP, require */
  8234. var Avatar = require("../avatar/Avatar");
  8235. var UIUtil = require("../util/UIUtil");
  8236. var LargeVideo = require("./LargeVideo");
  8237. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8238. function SmallVideo() {
  8239. this.isMuted = false;
  8240. this.hasAvatar = false;
  8241. }
  8242. function setVisibility(selector, show) {
  8243. if (selector && selector.length > 0) {
  8244. selector.css("visibility", show ? "visible" : "hidden");
  8245. }
  8246. }
  8247. SmallVideo.prototype.showDisplayName = function(isShow) {
  8248. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8249. if (isShow) {
  8250. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8251. nameSpan.setAttribute("style", "display:inline-block;");
  8252. }
  8253. else {
  8254. if (nameSpan)
  8255. nameSpan.setAttribute("style", "display:none;");
  8256. }
  8257. };
  8258. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8259. if(!this.container)
  8260. return;
  8261. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8262. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8263. noMic.remove();
  8264. noVideo.remove();
  8265. if (!devices.audio) {
  8266. this.container.appendChild(
  8267. document.createElement("div")).setAttribute("class", "noMic");
  8268. }
  8269. if (!devices.video) {
  8270. this.container.appendChild(
  8271. document.createElement("div")).setAttribute("class", "noVideo");
  8272. }
  8273. if (!devices.audio && !devices.video) {
  8274. noMic.css("background-position", "75%");
  8275. noVideo.css("background-position", "25%");
  8276. noVideo.css("background-color", "transparent");
  8277. }
  8278. };
  8279. /**
  8280. * Sets the type of the video displayed by this instance.
  8281. * @param videoType 'camera' or 'screen'
  8282. */
  8283. SmallVideo.prototype.setVideoType = function (videoType) {
  8284. this.videoType = videoType;
  8285. };
  8286. /**
  8287. * Returns the type of the video displayed by this instance.
  8288. * @returns {String} 'camera', 'screen' or undefined.
  8289. */
  8290. SmallVideo.prototype.getVideoType = function () {
  8291. return this.videoType;
  8292. };
  8293. /**
  8294. * Shows the presence status message for the given video.
  8295. */
  8296. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8297. if (!this.container) {
  8298. // No container
  8299. return;
  8300. }
  8301. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8302. if (!statusSpan.length) {
  8303. //Add status span
  8304. statusSpan = document.createElement('span');
  8305. statusSpan.className = 'status';
  8306. statusSpan.id = this.videoSpanId + '_status';
  8307. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8308. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8309. }
  8310. // Display status
  8311. if (statusMsg && statusMsg.length) {
  8312. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8313. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8314. }
  8315. else {
  8316. // Hide
  8317. statusSpan.get(0).setAttribute("style", "display:none;");
  8318. }
  8319. };
  8320. /**
  8321. * Creates an audio or video stream element.
  8322. */
  8323. SmallVideo.createStreamElement = function (sid, stream) {
  8324. var isVideo = stream.getVideoTracks().length > 0;
  8325. var element = isVideo ? document.createElement('video')
  8326. : document.createElement('audio');
  8327. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8328. APP.RTC.getStreamID(stream);
  8329. element.id = id;
  8330. if (!RTCBrowserType.isIExplorer()) {
  8331. element.autoplay = true;
  8332. }
  8333. element.oncontextmenu = function () { return false; };
  8334. return element;
  8335. };
  8336. /**
  8337. * Updates the data for the indicator
  8338. * @param id the id of the indicator
  8339. * @param percent the percent for connection quality
  8340. * @param object the data
  8341. */
  8342. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8343. if(this.connectionIndicator)
  8344. this.connectionIndicator.updateConnectionQuality(percent, object);
  8345. };
  8346. SmallVideo.prototype.hideIndicator = function () {
  8347. if(this.connectionIndicator)
  8348. this.connectionIndicator.hideIndicator();
  8349. };
  8350. /**
  8351. * Shows audio muted indicator over small videos.
  8352. * @param {string} isMuted
  8353. */
  8354. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8355. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8356. if (!isMuted) {
  8357. if (audioMutedSpan.length > 0) {
  8358. audioMutedSpan.popover('hide');
  8359. audioMutedSpan.remove();
  8360. }
  8361. }
  8362. else {
  8363. if(audioMutedSpan.length == 0 ) {
  8364. audioMutedSpan = document.createElement('span');
  8365. audioMutedSpan.className = 'audioMuted';
  8366. UIUtil.setTooltip(audioMutedSpan,
  8367. "videothumbnail.mute",
  8368. "top");
  8369. this.container.appendChild(audioMutedSpan);
  8370. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8371. var mutedIndicator = document.createElement('i');
  8372. mutedIndicator.className = 'icon-mic-disabled';
  8373. audioMutedSpan.appendChild(mutedIndicator);
  8374. }
  8375. this.updateIconPositions();
  8376. }
  8377. this.isMuted = isMuted;
  8378. };
  8379. /**
  8380. * Shows video muted indicator over small videos.
  8381. */
  8382. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8383. this.showAvatar(isMuted);
  8384. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8385. if (isMuted === false) {
  8386. if (videoMutedSpan.length > 0) {
  8387. videoMutedSpan.remove();
  8388. }
  8389. }
  8390. else {
  8391. if(videoMutedSpan.length == 0) {
  8392. videoMutedSpan = document.createElement('span');
  8393. videoMutedSpan.className = 'videoMuted';
  8394. this.container.appendChild(videoMutedSpan);
  8395. var mutedIndicator = document.createElement('i');
  8396. mutedIndicator.className = 'icon-camera-disabled';
  8397. UIUtil.setTooltip(mutedIndicator,
  8398. "videothumbnail.videomute",
  8399. "top");
  8400. videoMutedSpan.appendChild(mutedIndicator);
  8401. //translate texts for muted indicator
  8402. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8403. }
  8404. this.updateIconPositions();
  8405. }
  8406. };
  8407. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8408. var resourceJid = this.getResourceJid();
  8409. var displayName = resourceJid;
  8410. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8411. if (nameSpan.length > 0)
  8412. displayName = nameSpan.html();
  8413. console.log("UI enable dominant speaker",
  8414. displayName,
  8415. resourceJid,
  8416. isEnable);
  8417. if (!this.container) {
  8418. return;
  8419. }
  8420. if (isEnable) {
  8421. this.showDisplayName(LargeVideo.getState() === "video");
  8422. if (!this.container.classList.contains("dominantspeaker"))
  8423. this.container.classList.add("dominantspeaker");
  8424. }
  8425. else {
  8426. this.showDisplayName(false);
  8427. if (this.container.classList.contains("dominantspeaker"))
  8428. this.container.classList.remove("dominantspeaker");
  8429. }
  8430. this.showAvatar();
  8431. };
  8432. SmallVideo.prototype.updateIconPositions = function () {
  8433. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8434. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8435. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8436. if(connectionIndicator.length > 0 &&
  8437. connectionIndicator[0].style.display != "none") {
  8438. audioMutedSpan.css({right: "23px"});
  8439. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8440. } else {
  8441. audioMutedSpan.css({right: "0px"});
  8442. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8443. }
  8444. };
  8445. /**
  8446. * Creates the element indicating the moderator(owner) of the conference.
  8447. *
  8448. * @param parentElement the parent element where the owner indicator will
  8449. * be added
  8450. */
  8451. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8452. // Show moderator indicator
  8453. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8454. if (!indicatorSpan || indicatorSpan.length === 0) {
  8455. indicatorSpan = document.createElement('span');
  8456. indicatorSpan.className = 'focusindicator';
  8457. this.container.appendChild(indicatorSpan);
  8458. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8459. }
  8460. if (indicatorSpan.children().length !== 0)
  8461. return;
  8462. var moderatorIndicator = document.createElement('i');
  8463. moderatorIndicator.className = 'fa fa-star';
  8464. indicatorSpan[0].appendChild(moderatorIndicator);
  8465. UIUtil.setTooltip(indicatorSpan[0],
  8466. "videothumbnail.moderator",
  8467. "top");
  8468. //translates text in focus indicators
  8469. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8470. };
  8471. SmallVideo.prototype.getSrc = function () {
  8472. var videoElement = APP.RTC.getVideoElementName();
  8473. return APP.RTC.getVideoSrc(
  8474. $('#' + this.videoSpanId).find(videoElement).get(0));
  8475. };
  8476. SmallVideo.prototype.focus = function(isFocused) {
  8477. if(!isFocused) {
  8478. this.container.classList.remove("videoContainerFocused");
  8479. } else {
  8480. this.container.classList.add("videoContainerFocused");
  8481. }
  8482. };
  8483. SmallVideo.prototype.hasVideo = function () {
  8484. return $("#" + this.videoSpanId).find(
  8485. APP.RTC.getVideoElementName()).length !== 0;
  8486. };
  8487. /**
  8488. * Hides or shows the user's avatar
  8489. * @param show whether we should show the avatar or not
  8490. * video because there is no dominant speaker and no focused speaker
  8491. */
  8492. SmallVideo.prototype.showAvatar = function (show) {
  8493. if (!this.hasAvatar) {
  8494. if (this.peerJid) {
  8495. // Init avatar
  8496. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8497. } else {
  8498. console.error("Unable to init avatar - no peerjid", this);
  8499. return;
  8500. }
  8501. }
  8502. var resourceJid = this.getResourceJid();
  8503. var videoElem = APP.RTC.getVideoElementName();
  8504. var video = $('#' + this.videoSpanId).find(videoElem);
  8505. var avatar = $('#avatar_' + resourceJid);
  8506. if (show === undefined || show === null) {
  8507. if (!this.isLocal &&
  8508. !this.VideoLayout.isInLastN(resourceJid)) {
  8509. show = true;
  8510. } else {
  8511. // We want to show the avatar when the video is muted or not exists
  8512. // that is when 'true' or 'null' is returned
  8513. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8514. }
  8515. }
  8516. if (LargeVideo.showAvatar(resourceJid, show)) {
  8517. setVisibility(avatar, false);
  8518. setVisibility(video, false);
  8519. } else {
  8520. if (video && video.length > 0) {
  8521. setVisibility(video, !show);
  8522. }
  8523. setVisibility(avatar, show);
  8524. }
  8525. };
  8526. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8527. var thumbnail = $('#' + this.videoSpanId);
  8528. var resourceJid = this.getResourceJid();
  8529. var avatar = $('#avatar_' + resourceJid);
  8530. this.hasAvatar = true;
  8531. // set the avatar in the thumbnail
  8532. if (avatar && avatar.length > 0) {
  8533. avatar[0].src = thumbUrl;
  8534. } else {
  8535. if (thumbnail && thumbnail.length > 0) {
  8536. avatar = document.createElement('img');
  8537. avatar.id = 'avatar_' + resourceJid;
  8538. avatar.className = 'userAvatar';
  8539. avatar.src = thumbUrl;
  8540. thumbnail.append(avatar);
  8541. }
  8542. }
  8543. };
  8544. module.exports = SmallVideo;
  8545. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8546. /* global config, APP, $, Strophe, require, interfaceConfig */
  8547. var AudioLevels = require("../audio_levels/AudioLevels");
  8548. var ContactList = require("../side_pannels/contactlist/ContactList");
  8549. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8550. var UIEvents = require("../../../service/UI/UIEvents");
  8551. var RTC = require("../../RTC/RTC");
  8552. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8553. var RemoteVideo = require("./RemoteVideo");
  8554. var LargeVideo = require("./LargeVideo");
  8555. var LocalVideo = require("./LocalVideo");
  8556. var remoteVideos = {};
  8557. var remoteVideoTypes = {};
  8558. var localVideoThumbnail = null;
  8559. var currentDominantSpeaker = null;
  8560. var lastNCount = config.channelLastN;
  8561. var localLastNCount = config.channelLastN;
  8562. var localLastNSet = [];
  8563. var lastNEndpointsCache = [];
  8564. var lastNPickupJid = null;
  8565. var eventEmitter = null;
  8566. /**
  8567. * Currently focused video jid
  8568. * @type {String}
  8569. */
  8570. var focusedVideoResourceJid = null;
  8571. var VideoLayout = (function (my) {
  8572. my.init = function (emitter) {
  8573. eventEmitter = emitter;
  8574. localVideoThumbnail = new LocalVideo(VideoLayout);
  8575. LargeVideo.init(VideoLayout, emitter);
  8576. VideoLayout.resizeLargeVideoContainer();
  8577. };
  8578. my.isInLastN = function(resource) {
  8579. return lastNCount < 0 || // lastN is disabled
  8580. // lastNEndpoints cache not built yet
  8581. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8582. (lastNEndpointsCache &&
  8583. lastNEndpointsCache.indexOf(resource) !== -1);
  8584. };
  8585. my.changeLocalStream = function (stream, isMuted) {
  8586. VideoLayout.changeLocalVideo(stream, isMuted);
  8587. };
  8588. my.changeLocalAudio = function(stream, isMuted) {
  8589. if (isMuted)
  8590. APP.UI.setAudioMuted(true, true);
  8591. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8592. var localAudio = document.getElementById('localAudio');
  8593. // Writing volume not allowed in IE
  8594. if (!RTCBrowserType.isIExplorer()) {
  8595. localAudio.autoplay = true;
  8596. localAudio.volume = 0;
  8597. }
  8598. };
  8599. my.changeLocalVideo = function(stream, isMuted) {
  8600. // Set default display name.
  8601. localVideoThumbnail.setDisplayName();
  8602. localVideoThumbnail.createConnectionIndicator();
  8603. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  8604. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8605. localVideoThumbnail.changeVideo(stream, isMuted);
  8606. /* force update if we're currently being displayed */
  8607. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8608. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8609. }
  8610. };
  8611. my.mucJoined = function () {
  8612. var myResourceJid = APP.xmpp.myResource();
  8613. localVideoThumbnail.joined(APP.xmpp.myJid());
  8614. if (!LargeVideo.getResourceJid())
  8615. LargeVideo.updateLargeVideo(myResourceJid, true);
  8616. };
  8617. /**
  8618. * Adds or removes icons for not available camera and microphone.
  8619. * @param resourceJid the jid of user
  8620. * @param devices available devices
  8621. */
  8622. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8623. if(!devices)
  8624. return;
  8625. if(!resourceJid) {
  8626. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8627. } else {
  8628. if(remoteVideos[resourceJid])
  8629. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8630. }
  8631. };
  8632. /**
  8633. * Checks if removed video is currently displayed and tries to display
  8634. * another one instead.
  8635. * @param removedVideoSrc src stream identifier of the video.
  8636. */
  8637. my.updateRemovedVideo = function(resourceJid) {
  8638. if (resourceJid === LargeVideo.getResourceJid()) {
  8639. var newResourceJid;
  8640. // We'll show user's avatar if he is the dominant speaker or if
  8641. // his video thumbnail is pinned
  8642. if (remoteVideos[resourceJid] &&
  8643. resourceJid === focusedVideoResourceJid ||
  8644. resourceJid === currentDominantSpeaker) {
  8645. newResourceJid = resourceJid;
  8646. } else {
  8647. // Otherwise select last visible video
  8648. newResourceJid = this.electLastVisibleVideo();
  8649. }
  8650. LargeVideo.updateLargeVideo(newResourceJid);
  8651. }
  8652. };
  8653. my.electLastVisibleVideo = function() {
  8654. // pick the last visible video in the row
  8655. // if nobody else is left, this picks the local video
  8656. var jid;
  8657. var videoElem = RTC.getVideoElementName();
  8658. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8659. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8660. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8661. } else {
  8662. console.info("Last visible video no longer exists");
  8663. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8664. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8665. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8666. } else {
  8667. // Try local video
  8668. console.info("Fallback to local video...");
  8669. jid = APP.xmpp.myResource();
  8670. }
  8671. }
  8672. console.info("electLastVisibleVideo: " + jid);
  8673. return jid;
  8674. };
  8675. my.onRemoteStreamAdded = function (stream) {
  8676. if (stream.peerjid) {
  8677. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8678. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8679. remoteVideos[resourceJid].addRemoteStreamElement(
  8680. stream.sid,
  8681. stream.getOriginalStream(),
  8682. stream.ssrc);
  8683. }
  8684. };
  8685. my.getLargeVideoJid = function () {
  8686. return LargeVideo.getResourceJid();
  8687. };
  8688. /**
  8689. * Called when large video update is finished
  8690. * @param currentSmallVideo small video currently displayed on large video
  8691. */
  8692. my.largeVideoUpdated = function (currentSmallVideo) {
  8693. // Makes sure that dominant speaker UI
  8694. // is enabled only on current small video
  8695. localVideoThumbnail.enableDominantSpeaker(
  8696. localVideoThumbnail === currentSmallVideo);
  8697. Object.keys(remoteVideos).forEach(
  8698. function (resourceJid) {
  8699. var remoteVideo = remoteVideos[resourceJid];
  8700. if (remoteVideo) {
  8701. remoteVideo.enableDominantSpeaker(
  8702. remoteVideo === currentSmallVideo);
  8703. }
  8704. }
  8705. );
  8706. };
  8707. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8708. resourceJid) {
  8709. if(focusedVideoResourceJid) {
  8710. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8711. if(oldSmallVideo)
  8712. oldSmallVideo.focus(false);
  8713. }
  8714. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8715. // Unlock current focused.
  8716. if (focusedVideoResourceJid === resourceJid)
  8717. {
  8718. focusedVideoResourceJid = null;
  8719. // Enable the currently set dominant speaker.
  8720. if (currentDominantSpeaker) {
  8721. if(smallVideo && smallVideo.hasVideo()) {
  8722. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8723. }
  8724. }
  8725. if (!noPinnedEndpointChangedEvent) {
  8726. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8727. }
  8728. return;
  8729. }
  8730. // Lock new video
  8731. focusedVideoResourceJid = resourceJid;
  8732. // Update focused/pinned interface.
  8733. if (resourceJid) {
  8734. if(smallVideo)
  8735. smallVideo.focus(true);
  8736. if (!noPinnedEndpointChangedEvent) {
  8737. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8738. }
  8739. }
  8740. LargeVideo.setState("video");
  8741. LargeVideo.updateLargeVideo(resourceJid);
  8742. // Writing volume not allowed in IE
  8743. if (!RTCBrowserType.isIExplorer()) {
  8744. $('audio').each(function (idx, el) {
  8745. el.volume = 0;
  8746. el.volume = 1;
  8747. });
  8748. }
  8749. };
  8750. /**
  8751. * Checks if container for participant identified by given peerJid exists
  8752. * in the document and creates it eventually.
  8753. *
  8754. * @param peerJid peer Jid to check.
  8755. *
  8756. * @return Returns <tt>true</tt> if the peer container exists,
  8757. * <tt>false</tt> - otherwise
  8758. */
  8759. my.ensurePeerContainerExists = function(peerJid) {
  8760. ContactList.ensureAddContact(peerJid);
  8761. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8762. if (!remoteVideos[resourceJid]) {
  8763. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  8764. remoteVideos[resourceJid] = remoteVideo;
  8765. var videoType = remoteVideoTypes[resourceJid];
  8766. if (videoType) {
  8767. remoteVideo.setVideoType(videoType);
  8768. }
  8769. // In case this is not currently in the last n we don't show it.
  8770. if (localLastNCount &&
  8771. localLastNCount > 0 &&
  8772. $('#remoteVideos>span').length >= localLastNCount + 2) {
  8773. remoteVideo.showPeerContainer('hide');
  8774. }
  8775. else
  8776. VideoLayout.resizeThumbnails();
  8777. }
  8778. };
  8779. my.inputDisplayNameHandler = function (name) {
  8780. localVideoThumbnail.inputDisplayNameHandler(name);
  8781. };
  8782. my.videoactive = function (videoelem, resourceJid) {
  8783. console.info(resourceJid + " video is now active");
  8784. videoelem.show();
  8785. VideoLayout.resizeThumbnails();
  8786. // Update the large video to the last added video only if there's no
  8787. // current dominant, focused speaker or prezi playing or update it to
  8788. // the current dominant speaker.
  8789. if ((!focusedVideoResourceJid &&
  8790. !currentDominantSpeaker &&
  8791. !require("../prezi/Prezi").isPresentationVisible()) ||
  8792. focusedVideoResourceJid === resourceJid ||
  8793. (resourceJid &&
  8794. currentDominantSpeaker === resourceJid)) {
  8795. LargeVideo.updateLargeVideo(resourceJid, true);
  8796. }
  8797. };
  8798. /**
  8799. * Shows the presence status message for the given video.
  8800. */
  8801. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8802. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8803. };
  8804. /**
  8805. * Shows a visual indicator for the moderator of the conference.
  8806. */
  8807. my.showModeratorIndicator = function () {
  8808. var isModerator = APP.xmpp.isModerator();
  8809. if (isModerator) {
  8810. localVideoThumbnail.createModeratorIndicatorElement();
  8811. }
  8812. var members = APP.xmpp.getMembers();
  8813. Object.keys(members).forEach(function (jid) {
  8814. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8815. // Skip server side focus
  8816. return;
  8817. }
  8818. var resourceJid = Strophe.getResourceFromJid(jid);
  8819. var member = members[jid];
  8820. if (member.role === 'moderator') {
  8821. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8822. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8823. } else if (isModerator) {
  8824. // We are moderator, but user is not - add menu
  8825. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8826. remoteVideos[resourceJid].addRemoteVideoMenu();
  8827. }
  8828. }
  8829. });
  8830. };
  8831. /*
  8832. * Shows or hides the audio muted indicator over the local thumbnail video.
  8833. * @param {boolean} isMuted
  8834. */
  8835. my.showLocalAudioIndicator = function(isMuted) {
  8836. localVideoThumbnail.showAudioIndicator(isMuted);
  8837. };
  8838. /**
  8839. * Resizes the large video container.
  8840. */
  8841. my.resizeLargeVideoContainer = function () {
  8842. LargeVideo.resize();
  8843. VideoLayout.resizeThumbnails();
  8844. LargeVideo.position();
  8845. };
  8846. /**
  8847. * Resizes thumbnails.
  8848. */
  8849. my.resizeThumbnails = function(animate) {
  8850. var videoSpaceWidth = $('#remoteVideos').width();
  8851. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8852. var width = thumbnailSize[0];
  8853. var height = thumbnailSize[1];
  8854. $('.userAvatar').css('left', (width - height) / 2);
  8855. if(animate) {
  8856. $('#remoteVideos').animate({
  8857. height: height
  8858. },
  8859. {
  8860. queue: false,
  8861. duration: 500
  8862. });
  8863. $('#remoteVideos>span').animate({
  8864. height: height,
  8865. width: width
  8866. },
  8867. {
  8868. queue: false,
  8869. duration: 500,
  8870. complete: function () {
  8871. $(document).trigger(
  8872. "remotevideo.resized",
  8873. [width,
  8874. height]);
  8875. }
  8876. });
  8877. } else {
  8878. // size videos so that while keeping AR and max height, we have a
  8879. // nice fit
  8880. $('#remoteVideos').height(height);
  8881. $('#remoteVideos>span').width(width);
  8882. $('#remoteVideos>span').height(height);
  8883. $(document).trigger("remotevideo.resized", [width, height]);
  8884. }
  8885. };
  8886. /**
  8887. * Calculates the thumbnail size.
  8888. *
  8889. * @param videoSpaceWidth the width of the video space
  8890. */
  8891. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8892. // Calculate the available height, which is the inner window height minus
  8893. // 39px for the header minus 2px for the delimiter lines on the top and
  8894. // bottom of the large video, minus the 36px space inside the remoteVideos
  8895. // container used for highlighting shadow.
  8896. var availableHeight = 100;
  8897. var numvids = $('#remoteVideos>span:visible').length;
  8898. if (localLastNCount && localLastNCount > 0) {
  8899. numvids = Math.min(localLastNCount + 1, numvids);
  8900. }
  8901. // Remove the 3px borders arround videos and border around the remote
  8902. // videos area and the 4 pixels between the local video and the others
  8903. //TODO: Find out where the 4 pixels come from and remove them
  8904. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8905. var availableWidth = availableWinWidth / numvids;
  8906. var aspectRatio = 16.0 / 9.0;
  8907. var maxHeight = Math.min(160, availableHeight);
  8908. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  8909. if (availableHeight < availableWidth / aspectRatio) {
  8910. availableWidth = Math.floor(availableHeight * aspectRatio);
  8911. }
  8912. return [availableWidth, availableHeight];
  8913. };
  8914. /**
  8915. * Returns the corresponding resource jid to the given peer container
  8916. * DOM element.
  8917. *
  8918. * @return the corresponding resource jid to the given peer container
  8919. * DOM element
  8920. */
  8921. my.getPeerContainerResourceJid = function (containerElement) {
  8922. var i = containerElement.id.indexOf('participant_');
  8923. if (i >= 0)
  8924. return containerElement.id.substring(i + 12);
  8925. };
  8926. my.getPeerVideoSel = function (peerResourceJid) {
  8927. return $('#participant_' + peerResourceJid +
  8928. '>' + APP.RTC.getVideoElementName());
  8929. };
  8930. /**
  8931. * On contact list item clicked.
  8932. */
  8933. $(ContactList).bind('contactclicked', function(event, jid) {
  8934. if (!jid) {
  8935. return;
  8936. }
  8937. if (jid === APP.xmpp.myJid()) {
  8938. $("#localVideoContainer").click();
  8939. return;
  8940. }
  8941. var resource = Strophe.getResourceFromJid(jid);
  8942. var videoSel = VideoLayout.getPeerVideoSel(resource);
  8943. if (videoSel.length > 0) {
  8944. var videoThumb = videoSel[0];
  8945. // It is not always the case that a videoThumb exists (if there is
  8946. // no actual video).
  8947. if (RTC.getVideoSrc(videoThumb)) {
  8948. // We have a video src, great! Let's update the large video
  8949. // now.
  8950. VideoLayout.handleVideoThumbClicked(
  8951. false,
  8952. Strophe.getResourceFromJid(jid));
  8953. } else {
  8954. // If we don't have a video src for jid, there's absolutely
  8955. // no point in calling handleVideoThumbClicked; Quite
  8956. // simply, it won't work because it needs an src to attach
  8957. // to the large video.
  8958. //
  8959. // Instead, we trigger the pinned endpoint changed event to
  8960. // let the bridge adjust its lastN set for myjid and store
  8961. // the pinned user in the lastNPickupJid variable to be
  8962. // picked up later by the lastN changed event handler.
  8963. lastNPickupJid = jid;
  8964. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  8965. Strophe.getResourceFromJid(jid));
  8966. }
  8967. }
  8968. });
  8969. /**
  8970. * On audio muted event.
  8971. */
  8972. my.onAudioMute = function (jid, isMuted) {
  8973. var resourceJid = Strophe.getResourceFromJid(jid);
  8974. if (resourceJid === APP.xmpp.myResource()) {
  8975. localVideoThumbnail.showAudioIndicator(isMuted);
  8976. } else {
  8977. VideoLayout.ensurePeerContainerExists(jid);
  8978. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  8979. if (APP.xmpp.isModerator()) {
  8980. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  8981. }
  8982. }
  8983. };
  8984. /**
  8985. * On video muted event.
  8986. */
  8987. my.onVideoMute = function (jid, value) {
  8988. if (jid !== APP.xmpp.myJid() &&
  8989. !APP.RTC.muteRemoteVideoStream(jid, value))
  8990. return;
  8991. if (jid === APP.xmpp.myJid()) {
  8992. localVideoThumbnail.showVideoIndicator(value);
  8993. } else {
  8994. var resource = Strophe.getResourceFromJid(jid);
  8995. VideoLayout.ensurePeerContainerExists(jid);
  8996. remoteVideos[resource].showVideoIndicator(value);
  8997. var el = VideoLayout.getPeerVideoSel(resource);
  8998. if (!value)
  8999. el.show();
  9000. else
  9001. el.hide();
  9002. }
  9003. };
  9004. /**
  9005. * Display name changed.
  9006. */
  9007. my.onDisplayNameChanged =
  9008. function (jid, displayName, status) {
  9009. if (jid === 'localVideoContainer' ||
  9010. jid === APP.xmpp.myJid()) {
  9011. localVideoThumbnail.setDisplayName(displayName);
  9012. } else {
  9013. VideoLayout.ensurePeerContainerExists(jid);
  9014. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9015. displayName,
  9016. status);
  9017. }
  9018. };
  9019. /**
  9020. * On dominant speaker changed event.
  9021. */
  9022. my.onDominantSpeakerChanged = function (resourceJid) {
  9023. // We ignore local user events.
  9024. if (resourceJid === APP.xmpp.myResource())
  9025. return;
  9026. var members = APP.xmpp.getMembers();
  9027. // Update the current dominant speaker.
  9028. if (resourceJid !== currentDominantSpeaker) {
  9029. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9030. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9031. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9032. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9033. remoteVideos[resourceJid].setDisplayName(null);
  9034. }
  9035. if(resourceJid && (!members || !members[newJID] ||
  9036. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9037. remoteVideos[resourceJid].setDisplayName(null,
  9038. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9039. }
  9040. currentDominantSpeaker = resourceJid;
  9041. } else {
  9042. return;
  9043. }
  9044. // Obtain container for new dominant speaker.
  9045. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9046. // Local video will not have container found, but that's ok
  9047. // since we don't want to switch to local video.
  9048. if (!focusedVideoResourceJid && videoSel.length) {
  9049. // Update the large video if the video source is already available,
  9050. // otherwise wait for the "videoactive.jingle" event.
  9051. if (videoSel[0].currentTime > 0) {
  9052. LargeVideo.updateLargeVideo(resourceJid);
  9053. }
  9054. }
  9055. };
  9056. /**
  9057. * On last N change event.
  9058. *
  9059. * @param lastNEndpoints the list of last N endpoints
  9060. * @param endpointsEnteringLastN the list currently entering last N
  9061. * endpoints
  9062. */
  9063. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9064. endpointsEnteringLastN,
  9065. stream) {
  9066. if (lastNCount !== lastNEndpoints.length)
  9067. lastNCount = lastNEndpoints.length;
  9068. lastNEndpointsCache = lastNEndpoints;
  9069. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9070. //
  9071. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9072. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9073. // so E sees them. C is only in E's local LastN set.
  9074. //
  9075. // If F starts talking and LastN = 3, then E should see thumbnails for
  9076. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9077. // enters E's local LastN ejecting C.
  9078. // Increase the local LastN set size, if necessary.
  9079. if (lastNCount > localLastNCount) {
  9080. localLastNCount = lastNCount;
  9081. }
  9082. // Update the local LastN set preserving the order in which the
  9083. // endpoints appeared in the LastN/local LastN set.
  9084. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9085. for (var i = 0; i < localLastNSet.length; i++) {
  9086. if (nextLocalLastNSet.length >= localLastNCount) {
  9087. break;
  9088. }
  9089. var resourceJid = localLastNSet[i];
  9090. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9091. nextLocalLastNSet.push(resourceJid);
  9092. }
  9093. }
  9094. localLastNSet = nextLocalLastNSet;
  9095. var updateLargeVideo = false;
  9096. // Handle LastN/local LastN changes.
  9097. $('#remoteVideos>span').each(function( index, element ) {
  9098. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9099. var isReceived = true;
  9100. if (resourceJid &&
  9101. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9102. localLastNSet.indexOf(resourceJid) < 0) {
  9103. console.log("Remove from last N", resourceJid);
  9104. remoteVideos[resourceJid].showPeerContainer('hide');
  9105. isReceived = false;
  9106. } else if (resourceJid &&
  9107. $('#participant_' + resourceJid).is(':visible') &&
  9108. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9109. localLastNSet.indexOf(resourceJid) >= 0) {
  9110. remoteVideos[resourceJid].showPeerContainer('avatar');
  9111. isReceived = false;
  9112. }
  9113. if (!isReceived) {
  9114. // resourceJid has dropped out of the server side lastN set, so
  9115. // it is no longer being received. If resourceJid was being
  9116. // displayed in the large video we have to switch to another
  9117. // user.
  9118. if (!updateLargeVideo &&
  9119. resourceJid === LargeVideo.getResourceJid()) {
  9120. updateLargeVideo = true;
  9121. }
  9122. }
  9123. });
  9124. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9125. endpointsEnteringLastN = lastNEndpoints;
  9126. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9127. endpointsEnteringLastN.forEach(function (resourceJid) {
  9128. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9129. remoteVideos[resourceJid].showPeerContainer('show');
  9130. if (!isVisible) {
  9131. console.log("Add to last N", resourceJid);
  9132. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9133. var mediaStream =
  9134. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9135. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9136. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9137. if (lastNPickupJid == mediaStream.peerjid) {
  9138. // Clean up the lastN pickup jid.
  9139. lastNPickupJid = null;
  9140. // Don't fire the events again, they've already
  9141. // been fired in the contact list click handler.
  9142. VideoLayout.handleVideoThumbClicked(
  9143. false,
  9144. Strophe.getResourceFromJid(mediaStream.peerjid));
  9145. updateLargeVideo = false;
  9146. }
  9147. remoteVideos[resourceJid].
  9148. waitForPlayback(sel, mediaStream.stream);
  9149. }
  9150. });
  9151. }
  9152. // The endpoint that was being shown in the large video has dropped out
  9153. // of the lastN set and there was no lastN pickup jid. We need to update
  9154. // the large video now.
  9155. if (updateLargeVideo) {
  9156. var resource;
  9157. var myResource
  9158. = APP.xmpp.myResource();
  9159. // Find out which endpoint to show in the large video.
  9160. for (i = 0; i < lastNEndpoints.length; i++) {
  9161. resource = lastNEndpoints[i];
  9162. if (!resource || resource === myResource)
  9163. continue;
  9164. // videoSrcToSsrc needs to be update for this call to succeed.
  9165. LargeVideo.updateLargeVideo(resource);
  9166. break;
  9167. }
  9168. }
  9169. };
  9170. /**
  9171. * Updates local stats
  9172. * @param percent
  9173. * @param object
  9174. */
  9175. my.updateLocalConnectionStats = function (percent, object) {
  9176. var resolution = null;
  9177. if (object.resolution !== null) {
  9178. resolution = object.resolution;
  9179. object.resolution = resolution[APP.xmpp.myJid()];
  9180. delete resolution[APP.xmpp.myJid()];
  9181. }
  9182. localVideoThumbnail.updateStatsIndicator(percent, object);
  9183. for (var jid in resolution) {
  9184. if (resolution[jid] === null)
  9185. continue;
  9186. var resourceJid = Strophe.getResourceFromJid(jid);
  9187. if (remoteVideos[resourceJid] &&
  9188. remoteVideos[resourceJid].connectionIndicator) {
  9189. remoteVideos[resourceJid].connectionIndicator.
  9190. updateResolution(resolution[jid]);
  9191. }
  9192. }
  9193. };
  9194. /**
  9195. * Updates remote stats.
  9196. * @param jid the jid associated with the stats
  9197. * @param percent the connection quality percent
  9198. * @param object the stats data
  9199. */
  9200. my.updateConnectionStats = function (jid, percent, object) {
  9201. var resourceJid = Strophe.getResourceFromJid(jid);
  9202. if (remoteVideos[resourceJid])
  9203. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9204. };
  9205. /**
  9206. * Hides the connection indicator
  9207. * @param jid
  9208. */
  9209. my.hideConnectionIndicator = function (jid) {
  9210. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9211. };
  9212. /**
  9213. * Hides all the indicators
  9214. */
  9215. my.onStatsStop = function () {
  9216. for(var video in remoteVideos) {
  9217. remoteVideos[video].hideIndicator();
  9218. }
  9219. localVideoThumbnail.hideIndicator();
  9220. };
  9221. my.participantLeft = function (jid) {
  9222. // Unlock large video
  9223. var resourceJid = Strophe.getResourceFromJid(jid);
  9224. if (focusedVideoResourceJid === resourceJid) {
  9225. console.info("Focused video owner has left the conference");
  9226. focusedVideoResourceJid = null;
  9227. }
  9228. if (currentDominantSpeaker === resourceJid)
  9229. {
  9230. console.info("Dominant speaker has left the conference");
  9231. currentDominantSpeaker = null;
  9232. }
  9233. var remoteVideo = remoteVideos[resourceJid];
  9234. if (remoteVideo) {
  9235. // Remove remote video
  9236. console.info("Removing remote video: " + resourceJid);
  9237. remoteVideo.remove();
  9238. delete remoteVideos[resourceJid];
  9239. } else {
  9240. console.warn("No remote video for " + resourceJid);
  9241. }
  9242. VideoLayout.resizeThumbnails();
  9243. };
  9244. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9245. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9246. return;
  9247. }
  9248. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9249. remoteVideoTypes[resourceJid] = newVideoType;
  9250. var smallVideo;
  9251. if (resourceJid === APP.xmpp.myResource()) {
  9252. if (!localVideoThumbnail) {
  9253. console.warn("Local video not ready yet");
  9254. return;
  9255. }
  9256. smallVideo = localVideoThumbnail;
  9257. } else if (remoteVideos[resourceJid]) {
  9258. smallVideo = remoteVideos[resourceJid];
  9259. } else {
  9260. return;
  9261. }
  9262. smallVideo.setVideoType(newVideoType);
  9263. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9264. };
  9265. my.showMore = function (jid) {
  9266. if (jid === 'local') {
  9267. localVideoThumbnail.connectionIndicator.showMore();
  9268. } else {
  9269. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9270. if (remoteVideo) {
  9271. remoteVideo.connectionIndicator.showMore();
  9272. } else {
  9273. console.info("Error - no remote video for jid: " + jid);
  9274. }
  9275. }
  9276. };
  9277. my.addPreziContainer = function (id) {
  9278. var container = RemoteVideo.createContainer(id);
  9279. VideoLayout.resizeThumbnails();
  9280. return container;
  9281. };
  9282. my.setLargeVideoVisible = function (isVisible) {
  9283. LargeVideo.setLargeVideoVisible(isVisible);
  9284. if(!isVisible && focusedVideoResourceJid) {
  9285. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9286. if(smallVideo) {
  9287. smallVideo.focus(false);
  9288. smallVideo.showAvatar();
  9289. }
  9290. focusedVideoResourceJid = null;
  9291. }
  9292. };
  9293. /**
  9294. * Resizes the video area
  9295. * @param callback a function to be called when the video space is
  9296. * resized.
  9297. */
  9298. my.resizeVideoArea = function(isVisible, callback) {
  9299. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9300. VideoLayout.resizeThumbnails(true);
  9301. };
  9302. my.getSmallVideo = function (resourceJid) {
  9303. if(resourceJid == APP.xmpp.myResource()) {
  9304. return localVideoThumbnail;
  9305. } else {
  9306. if(!remoteVideos[resourceJid])
  9307. return null;
  9308. return remoteVideos[resourceJid];
  9309. }
  9310. };
  9311. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9312. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9313. if(smallVideo)
  9314. smallVideo.avatarChanged(thumbUrl);
  9315. else
  9316. console.warn(
  9317. "Missed avatar update - no small video yet for " + resourceJid);
  9318. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9319. };
  9320. my.createEtherpadIframe = function(src, onloadHandler)
  9321. {
  9322. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9323. };
  9324. my.setLargeVideoState = function (state) {
  9325. LargeVideo.setState(state);
  9326. };
  9327. my.getLargeVideoState = function () {
  9328. return LargeVideo.getState();
  9329. };
  9330. my.setLargeVideoHover = function (inHandler, outHandler) {
  9331. LargeVideo.setHover(inHandler, outHandler);
  9332. };
  9333. /**
  9334. * Indicates that the video has been interrupted.
  9335. */
  9336. my.onVideoInterrupted = function () {
  9337. LargeVideo.enableVideoProblemFilter(true);
  9338. var reconnectingKey = "connection.RECONNECTING";
  9339. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9340. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9341. $('#videoConnectionMessage').css({display: "block"});
  9342. };
  9343. /**
  9344. * Indicates that the video has been restored.
  9345. */
  9346. my.onVideoRestored = function () {
  9347. LargeVideo.enableVideoProblemFilter(false);
  9348. $('#videoConnectionMessage').css({display: "none"});
  9349. };
  9350. return my;
  9351. }(VideoLayout || {}));
  9352. module.exports = VideoLayout;
  9353. },{"../../../service/RTC/MediaStreamTypes":107,"../../../service/UI/UIEvents":111,"../../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){
  9354. //var nouns = [
  9355. //];
  9356. var pluralNouns = [
  9357. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9358. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9359. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9360. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9361. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9362. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9363. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9364. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9365. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9366. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9367. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9368. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9369. ];
  9370. //var places = [
  9371. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9372. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9373. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9374. // "Bridge"
  9375. //];
  9376. var verbs = [
  9377. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9378. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9379. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9380. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9381. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9382. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9383. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9384. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9385. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9386. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9387. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9388. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9389. ];
  9390. var adverbs = [
  9391. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9392. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9393. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9394. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9395. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9396. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9397. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9398. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9399. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9400. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9401. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9402. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9403. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9404. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9405. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9406. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9407. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9408. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9409. ];
  9410. var adjectives = [
  9411. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9412. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9413. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9414. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9415. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9416. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9417. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9418. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9419. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9420. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9421. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9422. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9423. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9424. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9425. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9426. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9427. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9428. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9429. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9430. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9431. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9432. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9433. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9434. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9435. "Zealous"
  9436. ];
  9437. //var pronouns = [
  9438. //];
  9439. //var conjunctions = [
  9440. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9441. //];
  9442. /*
  9443. * Maps a string (category name) to the array of words from that category.
  9444. */
  9445. var CATEGORIES =
  9446. {
  9447. //"_NOUN_": nouns,
  9448. "_PLURALNOUN_": pluralNouns,
  9449. //"_PLACE_": places,
  9450. "_VERB_": verbs,
  9451. "_ADVERB_": adverbs,
  9452. "_ADJECTIVE_": adjectives
  9453. //"_PRONOUN_": pronouns,
  9454. //"_CONJUNCTION_": conjunctions,
  9455. };
  9456. var PATTERNS = [
  9457. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9458. // BeautifulFungiOrSpaghetti
  9459. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9460. // AmazinglyScaryToy
  9461. //"_ADVERB__ADJECTIVE__NOUN_",
  9462. // NeitherTrashNorRifle
  9463. //"Neither_NOUN_Nor_NOUN_",
  9464. //"Either_NOUN_Or_NOUN_",
  9465. // EitherCopulateOrInvestigate
  9466. //"Either_VERB_Or_VERB_",
  9467. //"Neither_VERB_Nor_VERB_",
  9468. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9469. //"The_ADVERB__ADJECTIVE__NOUN_",
  9470. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9471. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9472. // WolvesComputeBadly
  9473. //"_PLURALNOUN__VERB__ADVERB_",
  9474. // UniteFacilitateAndMerge
  9475. //"_VERB__VERB_And_VERB_",
  9476. //NastyWitchesAtThePub
  9477. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9478. ];
  9479. /*
  9480. * Returns a random element from the array 'arr'
  9481. */
  9482. function randomElement(arr) {
  9483. return arr[Math.floor(Math.random() * arr.length)];
  9484. }
  9485. /*
  9486. * Returns true if the string 's' contains one of the
  9487. * template strings.
  9488. */
  9489. function hasTemplate(s) {
  9490. for (var template in CATEGORIES){
  9491. if (s.indexOf(template) >= 0){
  9492. return true;
  9493. }
  9494. }
  9495. }
  9496. /**
  9497. * Generates new room name.
  9498. */
  9499. var RoomNameGenerator = {
  9500. generateRoomWithoutSeparator: function() {
  9501. // Note that if more than one pattern is available, the choice of
  9502. // 'name' won't have a uniform distribution amongst all patterns (names
  9503. // from patterns with fewer options will have higher probability of
  9504. // being chosen that names from patterns with more options).
  9505. var name = randomElement(PATTERNS);
  9506. var word;
  9507. while (hasTemplate(name)) {
  9508. for (var template in CATEGORIES) {
  9509. word = randomElement(CATEGORIES[template]);
  9510. name = name.replace(template, word);
  9511. }
  9512. }
  9513. return name;
  9514. }
  9515. };
  9516. module.exports = RoomNameGenerator;
  9517. },{}],41:[function(require,module,exports){
  9518. /* global $, interfaceConfig */
  9519. var animateTimeout, updateTimeout;
  9520. var RoomNameGenerator = require("./RoomnameGenerator");
  9521. function enter_room() {
  9522. var val = $("#enter_room_field").val();
  9523. if(!val) {
  9524. val = $("#enter_room_field").attr("room_name");
  9525. }
  9526. if (val) {
  9527. window.location.pathname = "/" + val;
  9528. }
  9529. }
  9530. function animate(word) {
  9531. var currentVal = $("#enter_room_field").attr("placeholder");
  9532. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9533. animateTimeout = setTimeout(function() {
  9534. animate(word.substring(1, word.length))
  9535. }, 70);
  9536. }
  9537. function update_roomname() {
  9538. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9539. $("#enter_room_field").attr("room_name", word);
  9540. $("#enter_room_field").attr("placeholder", "");
  9541. clearTimeout(animateTimeout);
  9542. animate(word);
  9543. updateTimeout = setTimeout(update_roomname, 10000);
  9544. }
  9545. function setupWelcomePage() {
  9546. $("#videoconference_page").hide();
  9547. $("#domain_name").text(
  9548. window.location.protocol + "//" + window.location.host + "/");
  9549. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9550. var leftWatermarkDiv =
  9551. $("#welcome_page_header div[class='watermark leftwatermark']");
  9552. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9553. leftWatermarkDiv.css({display: 'block'});
  9554. leftWatermarkDiv.parent().get(0).href =
  9555. interfaceConfig.JITSI_WATERMARK_LINK;
  9556. }
  9557. }
  9558. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9559. var rightWatermarkDiv =
  9560. $("#welcome_page_header div[class='watermark rightwatermark']");
  9561. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9562. rightWatermarkDiv.css({display: 'block'});
  9563. rightWatermarkDiv.parent().get(0).href =
  9564. interfaceConfig.BRAND_WATERMARK_LINK;
  9565. rightWatermarkDiv.get(0).style.backgroundImage =
  9566. "url(images/rightwatermark.png)";
  9567. }
  9568. }
  9569. if (interfaceConfig.SHOW_POWERED_BY) {
  9570. $("#welcome_page_header>a[class='poweredby']")
  9571. .css({display: 'block'});
  9572. }
  9573. $("#enter_room_button").click(function() {
  9574. enter_room();
  9575. });
  9576. $("#enter_room_field").keydown(function (event) {
  9577. if (event.keyCode === 13 /* enter */) {
  9578. enter_room();
  9579. }
  9580. });
  9581. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9582. var updateTimeout;
  9583. var animateTimeout;
  9584. var selector = $("#reload_roomname");
  9585. selector.click(function () {
  9586. clearTimeout(updateTimeout);
  9587. clearTimeout(animateTimeout);
  9588. update_roomname();
  9589. });
  9590. selector.show();
  9591. update_roomname();
  9592. }
  9593. $("#disable_welcome").click(function () {
  9594. window.localStorage.welcomePageDisabled =
  9595. $("#disable_welcome").is(":checked");
  9596. });
  9597. }
  9598. module.exports = setupWelcomePage;
  9599. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9600. /* global $, $iq, config */
  9601. var params = {};
  9602. function getConfigParamsFromUrl() {
  9603. if(!location.hash)
  9604. return {};
  9605. var hash = location.hash.substr(1);
  9606. var result = {};
  9607. hash.split("&").forEach(function(part) {
  9608. var item = part.split("=");
  9609. result[item[0]] = JSON.parse(
  9610. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9611. });
  9612. return result;
  9613. }
  9614. params = getConfigParamsFromUrl();
  9615. var URLProcessor = {
  9616. setConfigParametersFromUrl: function () {
  9617. for(var k in params)
  9618. {
  9619. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9620. continue;
  9621. var v = params[k];
  9622. var confKey = k.substr(7);
  9623. if(config[confKey] && typeof config[confKey] !== typeof v)
  9624. {
  9625. console.warn("The type of " + k +
  9626. " is wrong. That parameter won't be updated in config.js.");
  9627. continue;
  9628. }
  9629. config[confKey] = v;
  9630. }
  9631. }
  9632. };
  9633. module.exports = URLProcessor;
  9634. },{}],43:[function(require,module,exports){
  9635. /* global APP, require */
  9636. var EventEmitter = require("events");
  9637. var eventEmitter = new EventEmitter();
  9638. var CQEvents = require("../../service/connectionquality/CQEvents");
  9639. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9640. /**
  9641. * local stats
  9642. * @type {{}}
  9643. */
  9644. var stats = {};
  9645. /**
  9646. * remote stats
  9647. * @type {{}}
  9648. */
  9649. var remoteStats = {};
  9650. /**
  9651. * Interval for sending statistics to other participants
  9652. * @type {null}
  9653. */
  9654. var sendIntervalId = null;
  9655. /**
  9656. * Start statistics sending.
  9657. */
  9658. function startSendingStats() {
  9659. sendStats();
  9660. sendIntervalId = setInterval(sendStats, 10000);
  9661. }
  9662. /**
  9663. * Sends statistics to other participants
  9664. */
  9665. function sendStats() {
  9666. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9667. }
  9668. /**
  9669. * Converts statistics to format for sending through XMPP
  9670. * @param stats the statistics
  9671. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9672. */
  9673. function convertToMUCStats(stats) {
  9674. return {
  9675. "bitrate_download": stats.bitrate.download,
  9676. "bitrate_upload": stats.bitrate.upload,
  9677. "packetLoss_total": stats.packetLoss.total,
  9678. "packetLoss_download": stats.packetLoss.download,
  9679. "packetLoss_upload": stats.packetLoss.upload
  9680. };
  9681. }
  9682. /**
  9683. * Converts statistics to format used by VideoLayout
  9684. * @param stats
  9685. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9686. */
  9687. function parseMUCStats(stats) {
  9688. return {
  9689. bitrate: {
  9690. download: stats.bitrate_download,
  9691. upload: stats.bitrate_upload
  9692. },
  9693. packetLoss: {
  9694. total: stats.packetLoss_total,
  9695. download: stats.packetLoss_download,
  9696. upload: stats.packetLoss_upload
  9697. }
  9698. };
  9699. }
  9700. var ConnectionQuality = {
  9701. init: function () {
  9702. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9703. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9704. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9705. },
  9706. /**
  9707. * Updates the local statistics
  9708. * @param data new statistics
  9709. */
  9710. updateLocalStats: function (data) {
  9711. stats = data;
  9712. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9713. if (sendIntervalId == null) {
  9714. startSendingStats();
  9715. }
  9716. },
  9717. /**
  9718. * Updates remote statistics
  9719. * @param jid the jid associated with the statistics
  9720. * @param data the statistics
  9721. */
  9722. updateRemoteStats: function (jid, data) {
  9723. if (data == null || data.packetLoss_total == null) {
  9724. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9725. return;
  9726. }
  9727. remoteStats[jid] = parseMUCStats(data);
  9728. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9729. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9730. },
  9731. /**
  9732. * Stops statistics sending.
  9733. */
  9734. stopSendingStats: function () {
  9735. clearInterval(sendIntervalId);
  9736. sendIntervalId = null;
  9737. //notify UI about stopping statistics gathering
  9738. eventEmitter.emit(CQEvents.STOP);
  9739. },
  9740. /**
  9741. * Returns the local statistics.
  9742. */
  9743. getStats: function () {
  9744. return stats;
  9745. },
  9746. addListener: function (type, listener) {
  9747. eventEmitter.on(type, listener);
  9748. }
  9749. };
  9750. module.exports = ConnectionQuality;
  9751. },{"../../service/connectionquality/CQEvents":113,"../../service/xmpp/XMPPEvents":117,"events":118}],44:[function(require,module,exports){
  9752. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9753. getUserMediaWithConstraints */
  9754. /**
  9755. * Indicates that desktop stream is currently in use(for toggle purpose).
  9756. * @type {boolean}
  9757. */
  9758. var isUsingScreenStream = false;
  9759. /**
  9760. * Indicates that switch stream operation is in progress and prevent from
  9761. * triggering new events.
  9762. * @type {boolean}
  9763. */
  9764. var switchInProgress = false;
  9765. /**
  9766. * Method used to get screen sharing stream.
  9767. *
  9768. * @type {function (stream_callback, failure_callback}
  9769. */
  9770. var obtainDesktopStream = null;
  9771. /**
  9772. * Indicates whether desktop sharing extension is installed.
  9773. * @type {boolean}
  9774. */
  9775. var extInstalled = false;
  9776. /**
  9777. * Indicates whether update of desktop sharing extension is required.
  9778. * @type {boolean}
  9779. */
  9780. var extUpdateRequired = false;
  9781. var AdapterJS = require("../RTC/adapter.screenshare");
  9782. var EventEmitter = require("events");
  9783. var eventEmitter = new EventEmitter();
  9784. var DesktopSharingEventTypes
  9785. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9786. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9787. var RTCEvents = require("../../service/RTC/RTCEvents");
  9788. /**
  9789. * Method obtains desktop stream from WebRTC 'screen' source.
  9790. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9791. */
  9792. function obtainWebRTCScreen(streamCallback, failCallback) {
  9793. APP.RTC.getUserMediaWithConstraints(
  9794. ['screen'],
  9795. streamCallback,
  9796. failCallback
  9797. );
  9798. }
  9799. /**
  9800. * Constructs inline install URL for Chrome desktop streaming extension.
  9801. * The 'chromeExtensionId' must be defined in config.js.
  9802. * @returns {string}
  9803. */
  9804. function getWebStoreInstallUrl()
  9805. {
  9806. return "https://chrome.google.com/webstore/detail/" +
  9807. config.chromeExtensionId;
  9808. }
  9809. /**
  9810. * Checks whether extension update is required.
  9811. * @param minVersion minimal required version
  9812. * @param extVersion current extension version
  9813. * @returns {boolean}
  9814. */
  9815. function isUpdateRequired(minVersion, extVersion)
  9816. {
  9817. try
  9818. {
  9819. var s1 = minVersion.split('.');
  9820. var s2 = extVersion.split('.');
  9821. var len = Math.max(s1.length, s2.length);
  9822. for (var i = 0; i < len; i++)
  9823. {
  9824. var n1 = 0,
  9825. n2 = 0;
  9826. if (i < s1.length)
  9827. n1 = parseInt(s1[i]);
  9828. if (i < s2.length)
  9829. n2 = parseInt(s2[i]);
  9830. if (isNaN(n1) || isNaN(n2))
  9831. {
  9832. return true;
  9833. }
  9834. else if (n1 !== n2)
  9835. {
  9836. return n1 > n2;
  9837. }
  9838. }
  9839. // will happen if boths version has identical numbers in
  9840. // their components (even if one of them is longer, has more components)
  9841. return false;
  9842. }
  9843. catch (e)
  9844. {
  9845. console.error("Failed to parse extension version", e);
  9846. APP.UI.messageHandler.showError("dialog.error",
  9847. "dialog.detectext");
  9848. return true;
  9849. }
  9850. }
  9851. function checkChromeExtInstalled(callback) {
  9852. if (!chrome.runtime) {
  9853. // No API, so no extension for sure
  9854. callback(false, false);
  9855. return;
  9856. }
  9857. chrome.runtime.sendMessage(
  9858. config.chromeExtensionId,
  9859. { getVersion: true },
  9860. function (response) {
  9861. if (!response || !response.version) {
  9862. // Communication failure - assume that no endpoint exists
  9863. console.warn(
  9864. "Extension not installed?: ", chrome.runtime.lastError);
  9865. callback(false, false);
  9866. return;
  9867. }
  9868. // Check installed extension version
  9869. var extVersion = response.version;
  9870. console.log('Extension version is: ' + extVersion);
  9871. var updateRequired
  9872. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  9873. callback(!updateRequired, updateRequired);
  9874. }
  9875. );
  9876. }
  9877. function doGetStreamFromExtension(streamCallback, failCallback) {
  9878. // Sends 'getStream' msg to the extension.
  9879. // Extension id must be defined in the config.
  9880. chrome.runtime.sendMessage(
  9881. config.chromeExtensionId,
  9882. { getStream: true, sources: config.desktopSharingSources },
  9883. function (response) {
  9884. if (!response) {
  9885. failCallback(chrome.runtime.lastError);
  9886. return;
  9887. }
  9888. console.log("Response from extension: " + response);
  9889. if (response.streamId) {
  9890. APP.RTC.getUserMediaWithConstraints(
  9891. ['desktop'],
  9892. function (stream) {
  9893. streamCallback(stream);
  9894. },
  9895. failCallback,
  9896. null, null, null,
  9897. response.streamId);
  9898. } else {
  9899. failCallback("Extension failed to get the stream");
  9900. }
  9901. }
  9902. );
  9903. }
  9904. /**
  9905. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  9906. * stream for returned stream token.
  9907. */
  9908. function obtainScreenFromExtension(streamCallback, failCallback) {
  9909. if (extInstalled) {
  9910. doGetStreamFromExtension(streamCallback, failCallback);
  9911. } else {
  9912. if (extUpdateRequired) {
  9913. alert(
  9914. 'Jitsi Desktop Streamer requires update. ' +
  9915. 'Changes will take effect after next Chrome restart.');
  9916. }
  9917. chrome.webstore.install(
  9918. getWebStoreInstallUrl(),
  9919. function (arg) {
  9920. console.log("Extension installed successfully", arg);
  9921. extInstalled = true;
  9922. // We need to give a moment for the endpoint to become available
  9923. window.setTimeout(function () {
  9924. doGetStreamFromExtension(streamCallback, failCallback);
  9925. }, 500);
  9926. },
  9927. function (arg) {
  9928. console.log("Failed to install the extension", arg);
  9929. failCallback(arg);
  9930. APP.UI.messageHandler.showError("dialog.error",
  9931. "dialog.failtoinstall");
  9932. }
  9933. );
  9934. }
  9935. }
  9936. /**
  9937. * Call this method to toggle desktop sharing feature.
  9938. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  9939. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  9940. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  9941. * enabled), pass any other string or nothing in order to disable this
  9942. * feature completely.
  9943. */
  9944. function setDesktopSharing(method) {
  9945. obtainDesktopStream = null;
  9946. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  9947. // care about 'method' parameter
  9948. if (RTCBrowserType.isTemasysPluginUsed()) {
  9949. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  9950. console.info("Screensharing not supported by this plugin version");
  9951. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  9952. console.info(
  9953. "Screensharing not available with Temasys plugin on this site");
  9954. } else {
  9955. obtainDesktopStream = obtainWebRTCScreen;
  9956. console.info("Using Temasys plugin for desktop sharing");
  9957. }
  9958. } else if (RTCBrowserType.isChrome()) {
  9959. if (method == "ext") {
  9960. if (RTCBrowserType.getChromeVersion() >= 34) {
  9961. obtainDesktopStream = obtainScreenFromExtension;
  9962. console.info("Using Chrome extension for desktop sharing");
  9963. initChromeExtension();
  9964. } else {
  9965. console.info("Chrome extension not supported until ver 34");
  9966. }
  9967. } else if (method == "webrtc") {
  9968. obtainDesktopStream = obtainWebRTCScreen;
  9969. console.info("Using Chrome WebRTC for desktop sharing");
  9970. }
  9971. }
  9972. if (!obtainDesktopStream) {
  9973. console.info("Desktop sharing disabled");
  9974. }
  9975. }
  9976. /**
  9977. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  9978. * config.js to support inline installs. Host site must be selected as main
  9979. * website of published extension.
  9980. */
  9981. function initInlineInstalls()
  9982. {
  9983. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  9984. }
  9985. function initChromeExtension() {
  9986. // Initialize Chrome extension inline installs
  9987. initInlineInstalls();
  9988. // Check if extension is installed
  9989. checkChromeExtInstalled(function (installed, updateRequired) {
  9990. extInstalled = installed;
  9991. extUpdateRequired = updateRequired;
  9992. console.info(
  9993. "Chrome extension installed: " + extInstalled +
  9994. " updateRequired: " + extUpdateRequired);
  9995. });
  9996. }
  9997. function getVideoStreamFailed(error) {
  9998. console.error("Failed to obtain the stream to switch to", error);
  9999. switchInProgress = false;
  10000. isUsingScreenStream = false;
  10001. newStreamCreated(null);
  10002. }
  10003. function getDesktopStreamFailed(error) {
  10004. console.error("Failed to obtain the stream to switch to", error);
  10005. switchInProgress = false;
  10006. }
  10007. function streamSwitchDone() {
  10008. switchInProgress = false;
  10009. eventEmitter.emit(
  10010. DesktopSharingEventTypes.SWITCHING_DONE,
  10011. isUsingScreenStream);
  10012. }
  10013. function newStreamCreated(stream)
  10014. {
  10015. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10016. stream, isUsingScreenStream, streamSwitchDone);
  10017. }
  10018. function onEndedHandler(stream) {
  10019. if (!switchInProgress && isUsingScreenStream) {
  10020. APP.desktopsharing.toggleScreenSharing();
  10021. }
  10022. //FIXME: to be verified
  10023. if (stream.removeEventListener) {
  10024. stream.removeEventListener('ended', onEndedHandler);
  10025. } else {
  10026. stream.detachEvent('ended', onEndedHandler);
  10027. }
  10028. }
  10029. // Called when RTC finishes initialization
  10030. function onWebRtcReady() {
  10031. setDesktopSharing(config.desktopSharing);
  10032. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10033. }
  10034. module.exports = {
  10035. isUsingScreenStream: function () {
  10036. return isUsingScreenStream;
  10037. },
  10038. /**
  10039. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10040. * and enabled.
  10041. */
  10042. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10043. init: function () {
  10044. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10045. },
  10046. addListener: function (listener, type)
  10047. {
  10048. eventEmitter.on(type, listener);
  10049. },
  10050. removeListener: function (listener, type) {
  10051. eventEmitter.removeListener(type, listener);
  10052. },
  10053. /*
  10054. * Toggles screen sharing.
  10055. */
  10056. toggleScreenSharing: function () {
  10057. if (switchInProgress || !obtainDesktopStream) {
  10058. console.warn("Switch in progress or no method defined");
  10059. return;
  10060. }
  10061. switchInProgress = true;
  10062. if (!isUsingScreenStream)
  10063. {
  10064. // Switch to desktop stream
  10065. obtainDesktopStream(
  10066. function (stream) {
  10067. // We now use screen stream
  10068. isUsingScreenStream = true;
  10069. // Hook 'ended' event to restore camera
  10070. // when screen stream stops
  10071. //FIXME: to be verified
  10072. if (stream.addEventListener) {
  10073. stream.addEventListener('ended', function () {
  10074. onEndedHandler(stream);
  10075. });
  10076. } else {
  10077. stream.attachEvent('ended', function () {
  10078. onEndedHandler(stream);
  10079. });
  10080. }
  10081. newStreamCreated(stream);
  10082. },
  10083. getDesktopStreamFailed);
  10084. } else {
  10085. // Disable screen stream
  10086. APP.RTC.getUserMediaWithConstraints(
  10087. ['video'],
  10088. function (stream) {
  10089. // We are now using camera stream
  10090. isUsingScreenStream = false;
  10091. newStreamCreated(stream);
  10092. },
  10093. getVideoStreamFailed, config.resolution || '360'
  10094. );
  10095. }
  10096. }
  10097. };
  10098. },{"../../service/RTC/RTCEvents":108,"../../service/desktopsharing/DesktopSharingEventTypes":114,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":118}],45:[function(require,module,exports){
  10099. /* global APP, $ */
  10100. //maps keycode to character, id of popover for given function and function
  10101. var shortcuts = {};
  10102. function initShortcutHandlers() {
  10103. shortcuts = {
  10104. 67: {
  10105. character: "C",
  10106. id: "toggleChatPopover",
  10107. function: APP.UI.toggleChat
  10108. },
  10109. 70: {
  10110. character: "F",
  10111. id: "filmstripPopover",
  10112. function: APP.UI.toggleFilmStrip
  10113. },
  10114. 77: {
  10115. character: "M",
  10116. id: "mutePopover",
  10117. function: APP.UI.toggleAudio
  10118. },
  10119. 84: {
  10120. character: "T",
  10121. function: function() {
  10122. if(!APP.RTC.localAudio.isMuted()) {
  10123. APP.UI.toggleAudio();
  10124. }
  10125. }
  10126. },
  10127. 86: {
  10128. character: "V",
  10129. id: "toggleVideoPopover",
  10130. function: APP.UI.toggleVideo
  10131. }
  10132. };
  10133. }
  10134. var KeyboardShortcut = {
  10135. init: function () {
  10136. initShortcutHandlers();
  10137. window.onkeyup = function(e) {
  10138. var keycode = e.which;
  10139. if(!($(":focus").is("input[type=text]") ||
  10140. $(":focus").is("input[type=password]") ||
  10141. $(":focus").is("textarea"))) {
  10142. if (typeof shortcuts[keycode] === "object") {
  10143. shortcuts[keycode].function();
  10144. }
  10145. else if (keycode >= "0".charCodeAt(0) &&
  10146. keycode <= "9".charCodeAt(0)) {
  10147. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10148. }
  10149. //esc while the smileys are visible hides them
  10150. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10151. APP.UI.toggleSmileys();
  10152. }
  10153. };
  10154. window.onkeydown = function(e) {
  10155. if(!($(":focus").is("input[type=text]") ||
  10156. $(":focus").is("input[type=password]") ||
  10157. $(":focus").is("textarea"))) {
  10158. if(e.which === "T".charCodeAt(0)) {
  10159. if(APP.RTC.localAudio.isMuted()) {
  10160. APP.UI.toggleAudio();
  10161. }
  10162. }
  10163. }
  10164. };
  10165. var self = this;
  10166. $('body').popover({ selector: '[data-toggle=popover]',
  10167. trigger: 'click hover',
  10168. content: function() {
  10169. return this.getAttribute("content") +
  10170. self.getShortcut(this.getAttribute("shortcut"));
  10171. }
  10172. });
  10173. },
  10174. /**
  10175. *
  10176. * @param id indicates the popover associated with the shortcut
  10177. * @returns {string} the keyboard shortcut used for the id given
  10178. */
  10179. getShortcut: function (id) {
  10180. for (var keycode in shortcuts) {
  10181. if (shortcuts.hasOwnProperty(keycode)) {
  10182. if (shortcuts[keycode].id === id) {
  10183. return " (" + shortcuts[keycode].character + ")";
  10184. }
  10185. }
  10186. }
  10187. return "";
  10188. }
  10189. };
  10190. module.exports = KeyboardShortcut;
  10191. },{}],46:[function(require,module,exports){
  10192. /* global APP, require, $ */
  10193. /**
  10194. * This module is meant to (eventually) contain and manage all information
  10195. * about members/participants of the conference, so that other modules don't
  10196. * have to do it on their own, and so that other modules can access members'
  10197. * information from a single place.
  10198. *
  10199. * Currently this module only manages information about the support of jingle
  10200. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10201. * be added as needed.
  10202. */
  10203. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10204. var Events = require("../../service/members/Events");
  10205. var EventEmitter = require("events");
  10206. var eventEmitter = new EventEmitter();
  10207. /**
  10208. * The actual container.
  10209. */
  10210. var members = {};
  10211. /**
  10212. * There is at least one member that supports DTMF (i.e. is jigasi).
  10213. */
  10214. var atLeastOneDtmf = false;
  10215. function registerListeners() {
  10216. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10217. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10218. }
  10219. /**
  10220. * Handles a new member joining the MUC.
  10221. */
  10222. function onMucMemberJoined(jid, id, displayName) {
  10223. var member = {
  10224. displayName: displayName
  10225. };
  10226. APP.xmpp.getConnection().disco.info(
  10227. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10228. members[jid] = member;
  10229. }
  10230. /**
  10231. * Handles a member leaving the MUC.
  10232. */
  10233. function onMucMemberLeft(jid) {
  10234. delete members[jid];
  10235. updateAtLeastOneDtmf();
  10236. }
  10237. /**
  10238. * Handles the reception of a disco#info packet from a particular JID.
  10239. * @param jid the JID sending the packet.
  10240. * @param iq the packet.
  10241. */
  10242. function onDiscoInfoReceived(jid, iq) {
  10243. if (!members[jid])
  10244. return;
  10245. var supportsDtmf
  10246. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10247. updateDtmf(jid, supportsDtmf);
  10248. }
  10249. /**
  10250. * Updates the 'supportsDtmf' field for a member.
  10251. * @param jid the jid of the member.
  10252. * @param newValue the new value for the 'supportsDtmf' field.
  10253. */
  10254. function updateDtmf(jid, newValue) {
  10255. var oldValue = members[jid].supportsDtmf;
  10256. members[jid].supportsDtmf = newValue;
  10257. if (newValue != oldValue) {
  10258. updateAtLeastOneDtmf();
  10259. }
  10260. }
  10261. /**
  10262. * Checks each member's 'supportsDtmf' field and updates
  10263. * 'atLastOneSupportsDtmf'.
  10264. */
  10265. function updateAtLeastOneDtmf() {
  10266. var newAtLeastOneDtmf = false;
  10267. for (var key in members) {
  10268. if (typeof members[key].supportsDtmf !== 'undefined'
  10269. && members[key].supportsDtmf) {
  10270. newAtLeastOneDtmf= true;
  10271. break;
  10272. }
  10273. }
  10274. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10275. atLeastOneDtmf = newAtLeastOneDtmf;
  10276. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10277. }
  10278. }
  10279. /**
  10280. * Exported interface.
  10281. */
  10282. var Members = {
  10283. start: function() {
  10284. registerListeners();
  10285. },
  10286. addListener: function(type, listener) {
  10287. eventEmitter.on(type, listener);
  10288. },
  10289. removeListener: function (type, listener) {
  10290. eventEmitter.removeListener(type, listener);
  10291. },
  10292. size: function () {
  10293. return Object.keys(members).length;
  10294. },
  10295. getMembers: function () {
  10296. return members;
  10297. }
  10298. };
  10299. module.exports = Members;
  10300. },{"../../service/members/Events":115,"../../service/xmpp/XMPPEvents":117,"events":118}],47:[function(require,module,exports){
  10301. var email = '';
  10302. var displayName = '';
  10303. var userId;
  10304. var language = null;
  10305. function supportsLocalStorage() {
  10306. try {
  10307. return 'localStorage' in window && window.localStorage !== null;
  10308. } catch (e) {
  10309. console.log("localstorage is not supported");
  10310. return false;
  10311. }
  10312. }
  10313. function generateUniqueId() {
  10314. function _p8() {
  10315. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10316. }
  10317. return _p8() + _p8() + _p8() + _p8();
  10318. }
  10319. if (supportsLocalStorage()) {
  10320. if (!window.localStorage.jitsiMeetId) {
  10321. window.localStorage.jitsiMeetId = generateUniqueId();
  10322. console.log("generated id", window.localStorage.jitsiMeetId);
  10323. }
  10324. userId = window.localStorage.jitsiMeetId || '';
  10325. email = window.localStorage.email || '';
  10326. displayName = window.localStorage.displayname || '';
  10327. language = window.localStorage.language;
  10328. } else {
  10329. console.log("local storage is not supported");
  10330. userId = generateUniqueId();
  10331. }
  10332. var Settings = {
  10333. setDisplayName: function (newDisplayName) {
  10334. displayName = newDisplayName;
  10335. window.localStorage.displayname = displayName;
  10336. return displayName;
  10337. },
  10338. setEmail: function (newEmail) {
  10339. email = newEmail;
  10340. window.localStorage.email = newEmail;
  10341. return email;
  10342. },
  10343. getSettings: function () {
  10344. return {
  10345. email: email,
  10346. displayName: displayName,
  10347. uid: userId,
  10348. language: language
  10349. };
  10350. },
  10351. setLanguage: function (lang) {
  10352. language = lang;
  10353. window.localStorage.language = lang;
  10354. }
  10355. };
  10356. module.exports = Settings;
  10357. },{}],48:[function(require,module,exports){
  10358. /* global config, $, APP, Strophe, callstats */
  10359. var callStats = null;
  10360. function initCallback (err, msg) {
  10361. console.log("Initializing Status: err="+err+" msg="+msg);
  10362. }
  10363. var CallStats = {
  10364. init: function (jingleSession) {
  10365. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10366. return;
  10367. callStats = new callstats($,io,jsSHA);
  10368. this.session = jingleSession;
  10369. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10370. this.userID = APP.xmpp.myResource();
  10371. var location = window.location;
  10372. this.confID = location.protocol + "//" +
  10373. location.hostname + location.pathname;
  10374. //userID is generated or given by the origin server
  10375. callStats.initialize(config.callStatsID,
  10376. config.callStatsSecret,
  10377. this.userID,
  10378. initCallback);
  10379. var usage = callStats.fabricUsage.multiplex;
  10380. callStats.addNewFabric(this.peerconnection,
  10381. Strophe.getResourceFromJid(jingleSession.peerjid),
  10382. usage,
  10383. this.confID,
  10384. this.pcCallback.bind(this));
  10385. },
  10386. pcCallback: function (err, msg) {
  10387. if (!callStats)
  10388. return;
  10389. console.log("Monitoring status: "+ err + " msg: " + msg);
  10390. callStats.sendFabricEvent(this.peerconnection,
  10391. callStats.fabricEvent.fabricSetup, this.confID);
  10392. },
  10393. sendMuteEvent: function (mute, type) {
  10394. if (!callStats)
  10395. return;
  10396. var event = null;
  10397. if (type === "video") {
  10398. event = (mute? callStats.fabricEvent.videoPause :
  10399. callStats.fabricEvent.videoResume);
  10400. }
  10401. else {
  10402. event = (mute? callStats.fabricEvent.audioMute :
  10403. callStats.fabricEvent.audioUnmute);
  10404. }
  10405. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10406. },
  10407. sendTerminateEvent: function () {
  10408. if(!callStats) {
  10409. return;
  10410. }
  10411. callStats.sendFabricEvent(this.peerconnection,
  10412. callStats.fabricEvent.fabricTerminated, this.confID);
  10413. },
  10414. sendSetupFailedEvent: function () {
  10415. if(!callStats) {
  10416. return;
  10417. }
  10418. callStats.sendFabricEvent(this.peerconnection,
  10419. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10420. }
  10421. };
  10422. module.exports = CallStats;
  10423. },{}],49:[function(require,module,exports){
  10424. /* global config */
  10425. /**
  10426. * Provides statistics for the local stream.
  10427. */
  10428. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10429. /**
  10430. * Size of the webaudio analyzer buffer.
  10431. * @type {number}
  10432. */
  10433. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10434. /**
  10435. * Value of the webaudio analyzer smoothing time parameter.
  10436. * @type {number}
  10437. */
  10438. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10439. /**
  10440. * Converts time domain data array to audio level.
  10441. * @param samples the time domain data array.
  10442. * @returns {number} the audio level
  10443. */
  10444. function timeDomainDataToAudioLevel(samples) {
  10445. var maxVolume = 0;
  10446. var length = samples.length;
  10447. for (var i = 0; i < length; i++) {
  10448. if (maxVolume < samples[i])
  10449. maxVolume = samples[i];
  10450. }
  10451. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10452. }
  10453. /**
  10454. * Animates audio level change
  10455. * @param newLevel the new audio level
  10456. * @param lastLevel the last audio level
  10457. * @returns {Number} the audio level to be set
  10458. */
  10459. function animateLevel(newLevel, lastLevel) {
  10460. var value = 0;
  10461. var diff = lastLevel - newLevel;
  10462. if(diff > 0.2) {
  10463. value = lastLevel - 0.2;
  10464. }
  10465. else if(diff < -0.4) {
  10466. value = lastLevel + 0.4;
  10467. }
  10468. else {
  10469. value = newLevel;
  10470. }
  10471. return parseFloat(value.toFixed(3));
  10472. }
  10473. /**
  10474. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10475. *
  10476. * @param stream the local stream
  10477. * @param interval stats refresh interval given in ms.
  10478. * @constructor
  10479. */
  10480. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10481. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10482. this.stream = stream;
  10483. this.intervalId = null;
  10484. this.intervalMilis = interval;
  10485. this.eventEmitter = eventEmitter;
  10486. this.audioLevel = 0;
  10487. this.statisticsService = statisticsService;
  10488. }
  10489. /**
  10490. * Starts the collecting the statistics.
  10491. */
  10492. LocalStatsCollector.prototype.start = function () {
  10493. if (config.disableAudioLevels || !window.AudioContext ||
  10494. RTCBrowserType.isTemasysPluginUsed())
  10495. return;
  10496. var context = new AudioContext();
  10497. var analyser = context.createAnalyser();
  10498. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10499. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10500. var source = context.createMediaStreamSource(this.stream);
  10501. source.connect(analyser);
  10502. var self = this;
  10503. this.intervalId = setInterval(
  10504. function () {
  10505. var array = new Uint8Array(analyser.frequencyBinCount);
  10506. analyser.getByteTimeDomainData(array);
  10507. var audioLevel = timeDomainDataToAudioLevel(array);
  10508. if (audioLevel != self.audioLevel) {
  10509. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10510. self.eventEmitter.emit(
  10511. "statistics.audioLevel",
  10512. self.statisticsService.LOCAL_JID,
  10513. self.audioLevel);
  10514. }
  10515. },
  10516. this.intervalMilis
  10517. );
  10518. };
  10519. /**
  10520. * Stops collecting the statistics.
  10521. */
  10522. LocalStatsCollector.prototype.stop = function () {
  10523. if (this.intervalId) {
  10524. clearInterval(this.intervalId);
  10525. this.intervalId = null;
  10526. }
  10527. };
  10528. module.exports = LocalStatsCollector;
  10529. },{"../RTC/RTCBrowserType":8}],50:[function(require,module,exports){
  10530. /* global require, ssrc2jid */
  10531. /* jshint -W117 */
  10532. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10533. /* Whether we support the browser we are running into for logging statistics */
  10534. var browserSupported = RTCBrowserType.isChrome() ||
  10535. RTCBrowserType.isOpera();
  10536. /**
  10537. * Calculates packet lost percent using the number of lost packets and the
  10538. * number of all packet.
  10539. * @param lostPackets the number of lost packets
  10540. * @param totalPackets the number of all packets.
  10541. * @returns {number} packet loss percent
  10542. */
  10543. function calculatePacketLoss(lostPackets, totalPackets) {
  10544. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10545. return 0;
  10546. return Math.round((lostPackets/totalPackets)*100);
  10547. }
  10548. function getStatValue(item, name) {
  10549. var browserType = RTCBrowserType.getBrowserType();
  10550. if (!keyMap[browserType][name])
  10551. throw "The property isn't supported!";
  10552. var key = keyMap[browserType][name];
  10553. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10554. item.stat(key) : item[key];
  10555. }
  10556. /**
  10557. * Peer statistics data holder.
  10558. * @constructor
  10559. */
  10560. function PeerStats()
  10561. {
  10562. this.ssrc2Loss = {};
  10563. this.ssrc2AudioLevel = {};
  10564. this.ssrc2bitrate = {};
  10565. this.ssrc2resolution = {};
  10566. }
  10567. /**
  10568. * The bandwidth
  10569. * @type {{}}
  10570. */
  10571. PeerStats.bandwidth = {};
  10572. /**
  10573. * The bit rate
  10574. * @type {{}}
  10575. */
  10576. PeerStats.bitrate = {};
  10577. /**
  10578. * The packet loss rate
  10579. * @type {{}}
  10580. */
  10581. PeerStats.packetLoss = null;
  10582. /**
  10583. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10584. * represented by this instance.
  10585. * @param ssrc audio or video RTP stream SSRC.
  10586. * @param lossRate new packet loss rate value to be set.
  10587. */
  10588. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10589. {
  10590. this.ssrc2Loss[ssrc] = lossRate;
  10591. };
  10592. /**
  10593. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10594. * represented by this instance.
  10595. * @param ssrc audio or video RTP stream SSRC.
  10596. * @param resolution new resolution value to be set.
  10597. */
  10598. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10599. {
  10600. if(resolution === null && this.ssrc2resolution[ssrc])
  10601. {
  10602. delete this.ssrc2resolution[ssrc];
  10603. }
  10604. else if(resolution !== null)
  10605. this.ssrc2resolution[ssrc] = resolution;
  10606. };
  10607. /**
  10608. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10609. * represented by this instance.
  10610. * @param ssrc audio or video RTP stream SSRC.
  10611. * @param bitrate new bitrate value to be set.
  10612. */
  10613. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10614. {
  10615. if(this.ssrc2bitrate[ssrc])
  10616. {
  10617. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10618. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10619. }
  10620. else {
  10621. this.ssrc2bitrate[ssrc] = bitrate;
  10622. }
  10623. };
  10624. /**
  10625. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10626. * the stream which belongs to the peer represented by this instance.
  10627. * @param ssrc RTP stream SSRC for which current audio level value will be
  10628. * updated.
  10629. * @param audioLevel the new audio level value to be set. Value is truncated to
  10630. * fit the range from 0 to 1.
  10631. */
  10632. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10633. {
  10634. // Range limit 0 - 1
  10635. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10636. };
  10637. function formatAudioLevel(audioLevel) {
  10638. return Math.min(Math.max(audioLevel, 0), 1);
  10639. }
  10640. /**
  10641. * Array with the transport information.
  10642. * @type {Array}
  10643. */
  10644. PeerStats.transport = [];
  10645. /**
  10646. * <tt>StatsCollector</tt> registers for stats updates of given
  10647. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10648. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10649. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10650. * instance as an event source.
  10651. *
  10652. * @param peerconnection webRTC peer connection object.
  10653. * @param interval stats refresh interval given in ms.
  10654. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10655. * called on stats update.
  10656. * @constructor
  10657. */
  10658. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10659. {
  10660. this.peerconnection = peerconnection;
  10661. this.baselineAudioLevelsReport = null;
  10662. this.currentAudioLevelsReport = null;
  10663. this.currentStatsReport = null;
  10664. this.baselineStatsReport = null;
  10665. this.audioLevelsIntervalId = null;
  10666. this.eventEmitter = eventEmitter;
  10667. /**
  10668. * Gather PeerConnection stats once every this many milliseconds.
  10669. */
  10670. this.GATHER_INTERVAL = 15000;
  10671. /**
  10672. * Log stats via the focus once every this many milliseconds.
  10673. */
  10674. this.LOG_INTERVAL = 60000;
  10675. /**
  10676. * Gather stats and store them in this.statsToBeLogged.
  10677. */
  10678. this.gatherStatsIntervalId = null;
  10679. /**
  10680. * Send the stats already saved in this.statsToBeLogged to be logged via
  10681. * the focus.
  10682. */
  10683. this.logStatsIntervalId = null;
  10684. /**
  10685. * Stores the statistics which will be send to the focus to be logged.
  10686. */
  10687. this.statsToBeLogged =
  10688. {
  10689. timestamps: [],
  10690. stats: {}
  10691. };
  10692. // Updates stats interval
  10693. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10694. this.statsIntervalId = null;
  10695. this.statsIntervalMilis = statsInterval;
  10696. // Map of jids to PeerStats
  10697. this.jid2stats = {};
  10698. }
  10699. module.exports = StatsCollector;
  10700. /**
  10701. * Stops stats updates.
  10702. */
  10703. StatsCollector.prototype.stop = function () {
  10704. if (this.audioLevelsIntervalId) {
  10705. clearInterval(this.audioLevelsIntervalId);
  10706. this.audioLevelsIntervalId = null;
  10707. }
  10708. if (this.statsIntervalId)
  10709. {
  10710. clearInterval(this.statsIntervalId);
  10711. this.statsIntervalId = null;
  10712. }
  10713. if(this.logStatsIntervalId)
  10714. {
  10715. clearInterval(this.logStatsIntervalId);
  10716. this.logStatsIntervalId = null;
  10717. }
  10718. if(this.gatherStatsIntervalId)
  10719. {
  10720. clearInterval(this.gatherStatsIntervalId);
  10721. this.gatherStatsIntervalId = null;
  10722. }
  10723. };
  10724. /**
  10725. * Callback passed to <tt>getStats</tt> method.
  10726. * @param error an error that occurred on <tt>getStats</tt> call.
  10727. */
  10728. StatsCollector.prototype.errorCallback = function (error)
  10729. {
  10730. console.error("Get stats error", error);
  10731. this.stop();
  10732. };
  10733. /**
  10734. * Starts stats updates.
  10735. */
  10736. StatsCollector.prototype.start = function ()
  10737. {
  10738. var self = this;
  10739. if (!config.disableAudioLevels) {
  10740. this.audioLevelsIntervalId = setInterval(
  10741. function () {
  10742. // Interval updates
  10743. self.peerconnection.getStats(
  10744. function (report) {
  10745. var results = null;
  10746. if (!report || !report.result ||
  10747. typeof report.result != 'function') {
  10748. results = report;
  10749. }
  10750. else {
  10751. results = report.result();
  10752. }
  10753. //console.error("Got interval report", results);
  10754. self.currentAudioLevelsReport = results;
  10755. self.processAudioLevelReport();
  10756. self.baselineAudioLevelsReport =
  10757. self.currentAudioLevelsReport;
  10758. },
  10759. self.errorCallback
  10760. );
  10761. },
  10762. self.audioLevelsIntervalMilis
  10763. );
  10764. }
  10765. if (!config.disableStats && browserSupported) {
  10766. this.statsIntervalId = setInterval(
  10767. function () {
  10768. // Interval updates
  10769. self.peerconnection.getStats(
  10770. function (report) {
  10771. var results = null;
  10772. if (!report || !report.result ||
  10773. typeof report.result != 'function') {
  10774. //firefox
  10775. results = report;
  10776. }
  10777. else {
  10778. //chrome
  10779. results = report.result();
  10780. }
  10781. //console.error("Got interval report", results);
  10782. self.currentStatsReport = results;
  10783. try {
  10784. self.processStatsReport();
  10785. }
  10786. catch (e) {
  10787. console.error("Unsupported key:" + e, e);
  10788. }
  10789. self.baselineStatsReport = self.currentStatsReport;
  10790. },
  10791. self.errorCallback
  10792. );
  10793. },
  10794. self.statsIntervalMilis
  10795. );
  10796. }
  10797. if (config.logStats && browserSupported) {
  10798. this.gatherStatsIntervalId = setInterval(
  10799. function () {
  10800. self.peerconnection.getStats(
  10801. function (report) {
  10802. self.addStatsToBeLogged(report.result());
  10803. },
  10804. function () {
  10805. }
  10806. );
  10807. },
  10808. this.GATHER_INTERVAL
  10809. );
  10810. this.logStatsIntervalId = setInterval(
  10811. function() { self.logStats(); },
  10812. this.LOG_INTERVAL);
  10813. }
  10814. };
  10815. /**
  10816. * Checks whether a certain record should be included in the logged statistics.
  10817. */
  10818. function acceptStat(reportId, reportType, statName) {
  10819. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10820. return false;
  10821. if (reportType == "ssrc") {
  10822. if (statName == "googTrackId" ||
  10823. statName == "transportId" ||
  10824. statName == "ssrc")
  10825. return false;
  10826. }
  10827. return true;
  10828. }
  10829. /**
  10830. * Checks whether a certain record should be included in the logged statistics.
  10831. */
  10832. function acceptReport(id, type) {
  10833. if (id.substring(0, 15) == "googCertificate" ||
  10834. id.substring(0, 9) == "googTrack" ||
  10835. id.substring(0, 20) == "googLibjingleSession")
  10836. return false;
  10837. if (type == "googComponent")
  10838. return false;
  10839. return true;
  10840. }
  10841. /**
  10842. * Converts the stats to the format used for logging, and saves the data in
  10843. * this.statsToBeLogged.
  10844. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10845. */
  10846. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10847. var self = this;
  10848. var num_records = this.statsToBeLogged.timestamps.length;
  10849. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10850. reports.map(function (report) {
  10851. if (!acceptReport(report.id, report.type))
  10852. return;
  10853. var stat = self.statsToBeLogged.stats[report.id];
  10854. if (!stat) {
  10855. stat = self.statsToBeLogged.stats[report.id] = {};
  10856. }
  10857. stat.type = report.type;
  10858. report.names().map(function (name) {
  10859. if (!acceptStat(report.id, report.type, name))
  10860. return;
  10861. var values = stat[name];
  10862. if (!values) {
  10863. values = stat[name] = [];
  10864. }
  10865. while (values.length < num_records) {
  10866. values.push(null);
  10867. }
  10868. values.push(report.stat(name));
  10869. });
  10870. });
  10871. };
  10872. StatsCollector.prototype.logStats = function () {
  10873. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10874. return;
  10875. // Reset the stats
  10876. this.statsToBeLogged.stats = {};
  10877. this.statsToBeLogged.timestamps = [];
  10878. };
  10879. var keyMap = {};
  10880. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10881. "ssrc": "ssrc",
  10882. "packetsReceived": "packetsReceived",
  10883. "packetsLost": "packetsLost",
  10884. "packetsSent": "packetsSent",
  10885. "bytesReceived": "bytesReceived",
  10886. "bytesSent": "bytesSent"
  10887. };
  10888. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10889. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10890. "sendBandwidth": "googAvailableSendBandwidth",
  10891. "remoteAddress": "googRemoteAddress",
  10892. "transportType": "googTransportType",
  10893. "localAddress": "googLocalAddress",
  10894. "activeConnection": "googActiveConnection",
  10895. "ssrc": "ssrc",
  10896. "packetsReceived": "packetsReceived",
  10897. "packetsSent": "packetsSent",
  10898. "packetsLost": "packetsLost",
  10899. "bytesReceived": "bytesReceived",
  10900. "bytesSent": "bytesSent",
  10901. "googFrameHeightReceived": "googFrameHeightReceived",
  10902. "googFrameWidthReceived": "googFrameWidthReceived",
  10903. "googFrameHeightSent": "googFrameHeightSent",
  10904. "googFrameWidthSent": "googFrameWidthSent",
  10905. "audioInputLevel": "audioInputLevel",
  10906. "audioOutputLevel": "audioOutputLevel"
  10907. };
  10908. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  10909. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  10910. /**
  10911. * Stats processing logic.
  10912. */
  10913. StatsCollector.prototype.processStatsReport = function () {
  10914. if (!this.baselineStatsReport) {
  10915. return;
  10916. }
  10917. for (var idx in this.currentStatsReport) {
  10918. var now = this.currentStatsReport[idx];
  10919. try {
  10920. if (getStatValue(now, 'receiveBandwidth') ||
  10921. getStatValue(now, 'sendBandwidth')) {
  10922. PeerStats.bandwidth = {
  10923. "download": Math.round(
  10924. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10925. "upload": Math.round(
  10926. (getStatValue(now, 'sendBandwidth')) / 1000)
  10927. };
  10928. }
  10929. }
  10930. catch(e){/*not supported*/}
  10931. if(now.type == 'googCandidatePair')
  10932. {
  10933. var ip, type, localIP, active;
  10934. try {
  10935. ip = getStatValue(now, 'remoteAddress');
  10936. type = getStatValue(now, "transportType");
  10937. localIP = getStatValue(now, "localAddress");
  10938. active = getStatValue(now, "activeConnection");
  10939. }
  10940. catch(e){/*not supported*/}
  10941. if(!ip || !type || !localIP || active != "true")
  10942. continue;
  10943. var addressSaved = false;
  10944. for(var i = 0; i < PeerStats.transport.length; i++)
  10945. {
  10946. if(PeerStats.transport[i].ip == ip &&
  10947. PeerStats.transport[i].type == type &&
  10948. PeerStats.transport[i].localip == localIP)
  10949. {
  10950. addressSaved = true;
  10951. }
  10952. }
  10953. if(addressSaved)
  10954. continue;
  10955. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10956. continue;
  10957. }
  10958. if(now.type == "candidatepair")
  10959. {
  10960. if(now.state == "succeeded")
  10961. continue;
  10962. var local = this.currentStatsReport[now.localCandidateId];
  10963. var remote = this.currentStatsReport[now.remoteCandidateId];
  10964. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10965. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10966. }
  10967. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10968. now.type != "inboundrtp") {
  10969. continue;
  10970. }
  10971. var before = this.baselineStatsReport[idx];
  10972. if (!before) {
  10973. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10974. continue;
  10975. }
  10976. var ssrc = getStatValue(now, 'ssrc');
  10977. if(!ssrc)
  10978. continue;
  10979. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10980. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10981. console.warn("No jid for ssrc: " + ssrc);
  10982. continue;
  10983. }
  10984. var jidStats = this.jid2stats[jid];
  10985. if (!jidStats) {
  10986. jidStats = new PeerStats();
  10987. this.jid2stats[jid] = jidStats;
  10988. }
  10989. var isDownloadStream = true;
  10990. var key = 'packetsReceived';
  10991. if (!getStatValue(now, key))
  10992. {
  10993. isDownloadStream = false;
  10994. key = 'packetsSent';
  10995. if (!getStatValue(now, key))
  10996. {
  10997. console.warn("No packetsReceived nor packetSent stat found");
  10998. continue;
  10999. }
  11000. }
  11001. var packetsNow = getStatValue(now, key);
  11002. if(!packetsNow || packetsNow < 0)
  11003. packetsNow = 0;
  11004. var packetsBefore = getStatValue(before, key);
  11005. if(!packetsBefore || packetsBefore < 0)
  11006. packetsBefore = 0;
  11007. var packetRate = packetsNow - packetsBefore;
  11008. if(!packetRate || packetRate < 0)
  11009. packetRate = 0;
  11010. var currentLoss = getStatValue(now, 'packetsLost');
  11011. if(!currentLoss || currentLoss < 0)
  11012. currentLoss = 0;
  11013. var previousLoss = getStatValue(before, 'packetsLost');
  11014. if(!previousLoss || previousLoss < 0)
  11015. previousLoss = 0;
  11016. var lossRate = currentLoss - previousLoss;
  11017. if(!lossRate || lossRate < 0)
  11018. lossRate = 0;
  11019. var packetsTotal = (packetRate + lossRate);
  11020. jidStats.setSsrcLoss(ssrc,
  11021. {"packetsTotal": packetsTotal,
  11022. "packetsLost": lossRate,
  11023. "isDownloadStream": isDownloadStream});
  11024. var bytesReceived = 0, bytesSent = 0;
  11025. if(getStatValue(now, "bytesReceived"))
  11026. {
  11027. bytesReceived = getStatValue(now, "bytesReceived") -
  11028. getStatValue(before, "bytesReceived");
  11029. }
  11030. if(getStatValue(now, "bytesSent"))
  11031. {
  11032. bytesSent = getStatValue(now, "bytesSent") -
  11033. getStatValue(before, "bytesSent");
  11034. }
  11035. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11036. if(bytesReceived <= 0 || time <= 0)
  11037. {
  11038. bytesReceived = 0;
  11039. }
  11040. else
  11041. {
  11042. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11043. }
  11044. if(bytesSent <= 0 || time <= 0)
  11045. {
  11046. bytesSent = 0;
  11047. }
  11048. else
  11049. {
  11050. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11051. }
  11052. jidStats.setSsrcBitrate(ssrc, {
  11053. "download": bytesReceived,
  11054. "upload": bytesSent});
  11055. var resolution = {height: null, width: null};
  11056. try {
  11057. if (getStatValue(now, "googFrameHeightReceived") &&
  11058. getStatValue(now, "googFrameWidthReceived")) {
  11059. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11060. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11061. }
  11062. else if (getStatValue(now, "googFrameHeightSent") &&
  11063. getStatValue(now, "googFrameWidthSent")) {
  11064. resolution.height = getStatValue(now, "googFrameHeightSent");
  11065. resolution.width = getStatValue(now, "googFrameWidthSent");
  11066. }
  11067. }
  11068. catch(e){/*not supported*/}
  11069. if(resolution.height && resolution.width)
  11070. {
  11071. jidStats.setSsrcResolution(ssrc, resolution);
  11072. }
  11073. else
  11074. {
  11075. jidStats.setSsrcResolution(ssrc, null);
  11076. }
  11077. }
  11078. var self = this;
  11079. // Jid stats
  11080. var totalPackets = {download: 0, upload: 0};
  11081. var lostPackets = {download: 0, upload: 0};
  11082. var bitrateDownload = 0;
  11083. var bitrateUpload = 0;
  11084. var resolutions = {};
  11085. Object.keys(this.jid2stats).forEach(
  11086. function (jid)
  11087. {
  11088. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11089. function (ssrc)
  11090. {
  11091. var type = "upload";
  11092. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11093. type = "download";
  11094. totalPackets[type] +=
  11095. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11096. lostPackets[type] +=
  11097. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11098. }
  11099. );
  11100. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11101. function (ssrc) {
  11102. bitrateDownload +=
  11103. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11104. bitrateUpload +=
  11105. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11106. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11107. }
  11108. );
  11109. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11110. }
  11111. );
  11112. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11113. PeerStats.packetLoss = {
  11114. total:
  11115. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11116. totalPackets.download + totalPackets.upload),
  11117. download:
  11118. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11119. upload:
  11120. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11121. };
  11122. this.eventEmitter.emit("statistics.connectionstats",
  11123. {
  11124. "bitrate": PeerStats.bitrate,
  11125. "packetLoss": PeerStats.packetLoss,
  11126. "bandwidth": PeerStats.bandwidth,
  11127. "resolution": resolutions,
  11128. "transport": PeerStats.transport
  11129. });
  11130. PeerStats.transport = [];
  11131. };
  11132. /**
  11133. * Stats processing logic.
  11134. */
  11135. StatsCollector.prototype.processAudioLevelReport = function () {
  11136. if (!this.baselineAudioLevelsReport) {
  11137. return;
  11138. }
  11139. for (var idx in this.currentAudioLevelsReport) {
  11140. var now = this.currentAudioLevelsReport[idx];
  11141. if (now.type != 'ssrc') {
  11142. continue;
  11143. }
  11144. var before = this.baselineAudioLevelsReport[idx];
  11145. if (!before) {
  11146. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11147. continue;
  11148. }
  11149. var ssrc = getStatValue(now, 'ssrc');
  11150. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11151. if (!jid) {
  11152. if((Date.now() - now.timestamp) < 3000)
  11153. console.warn("No jid for ssrc: " + ssrc);
  11154. continue;
  11155. }
  11156. var jidStats = this.jid2stats[jid];
  11157. if (!jidStats) {
  11158. jidStats = new PeerStats();
  11159. this.jid2stats[jid] = jidStats;
  11160. }
  11161. // Audio level
  11162. var audioLevel = null;
  11163. try {
  11164. audioLevel = getStatValue(now, 'audioInputLevel');
  11165. if (!audioLevel)
  11166. audioLevel = getStatValue(now, 'audioOutputLevel');
  11167. }
  11168. catch(e) {/*not supported*/
  11169. console.warn("Audio Levels are not available in the statistics.");
  11170. clearInterval(this.audioLevelsIntervalId);
  11171. return;
  11172. }
  11173. if (audioLevel) {
  11174. // TODO: can't find specs about what this value really is,
  11175. // but it seems to vary between 0 and around 32k.
  11176. audioLevel = audioLevel / 32767;
  11177. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11178. if(jid != APP.xmpp.myJid())
  11179. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11180. }
  11181. }
  11182. };
  11183. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11184. /* global require, APP */
  11185. /**
  11186. * Created by hristo on 8/4/14.
  11187. */
  11188. var LocalStats = require("./LocalStatsCollector.js");
  11189. var RTPStats = require("./RTPStatsCollector.js");
  11190. var EventEmitter = require("events");
  11191. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11192. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11193. var CallStats = require("./CallStats");
  11194. var RTCEvents = require("../../service/RTC/RTCEvents");
  11195. var eventEmitter = new EventEmitter();
  11196. var localStats = null;
  11197. var rtpStats = null;
  11198. function stopLocal() {
  11199. if (localStats) {
  11200. localStats.stop();
  11201. localStats = null;
  11202. }
  11203. }
  11204. function stopRemote() {
  11205. if (rtpStats) {
  11206. rtpStats.stop();
  11207. eventEmitter.emit("statistics.stop");
  11208. rtpStats = null;
  11209. }
  11210. }
  11211. function startRemoteStats (peerconnection) {
  11212. if (rtpStats) {
  11213. rtpStats.stop();
  11214. }
  11215. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11216. rtpStats.start();
  11217. }
  11218. function onStreamCreated(stream) {
  11219. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11220. return;
  11221. }
  11222. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11223. eventEmitter);
  11224. localStats.start();
  11225. }
  11226. function onDisposeConference(onUnload) {
  11227. CallStats.sendTerminateEvent();
  11228. stopRemote();
  11229. if(onUnload) {
  11230. stopLocal();
  11231. eventEmitter.removeAllListeners();
  11232. }
  11233. }
  11234. var statistics = {
  11235. /**
  11236. * Indicates that this audio level is for local jid.
  11237. * @type {string}
  11238. */
  11239. LOCAL_JID: 'local',
  11240. addAudioLevelListener: function(listener)
  11241. {
  11242. eventEmitter.on("statistics.audioLevel", listener);
  11243. },
  11244. removeAudioLevelListener: function(listener)
  11245. {
  11246. eventEmitter.removeListener("statistics.audioLevel", listener);
  11247. },
  11248. addConnectionStatsListener: function(listener)
  11249. {
  11250. eventEmitter.on("statistics.connectionstats", listener);
  11251. },
  11252. removeConnectionStatsListener: function(listener)
  11253. {
  11254. eventEmitter.removeListener("statistics.connectionstats", listener);
  11255. },
  11256. addRemoteStatsStopListener: function(listener)
  11257. {
  11258. eventEmitter.on("statistics.stop", listener);
  11259. },
  11260. removeRemoteStatsStopListener: function(listener)
  11261. {
  11262. eventEmitter.removeListener("statistics.stop", listener);
  11263. },
  11264. stop: function () {
  11265. stopLocal();
  11266. stopRemote();
  11267. if(eventEmitter)
  11268. {
  11269. eventEmitter.removeAllListeners();
  11270. }
  11271. },
  11272. stopRemoteStatistics: function()
  11273. {
  11274. stopRemote();
  11275. },
  11276. start: function () {
  11277. APP.RTC.addStreamListener(onStreamCreated,
  11278. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11279. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11280. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11281. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11282. startRemoteStats(event.peerconnection);
  11283. // CallStats.init(event);
  11284. });
  11285. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11286. CallStats.init(session);
  11287. });
  11288. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11289. CallStats.sendMuteEvent(mute, "audio");
  11290. });
  11291. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11292. CallStats.sendSetupFailedEvent();
  11293. });
  11294. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11295. CallStats.sendMuteEvent(mute, "video");
  11296. });
  11297. }
  11298. };
  11299. module.exports = statistics;
  11300. },{"../../service/RTC/RTCEvents":108,"../../service/RTC/StreamEventTypes.js":110,"../../service/xmpp/XMPPEvents":117,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":118}],52:[function(require,module,exports){
  11301. /* global $, require, config, interfaceConfig */
  11302. var i18n = require("i18next-client");
  11303. var languages = require("../../service/translation/languages");
  11304. var Settings = require("../settings/Settings");
  11305. var DEFAULT_LANG = languages.EN;
  11306. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11307. return value.replace("__app__", interfaceConfig.APP_NAME);
  11308. });
  11309. var defaultOptions = {
  11310. detectLngQS: "lang",
  11311. useCookie: false,
  11312. fallbackLng: DEFAULT_LANG,
  11313. load: "unspecific",
  11314. resGetPath: 'lang/__ns__-__lng__.json',
  11315. ns: {
  11316. namespaces: ['main', 'languages'],
  11317. defaultNs: 'main'
  11318. },
  11319. lngWhitelist : languages.getLanguages(),
  11320. fallbackOnNull: true,
  11321. fallbackOnEmpty: true,
  11322. useDataAttrOptions: true,
  11323. app: interfaceConfig.APP_NAME,
  11324. getAsync: false,
  11325. defaultValueFromContent: false,
  11326. customLoad: function(lng, ns, options, done) {
  11327. var resPath = "lang/__ns__-__lng__.json";
  11328. if(lng === languages.EN)
  11329. resPath = "lang/__ns__.json";
  11330. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11331. i18n.functions.ajax({
  11332. url: url,
  11333. success: function(data, status, xhr) {
  11334. i18n.functions.log('loaded: ' + url);
  11335. done(null, data);
  11336. },
  11337. error : function(xhr, status, error) {
  11338. if ((status && status == 200) ||
  11339. (xhr && xhr.status && xhr.status == 200)) {
  11340. // file loaded but invalid json, stop waste time !
  11341. i18n.functions.error('There is a typo in: ' + url);
  11342. } else if ((status && status == 404) ||
  11343. (xhr && xhr.status && xhr.status == 404)) {
  11344. i18n.functions.log('Does not exist: ' + url);
  11345. } else {
  11346. var theStatus = status ? status :
  11347. ((xhr && xhr.status) ? xhr.status : null);
  11348. i18n.functions.log(theStatus + ' when loading ' + url);
  11349. }
  11350. done(error, {});
  11351. },
  11352. dataType: "json",
  11353. async : options.getAsync
  11354. });
  11355. }
  11356. // options for caching
  11357. // useLocalStorage: true,
  11358. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11359. };
  11360. function initCompleted(t) {
  11361. $("[data-i18n]").i18n();
  11362. }
  11363. function checkForParameter() {
  11364. var query = window.location.search.substring(1);
  11365. var vars = query.split("&");
  11366. for (var i=0;i<vars.length;i++) {
  11367. var pair = vars[i].split("=");
  11368. if(pair[0] == "lang")
  11369. {
  11370. return pair[1];
  11371. }
  11372. }
  11373. return null;
  11374. }
  11375. module.exports = {
  11376. init: function (lang) {
  11377. var options = defaultOptions;
  11378. if(!lang)
  11379. {
  11380. lang = checkForParameter();
  11381. if(!lang)
  11382. {
  11383. var settings = Settings.getSettings();
  11384. if(settings)
  11385. lang = settings.language;
  11386. if(!lang && config.defaultLanguage)
  11387. {
  11388. lang = config.defaultLanguage;
  11389. }
  11390. }
  11391. }
  11392. if(lang) {
  11393. options.lng = lang;
  11394. }
  11395. i18n.init(options, initCompleted);
  11396. },
  11397. translateString: function (key, options) {
  11398. return i18n.t(key, options);
  11399. },
  11400. setLanguage: function (lang) {
  11401. if(!lang)
  11402. lang = DEFAULT_LANG;
  11403. i18n.setLng(lang, defaultOptions, initCompleted);
  11404. },
  11405. getCurrentLanguage: function () {
  11406. return i18n.lng();
  11407. },
  11408. translateElement: function (selector) {
  11409. selector.i18n();
  11410. },
  11411. generateTranslationHTML: function (key, options) {
  11412. var str = "<span data-i18n=\"" + key + "\"";
  11413. if(options)
  11414. {
  11415. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11416. }
  11417. str += ">";
  11418. str += this.translateString(key, options);
  11419. str += "</span>";
  11420. return str;
  11421. }
  11422. };
  11423. },{"../../service/translation/languages":116,"../settings/Settings":47,"i18next-client":69}],53:[function(require,module,exports){
  11424. /* jshint -W117 */
  11425. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11426. var SDPDiffer = require("./SDPDiffer");
  11427. var SDPUtil = require("./SDPUtil");
  11428. var SDP = require("./SDP");
  11429. var async = require("async");
  11430. var transform = require("sdp-transform");
  11431. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11432. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11433. var VideoSSRCHack = require("./VideoSSRCHack");
  11434. // Jingle stuff
  11435. function JingleSession(me, sid, connection, service, eventEmitter) {
  11436. this.me = me;
  11437. this.sid = sid;
  11438. this.connection = connection;
  11439. this.initiator = null;
  11440. this.responder = null;
  11441. this.isInitiator = null;
  11442. this.peerjid = null;
  11443. this.state = null;
  11444. this.localSDP = null;
  11445. this.remoteSDP = null;
  11446. this.relayedStreams = [];
  11447. this.startTime = null;
  11448. this.stopTime = null;
  11449. this.media_constraints = null;
  11450. this.pc_constraints = null;
  11451. this.ice_config = {};
  11452. this.drip_container = [];
  11453. this.service = service;
  11454. this.eventEmitter = eventEmitter;
  11455. this.usetrickle = true;
  11456. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11457. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11458. this.hadstuncandidate = false;
  11459. this.hadturncandidate = false;
  11460. this.lasticecandidate = false;
  11461. this.statsinterval = null;
  11462. this.reason = null;
  11463. this.addssrc = [];
  11464. this.removessrc = [];
  11465. this.pendingop = null;
  11466. this.switchstreams = false;
  11467. this.wait = true;
  11468. this.localStreamsSSRC = null;
  11469. this.ssrcOwners = {};
  11470. this.ssrcVideoTypes = {};
  11471. this.eventEmitter = eventEmitter;
  11472. /**
  11473. * The indicator which determines whether the (local) video has been muted
  11474. * in response to a user command in contrast to an automatic decision made
  11475. * by the application logic.
  11476. */
  11477. this.videoMuteByUser = false;
  11478. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11479. // We start with the queue paused. We resume it when the signaling state is
  11480. // stable and the ice connection state is connected.
  11481. this.modifySourcesQueue.pause();
  11482. }
  11483. JingleSession.prototype.updateModifySourcesQueue = function() {
  11484. var signalingState = this.peerconnection.signalingState;
  11485. var iceConnectionState = this.peerconnection.iceConnectionState;
  11486. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11487. this.modifySourcesQueue.resume();
  11488. } else {
  11489. this.modifySourcesQueue.pause();
  11490. }
  11491. };
  11492. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11493. var self = this;
  11494. if (this.state !== null) {
  11495. console.error('attempt to initiate on session ' + this.sid +
  11496. 'in state ' + this.state);
  11497. return;
  11498. }
  11499. this.isInitiator = isInitiator;
  11500. this.state = 'pending';
  11501. this.initiator = isInitiator ? this.me : peerjid;
  11502. this.responder = !isInitiator ? this.me : peerjid;
  11503. this.peerjid = peerjid;
  11504. this.hadstuncandidate = false;
  11505. this.hadturncandidate = false;
  11506. this.lasticecandidate = false;
  11507. this.isreconnect = false;
  11508. this.peerconnection
  11509. = new TraceablePeerConnection(
  11510. this.connection.jingle.ice_config,
  11511. this.connection.jingle.pc_constraints,
  11512. this);
  11513. this.peerconnection.onicecandidate = function (event) {
  11514. self.sendIceCandidate(event.candidate);
  11515. };
  11516. this.peerconnection.onaddstream = function (event) {
  11517. if (event.stream.id !== 'default') {
  11518. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11519. self.remoteStreamAdded(event);
  11520. } else {
  11521. // This is a recvonly stream. Clients that implement Unified Plan,
  11522. // such as Firefox use recvonly "streams/channels/tracks" for
  11523. // receiving remote stream/tracks, as opposed to Plan B where there
  11524. // are only 3 channels: audio, video and data.
  11525. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11526. }
  11527. };
  11528. this.peerconnection.onremovestream = function (event) {
  11529. // Remove the stream from remoteStreams
  11530. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11531. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11532. };
  11533. this.peerconnection.onsignalingstatechange = function (event) {
  11534. if (!(self && self.peerconnection)) return;
  11535. self.updateModifySourcesQueue();
  11536. };
  11537. /**
  11538. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  11539. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  11540. * RTCPeerConnection.iceConnectionState changes.
  11541. *
  11542. * @param event the event containing information about the change
  11543. */
  11544. this.peerconnection.oniceconnectionstatechange = function (event) {
  11545. if (!(self && self.peerconnection)) return;
  11546. self.updateModifySourcesQueue();
  11547. switch (self.peerconnection.iceConnectionState) {
  11548. case 'connected':
  11549. self.startTime = new Date();
  11550. // Informs interested parties that the connection has been restored.
  11551. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  11552. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  11553. self.isreconnect = false;
  11554. break;
  11555. case 'disconnected':
  11556. self.isreconnect = true;
  11557. self.stopTime = new Date();
  11558. // Informs interested parties that the connection has been interrupted.
  11559. if (self.peerconnection.signalingState === 'stable')
  11560. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  11561. break;
  11562. case 'failed':
  11563. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11564. break;
  11565. }
  11566. onIceConnectionStateChange(self.sid, self);
  11567. };
  11568. this.peerconnection.onnegotiationneeded = function (event) {
  11569. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11570. };
  11571. // add any local and relayed stream
  11572. APP.RTC.localStreams.forEach(function(stream) {
  11573. self.peerconnection.addStream(stream.getOriginalStream());
  11574. });
  11575. this.relayedStreams.forEach(function(stream) {
  11576. self.peerconnection.addStream(stream);
  11577. });
  11578. };
  11579. function onIceConnectionStateChange(sid, session) {
  11580. switch (session.peerconnection.iceConnectionState) {
  11581. case 'checking':
  11582. session.timeChecking = (new Date()).getTime();
  11583. session.firstconnect = true;
  11584. break;
  11585. case 'completed': // on caller side
  11586. case 'connected':
  11587. if (session.firstconnect) {
  11588. session.firstconnect = false;
  11589. var metadata = {};
  11590. metadata.setupTime
  11591. = (new Date()).getTime() - session.timeChecking;
  11592. session.peerconnection.getStats(function (res) {
  11593. if(res && res.result) {
  11594. res.result().forEach(function (report) {
  11595. if (report.type == 'googCandidatePair' &&
  11596. report.stat('googActiveConnection') == 'true') {
  11597. metadata.localCandidateType
  11598. = report.stat('googLocalCandidateType');
  11599. metadata.remoteCandidateType
  11600. = report.stat('googRemoteCandidateType');
  11601. // log pair as well so we can get nice pie
  11602. // charts
  11603. metadata.candidatePair
  11604. = report.stat('googLocalCandidateType') +
  11605. ';' +
  11606. report.stat('googRemoteCandidateType');
  11607. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11608. {
  11609. metadata.ipv6 = true;
  11610. }
  11611. }
  11612. });
  11613. }
  11614. });
  11615. }
  11616. break;
  11617. }
  11618. }
  11619. JingleSession.prototype.accept = function () {
  11620. this.state = 'active';
  11621. var pranswer = this.peerconnection.localDescription;
  11622. if (!pranswer || pranswer.type != 'pranswer') {
  11623. return;
  11624. }
  11625. console.log('going from pranswer to answer');
  11626. if (this.usetrickle) {
  11627. // remove candidates already sent from session-accept
  11628. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11629. for (var i = 0; i < lines.length; i++) {
  11630. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11631. }
  11632. }
  11633. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11634. // FIXME: change any inactive to sendrecv or whatever they were originally
  11635. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11636. }
  11637. var prsdp = new SDP(pranswer.sdp);
  11638. var accept = $iq({to: this.peerjid,
  11639. type: 'set'})
  11640. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11641. action: 'session-accept',
  11642. initiator: this.initiator,
  11643. responder: this.responder,
  11644. sid: this.sid });
  11645. // FIXME why do we generate session-accept in 3 different places ?
  11646. prsdp.toJingle(
  11647. accept,
  11648. this.initiator == this.me ? 'initiator' : 'responder',
  11649. this.localStreamsSSRC);
  11650. var sdp = this.peerconnection.localDescription.sdp;
  11651. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11652. // FIXME: change any inactive to sendrecv or whatever they were originally
  11653. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11654. }
  11655. var self = this;
  11656. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11657. function () {
  11658. //console.log('setLocalDescription success');
  11659. self.setLocalDescription();
  11660. VideoSSRCHack.processSessionInit(accept);
  11661. self.connection.sendIQ(accept,
  11662. function () {
  11663. var ack = {};
  11664. ack.source = 'answer';
  11665. $(document).trigger('ack.jingle', [self.sid, ack]);
  11666. },
  11667. function (stanza) {
  11668. var error = ($(stanza).find('error').length) ? {
  11669. code: $(stanza).find('error').attr('code'),
  11670. reason: $(stanza).find('error :first')[0].tagName
  11671. }:{};
  11672. error.source = 'answer';
  11673. JingleSession.onJingleError(self.sid, error);
  11674. },
  11675. 10000);
  11676. },
  11677. function (e) {
  11678. console.error('setLocalDescription failed', e);
  11679. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11680. }
  11681. );
  11682. };
  11683. JingleSession.prototype.terminate = function (reason) {
  11684. this.state = 'ended';
  11685. this.reason = reason;
  11686. this.peerconnection.close();
  11687. if (this.statsinterval !== null) {
  11688. window.clearInterval(this.statsinterval);
  11689. this.statsinterval = null;
  11690. }
  11691. };
  11692. JingleSession.prototype.active = function () {
  11693. return this.state == 'active';
  11694. };
  11695. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11696. var self = this;
  11697. if (candidate && !this.lasticecandidate) {
  11698. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11699. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11700. if (!(ice && jcand)) {
  11701. console.error('failed to get ice && jcand');
  11702. return;
  11703. }
  11704. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11705. if (jcand.type === 'srflx') {
  11706. this.hadstuncandidate = true;
  11707. } else if (jcand.type === 'relay') {
  11708. this.hadturncandidate = true;
  11709. }
  11710. if (this.usetrickle) {
  11711. if (this.usedrip) {
  11712. if (this.drip_container.length === 0) {
  11713. // start 20ms callout
  11714. window.setTimeout(function () {
  11715. if (self.drip_container.length === 0) return;
  11716. self.sendIceCandidates(self.drip_container);
  11717. self.drip_container = [];
  11718. }, 20);
  11719. }
  11720. this.drip_container.push(candidate);
  11721. return;
  11722. } else {
  11723. self.sendIceCandidate([candidate]);
  11724. }
  11725. }
  11726. } else {
  11727. //console.log('sendIceCandidate: last candidate.');
  11728. if (!this.usetrickle) {
  11729. //console.log('should send full offer now...');
  11730. //FIXME why do we generate session-accept in 3 different places ?
  11731. var init = $iq({to: this.peerjid,
  11732. type: 'set'})
  11733. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11734. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11735. initiator: this.initiator,
  11736. sid: this.sid});
  11737. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11738. var self = this;
  11739. var sendJingle = function (ssrc) {
  11740. if(!ssrc)
  11741. ssrc = {};
  11742. self.localSDP.toJingle(
  11743. init,
  11744. self.initiator == self.me ? 'initiator' : 'responder',
  11745. ssrc);
  11746. VideoSSRCHack.processSessionInit(init);
  11747. self.connection.sendIQ(init,
  11748. function () {
  11749. //console.log('session initiate ack');
  11750. var ack = {};
  11751. ack.source = 'offer';
  11752. $(document).trigger('ack.jingle', [self.sid, ack]);
  11753. },
  11754. function (stanza) {
  11755. self.state = 'error';
  11756. self.peerconnection.close();
  11757. var error = ($(stanza).find('error').length) ? {
  11758. code: $(stanza).find('error').attr('code'),
  11759. reason: $(stanza).find('error :first')[0].tagName,
  11760. }:{};
  11761. error.source = 'offer';
  11762. JingleSession.onJingleError(self.sid, error);
  11763. },
  11764. 10000);
  11765. }
  11766. sendJingle();
  11767. }
  11768. this.lasticecandidate = true;
  11769. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11770. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11771. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11772. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11773. }
  11774. }
  11775. };
  11776. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11777. console.log('sendIceCandidates', candidates);
  11778. var cand = $iq({to: this.peerjid, type: 'set'})
  11779. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11780. action: 'transport-info',
  11781. initiator: this.initiator,
  11782. sid: this.sid});
  11783. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11784. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11785. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11786. if (cands.length > 0) {
  11787. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11788. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11789. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11790. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11791. }).c('transport', ice);
  11792. for (var i = 0; i < cands.length; i++) {
  11793. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11794. }
  11795. // add fingerprint
  11796. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11797. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11798. tmp.required = true;
  11799. cand.c(
  11800. 'fingerprint',
  11801. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11802. .t(tmp.fingerprint);
  11803. delete tmp.fingerprint;
  11804. cand.attrs(tmp);
  11805. cand.up();
  11806. }
  11807. cand.up(); // transport
  11808. cand.up(); // content
  11809. }
  11810. }
  11811. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11812. //console.log('was this the last candidate', this.lasticecandidate);
  11813. this.connection.sendIQ(cand,
  11814. function () {
  11815. var ack = {};
  11816. ack.source = 'transportinfo';
  11817. $(document).trigger('ack.jingle', [this.sid, ack]);
  11818. },
  11819. function (stanza) {
  11820. var error = ($(stanza).find('error').length) ? {
  11821. code: $(stanza).find('error').attr('code'),
  11822. reason: $(stanza).find('error :first')[0].tagName,
  11823. }:{};
  11824. error.source = 'transportinfo';
  11825. JingleSession.onJingleError(this.sid, error);
  11826. },
  11827. 10000);
  11828. };
  11829. JingleSession.prototype.sendOffer = function () {
  11830. //console.log('sendOffer...');
  11831. var self = this;
  11832. this.peerconnection.createOffer(function (sdp) {
  11833. self.createdOffer(sdp);
  11834. },
  11835. function (e) {
  11836. console.error('createOffer failed', e);
  11837. },
  11838. this.media_constraints
  11839. );
  11840. };
  11841. // FIXME createdOffer is never used in jitsi-meet
  11842. JingleSession.prototype.createdOffer = function (sdp) {
  11843. //console.log('createdOffer', sdp);
  11844. var self = this;
  11845. this.localSDP = new SDP(sdp.sdp);
  11846. //this.localSDP.mangle();
  11847. var sendJingle = function () {
  11848. var init = $iq({to: this.peerjid,
  11849. type: 'set'})
  11850. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11851. action: 'session-initiate',
  11852. initiator: this.initiator,
  11853. sid: this.sid});
  11854. self.localSDP.toJingle(
  11855. init,
  11856. this.initiator == this.me ? 'initiator' : 'responder',
  11857. this.localStreamsSSRC);
  11858. VideoSSRCHack.processSessionInit(init);
  11859. self.connection.sendIQ(init,
  11860. function () {
  11861. var ack = {};
  11862. ack.source = 'offer';
  11863. $(document).trigger('ack.jingle', [self.sid, ack]);
  11864. },
  11865. function (stanza) {
  11866. self.state = 'error';
  11867. self.peerconnection.close();
  11868. var error = ($(stanza).find('error').length) ? {
  11869. code: $(stanza).find('error').attr('code'),
  11870. reason: $(stanza).find('error :first')[0].tagName,
  11871. }:{};
  11872. error.source = 'offer';
  11873. JingleSession.onJingleError(self.sid, error);
  11874. },
  11875. 10000);
  11876. }
  11877. sdp.sdp = this.localSDP.raw;
  11878. this.peerconnection.setLocalDescription(sdp,
  11879. function () {
  11880. if(self.usetrickle)
  11881. {
  11882. sendJingle();
  11883. }
  11884. self.setLocalDescription();
  11885. //console.log('setLocalDescription success');
  11886. },
  11887. function (e) {
  11888. console.error('setLocalDescription failed', e);
  11889. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11890. }
  11891. );
  11892. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11893. for (var i = 0; i < cands.length; i++) {
  11894. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11895. if (cand.type == 'srflx') {
  11896. this.hadstuncandidate = true;
  11897. } else if (cand.type == 'relay') {
  11898. this.hadturncandidate = true;
  11899. }
  11900. }
  11901. };
  11902. JingleSession.prototype.readSsrcInfo = function (contents) {
  11903. var self = this;
  11904. $(contents).each(function (idx, content) {
  11905. var name = $(content).attr('name');
  11906. var mediaType = this.getAttribute('name');
  11907. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11908. ssrcs.each(function () {
  11909. var ssrc = this.getAttribute('ssrc');
  11910. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  11911. function () {
  11912. var owner = this.getAttribute('owner');
  11913. self.ssrcOwners[ssrc] = owner;
  11914. }
  11915. );
  11916. });
  11917. });
  11918. };
  11919. JingleSession.prototype.getSsrcOwner = function (ssrc) {
  11920. return this.ssrcOwners[ssrc];
  11921. };
  11922. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11923. //console.log('setting remote description... ', desctype);
  11924. this.remoteSDP = new SDP('');
  11925. this.remoteSDP.fromJingle(elem);
  11926. this.readSsrcInfo($(elem).find(">content"));
  11927. if (this.peerconnection.remoteDescription !== null) {
  11928. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11929. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11930. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11931. for (var i = 0; i < pranswer.media.length; i++) {
  11932. // make sure we have ice ufrag and pwd
  11933. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11934. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11935. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11936. } else {
  11937. console.warn('no ice ufrag?');
  11938. }
  11939. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11940. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11941. } else {
  11942. console.warn('no ice pwd?');
  11943. }
  11944. }
  11945. // copy over candidates
  11946. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11947. for (var j = 0; j < lines.length; j++) {
  11948. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11949. }
  11950. }
  11951. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11952. }
  11953. }
  11954. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11955. this.peerconnection.setRemoteDescription(remotedesc,
  11956. function () {
  11957. //console.log('setRemoteDescription success');
  11958. },
  11959. function (e) {
  11960. console.error('setRemoteDescription error', e);
  11961. JingleSession.onJingleFatalError(self, e);
  11962. }
  11963. );
  11964. };
  11965. JingleSession.prototype.addIceCandidate = function (elem) {
  11966. var self = this;
  11967. if (this.peerconnection.signalingState == 'closed') {
  11968. return;
  11969. }
  11970. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11971. console.log('trickle ice candidate arriving before session accept...');
  11972. // create a PRANSWER for setRemoteDescription
  11973. if (!this.remoteSDP) {
  11974. var cobbled = 'v=0\r\n' +
  11975. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11976. 's=-\r\n' +
  11977. 't=0 0\r\n';
  11978. // first, take some things from the local description
  11979. for (var i = 0; i < this.localSDP.media.length; i++) {
  11980. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11981. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11982. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11983. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11984. }
  11985. cobbled += 'a=inactive\r\n';
  11986. }
  11987. this.remoteSDP = new SDP(cobbled);
  11988. }
  11989. // then add things like ice and dtls from remote candidate
  11990. elem.each(function () {
  11991. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11992. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11993. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11994. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11995. var tmp = $(this).find('transport');
  11996. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11997. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11998. tmp = $(this).find('transport>fingerprint');
  11999. if (tmp.length) {
  12000. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12001. } else {
  12002. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12003. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12004. }
  12005. break;
  12006. }
  12007. }
  12008. }
  12009. });
  12010. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12011. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12012. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12013. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12014. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12015. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12016. }).length == this.remoteSDP.media.length;
  12017. if (iscomplete) {
  12018. console.log('setting pranswer');
  12019. try {
  12020. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12021. function() {
  12022. },
  12023. function(e) {
  12024. console.log('setRemoteDescription pranswer failed', e.toString());
  12025. });
  12026. } catch (e) {
  12027. console.error('setting pranswer failed', e);
  12028. }
  12029. } else {
  12030. //console.log('not yet setting pranswer');
  12031. }
  12032. }
  12033. // operate on each content element
  12034. elem.each(function () {
  12035. // would love to deactivate this, but firefox still requires it
  12036. var idx = -1;
  12037. var i;
  12038. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12039. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12040. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12041. idx = i;
  12042. break;
  12043. }
  12044. }
  12045. if (idx == -1) { // fall back to localdescription
  12046. for (i = 0; i < self.localSDP.media.length; i++) {
  12047. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12048. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12049. idx = i;
  12050. break;
  12051. }
  12052. }
  12053. }
  12054. var name = $(this).attr('name');
  12055. // TODO: check ice-pwd and ice-ufrag?
  12056. $(this).find('transport>candidate').each(function () {
  12057. var line, candidate;
  12058. line = SDPUtil.candidateFromJingle(this);
  12059. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12060. sdpMid: name,
  12061. candidate: line});
  12062. try {
  12063. self.peerconnection.addIceCandidate(candidate);
  12064. } catch (e) {
  12065. console.error('addIceCandidate failed', e.toString(), line);
  12066. }
  12067. });
  12068. });
  12069. };
  12070. JingleSession.prototype.sendAnswer = function (provisional) {
  12071. //console.log('createAnswer', provisional);
  12072. var self = this;
  12073. this.peerconnection.createAnswer(
  12074. function (sdp) {
  12075. self.createdAnswer(sdp, provisional);
  12076. },
  12077. function (e) {
  12078. console.error('createAnswer failed', e);
  12079. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12080. },
  12081. this.media_constraints
  12082. );
  12083. };
  12084. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  12085. //console.log('createAnswer callback');
  12086. var self = this;
  12087. this.localSDP = new SDP(sdp.sdp);
  12088. //this.localSDP.mangle();
  12089. this.usepranswer = provisional === true;
  12090. if (this.usetrickle) {
  12091. if (this.usepranswer) {
  12092. sdp.type = 'pranswer';
  12093. for (var i = 0; i < this.localSDP.media.length; i++) {
  12094. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12095. }
  12096. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12097. }
  12098. }
  12099. var self = this;
  12100. var sendJingle = function (ssrcs) {
  12101. // FIXME why do we generate session-accept in 3 different places ?
  12102. var accept = $iq({to: self.peerjid,
  12103. type: 'set'})
  12104. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12105. action: 'session-accept',
  12106. initiator: self.initiator,
  12107. responder: self.responder,
  12108. sid: self.sid });
  12109. self.localSDP.toJingle(
  12110. accept,
  12111. self.initiator == self.me ? 'initiator' : 'responder',
  12112. ssrcs);
  12113. VideoSSRCHack.processSessionInit(accept);
  12114. self.connection.sendIQ(accept,
  12115. function () {
  12116. var ack = {};
  12117. ack.source = 'answer';
  12118. $(document).trigger('ack.jingle', [self.sid, ack]);
  12119. },
  12120. function (stanza) {
  12121. var error = ($(stanza).find('error').length) ? {
  12122. code: $(stanza).find('error').attr('code'),
  12123. reason: $(stanza).find('error :first')[0].tagName,
  12124. }:{};
  12125. error.source = 'answer';
  12126. JingleSession.onJingleError(self.sid, error);
  12127. },
  12128. 10000);
  12129. }
  12130. sdp.sdp = this.localSDP.raw;
  12131. this.peerconnection.setLocalDescription(sdp,
  12132. function () {
  12133. //console.log('setLocalDescription success');
  12134. if (self.usetrickle && !self.usepranswer) {
  12135. sendJingle();
  12136. }
  12137. self.setLocalDescription();
  12138. },
  12139. function (e) {
  12140. console.error('setLocalDescription failed', e);
  12141. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12142. }
  12143. );
  12144. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12145. for (var j = 0; j < cands.length; j++) {
  12146. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12147. if (cand.type == 'srflx') {
  12148. this.hadstuncandidate = true;
  12149. } else if (cand.type == 'relay') {
  12150. this.hadturncandidate = true;
  12151. }
  12152. }
  12153. };
  12154. JingleSession.prototype.sendTerminate = function (reason, text) {
  12155. var self = this,
  12156. term = $iq({to: this.peerjid,
  12157. type: 'set'})
  12158. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12159. action: 'session-terminate',
  12160. initiator: this.initiator,
  12161. sid: this.sid})
  12162. .c('reason')
  12163. .c(reason || 'success');
  12164. if (text) {
  12165. term.up().c('text').t(text);
  12166. }
  12167. this.connection.sendIQ(term,
  12168. function () {
  12169. self.peerconnection.close();
  12170. self.peerconnection = null;
  12171. self.terminate();
  12172. var ack = {};
  12173. ack.source = 'terminate';
  12174. $(document).trigger('ack.jingle', [self.sid, ack]);
  12175. },
  12176. function (stanza) {
  12177. var error = ($(stanza).find('error').length) ? {
  12178. code: $(stanza).find('error').attr('code'),
  12179. reason: $(stanza).find('error :first')[0].tagName,
  12180. }:{};
  12181. $(document).trigger('ack.jingle', [self.sid, error]);
  12182. },
  12183. 10000);
  12184. if (this.statsinterval !== null) {
  12185. window.clearInterval(this.statsinterval);
  12186. this.statsinterval = null;
  12187. }
  12188. };
  12189. JingleSession.prototype.addSource = function (elem, fromJid) {
  12190. var self = this;
  12191. // FIXME: dirty waiting
  12192. if (!this.peerconnection.localDescription)
  12193. {
  12194. console.warn("addSource - localDescription not ready yet")
  12195. setTimeout(function()
  12196. {
  12197. self.addSource(elem, fromJid);
  12198. },
  12199. 200
  12200. );
  12201. return;
  12202. }
  12203. console.log('addssrc', new Date().getTime());
  12204. console.log('ice', this.peerconnection.iceConnectionState);
  12205. this.readSsrcInfo(elem);
  12206. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12207. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12208. $(elem).each(function (idx, content) {
  12209. var name = $(content).attr('name');
  12210. var lines = '';
  12211. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12212. var semantics = this.getAttribute('semantics');
  12213. var ssrcs = $(this).find('>source').map(function () {
  12214. return this.getAttribute('ssrc');
  12215. }).get();
  12216. if (ssrcs.length != 0) {
  12217. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12218. }
  12219. });
  12220. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12221. tmp.each(function () {
  12222. var ssrc = $(this).attr('ssrc');
  12223. if(mySdp.containsSSRC(ssrc)){
  12224. /**
  12225. * This happens when multiple participants change their streams at the same time and
  12226. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12227. * addssrc are scheduled for update IQ. See
  12228. */
  12229. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12230. return;
  12231. }
  12232. if (sdp.containsSSRC(ssrc)) {
  12233. console.warn("Source-add request for existing SSRC: " + ssrc);
  12234. return;
  12235. }
  12236. $(this).find('>parameter').each(function () {
  12237. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12238. if ($(this).attr('value') && $(this).attr('value').length)
  12239. lines += ':' + $(this).attr('value');
  12240. lines += '\r\n';
  12241. });
  12242. });
  12243. sdp.media.forEach(function(media, idx) {
  12244. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12245. return;
  12246. sdp.media[idx] += lines;
  12247. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12248. self.addssrc[idx] += lines;
  12249. });
  12250. sdp.raw = sdp.session + sdp.media.join('');
  12251. });
  12252. this.modifySourcesQueue.push(function() {
  12253. // When a source is added and if this is FF, a new channel is allocated
  12254. // for receiving the added source. We need to diffuse the SSRC of this
  12255. // new recvonly channel to the rest of the peers.
  12256. console.log('modify sources done');
  12257. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12258. console.log("SDPs", mySdp, newSdp);
  12259. self.notifyMySSRCUpdate(mySdp, newSdp);
  12260. });
  12261. };
  12262. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12263. var self = this;
  12264. // FIXME: dirty waiting
  12265. if (!this.peerconnection.localDescription)
  12266. {
  12267. console.warn("removeSource - localDescription not ready yet")
  12268. setTimeout(function()
  12269. {
  12270. self.removeSource(elem, fromJid);
  12271. },
  12272. 200
  12273. );
  12274. return;
  12275. }
  12276. console.log('removessrc', new Date().getTime());
  12277. console.log('ice', this.peerconnection.iceConnectionState);
  12278. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12279. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12280. $(elem).each(function (idx, content) {
  12281. var name = $(content).attr('name');
  12282. var lines = '';
  12283. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12284. var semantics = this.getAttribute('semantics');
  12285. var ssrcs = $(this).find('>source').map(function () {
  12286. return this.getAttribute('ssrc');
  12287. }).get();
  12288. if (ssrcs.length != 0) {
  12289. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12290. }
  12291. });
  12292. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12293. tmp.each(function () {
  12294. var ssrc = $(this).attr('ssrc');
  12295. // This should never happen, but can be useful for bug detection
  12296. if(mySdp.containsSSRC(ssrc)){
  12297. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12298. return;
  12299. }
  12300. $(this).find('>parameter').each(function () {
  12301. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12302. if ($(this).attr('value') && $(this).attr('value').length)
  12303. lines += ':' + $(this).attr('value');
  12304. lines += '\r\n';
  12305. });
  12306. });
  12307. sdp.media.forEach(function(media, idx) {
  12308. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12309. return;
  12310. sdp.media[idx] += lines;
  12311. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12312. self.removessrc[idx] += lines;
  12313. });
  12314. sdp.raw = sdp.session + sdp.media.join('');
  12315. });
  12316. this.modifySourcesQueue.push(function() {
  12317. // When a source is removed and if this is FF, the recvonly channel that
  12318. // receives the remote stream is deactivated . We need to diffuse the
  12319. // recvonly SSRC removal to the rest of the peers.
  12320. console.log('modify sources done');
  12321. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12322. console.log("SDPs", mySdp, newSdp);
  12323. self.notifyMySSRCUpdate(mySdp, newSdp);
  12324. });
  12325. };
  12326. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12327. var self = this;
  12328. if (this.peerconnection.signalingState == 'closed') return;
  12329. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12330. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12331. this.setLocalDescription();
  12332. if(successCallback){
  12333. successCallback();
  12334. }
  12335. queueCallback();
  12336. return;
  12337. }
  12338. // Reset switch streams flag
  12339. this.switchstreams = false;
  12340. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12341. // add sources
  12342. this.addssrc.forEach(function(lines, idx) {
  12343. sdp.media[idx] += lines;
  12344. });
  12345. this.addssrc = [];
  12346. // remove sources
  12347. this.removessrc.forEach(function(lines, idx) {
  12348. lines = lines.split('\r\n');
  12349. lines.pop(); // remove empty last element;
  12350. lines.forEach(function(line) {
  12351. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12352. });
  12353. });
  12354. this.removessrc = [];
  12355. sdp.raw = sdp.session + sdp.media.join('');
  12356. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12357. function() {
  12358. if(self.signalingState == 'closed') {
  12359. console.error("createAnswer attempt on closed state");
  12360. queueCallback("createAnswer attempt on closed state");
  12361. return;
  12362. }
  12363. self.peerconnection.createAnswer(
  12364. function(modifiedAnswer) {
  12365. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12366. if (self.pendingop !== null) {
  12367. var sdp = new SDP(modifiedAnswer.sdp);
  12368. if (sdp.media.length > 1) {
  12369. switch(self.pendingop) {
  12370. case 'mute':
  12371. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12372. break;
  12373. case 'unmute':
  12374. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12375. break;
  12376. }
  12377. sdp.raw = sdp.session + sdp.media.join('');
  12378. modifiedAnswer.sdp = sdp.raw;
  12379. }
  12380. self.pendingop = null;
  12381. }
  12382. // FIXME: pushing down an answer while ice connection state
  12383. // is still checking is bad...
  12384. //console.log(self.peerconnection.iceConnectionState);
  12385. // trying to work around another chrome bug
  12386. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12387. self.peerconnection.setLocalDescription(modifiedAnswer,
  12388. function() {
  12389. //console.log('modified setLocalDescription ok');
  12390. self.setLocalDescription();
  12391. if(successCallback){
  12392. successCallback();
  12393. }
  12394. queueCallback();
  12395. },
  12396. function(error) {
  12397. console.error('modified setLocalDescription failed', error);
  12398. queueCallback(error);
  12399. }
  12400. );
  12401. },
  12402. function(error) {
  12403. console.error('modified answer failed', error);
  12404. queueCallback(error);
  12405. }
  12406. );
  12407. },
  12408. function(error) {
  12409. console.error('modify failed', error);
  12410. queueCallback(error);
  12411. }
  12412. );
  12413. };
  12414. /**
  12415. * Switches video streams.
  12416. * @param new_stream new stream that will be used as video of this session.
  12417. * @param oldStream old video stream of this session.
  12418. * @param success_callback callback executed after successful stream switch.
  12419. */
  12420. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12421. var self = this;
  12422. // Remember SDP to figure out added/removed SSRCs
  12423. var oldSdp = null;
  12424. if(self.peerconnection) {
  12425. if(self.peerconnection.localDescription) {
  12426. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12427. }
  12428. self.peerconnection.removeStream(oldStream, true);
  12429. if(new_stream)
  12430. self.peerconnection.addStream(new_stream);
  12431. }
  12432. // Conference is not active
  12433. if(!oldSdp || !self.peerconnection) {
  12434. success_callback();
  12435. return;
  12436. }
  12437. self.switchstreams = true;
  12438. self.modifySourcesQueue.push(function() {
  12439. console.log('modify sources done');
  12440. success_callback();
  12441. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12442. console.log("SDPs", oldSdp, newSdp);
  12443. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12444. });
  12445. };
  12446. /**
  12447. * Figures out added/removed ssrcs and send update IQs.
  12448. * @param old_sdp SDP object for old description.
  12449. * @param new_sdp SDP object for new description.
  12450. */
  12451. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12452. if (!(this.peerconnection.signalingState == 'stable' &&
  12453. this.peerconnection.iceConnectionState == 'connected')){
  12454. console.log("Too early to send updates");
  12455. return;
  12456. }
  12457. // send source-remove IQ.
  12458. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12459. var remove = $iq({to: this.peerjid, type: 'set'})
  12460. .c('jingle', {
  12461. xmlns: 'urn:xmpp:jingle:1',
  12462. action: 'source-remove',
  12463. initiator: this.initiator,
  12464. sid: this.sid
  12465. }
  12466. );
  12467. var removed = sdpDiffer.toJingle(remove);
  12468. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  12469. // it in the current form
  12470. if (removed)
  12471. remove = VideoSSRCHack.processSourceRemove(remove);
  12472. if (removed && remove) {
  12473. this.connection.sendIQ(remove,
  12474. function (res) {
  12475. console.info('got remove result', res);
  12476. },
  12477. function (err) {
  12478. console.error('got remove error', err);
  12479. }
  12480. );
  12481. } else {
  12482. console.log('removal not necessary');
  12483. }
  12484. // send source-add IQ.
  12485. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12486. var add = $iq({to: this.peerjid, type: 'set'})
  12487. .c('jingle', {
  12488. xmlns: 'urn:xmpp:jingle:1',
  12489. action: 'source-add',
  12490. initiator: this.initiator,
  12491. sid: this.sid
  12492. }
  12493. );
  12494. var added = sdpDiffer.toJingle(add);
  12495. // Let 'source-add' IQ through the hack and see if we're allowed to send
  12496. // it in the current form
  12497. if (added)
  12498. add = VideoSSRCHack.processSourceAdd(add);
  12499. if (added & add) {
  12500. this.connection.sendIQ(add,
  12501. function (res) {
  12502. console.info('got add result', res);
  12503. },
  12504. function (err) {
  12505. console.error('got add error', err);
  12506. }
  12507. );
  12508. } else {
  12509. console.log('addition not necessary');
  12510. }
  12511. };
  12512. /**
  12513. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12514. *
  12515. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12516. * tracks; otherwise, <tt>false</tt>
  12517. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12518. * tracks have been enabled/disabled. The function may, optionally, return
  12519. * another function which is to be invoked after the whole mute/unmute operation
  12520. * has completed successfully.
  12521. * @param options an object which specifies optional arguments such as the
  12522. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12523. * specifies whether the method was initiated in response to a user command (in
  12524. * contrast to an automatic decision made by the application logic)
  12525. */
  12526. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12527. var byUser;
  12528. if (options) {
  12529. byUser = options.byUser;
  12530. if (typeof byUser === 'undefined') {
  12531. byUser = true;
  12532. }
  12533. } else {
  12534. byUser = true;
  12535. }
  12536. // The user's command to mute the (local) video takes precedence over any
  12537. // automatic decision made by the application logic.
  12538. if (byUser) {
  12539. this.videoMuteByUser = mute;
  12540. } else if (this.videoMuteByUser) {
  12541. return;
  12542. }
  12543. this.hardMuteVideo(mute);
  12544. var self = this;
  12545. var oldSdp = null;
  12546. if(self.peerconnection) {
  12547. if(self.peerconnection.localDescription) {
  12548. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12549. }
  12550. }
  12551. this.modifySourcesQueue.push(function() {
  12552. console.log('modify sources done');
  12553. callback(mute);
  12554. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12555. console.log("SDPs", oldSdp, newSdp);
  12556. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12557. });
  12558. };
  12559. JingleSession.prototype.hardMuteVideo = function (muted) {
  12560. this.pendingop = muted ? 'mute' : 'unmute';
  12561. };
  12562. JingleSession.prototype.sendMute = function (muted, content) {
  12563. var info = $iq({to: this.peerjid,
  12564. type: 'set'})
  12565. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12566. action: 'session-info',
  12567. initiator: this.initiator,
  12568. sid: this.sid });
  12569. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12570. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12571. if (content) {
  12572. info.attrs({'name': content});
  12573. }
  12574. this.connection.send(info);
  12575. };
  12576. JingleSession.prototype.sendRinging = function () {
  12577. var info = $iq({to: this.peerjid,
  12578. type: 'set'})
  12579. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12580. action: 'session-info',
  12581. initiator: this.initiator,
  12582. sid: this.sid });
  12583. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12584. this.connection.send(info);
  12585. };
  12586. JingleSession.prototype.getStats = function (interval) {
  12587. var self = this;
  12588. var recv = {audio: 0, video: 0};
  12589. var lost = {audio: 0, video: 0};
  12590. var lastrecv = {audio: 0, video: 0};
  12591. var lastlost = {audio: 0, video: 0};
  12592. var loss = {audio: 0, video: 0};
  12593. var delta = {audio: 0, video: 0};
  12594. this.statsinterval = window.setInterval(function () {
  12595. if (self && self.peerconnection && self.peerconnection.getStats) {
  12596. self.peerconnection.getStats(function (stats) {
  12597. var results = stats.result();
  12598. // TODO: there are so much statistics you can get from this..
  12599. for (var i = 0; i < results.length; ++i) {
  12600. if (results[i].type == 'ssrc') {
  12601. var packetsrecv = results[i].stat('packetsReceived');
  12602. var packetslost = results[i].stat('packetsLost');
  12603. if (packetsrecv && packetslost) {
  12604. packetsrecv = parseInt(packetsrecv, 10);
  12605. packetslost = parseInt(packetslost, 10);
  12606. if (results[i].stat('googFrameRateReceived')) {
  12607. lastlost.video = lost.video;
  12608. lastrecv.video = recv.video;
  12609. recv.video = packetsrecv;
  12610. lost.video = packetslost;
  12611. } else {
  12612. lastlost.audio = lost.audio;
  12613. lastrecv.audio = recv.audio;
  12614. recv.audio = packetsrecv;
  12615. lost.audio = packetslost;
  12616. }
  12617. }
  12618. }
  12619. }
  12620. delta.audio = recv.audio - lastrecv.audio;
  12621. delta.video = recv.video - lastrecv.video;
  12622. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12623. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12624. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12625. });
  12626. }
  12627. }, interval || 3000);
  12628. return this.statsinterval;
  12629. };
  12630. JingleSession.onJingleError = function (session, error)
  12631. {
  12632. console.error("Jingle error", error);
  12633. }
  12634. JingleSession.onJingleFatalError = function (session, error)
  12635. {
  12636. this.service.sessionTerminated = true;
  12637. this.connection.emuc.doLeave();
  12638. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12639. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12640. }
  12641. JingleSession.prototype.setLocalDescription = function () {
  12642. var self = this;
  12643. var newssrcs = [];
  12644. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12645. session.media.forEach(function (media) {
  12646. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12647. // TODO(gp) maybe exclude FID streams?
  12648. media.ssrcs.forEach(function (ssrc) {
  12649. if (ssrc.attribute !== 'cname') {
  12650. return;
  12651. }
  12652. newssrcs.push({
  12653. 'ssrc': ssrc.id,
  12654. 'type': media.type
  12655. });
  12656. });
  12657. }
  12658. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12659. {
  12660. newssrcs.push({
  12661. 'ssrc': self.localStreamsSSRC[media.type],
  12662. 'type': media.type
  12663. });
  12664. }
  12665. });
  12666. console.log('new ssrcs', newssrcs);
  12667. // Bind us as local SSRCs owner
  12668. if (newssrcs.length > 0) {
  12669. for (var i = 1; i <= newssrcs.length; i ++) {
  12670. var ssrc = newssrcs[i-1].ssrc;
  12671. var myJid = self.connection.emuc.myroomjid;
  12672. self.ssrcOwners[ssrc] = myJid;
  12673. }
  12674. }
  12675. }
  12676. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12677. function sendKeyframe(pc) {
  12678. console.log('sendkeyframe', pc.iceConnectionState);
  12679. if (pc.iceConnectionState !== 'connected') return; // safe...
  12680. var self = this;
  12681. pc.setRemoteDescription(
  12682. pc.remoteDescription,
  12683. function () {
  12684. pc.createAnswer(
  12685. function (modifiedAnswer) {
  12686. pc.setLocalDescription(
  12687. modifiedAnswer,
  12688. function () {
  12689. // noop
  12690. },
  12691. function (error) {
  12692. console.log('triggerKeyframe setLocalDescription failed', error);
  12693. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  12694. }
  12695. );
  12696. },
  12697. function (error) {
  12698. console.log('triggerKeyframe createAnswer failed', error);
  12699. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  12700. }
  12701. );
  12702. },
  12703. function (error) {
  12704. console.log('triggerKeyframe setRemoteDescription failed', error);
  12705. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  12706. }
  12707. );
  12708. }
  12709. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12710. var self = this;
  12711. var thessrc;
  12712. var streamId = APP.RTC.getStreamID(data.stream);
  12713. // look up an associated JID for a stream id
  12714. if (!streamId) {
  12715. console.error("No stream ID for", data.stream);
  12716. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12717. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12718. var ssrclines
  12719. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12720. ssrclines = ssrclines.filter(function (line) {
  12721. // NOTE(gp) previously we filtered on the mslabel, but that property
  12722. // is not always present.
  12723. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12724. if (RTCBrowserType.isTemasysPluginUsed()) {
  12725. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12726. } else {
  12727. return ((line.indexOf('msid:' + streamId) !== -1));
  12728. }
  12729. });
  12730. if (ssrclines.length) {
  12731. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12732. if (!self.ssrcOwners[thessrc]) {
  12733. console.error("No SSRC owner known for: " + thessrc);
  12734. return;
  12735. }
  12736. data.peerjid = self.ssrcOwners[thessrc];
  12737. console.log('associated jid', self.ssrcOwners[thessrc]);
  12738. } else {
  12739. console.error("No SSRC lines for ", streamId);
  12740. }
  12741. }
  12742. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12743. var isVideo = data.stream.getVideoTracks().length > 0;
  12744. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12745. if (isVideo &&
  12746. data.peerjid && this.peerjid === data.peerjid &&
  12747. data.stream.getVideoTracks().length === 0 &&
  12748. APP.RTC.localVideo.getTracks().length > 0) {
  12749. window.setTimeout(function () {
  12750. sendKeyframe(self.peerconnection);
  12751. }, 3000);
  12752. }
  12753. }
  12754. module.exports = JingleSession;
  12755. },{"../../service/xmpp/XMPPEvents":117,"../RTC/RTCBrowserType":8,"./SDP":54,"./SDPDiffer":55,"./SDPUtil":56,"./TraceablePeerConnection":57,"./VideoSSRCHack":58,"async":68,"sdp-transform":104}],54:[function(require,module,exports){
  12756. /* jshint -W117 */
  12757. var SDPUtil = require("./SDPUtil");
  12758. // SDP STUFF
  12759. function SDP(sdp) {
  12760. this.media = sdp.split('\r\nm=');
  12761. for (var i = 1; i < this.media.length; i++) {
  12762. this.media[i] = 'm=' + this.media[i];
  12763. if (i != this.media.length - 1) {
  12764. this.media[i] += '\r\n';
  12765. }
  12766. }
  12767. this.session = this.media.shift() + '\r\n';
  12768. this.raw = this.session + this.media.join('');
  12769. }
  12770. /**
  12771. * Returns map of MediaChannel mapped per channel idx.
  12772. */
  12773. SDP.prototype.getMediaSsrcMap = function() {
  12774. var self = this;
  12775. var media_ssrcs = {};
  12776. var tmp;
  12777. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12778. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12779. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12780. var media = {
  12781. mediaindex: mediaindex,
  12782. mid: mid,
  12783. ssrcs: {},
  12784. ssrcGroups: []
  12785. };
  12786. media_ssrcs[mediaindex] = media;
  12787. tmp.forEach(function (line) {
  12788. var linessrc = line.substring(7).split(' ')[0];
  12789. // allocate new ChannelSsrc
  12790. if(!media.ssrcs[linessrc]) {
  12791. media.ssrcs[linessrc] = {
  12792. ssrc: linessrc,
  12793. lines: []
  12794. };
  12795. }
  12796. media.ssrcs[linessrc].lines.push(line);
  12797. });
  12798. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12799. tmp.forEach(function(line){
  12800. var semantics = line.substr(0, idx).substr(13);
  12801. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12802. if (ssrcs.length != 0) {
  12803. media.ssrcGroups.push({
  12804. semantics: semantics,
  12805. ssrcs: ssrcs
  12806. });
  12807. }
  12808. });
  12809. }
  12810. return media_ssrcs;
  12811. };
  12812. /**
  12813. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12814. * @param ssrc the ssrc to check.
  12815. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12816. */
  12817. SDP.prototype.containsSSRC = function(ssrc) {
  12818. var medias = this.getMediaSsrcMap();
  12819. var contains = false;
  12820. Object.keys(medias).forEach(function(mediaindex){
  12821. var media = medias[mediaindex];
  12822. //console.log("Check", channel, ssrc);
  12823. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12824. contains = true;
  12825. }
  12826. });
  12827. return contains;
  12828. };
  12829. // remove iSAC and CN from SDP
  12830. SDP.prototype.mangle = function () {
  12831. var i, j, mline, lines, rtpmap, newdesc;
  12832. for (i = 0; i < this.media.length; i++) {
  12833. lines = this.media[i].split('\r\n');
  12834. lines.pop(); // remove empty last element
  12835. mline = SDPUtil.parse_mline(lines.shift());
  12836. if (mline.media != 'audio')
  12837. continue;
  12838. newdesc = '';
  12839. mline.fmt.length = 0;
  12840. for (j = 0; j < lines.length; j++) {
  12841. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12842. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12843. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12844. continue;
  12845. mline.fmt.push(rtpmap.id);
  12846. newdesc += lines[j] + '\r\n';
  12847. } else {
  12848. newdesc += lines[j] + '\r\n';
  12849. }
  12850. }
  12851. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12852. this.media[i] += newdesc;
  12853. }
  12854. this.raw = this.session + this.media.join('');
  12855. };
  12856. // remove lines matching prefix from session section
  12857. SDP.prototype.removeSessionLines = function(prefix) {
  12858. var self = this;
  12859. var lines = SDPUtil.find_lines(this.session, prefix);
  12860. lines.forEach(function(line) {
  12861. self.session = self.session.replace(line + '\r\n', '');
  12862. });
  12863. this.raw = this.session + this.media.join('');
  12864. return lines;
  12865. }
  12866. // remove lines matching prefix from a media section specified by mediaindex
  12867. // TODO: non-numeric mediaindex could match mid
  12868. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12869. var self = this;
  12870. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12871. lines.forEach(function(line) {
  12872. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12873. });
  12874. this.raw = this.session + this.media.join('');
  12875. return lines;
  12876. }
  12877. // add content's to a jingle element
  12878. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  12879. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12880. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12881. var self = this;
  12882. // new bundle plan
  12883. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12884. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12885. for (i = 0; i < lines.length; i++) {
  12886. tmp = lines[i].split(' ');
  12887. var semantics = tmp.shift().substr(8);
  12888. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12889. for (j = 0; j < tmp.length; j++) {
  12890. elem.c('content', {name: tmp[j]}).up();
  12891. }
  12892. elem.up();
  12893. }
  12894. }
  12895. for (i = 0; i < this.media.length; i++) {
  12896. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12897. if (!(mline.media === 'audio' ||
  12898. mline.media === 'video' ||
  12899. mline.media === 'application'))
  12900. {
  12901. continue;
  12902. }
  12903. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12904. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12905. } else {
  12906. if(ssrcs && ssrcs[mline.media])
  12907. {
  12908. ssrc = ssrcs[mline.media];
  12909. }
  12910. else
  12911. ssrc = false;
  12912. }
  12913. elem.c('content', {creator: thecreator, name: mline.media});
  12914. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12915. // prefer identifier from a=mid if present
  12916. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12917. elem.attrs({ name: mid });
  12918. }
  12919. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12920. {
  12921. elem.c('description',
  12922. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12923. media: mline.media });
  12924. if (ssrc) {
  12925. elem.attrs({ssrc: ssrc});
  12926. }
  12927. for (j = 0; j < mline.fmt.length; j++) {
  12928. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12929. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12930. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12931. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12932. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12933. for (k = 0; k < tmp.length; k++) {
  12934. elem.c('parameter', tmp[k]).up();
  12935. }
  12936. }
  12937. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12938. elem.up();
  12939. }
  12940. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12941. elem.c('encryption', {required: 1});
  12942. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12943. crypto.forEach(function(line) {
  12944. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12945. });
  12946. elem.up(); // end of encryption
  12947. }
  12948. if (ssrc) {
  12949. // new style mapping
  12950. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12951. // FIXME: group by ssrc and support multiple different ssrcs
  12952. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12953. if(ssrclines.length > 0) {
  12954. ssrclines.forEach(function (line) {
  12955. idx = line.indexOf(' ');
  12956. var linessrc = line.substr(0, idx).substr(7);
  12957. if (linessrc != ssrc) {
  12958. elem.up();
  12959. ssrc = linessrc;
  12960. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12961. }
  12962. var kv = line.substr(idx + 1);
  12963. elem.c('parameter');
  12964. if (kv.indexOf(':') == -1) {
  12965. elem.attrs({ name: kv });
  12966. } else {
  12967. var k = kv.split(':', 2)[0];
  12968. elem.attrs({ name: k });
  12969. var v = kv.split(':', 2)[1];
  12970. v = SDPUtil.filter_special_chars(v);
  12971. elem.attrs({ value: v });
  12972. }
  12973. elem.up();
  12974. });
  12975. }
  12976. else
  12977. {
  12978. elem.up();
  12979. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12980. elem.c('parameter');
  12981. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12982. elem.up();
  12983. var msid = null;
  12984. if(mline.media == "audio")
  12985. {
  12986. msid = APP.RTC.localAudio.getId();
  12987. }
  12988. else
  12989. {
  12990. msid = APP.RTC.localVideo.getId();
  12991. }
  12992. if(msid != null)
  12993. {
  12994. msid = SDPUtil.filter_special_chars(msid);
  12995. elem.c('parameter');
  12996. elem.attrs({name: "msid", value:msid});
  12997. elem.up();
  12998. elem.c('parameter');
  12999. elem.attrs({name: "mslabel", value:msid});
  13000. elem.up();
  13001. elem.c('parameter');
  13002. elem.attrs({name: "label", value:msid});
  13003. elem.up();
  13004. }
  13005. }
  13006. elem.up();
  13007. // XEP-0339 handle ssrc-group attributes
  13008. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13009. ssrc_group_lines.forEach(function(line) {
  13010. idx = line.indexOf(' ');
  13011. var semantics = line.substr(0, idx).substr(13);
  13012. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13013. if (ssrcs.length != 0) {
  13014. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13015. ssrcs.forEach(function(ssrc) {
  13016. elem.c('source', { ssrc: ssrc })
  13017. .up();
  13018. });
  13019. elem.up();
  13020. }
  13021. });
  13022. }
  13023. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13024. elem.c('rtcp-mux').up();
  13025. }
  13026. // XEP-0293 -- map a=rtcp-fb:*
  13027. this.RtcpFbToJingle(i, elem, '*');
  13028. // XEP-0294
  13029. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13030. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13031. for (j = 0; j < lines.length; j++) {
  13032. tmp = SDPUtil.parse_extmap(lines[j]);
  13033. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13034. uri: tmp.uri,
  13035. id: tmp.value });
  13036. if (tmp.hasOwnProperty('direction')) {
  13037. switch (tmp.direction) {
  13038. case 'sendonly':
  13039. elem.attrs({senders: 'responder'});
  13040. break;
  13041. case 'recvonly':
  13042. elem.attrs({senders: 'initiator'});
  13043. break;
  13044. case 'sendrecv':
  13045. elem.attrs({senders: 'both'});
  13046. break;
  13047. case 'inactive':
  13048. elem.attrs({senders: 'none'});
  13049. break;
  13050. }
  13051. }
  13052. // TODO: handle params
  13053. elem.up();
  13054. }
  13055. }
  13056. elem.up(); // end of description
  13057. }
  13058. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13059. this.TransportToJingle(i, elem);
  13060. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13061. elem.attrs({senders: 'both'});
  13062. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13063. elem.attrs({senders: 'initiator'});
  13064. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13065. elem.attrs({senders: 'responder'});
  13066. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13067. elem.attrs({senders: 'none'});
  13068. }
  13069. if (mline.port == '0') {
  13070. // estos hack to reject an m-line
  13071. elem.attrs({senders: 'rejected'});
  13072. }
  13073. elem.up(); // end of content
  13074. }
  13075. elem.up();
  13076. return elem;
  13077. };
  13078. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13079. var i = mediaindex;
  13080. var tmp;
  13081. var self = this;
  13082. elem.c('transport');
  13083. // XEP-0343 DTLS/SCTP
  13084. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13085. {
  13086. var sctpmap = SDPUtil.find_line(
  13087. this.media[i], 'a=sctpmap:', self.session);
  13088. if (sctpmap)
  13089. {
  13090. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13091. elem.c('sctpmap',
  13092. {
  13093. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13094. number: sctpAttrs[0], /* SCTP port */
  13095. protocol: sctpAttrs[1], /* protocol */
  13096. });
  13097. // Optional stream count attribute
  13098. if (sctpAttrs.length > 2)
  13099. elem.attrs({ streams: sctpAttrs[2]});
  13100. elem.up();
  13101. }
  13102. }
  13103. // XEP-0320
  13104. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13105. fingerprints.forEach(function(line) {
  13106. tmp = SDPUtil.parse_fingerprint(line);
  13107. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13108. elem.c('fingerprint').t(tmp.fingerprint);
  13109. delete tmp.fingerprint;
  13110. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13111. if (line) {
  13112. tmp.setup = line.substr(8);
  13113. }
  13114. elem.attrs(tmp);
  13115. elem.up(); // end of fingerprint
  13116. });
  13117. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13118. if (tmp) {
  13119. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13120. elem.attrs(tmp);
  13121. // XEP-0176
  13122. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13123. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13124. lines.forEach(function (line) {
  13125. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13126. });
  13127. }
  13128. }
  13129. elem.up(); // end of transport
  13130. }
  13131. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13132. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13133. lines.forEach(function (line) {
  13134. var tmp = SDPUtil.parse_rtcpfb(line);
  13135. if (tmp.type == 'trr-int') {
  13136. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13137. elem.up();
  13138. } else {
  13139. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13140. if (tmp.params.length > 0) {
  13141. elem.attrs({'subtype': tmp.params[0]});
  13142. }
  13143. elem.up();
  13144. }
  13145. });
  13146. };
  13147. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13148. var media = '';
  13149. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13150. if (tmp.length) {
  13151. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13152. if (tmp.attr('value')) {
  13153. media += tmp.attr('value');
  13154. } else {
  13155. media += '0';
  13156. }
  13157. media += '\r\n';
  13158. }
  13159. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13160. tmp.each(function () {
  13161. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13162. if ($(this).attr('subtype')) {
  13163. media += ' ' + $(this).attr('subtype');
  13164. }
  13165. media += '\r\n';
  13166. });
  13167. return media;
  13168. };
  13169. // construct an SDP from a jingle stanza
  13170. SDP.prototype.fromJingle = function (jingle) {
  13171. var self = this;
  13172. this.raw = 'v=0\r\n' +
  13173. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13174. 's=-\r\n' +
  13175. 't=0 0\r\n';
  13176. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13177. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13178. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13179. var contents = $(group).find('>content').map(function (idx, content) {
  13180. return content.getAttribute('name');
  13181. }).get();
  13182. if (contents.length > 0) {
  13183. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13184. }
  13185. });
  13186. }
  13187. this.session = this.raw;
  13188. jingle.find('>content').each(function () {
  13189. var m = self.jingle2media($(this));
  13190. self.media.push(m);
  13191. });
  13192. // reconstruct msid-semantic -- apparently not necessary
  13193. /*
  13194. var msid = SDPUtil.parse_ssrc(this.raw);
  13195. if (msid.hasOwnProperty('mslabel')) {
  13196. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13197. }
  13198. */
  13199. this.raw = this.session + this.media.join('');
  13200. };
  13201. // translate a jingle content element into an an SDP media part
  13202. SDP.prototype.jingle2media = function (content) {
  13203. var media = '',
  13204. desc = content.find('description'),
  13205. ssrc = desc.attr('ssrc'),
  13206. self = this,
  13207. tmp;
  13208. var sctp = content.find(
  13209. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13210. tmp = { media: desc.attr('media') };
  13211. tmp.port = '1';
  13212. if (content.attr('senders') == 'rejected') {
  13213. // estos hack to reject an m-line.
  13214. tmp.port = '0';
  13215. }
  13216. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13217. if (sctp.length)
  13218. tmp.proto = 'DTLS/SCTP';
  13219. else
  13220. tmp.proto = 'RTP/SAVPF';
  13221. } else {
  13222. tmp.proto = 'RTP/AVPF';
  13223. }
  13224. if (!sctp.length)
  13225. {
  13226. tmp.fmt = desc.find('payload-type').map(
  13227. function () { return this.getAttribute('id'); }).get();
  13228. media += SDPUtil.build_mline(tmp) + '\r\n';
  13229. }
  13230. else
  13231. {
  13232. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13233. media += 'a=sctpmap:' + sctp.attr('number') +
  13234. ' ' + sctp.attr('protocol');
  13235. var streamCount = sctp.attr('streams');
  13236. if (streamCount)
  13237. media += ' ' + streamCount + '\r\n';
  13238. else
  13239. media += '\r\n';
  13240. }
  13241. media += 'c=IN IP4 0.0.0.0\r\n';
  13242. if (!sctp.length)
  13243. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13244. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13245. if (tmp.length) {
  13246. if (tmp.attr('ufrag')) {
  13247. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13248. }
  13249. if (tmp.attr('pwd')) {
  13250. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13251. }
  13252. tmp.find('>fingerprint').each(function () {
  13253. // FIXME: check namespace at some point
  13254. media += 'a=fingerprint:' + this.getAttribute('hash');
  13255. media += ' ' + $(this).text();
  13256. media += '\r\n';
  13257. if (this.getAttribute('setup')) {
  13258. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13259. }
  13260. });
  13261. }
  13262. switch (content.attr('senders')) {
  13263. case 'initiator':
  13264. media += 'a=sendonly\r\n';
  13265. break;
  13266. case 'responder':
  13267. media += 'a=recvonly\r\n';
  13268. break;
  13269. case 'none':
  13270. media += 'a=inactive\r\n';
  13271. break;
  13272. case 'both':
  13273. media += 'a=sendrecv\r\n';
  13274. break;
  13275. }
  13276. media += 'a=mid:' + content.attr('name') + '\r\n';
  13277. // <description><rtcp-mux/></description>
  13278. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13279. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13280. if (desc.find('rtcp-mux').length) {
  13281. media += 'a=rtcp-mux\r\n';
  13282. }
  13283. if (desc.find('encryption').length) {
  13284. desc.find('encryption>crypto').each(function () {
  13285. media += 'a=crypto:' + this.getAttribute('tag');
  13286. media += ' ' + this.getAttribute('crypto-suite');
  13287. media += ' ' + this.getAttribute('key-params');
  13288. if (this.getAttribute('session-params')) {
  13289. media += ' ' + this.getAttribute('session-params');
  13290. }
  13291. media += '\r\n';
  13292. });
  13293. }
  13294. desc.find('payload-type').each(function () {
  13295. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13296. if ($(this).find('>parameter').length) {
  13297. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13298. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13299. media += '\r\n';
  13300. }
  13301. // xep-0293
  13302. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13303. });
  13304. // xep-0293
  13305. media += self.RtcpFbFromJingle(desc, '*');
  13306. // xep-0294
  13307. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13308. tmp.each(function () {
  13309. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13310. });
  13311. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13312. media += SDPUtil.candidateFromJingle(this);
  13313. });
  13314. // XEP-0339 handle ssrc-group attributes
  13315. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13316. var semantics = this.getAttribute('semantics');
  13317. var ssrcs = $(this).find('>source').map(function() {
  13318. return this.getAttribute('ssrc');
  13319. }).get();
  13320. if (ssrcs.length != 0) {
  13321. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13322. }
  13323. });
  13324. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13325. tmp.each(function () {
  13326. var ssrc = this.getAttribute('ssrc');
  13327. $(this).find('>parameter').each(function () {
  13328. var name = this.getAttribute('name');
  13329. var value = this.getAttribute('value');
  13330. value = SDPUtil.filter_special_chars(value);
  13331. media += 'a=ssrc:' + ssrc + ' ' + name;
  13332. if (value && value.length)
  13333. media += ':' + value;
  13334. media += '\r\n';
  13335. });
  13336. });
  13337. return media;
  13338. };
  13339. module.exports = SDP;
  13340. },{"./SDPUtil":56}],55:[function(require,module,exports){
  13341. var SDPUtil = require("./SDPUtil");
  13342. function SDPDiffer(mySDP, otherSDP) {
  13343. this.mySDP = mySDP;
  13344. this.otherSDP = otherSDP;
  13345. }
  13346. /**
  13347. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13348. * @param otherSdp the other SDP to check ssrc with.
  13349. */
  13350. SDPDiffer.prototype.getNewMedia = function() {
  13351. // this could be useful in Array.prototype.
  13352. function arrayEquals(array) {
  13353. // if the other array is a falsy value, return
  13354. if (!array)
  13355. return false;
  13356. // compare lengths - can save a lot of time
  13357. if (this.length != array.length)
  13358. return false;
  13359. for (var i = 0, l=this.length; i < l; i++) {
  13360. // Check if we have nested arrays
  13361. if (this[i] instanceof Array && array[i] instanceof Array) {
  13362. // recurse into the nested arrays
  13363. if (!this[i].equals(array[i]))
  13364. return false;
  13365. }
  13366. else if (this[i] != array[i]) {
  13367. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13368. return false;
  13369. }
  13370. }
  13371. return true;
  13372. }
  13373. var myMedias = this.mySDP.getMediaSsrcMap();
  13374. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13375. var newMedia = {};
  13376. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13377. var myMedia = myMedias[othersMediaIdx];
  13378. var othersMedia = othersMedias[othersMediaIdx];
  13379. if(!myMedia && othersMedia) {
  13380. // Add whole channel
  13381. newMedia[othersMediaIdx] = othersMedia;
  13382. return;
  13383. }
  13384. // Look for new ssrcs accross the channel
  13385. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13386. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13387. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13388. if(!newMedia[othersMediaIdx]){
  13389. newMedia[othersMediaIdx] = {
  13390. mediaindex: othersMedia.mediaindex,
  13391. mid: othersMedia.mid,
  13392. ssrcs: {},
  13393. ssrcGroups: []
  13394. };
  13395. }
  13396. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13397. }
  13398. });
  13399. // Look for new ssrc groups across the channels
  13400. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13401. // try to match the other ssrc-group with an ssrc-group of ours
  13402. var matched = false;
  13403. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13404. var mySsrcGroup = myMedia.ssrcGroups[i];
  13405. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13406. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13407. matched = true;
  13408. break;
  13409. }
  13410. }
  13411. if (!matched) {
  13412. // Allocate channel if we've found an ssrc-group that doesn't
  13413. // exist in our channel
  13414. if(!newMedia[othersMediaIdx]){
  13415. newMedia[othersMediaIdx] = {
  13416. mediaindex: othersMedia.mediaindex,
  13417. mid: othersMedia.mid,
  13418. ssrcs: {},
  13419. ssrcGroups: []
  13420. };
  13421. }
  13422. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13423. }
  13424. });
  13425. });
  13426. return newMedia;
  13427. };
  13428. /**
  13429. * Sends SSRC update IQ.
  13430. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13431. * @param sid session identifier that will be put into the IQ.
  13432. * @param initiator initiator identifier.
  13433. * @param toJid destination Jid
  13434. * @param isAdd indicates if this is remove or add operation.
  13435. */
  13436. SDPDiffer.prototype.toJingle = function(modify) {
  13437. var sdpMediaSsrcs = this.getNewMedia();
  13438. var self = this;
  13439. // FIXME: only announce video ssrcs since we mix audio and dont need
  13440. // the audio ssrcs therefore
  13441. var modified = false;
  13442. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13443. modified = true;
  13444. var media = sdpMediaSsrcs[mediaindex];
  13445. modify.c('content', {name: media.mid});
  13446. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13447. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13448. // generate sources from lines
  13449. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13450. var mediaSsrc = media.ssrcs[ssrcNum];
  13451. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13452. modify.attrs({ssrc: mediaSsrc.ssrc});
  13453. // iterate over ssrc lines
  13454. mediaSsrc.lines.forEach(function (line) {
  13455. var idx = line.indexOf(' ');
  13456. var kv = line.substr(idx + 1);
  13457. modify.c('parameter');
  13458. if (kv.indexOf(':') == -1) {
  13459. modify.attrs({ name: kv });
  13460. } else {
  13461. var nv = kv.split(':', 2);
  13462. var name = nv[0];
  13463. var value = SDPUtil.filter_special_chars(nv[1]);
  13464. modify.attrs({ name: name });
  13465. modify.attrs({ value: value });
  13466. }
  13467. modify.up(); // end of parameter
  13468. });
  13469. modify.up(); // end of source
  13470. });
  13471. // generate source groups from lines
  13472. media.ssrcGroups.forEach(function(ssrcGroup) {
  13473. if (ssrcGroup.ssrcs.length != 0) {
  13474. modify.c('ssrc-group', {
  13475. semantics: ssrcGroup.semantics,
  13476. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13477. });
  13478. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13479. modify.c('source', { ssrc: ssrc })
  13480. .up(); // end of source
  13481. });
  13482. modify.up(); // end of ssrc-group
  13483. }
  13484. });
  13485. modify.up(); // end of description
  13486. modify.up(); // end of content
  13487. });
  13488. return modified;
  13489. };
  13490. module.exports = SDPDiffer;
  13491. },{"./SDPUtil":56}],56:[function(require,module,exports){
  13492. SDPUtil = {
  13493. filter_special_chars: function (text) {
  13494. return text.replace(/[\\\/\{,\}\+]/g, "");
  13495. },
  13496. iceparams: function (mediadesc, sessiondesc) {
  13497. var data = null;
  13498. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13499. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13500. data = {
  13501. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13502. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13503. };
  13504. }
  13505. return data;
  13506. },
  13507. parse_iceufrag: function (line) {
  13508. return line.substring(12);
  13509. },
  13510. build_iceufrag: function (frag) {
  13511. return 'a=ice-ufrag:' + frag;
  13512. },
  13513. parse_icepwd: function (line) {
  13514. return line.substring(10);
  13515. },
  13516. build_icepwd: function (pwd) {
  13517. return 'a=ice-pwd:' + pwd;
  13518. },
  13519. parse_mid: function (line) {
  13520. return line.substring(6);
  13521. },
  13522. parse_mline: function (line) {
  13523. var parts = line.substring(2).split(' '),
  13524. data = {};
  13525. data.media = parts.shift();
  13526. data.port = parts.shift();
  13527. data.proto = parts.shift();
  13528. if (parts[parts.length - 1] === '') { // trailing whitespace
  13529. parts.pop();
  13530. }
  13531. data.fmt = parts;
  13532. return data;
  13533. },
  13534. build_mline: function (mline) {
  13535. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13536. },
  13537. parse_rtpmap: function (line) {
  13538. var parts = line.substring(9).split(' '),
  13539. data = {};
  13540. data.id = parts.shift();
  13541. parts = parts[0].split('/');
  13542. data.name = parts.shift();
  13543. data.clockrate = parts.shift();
  13544. data.channels = parts.length ? parts.shift() : '1';
  13545. return data;
  13546. },
  13547. /**
  13548. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13549. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13550. * @returns [SCTP port number, protocol, streams]
  13551. */
  13552. parse_sctpmap: function (line)
  13553. {
  13554. var parts = line.substring(10).split(' ');
  13555. var sctpPort = parts[0];
  13556. var protocol = parts[1];
  13557. // Stream count is optional
  13558. var streamCount = parts.length > 2 ? parts[2] : null;
  13559. return [sctpPort, protocol, streamCount];// SCTP port
  13560. },
  13561. build_rtpmap: function (el) {
  13562. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13563. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13564. line += '/' + el.getAttribute('channels');
  13565. }
  13566. return line;
  13567. },
  13568. parse_crypto: function (line) {
  13569. var parts = line.substring(9).split(' '),
  13570. data = {};
  13571. data.tag = parts.shift();
  13572. data['crypto-suite'] = parts.shift();
  13573. data['key-params'] = parts.shift();
  13574. if (parts.length) {
  13575. data['session-params'] = parts.join(' ');
  13576. }
  13577. return data;
  13578. },
  13579. parse_fingerprint: function (line) { // RFC 4572
  13580. var parts = line.substring(14).split(' '),
  13581. data = {};
  13582. data.hash = parts.shift();
  13583. data.fingerprint = parts.shift();
  13584. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13585. return data;
  13586. },
  13587. parse_fmtp: function (line) {
  13588. var parts = line.split(' '),
  13589. i, key, value,
  13590. data = [];
  13591. parts.shift();
  13592. parts = parts.join(' ').split(';');
  13593. for (i = 0; i < parts.length; i++) {
  13594. key = parts[i].split('=')[0];
  13595. while (key.length && key[0] == ' ') {
  13596. key = key.substring(1);
  13597. }
  13598. value = parts[i].split('=')[1];
  13599. if (key && value) {
  13600. data.push({name: key, value: value});
  13601. } else if (key) {
  13602. // rfc 4733 (DTMF) style stuff
  13603. data.push({name: '', value: key});
  13604. }
  13605. }
  13606. return data;
  13607. },
  13608. parse_icecandidate: function (line) {
  13609. var candidate = {},
  13610. elems = line.split(' ');
  13611. candidate.foundation = elems[0].substring(12);
  13612. candidate.component = elems[1];
  13613. candidate.protocol = elems[2].toLowerCase();
  13614. candidate.priority = elems[3];
  13615. candidate.ip = elems[4];
  13616. candidate.port = elems[5];
  13617. // elems[6] => "typ"
  13618. candidate.type = elems[7];
  13619. candidate.generation = 0; // default value, may be overwritten below
  13620. for (var i = 8; i < elems.length; i += 2) {
  13621. switch (elems[i]) {
  13622. case 'raddr':
  13623. candidate['rel-addr'] = elems[i + 1];
  13624. break;
  13625. case 'rport':
  13626. candidate['rel-port'] = elems[i + 1];
  13627. break;
  13628. case 'generation':
  13629. candidate.generation = elems[i + 1];
  13630. break;
  13631. case 'tcptype':
  13632. candidate.tcptype = elems[i + 1];
  13633. break;
  13634. default: // TODO
  13635. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13636. }
  13637. }
  13638. candidate.network = '1';
  13639. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13640. return candidate;
  13641. },
  13642. build_icecandidate: function (cand) {
  13643. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13644. line += ' ';
  13645. switch (cand.type) {
  13646. case 'srflx':
  13647. case 'prflx':
  13648. case 'relay':
  13649. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13650. line += 'raddr';
  13651. line += ' ';
  13652. line += cand['rel-addr'];
  13653. line += ' ';
  13654. line += 'rport';
  13655. line += ' ';
  13656. line += cand['rel-port'];
  13657. line += ' ';
  13658. }
  13659. break;
  13660. }
  13661. if (cand.hasOwnAttribute('tcptype')) {
  13662. line += 'tcptype';
  13663. line += ' ';
  13664. line += cand.tcptype;
  13665. line += ' ';
  13666. }
  13667. line += 'generation';
  13668. line += ' ';
  13669. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13670. return line;
  13671. },
  13672. parse_ssrc: function (desc) {
  13673. // proprietary mapping of a=ssrc lines
  13674. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13675. // and parse according to that
  13676. var lines = desc.split('\r\n'),
  13677. data = {};
  13678. for (var i = 0; i < lines.length; i++) {
  13679. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13680. var idx = lines[i].indexOf(' ');
  13681. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13682. }
  13683. }
  13684. return data;
  13685. },
  13686. parse_rtcpfb: function (line) {
  13687. var parts = line.substr(10).split(' ');
  13688. var data = {};
  13689. data.pt = parts.shift();
  13690. data.type = parts.shift();
  13691. data.params = parts;
  13692. return data;
  13693. },
  13694. parse_extmap: function (line) {
  13695. var parts = line.substr(9).split(' ');
  13696. var data = {};
  13697. data.value = parts.shift();
  13698. if (data.value.indexOf('/') != -1) {
  13699. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13700. data.value = data.value.substr(0, data.value.indexOf('/'));
  13701. } else {
  13702. data.direction = 'both';
  13703. }
  13704. data.uri = parts.shift();
  13705. data.params = parts;
  13706. return data;
  13707. },
  13708. find_line: function (haystack, needle, sessionpart) {
  13709. var lines = haystack.split('\r\n');
  13710. for (var i = 0; i < lines.length; i++) {
  13711. if (lines[i].substring(0, needle.length) == needle) {
  13712. return lines[i];
  13713. }
  13714. }
  13715. if (!sessionpart) {
  13716. return false;
  13717. }
  13718. // search session part
  13719. lines = sessionpart.split('\r\n');
  13720. for (var j = 0; j < lines.length; j++) {
  13721. if (lines[j].substring(0, needle.length) == needle) {
  13722. return lines[j];
  13723. }
  13724. }
  13725. return false;
  13726. },
  13727. find_lines: function (haystack, needle, sessionpart) {
  13728. var lines = haystack.split('\r\n'),
  13729. needles = [];
  13730. for (var i = 0; i < lines.length; i++) {
  13731. if (lines[i].substring(0, needle.length) == needle)
  13732. needles.push(lines[i]);
  13733. }
  13734. if (needles.length || !sessionpart) {
  13735. return needles;
  13736. }
  13737. // search session part
  13738. lines = sessionpart.split('\r\n');
  13739. for (var j = 0; j < lines.length; j++) {
  13740. if (lines[j].substring(0, needle.length) == needle) {
  13741. needles.push(lines[j]);
  13742. }
  13743. }
  13744. return needles;
  13745. },
  13746. candidateToJingle: function (line) {
  13747. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13748. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13749. if (line.indexOf('candidate:') === 0) {
  13750. line = 'a=' + line;
  13751. } else if (line.substring(0, 12) != 'a=candidate:') {
  13752. console.log('parseCandidate called with a line that is not a candidate line');
  13753. console.log(line);
  13754. return null;
  13755. }
  13756. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13757. line = line.substring(0, line.length - 2);
  13758. var candidate = {},
  13759. elems = line.split(' '),
  13760. i;
  13761. if (elems[6] != 'typ') {
  13762. console.log('did not find typ in the right place');
  13763. console.log(line);
  13764. return null;
  13765. }
  13766. candidate.foundation = elems[0].substring(12);
  13767. candidate.component = elems[1];
  13768. candidate.protocol = elems[2].toLowerCase();
  13769. candidate.priority = elems[3];
  13770. candidate.ip = elems[4];
  13771. candidate.port = elems[5];
  13772. // elems[6] => "typ"
  13773. candidate.type = elems[7];
  13774. candidate.generation = '0'; // default, may be overwritten below
  13775. for (i = 8; i < elems.length; i += 2) {
  13776. switch (elems[i]) {
  13777. case 'raddr':
  13778. candidate['rel-addr'] = elems[i + 1];
  13779. break;
  13780. case 'rport':
  13781. candidate['rel-port'] = elems[i + 1];
  13782. break;
  13783. case 'generation':
  13784. candidate.generation = elems[i + 1];
  13785. break;
  13786. case 'tcptype':
  13787. candidate.tcptype = elems[i + 1];
  13788. break;
  13789. default: // TODO
  13790. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13791. }
  13792. }
  13793. candidate.network = '1';
  13794. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13795. return candidate;
  13796. },
  13797. candidateFromJingle: function (cand) {
  13798. var line = 'a=candidate:';
  13799. line += cand.getAttribute('foundation');
  13800. line += ' ';
  13801. line += cand.getAttribute('component');
  13802. line += ' ';
  13803. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13804. line += ' ';
  13805. line += cand.getAttribute('priority');
  13806. line += ' ';
  13807. line += cand.getAttribute('ip');
  13808. line += ' ';
  13809. line += cand.getAttribute('port');
  13810. line += ' ';
  13811. line += 'typ';
  13812. line += ' ' + cand.getAttribute('type');
  13813. line += ' ';
  13814. switch (cand.getAttribute('type')) {
  13815. case 'srflx':
  13816. case 'prflx':
  13817. case 'relay':
  13818. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13819. line += 'raddr';
  13820. line += ' ';
  13821. line += cand.getAttribute('rel-addr');
  13822. line += ' ';
  13823. line += 'rport';
  13824. line += ' ';
  13825. line += cand.getAttribute('rel-port');
  13826. line += ' ';
  13827. }
  13828. break;
  13829. }
  13830. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13831. line += 'tcptype';
  13832. line += ' ';
  13833. line += cand.getAttribute('tcptype');
  13834. line += ' ';
  13835. }
  13836. line += 'generation';
  13837. line += ' ';
  13838. line += cand.getAttribute('generation') || '0';
  13839. return line + '\r\n';
  13840. }
  13841. };
  13842. module.exports = SDPUtil;
  13843. },{}],57:[function(require,module,exports){
  13844. var RTC = require('../RTC/RTC');
  13845. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  13846. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13847. var VideoSSRCHack = require("./VideoSSRCHack");
  13848. function TraceablePeerConnection(ice_config, constraints, session) {
  13849. var self = this;
  13850. var RTCPeerConnectionType = null;
  13851. if (RTCBrowserType.isFirefox()) {
  13852. RTCPeerConnectionType = mozRTCPeerConnection;
  13853. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  13854. RTCPeerConnectionType = RTCPeerConnection;
  13855. } else {
  13856. RTCPeerConnectionType = webkitRTCPeerConnection;
  13857. }
  13858. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  13859. this.updateLog = [];
  13860. this.stats = {};
  13861. this.statsinterval = null;
  13862. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13863. var Interop = require('sdp-interop').Interop;
  13864. this.interop = new Interop();
  13865. var Simulcast = require('sdp-simulcast');
  13866. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  13867. // override as desired
  13868. this.trace = function (what, info) {
  13869. /*console.warn('WTRACE', what, info);
  13870. if (info && RTCBrowserType.isIExplorer()) {
  13871. if (info.length > 1024) {
  13872. console.warn('WTRACE', what, info.substr(1024));
  13873. }
  13874. if (info.length > 2048) {
  13875. console.warn('WTRACE', what, info.substr(2048));
  13876. }
  13877. }*/
  13878. self.updateLog.push({
  13879. time: new Date(),
  13880. type: what,
  13881. value: info || ""
  13882. });
  13883. };
  13884. this.onicecandidate = null;
  13885. this.peerconnection.onicecandidate = function (event) {
  13886. // FIXME: this causes stack overflow with Temasys Plugin
  13887. if (!RTCBrowserType.isTemasysPluginUsed())
  13888. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13889. if (self.onicecandidate !== null) {
  13890. self.onicecandidate(event);
  13891. }
  13892. };
  13893. this.onaddstream = null;
  13894. this.peerconnection.onaddstream = function (event) {
  13895. self.trace('onaddstream', event.stream.id);
  13896. if (self.onaddstream !== null) {
  13897. self.onaddstream(event);
  13898. }
  13899. };
  13900. this.onremovestream = null;
  13901. this.peerconnection.onremovestream = function (event) {
  13902. self.trace('onremovestream', event.stream.id);
  13903. if (self.onremovestream !== null) {
  13904. self.onremovestream(event);
  13905. }
  13906. };
  13907. this.onsignalingstatechange = null;
  13908. this.peerconnection.onsignalingstatechange = function (event) {
  13909. self.trace('onsignalingstatechange', self.signalingState);
  13910. if (self.onsignalingstatechange !== null) {
  13911. self.onsignalingstatechange(event);
  13912. }
  13913. };
  13914. this.oniceconnectionstatechange = null;
  13915. this.peerconnection.oniceconnectionstatechange = function (event) {
  13916. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13917. if (self.oniceconnectionstatechange !== null) {
  13918. self.oniceconnectionstatechange(event);
  13919. }
  13920. };
  13921. this.onnegotiationneeded = null;
  13922. this.peerconnection.onnegotiationneeded = function (event) {
  13923. self.trace('onnegotiationneeded');
  13924. if (self.onnegotiationneeded !== null) {
  13925. self.onnegotiationneeded(event);
  13926. }
  13927. };
  13928. self.ondatachannel = null;
  13929. this.peerconnection.ondatachannel = function (event) {
  13930. self.trace('ondatachannel', event);
  13931. if (self.ondatachannel !== null) {
  13932. self.ondatachannel(event);
  13933. }
  13934. };
  13935. // XXX: do all non-firefox browsers which we support also support this?
  13936. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  13937. this.statsinterval = window.setInterval(function() {
  13938. self.peerconnection.getStats(function(stats) {
  13939. var results = stats.result();
  13940. var now = new Date();
  13941. for (var i = 0; i < results.length; ++i) {
  13942. results[i].names().forEach(function (name) {
  13943. var id = results[i].id + '-' + name;
  13944. if (!self.stats[id]) {
  13945. self.stats[id] = {
  13946. startTime: now,
  13947. endTime: now,
  13948. values: [],
  13949. times: []
  13950. };
  13951. }
  13952. self.stats[id].values.push(results[i].stat(name));
  13953. self.stats[id].times.push(now.getTime());
  13954. if (self.stats[id].values.length > self.maxstats) {
  13955. self.stats[id].values.shift();
  13956. self.stats[id].times.shift();
  13957. }
  13958. self.stats[id].endTime = now;
  13959. });
  13960. }
  13961. });
  13962. }, 1000);
  13963. }
  13964. }
  13965. /**
  13966. * Returns a string representation of a SessionDescription object.
  13967. */
  13968. var dumpSDP = function(description) {
  13969. if (typeof description === 'undefined' || description == null) {
  13970. return '';
  13971. }
  13972. return 'type: ' + description.type + '\r\n' + description.sdp;
  13973. };
  13974. /**
  13975. * Takes a SessionDescription object and returns a "normalized" version.
  13976. * Currently it only takes care of ordering the a=ssrc lines.
  13977. */
  13978. var normalizePlanB = function(desc) {
  13979. if (typeof desc !== 'object' || desc === null ||
  13980. typeof desc.sdp !== 'string') {
  13981. console.warn('An empty description was passed as an argument.');
  13982. return desc;
  13983. }
  13984. var transform = require('sdp-transform');
  13985. var session = transform.parse(desc.sdp);
  13986. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  13987. Array.isArray(session.media)) {
  13988. session.media.forEach(function (mLine) {
  13989. // Chrome appears to be picky about the order in which a=ssrc lines
  13990. // are listed in an m-line when rtx is enabled (and thus there are
  13991. // a=ssrc-group lines with FID semantics). Specifically if we have
  13992. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  13993. // the "a=ssrc:S1" lines, SRD fails.
  13994. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  13995. // first.
  13996. var firstSsrcs = [];
  13997. var newSsrcLines = [];
  13998. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  13999. mLine.ssrcGroups.forEach(function (group) {
  14000. if (typeof group.semantics !== 'undefined' &&
  14001. group.semantics === 'FID') {
  14002. if (typeof group.ssrcs !== 'undefined') {
  14003. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14004. }
  14005. }
  14006. });
  14007. }
  14008. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14009. for (var i = 0; i<mLine.ssrcs.length; i++){
  14010. if (typeof mLine.ssrcs[i] === 'object'
  14011. && typeof mLine.ssrcs[i].id !== 'undefined'
  14012. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14013. newSsrcLines.push(mLine.ssrcs[i]);
  14014. delete mLine.ssrcs[i];
  14015. }
  14016. }
  14017. for (var i = 0; i<mLine.ssrcs.length; i++){
  14018. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14019. newSsrcLines.push(mLine.ssrcs[i]);
  14020. }
  14021. }
  14022. mLine.ssrcs = newSsrcLines;
  14023. }
  14024. });
  14025. }
  14026. var resStr = transform.write(session);
  14027. return new RTCSessionDescription({
  14028. type: desc.type,
  14029. sdp: resStr
  14030. });
  14031. };
  14032. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14033. TraceablePeerConnection.prototype.__defineGetter__(
  14034. 'signalingState',
  14035. function() { return this.peerconnection.signalingState; });
  14036. TraceablePeerConnection.prototype.__defineGetter__(
  14037. 'iceConnectionState',
  14038. function() { return this.peerconnection.iceConnectionState; });
  14039. TraceablePeerConnection.prototype.__defineGetter__(
  14040. 'localDescription',
  14041. function() {
  14042. var desc = this.peerconnection.localDescription;
  14043. desc = VideoSSRCHack.mungeLocalVideoSSRC(desc);
  14044. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14045. // if we're running on FF, transform to Plan B first.
  14046. if (RTCBrowserType.usesUnifiedPlan()) {
  14047. desc = this.interop.toPlanB(desc);
  14048. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14049. }
  14050. return desc;
  14051. });
  14052. TraceablePeerConnection.prototype.__defineGetter__(
  14053. 'remoteDescription',
  14054. function() {
  14055. var desc = this.peerconnection.remoteDescription;
  14056. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14057. // if we're running on FF, transform to Plan B first.
  14058. if (RTCBrowserType.usesUnifiedPlan()) {
  14059. desc = this.interop.toPlanB(desc);
  14060. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14061. }
  14062. return desc;
  14063. });
  14064. }
  14065. TraceablePeerConnection.prototype.addStream = function (stream) {
  14066. this.trace('addStream', stream.id);
  14067. try
  14068. {
  14069. this.peerconnection.addStream(stream);
  14070. }
  14071. catch (e)
  14072. {
  14073. console.error(e);
  14074. }
  14075. };
  14076. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14077. this.trace('removeStream', stream.id);
  14078. if(stopStreams) {
  14079. stream.getAudioTracks().forEach(function (track) {
  14080. // stop() not supported with IE
  14081. if (track.stop) {
  14082. track.stop();
  14083. }
  14084. });
  14085. stream.getVideoTracks().forEach(function (track) {
  14086. // stop() not supported with IE
  14087. if (track.stop) {
  14088. track.stop();
  14089. }
  14090. });
  14091. if (stream.stop) {
  14092. stream.stop();
  14093. }
  14094. }
  14095. try {
  14096. // FF doesn't support this yet.
  14097. if (this.peerconnection.removeStream)
  14098. this.peerconnection.removeStream(stream);
  14099. } catch (e) {
  14100. console.error(e);
  14101. }
  14102. };
  14103. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14104. this.trace('createDataChannel', label, opts);
  14105. return this.peerconnection.createDataChannel(label, opts);
  14106. };
  14107. TraceablePeerConnection.prototype.setLocalDescription
  14108. = function (description, successCallback, failureCallback) {
  14109. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14110. // if we're running on FF, transform to Plan A first.
  14111. if (RTCBrowserType.usesUnifiedPlan()) {
  14112. description = this.interop.toUnifiedPlan(description);
  14113. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14114. }
  14115. var self = this;
  14116. this.peerconnection.setLocalDescription(description,
  14117. function () {
  14118. self.trace('setLocalDescriptionOnSuccess');
  14119. successCallback();
  14120. },
  14121. function (err) {
  14122. self.trace('setLocalDescriptionOnFailure', err);
  14123. failureCallback(err);
  14124. }
  14125. );
  14126. /*
  14127. if (this.statsinterval === null && this.maxstats > 0) {
  14128. // start gathering stats
  14129. }
  14130. */
  14131. };
  14132. TraceablePeerConnection.prototype.setRemoteDescription
  14133. = function (description, successCallback, failureCallback) {
  14134. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14135. // TODO the focus should squeze or explode the remote simulcast
  14136. description = this.simulcast.mungeRemoteDescription(description);
  14137. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14138. // if we're running on FF, transform to Plan A first.
  14139. if (RTCBrowserType.usesUnifiedPlan()) {
  14140. description = this.interop.toUnifiedPlan(description);
  14141. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14142. }
  14143. if (RTCBrowserType.usesPlanB()) {
  14144. description = normalizePlanB(description);
  14145. }
  14146. var self = this;
  14147. this.peerconnection.setRemoteDescription(description,
  14148. function () {
  14149. self.trace('setRemoteDescriptionOnSuccess');
  14150. successCallback();
  14151. },
  14152. function (err) {
  14153. self.trace('setRemoteDescriptionOnFailure', err);
  14154. failureCallback(err);
  14155. }
  14156. );
  14157. /*
  14158. if (this.statsinterval === null && this.maxstats > 0) {
  14159. // start gathering stats
  14160. }
  14161. */
  14162. };
  14163. TraceablePeerConnection.prototype.close = function () {
  14164. this.trace('stop');
  14165. if (this.statsinterval !== null) {
  14166. window.clearInterval(this.statsinterval);
  14167. this.statsinterval = null;
  14168. }
  14169. this.peerconnection.close();
  14170. };
  14171. TraceablePeerConnection.prototype.createOffer
  14172. = function (successCallback, failureCallback, constraints) {
  14173. var self = this;
  14174. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14175. this.peerconnection.createOffer(
  14176. function (offer) {
  14177. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14178. // NOTE this is not tested because in meet the focus generates the
  14179. // offer.
  14180. // if we're running on FF, transform to Plan B first.
  14181. if (RTCBrowserType.usesUnifiedPlan()) {
  14182. offer = self.interop.toPlanB(offer);
  14183. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14184. }
  14185. offer = VideoSSRCHack.mungeLocalVideoSSRC(offer);
  14186. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14187. offer = self.simulcast.mungeLocalDescription(offer);
  14188. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14189. }
  14190. successCallback(offer);
  14191. },
  14192. function(err) {
  14193. self.trace('createOfferOnFailure', err);
  14194. failureCallback(err);
  14195. },
  14196. constraints
  14197. );
  14198. };
  14199. TraceablePeerConnection.prototype.createAnswer
  14200. = function (successCallback, failureCallback, constraints) {
  14201. var self = this;
  14202. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14203. this.peerconnection.createAnswer(
  14204. function (answer) {
  14205. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14206. // if we're running on FF, transform to Plan A first.
  14207. if (RTCBrowserType.usesUnifiedPlan()) {
  14208. answer = self.interop.toPlanB(answer);
  14209. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14210. }
  14211. // munge local video SSRC
  14212. answer = VideoSSRCHack.mungeLocalVideoSSRC(answer);
  14213. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14214. answer = self.simulcast.mungeLocalDescription(answer);
  14215. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14216. }
  14217. successCallback(answer);
  14218. },
  14219. function(err) {
  14220. self.trace('createAnswerOnFailure', err);
  14221. failureCallback(err);
  14222. },
  14223. constraints
  14224. );
  14225. };
  14226. TraceablePeerConnection.prototype.addIceCandidate
  14227. = function (candidate, successCallback, failureCallback) {
  14228. //var self = this;
  14229. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14230. this.peerconnection.addIceCandidate(candidate);
  14231. /* maybe later
  14232. this.peerconnection.addIceCandidate(candidate,
  14233. function () {
  14234. self.trace('addIceCandidateOnSuccess');
  14235. successCallback();
  14236. },
  14237. function (err) {
  14238. self.trace('addIceCandidateOnFailure', err);
  14239. failureCallback(err);
  14240. }
  14241. );
  14242. */
  14243. };
  14244. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14245. // TODO: Is this the correct way to handle Opera, Temasys?
  14246. if (RTCBrowserType.isFirefox()) {
  14247. // ignore for now...
  14248. if(!errback)
  14249. errback = function () {};
  14250. this.peerconnection.getStats(null, callback, errback);
  14251. } else {
  14252. this.peerconnection.getStats(callback);
  14253. }
  14254. };
  14255. module.exports = TraceablePeerConnection;
  14256. },{"../../service/xmpp/XMPPEvents":117,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"./VideoSSRCHack":58,"sdp-interop":90,"sdp-simulcast":97,"sdp-transform":104}],58:[function(require,module,exports){
  14257. /* global $ */
  14258. /*
  14259. The purpose of this hack is to re-use SSRC of first video stream ever created
  14260. for any video streams created later on. In order to do that this hack:
  14261. 1. Stores the SSRC of the first video stream created by
  14262. a) scanning Jingle session-accept/session-invite for existing video SSRC
  14263. b) watching for 'source-add' for new video stream if it has not been
  14264. created in step a)
  14265. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  14266. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  14267. returned to the other parts of the application.
  14268. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  14269. blocks those notifications. This makes Jicofo and all participants think
  14270. that it exists all the time even if the video stream has been removed or
  14271. replaced locally. Thanks to that there is no additional signaling activity
  14272. on video mute or when switching to the desktop stream.
  14273. */
  14274. var SDP = require('./SDP');
  14275. /**
  14276. * Stored SSRC of local video stream.
  14277. */
  14278. var localVideoSSRC;
  14279. /**
  14280. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  14281. * from given Jingle IQ.
  14282. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  14283. * @param actionName display name of the action which will be printed in log
  14284. * messages.
  14285. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  14286. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  14287. * other SSRCs left to be signaled after removing it.
  14288. */
  14289. var filterOutSource = function (modifyIq, actionName) {
  14290. if (!localVideoSSRC)
  14291. return modifyIq;
  14292. var modifyIqTree = $(modifyIq.tree());
  14293. var videoSSRC = modifyIqTree.find(
  14294. '>jingle>content[name="video"]' +
  14295. '>description>source[ssrc="' + localVideoSSRC + '"]');
  14296. if (!videoSSRC.length) {
  14297. return modifyIqTree;
  14298. }
  14299. console.info(
  14300. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  14301. videoSSRC.remove();
  14302. // Check if any sources still left to be added/removed
  14303. if (modifyIqTree.find('>jingle>content>description>source').length) {
  14304. return modifyIqTree;
  14305. } else {
  14306. return null;
  14307. }
  14308. };
  14309. /**
  14310. * Scans given Jingle IQ for video SSRC and stores it.
  14311. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  14312. */
  14313. var storeLocalVideoSSRC = function (jingleIq) {
  14314. var videoSSRCs =
  14315. $(jingleIq.tree())
  14316. .find('>jingle>content[name="video"]>description>source');
  14317. console.info('Video desc: ', videoSSRCs);
  14318. if (!videoSSRCs.length)
  14319. return;
  14320. var ssrc = videoSSRCs.attr('ssrc');
  14321. if (ssrc) {
  14322. localVideoSSRC = ssrc;
  14323. console.info(
  14324. 'Stored local video SSRC for future re-use: ' + localVideoSSRC);
  14325. } else {
  14326. console.error('No "ssrc" attribute present in <source> element');
  14327. }
  14328. };
  14329. var LocalVideoSSRCHack = {
  14330. /**
  14331. * Method must be called before 'session-initiate' or 'session-invite' is
  14332. * sent. Scans the IQ for local video SSRC and stores it if detected.
  14333. *
  14334. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  14335. * which will be scanned for local video SSRC.
  14336. */
  14337. processSessionInit: function (sessionInit) {
  14338. if (localVideoSSRC) {
  14339. console.error("Local SSRC stored already: " + localVideoSSRC);
  14340. return;
  14341. }
  14342. storeLocalVideoSSRC(sessionInit);
  14343. },
  14344. /**
  14345. * If we have local video SSRC stored searched given
  14346. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  14347. * with the stored one.
  14348. * @param localDescription local description object that will have local
  14349. * video SSRC replaced with the stored one
  14350. * @returns modified <tt>localDescription</tt> object.
  14351. */
  14352. mungeLocalVideoSSRC: function (localDescription) {
  14353. // IF we have local video SSRC stored make sure it is replaced
  14354. // with old SSRC
  14355. if (localVideoSSRC) {
  14356. var newSdp = new SDP(localDescription.sdp);
  14357. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  14358. !newSdp.containsSSRC(localVideoSSRC)) {
  14359. // Get new video SSRC
  14360. var map = newSdp.getMediaSsrcMap();
  14361. var videoPart = map[1];
  14362. var videoSSRCs = videoPart.ssrcs;
  14363. var newSSRC = Object.keys(videoSSRCs)[0];
  14364. console.info(
  14365. "Replacing new video SSRC: " + newSSRC +
  14366. " with " + localVideoSSRC);
  14367. localDescription.sdp =
  14368. newSdp.raw.replace(
  14369. new RegExp('a=ssrc:' + newSSRC, 'g'),
  14370. 'a=ssrc:' + localVideoSSRC);
  14371. }
  14372. }
  14373. return localDescription;
  14374. },
  14375. /**
  14376. * Method must be called before 'source-add' notification is sent. In case
  14377. * we have local video SSRC advertised already it will be removed from the
  14378. * notification. If no other SSRCs are described by given IQ null will be
  14379. * returned which means that there is no point in sending the notification.
  14380. * @param sourceAdd 'source-add' Jingle IQ to be processed
  14381. * @returns modified 'source-add' IQ which can be sent to the focus or
  14382. * <tt>null</tt> if no notification shall be sent. It is no longer
  14383. * a Strophe IQ Builder instance, but DOM element tree.
  14384. */
  14385. processSourceAdd: function (sourceAdd) {
  14386. if (!localVideoSSRC) {
  14387. // Store local SSRC if available
  14388. storeLocalVideoSSRC(sourceAdd);
  14389. return sourceAdd;
  14390. } else {
  14391. return filterOutSource(sourceAdd, 'source-add');
  14392. }
  14393. },
  14394. /**
  14395. * Method must be called before 'source-remove' notification is sent.
  14396. * Removes local video SSRC from the notification. If there are no other
  14397. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  14398. * means that there is no point in sending the notification.
  14399. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  14400. * @returns modified 'source-remove' IQ which can be sent to the focus or
  14401. * <tt>null</tt> if no notification shall be sent. It is no longer
  14402. * a Strophe IQ Builder instance, but DOM element tree.
  14403. */
  14404. processSourceRemove: function (sourceRemove) {
  14405. return filterOutSource(sourceRemove, 'source-remove');
  14406. }
  14407. };
  14408. module.exports = LocalVideoSSRCHack;
  14409. },{"./SDP":54}],59:[function(require,module,exports){
  14410. /* global $, $iq, APP, config, messageHandler,
  14411. roomName, sessionTerminated, Strophe, Util */
  14412. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14413. var Settings = require("../settings/Settings");
  14414. var AuthenticationEvents
  14415. = require("../../service/authentication/AuthenticationEvents");
  14416. /**
  14417. * Contains logic responsible for enabling/disabling functionality available
  14418. * only to moderator users.
  14419. */
  14420. var connection = null;
  14421. var focusUserJid;
  14422. function createExpBackoffTimer(step) {
  14423. var count = 1;
  14424. return function (reset) {
  14425. // Reset call
  14426. if (reset) {
  14427. count = 1;
  14428. return;
  14429. }
  14430. // Calculate next timeout
  14431. var timeout = Math.pow(2, count - 1);
  14432. count += 1;
  14433. return timeout * step;
  14434. };
  14435. }
  14436. var getNextTimeout = createExpBackoffTimer(1000);
  14437. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14438. // External authentication stuff
  14439. var externalAuthEnabled = false;
  14440. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14441. // it will be enabled automatically if focus detects the component through
  14442. // service discovery.
  14443. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14444. var eventEmitter = null;
  14445. var Moderator = {
  14446. isModerator: function () {
  14447. return connection && connection.emuc.isModerator();
  14448. },
  14449. isPeerModerator: function (peerJid) {
  14450. return connection &&
  14451. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14452. },
  14453. isExternalAuthEnabled: function () {
  14454. return externalAuthEnabled;
  14455. },
  14456. isSipGatewayEnabled: function () {
  14457. return sipGatewayEnabled;
  14458. },
  14459. setConnection: function (con) {
  14460. connection = con;
  14461. },
  14462. init: function (xmpp, emitter) {
  14463. this.xmppService = xmpp;
  14464. eventEmitter = emitter;
  14465. // Message listener that talks to POPUP window
  14466. function listener(event) {
  14467. if (event.data && event.data.sessionId) {
  14468. if (event.origin !== window.location.origin) {
  14469. console.warn("Ignoring sessionId from different origin: " +
  14470. event.origin);
  14471. return;
  14472. }
  14473. localStorage.setItem('sessionId', event.data.sessionId);
  14474. // After popup is closed we will authenticate
  14475. }
  14476. }
  14477. // Register
  14478. if (window.addEventListener) {
  14479. window.addEventListener("message", listener, false);
  14480. } else {
  14481. window.attachEvent("onmessage", listener);
  14482. }
  14483. },
  14484. onMucMemberLeft: function (jid) {
  14485. console.info("Someone left is it focus ? " + jid);
  14486. var resource = Strophe.getResourceFromJid(jid);
  14487. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14488. console.info(
  14489. "Focus has left the room - leaving conference");
  14490. //hangUp();
  14491. // We'd rather reload to have everything re-initialized
  14492. // FIXME: show some message before reload
  14493. location.reload();
  14494. }
  14495. },
  14496. setFocusUserJid: function (focusJid) {
  14497. if (!focusUserJid) {
  14498. focusUserJid = focusJid;
  14499. console.info("Focus jid set to: " + focusUserJid);
  14500. }
  14501. },
  14502. getFocusUserJid: function () {
  14503. return focusUserJid;
  14504. },
  14505. getFocusComponent: function () {
  14506. // Get focus component address
  14507. var focusComponent = config.hosts.focus;
  14508. // If not specified use default: 'focus.domain'
  14509. if (!focusComponent) {
  14510. focusComponent = 'focus.' + config.hosts.domain;
  14511. }
  14512. return focusComponent;
  14513. },
  14514. createConferenceIq: function (roomName) {
  14515. // Generate create conference IQ
  14516. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14517. // Session Id used for authentication
  14518. var sessionId = localStorage.getItem('sessionId');
  14519. var machineUID = Settings.getSettings().uid;
  14520. console.info(
  14521. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14522. elem.c('conference', {
  14523. xmlns: 'http://jitsi.org/protocol/focus',
  14524. room: roomName,
  14525. 'machine-uid': machineUID
  14526. });
  14527. if (sessionId) {
  14528. elem.attrs({ 'session-id': sessionId});
  14529. }
  14530. if (config.hosts.bridge !== undefined) {
  14531. elem.c(
  14532. 'property',
  14533. { name: 'bridge', value: config.hosts.bridge})
  14534. .up();
  14535. }
  14536. // Tell the focus we have Jigasi configured
  14537. if (config.hosts.call_control !== undefined) {
  14538. elem.c(
  14539. 'property',
  14540. { name: 'call_control', value: config.hosts.call_control})
  14541. .up();
  14542. }
  14543. if (config.channelLastN !== undefined) {
  14544. elem.c(
  14545. 'property',
  14546. { name: 'channelLastN', value: config.channelLastN})
  14547. .up();
  14548. }
  14549. if (config.adaptiveLastN !== undefined) {
  14550. elem.c(
  14551. 'property',
  14552. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14553. .up();
  14554. }
  14555. if (config.adaptiveSimulcast !== undefined) {
  14556. elem.c(
  14557. 'property',
  14558. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14559. .up();
  14560. }
  14561. if (config.openSctp !== undefined) {
  14562. elem.c(
  14563. 'property',
  14564. { name: 'openSctp', value: config.openSctp})
  14565. .up();
  14566. }
  14567. if(config.startAudioMuted !== undefined)
  14568. {
  14569. elem.c(
  14570. 'property',
  14571. { name: 'startAudioMuted', value: config.startAudioMuted})
  14572. .up();
  14573. }
  14574. if(config.startVideoMuted !== undefined)
  14575. {
  14576. elem.c(
  14577. 'property',
  14578. { name: 'startVideoMuted', value: config.startVideoMuted})
  14579. .up();
  14580. }
  14581. elem.c(
  14582. 'property',
  14583. { name: 'simulcastMode', value: 'rewriting'})
  14584. .up();
  14585. elem.up();
  14586. return elem;
  14587. },
  14588. parseSessionId: function (resultIq) {
  14589. var sessionId = $(resultIq).find('conference').attr('session-id');
  14590. if (sessionId) {
  14591. console.info('Received sessionId: ' + sessionId);
  14592. localStorage.setItem('sessionId', sessionId);
  14593. }
  14594. },
  14595. parseConfigOptions: function (resultIq) {
  14596. Moderator.setFocusUserJid(
  14597. $(resultIq).find('conference').attr('focusjid'));
  14598. var authenticationEnabled
  14599. = $(resultIq).find(
  14600. '>conference>property' +
  14601. '[name=\'authentication\'][value=\'true\']').length > 0;
  14602. console.info("Authentication enabled: " + authenticationEnabled);
  14603. externalAuthEnabled = $(resultIq).find(
  14604. '>conference>property' +
  14605. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14606. console.info('External authentication enabled: ' + externalAuthEnabled);
  14607. if (!externalAuthEnabled) {
  14608. // We expect to receive sessionId in 'internal' authentication mode
  14609. Moderator.parseSessionId(resultIq);
  14610. }
  14611. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14612. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14613. authenticationEnabled, authIdentity);
  14614. // Check if focus has auto-detected Jigasi component(this will be also
  14615. // included if we have passed our host from the config)
  14616. if ($(resultIq).find(
  14617. '>conference>property' +
  14618. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14619. sipGatewayEnabled = true;
  14620. }
  14621. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14622. },
  14623. // FIXME: we need to show the fact that we're waiting for the focus
  14624. // to the user(or that focus is not available)
  14625. allocateConferenceFocus: function (roomName, callback) {
  14626. // Try to use focus user JID from the config
  14627. Moderator.setFocusUserJid(config.focusUserJid);
  14628. // Send create conference IQ
  14629. var iq = Moderator.createConferenceIq(roomName);
  14630. var self = this;
  14631. connection.sendIQ(
  14632. iq,
  14633. function (result) {
  14634. // Setup config options
  14635. Moderator.parseConfigOptions(result);
  14636. if ('true' === $(result).find('conference').attr('ready')) {
  14637. // Reset both timers
  14638. getNextTimeout(true);
  14639. getNextErrorTimeout(true);
  14640. // Exec callback
  14641. callback();
  14642. } else {
  14643. var waitMs = getNextTimeout();
  14644. console.info("Waiting for the focus... " + waitMs);
  14645. // Reset error timeout
  14646. getNextErrorTimeout(true);
  14647. window.setTimeout(
  14648. function () {
  14649. Moderator.allocateConferenceFocus(
  14650. roomName, callback);
  14651. }, waitMs);
  14652. }
  14653. },
  14654. function (error) {
  14655. // Invalid session ? remove and try again
  14656. // without session ID to get a new one
  14657. var invalidSession
  14658. = $(error).find('>error>session-invalid').length;
  14659. if (invalidSession) {
  14660. console.info("Session expired! - removing");
  14661. localStorage.removeItem("sessionId");
  14662. }
  14663. if ($(error).find('>error>graceful-shutdown').length) {
  14664. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14665. return;
  14666. }
  14667. // Check for error returned by the reservation system
  14668. var reservationErr = $(error).find('>error>reservation-error');
  14669. if (reservationErr.length) {
  14670. // Trigger error event
  14671. var errorCode = reservationErr.attr('error-code');
  14672. var errorMsg;
  14673. if ($(error).find('>error>text')) {
  14674. errorMsg = $(error).find('>error>text').text();
  14675. }
  14676. eventEmitter.emit(
  14677. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14678. return;
  14679. }
  14680. // Not authorized to create new room
  14681. if ($(error).find('>error>not-authorized').length) {
  14682. console.warn("Unauthorized to start the conference", error);
  14683. var toDomain
  14684. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14685. if (toDomain !== config.hosts.anonymousdomain) {
  14686. // FIXME: "is external" should come either from
  14687. // the focus or config.js
  14688. externalAuthEnabled = true;
  14689. }
  14690. eventEmitter.emit(
  14691. XMPPEvents.AUTHENTICATION_REQUIRED,
  14692. function () {
  14693. Moderator.allocateConferenceFocus(
  14694. roomName, callback);
  14695. });
  14696. return;
  14697. }
  14698. var waitMs = getNextErrorTimeout();
  14699. console.error("Focus error, retry after " + waitMs, error);
  14700. // Show message
  14701. var focusComponent = Moderator.getFocusComponent();
  14702. var retrySec = waitMs / 1000;
  14703. // FIXME: message is duplicated ?
  14704. // Do not show in case of session invalid
  14705. // which means just a retry
  14706. if (!invalidSession) {
  14707. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  14708. focusComponent, retrySec);
  14709. }
  14710. // Reset response timeout
  14711. getNextTimeout(true);
  14712. window.setTimeout(
  14713. function () {
  14714. Moderator.allocateConferenceFocus(roomName, callback);
  14715. }, waitMs);
  14716. }
  14717. );
  14718. },
  14719. getLoginUrl: function (roomName, urlCallback) {
  14720. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14721. iq.c('login-url', {
  14722. xmlns: 'http://jitsi.org/protocol/focus',
  14723. room: roomName,
  14724. 'machine-uid': Settings.getSettings().uid
  14725. });
  14726. connection.sendIQ(
  14727. iq,
  14728. function (result) {
  14729. var url = $(result).find('login-url').attr('url');
  14730. url = url = decodeURIComponent(url);
  14731. if (url) {
  14732. console.info("Got auth url: " + url);
  14733. urlCallback(url);
  14734. } else {
  14735. console.error(
  14736. "Failed to get auth url from the focus", result);
  14737. }
  14738. },
  14739. function (error) {
  14740. console.error("Get auth url error", error);
  14741. }
  14742. );
  14743. },
  14744. getPopupLoginUrl: function (roomName, urlCallback) {
  14745. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14746. iq.c('login-url', {
  14747. xmlns: 'http://jitsi.org/protocol/focus',
  14748. room: roomName,
  14749. 'machine-uid': Settings.getSettings().uid,
  14750. popup: true
  14751. });
  14752. connection.sendIQ(
  14753. iq,
  14754. function (result) {
  14755. var url = $(result).find('login-url').attr('url');
  14756. url = url = decodeURIComponent(url);
  14757. if (url) {
  14758. console.info("Got POPUP auth url: " + url);
  14759. urlCallback(url);
  14760. } else {
  14761. console.error(
  14762. "Failed to get POPUP auth url from the focus", result);
  14763. }
  14764. },
  14765. function (error) {
  14766. console.error('Get POPUP auth url error', error);
  14767. }
  14768. );
  14769. },
  14770. logout: function (callback) {
  14771. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14772. var sessionId = localStorage.getItem('sessionId');
  14773. if (!sessionId) {
  14774. callback();
  14775. return;
  14776. }
  14777. iq.c('logout', {
  14778. xmlns: 'http://jitsi.org/protocol/focus',
  14779. 'session-id': sessionId
  14780. });
  14781. connection.sendIQ(
  14782. iq,
  14783. function (result) {
  14784. var logoutUrl = $(result).find('logout').attr('logout-url');
  14785. if (logoutUrl) {
  14786. logoutUrl = decodeURIComponent(logoutUrl);
  14787. }
  14788. console.info("Log out OK, url: " + logoutUrl, result);
  14789. localStorage.removeItem('sessionId');
  14790. callback(logoutUrl);
  14791. },
  14792. function (error) {
  14793. console.error("Logout error", error);
  14794. }
  14795. );
  14796. }
  14797. };
  14798. module.exports = Moderator;
  14799. },{"../../service/authentication/AuthenticationEvents":112,"../../service/xmpp/XMPPEvents":117,"../settings/Settings":47}],60:[function(require,module,exports){
  14800. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  14801. Toolbar, Util */
  14802. var Moderator = require("./moderator");
  14803. var recordingToken = null;
  14804. var recordingEnabled;
  14805. /**
  14806. * Whether to use a jirecon component for recording, or use the videobridge
  14807. * through COLIBRI.
  14808. */
  14809. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14810. /**
  14811. * The ID of the jirecon recording session. Jirecon generates it when we
  14812. * initially start recording, and it needs to be used in subsequent requests
  14813. * to jirecon.
  14814. */
  14815. var jireconRid = null;
  14816. /**
  14817. * The callback to update the recording button. Currently used from colibri
  14818. * after receiving a pending status.
  14819. */
  14820. var recordingStateChangeCallback = null;
  14821. function setRecordingToken(token) {
  14822. recordingToken = token;
  14823. }
  14824. function setRecordingJirecon(state, token, callback, connection) {
  14825. if (state == recordingEnabled){
  14826. return;
  14827. }
  14828. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14829. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14830. action: (state === 'on') ? 'start' : 'stop',
  14831. mucjid: connection.emuc.roomjid});
  14832. if (state === 'off'){
  14833. iq.attrs({rid: jireconRid});
  14834. }
  14835. console.log('Start recording');
  14836. connection.sendIQ(
  14837. iq,
  14838. function (result) {
  14839. // TODO wait for an IQ with the real status, since this is
  14840. // provisional?
  14841. jireconRid = $(result).find('recording').attr('rid');
  14842. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  14843. '(jirecon)' + result);
  14844. recordingEnabled = state;
  14845. if (state === 'off'){
  14846. jireconRid = null;
  14847. }
  14848. callback(state);
  14849. },
  14850. function (error) {
  14851. console.log('Failed to start recording, error: ', error);
  14852. callback(recordingEnabled);
  14853. });
  14854. }
  14855. // Sends a COLIBRI message which enables or disables (according to 'state')
  14856. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14857. // with the new recording state, according to the IQ.
  14858. function setRecordingColibri(state, token, callback, connection) {
  14859. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14860. elem.c('conference', {
  14861. xmlns: 'http://jitsi.org/protocol/colibri'
  14862. });
  14863. elem.c('recording', {state: state, token: token});
  14864. connection.sendIQ(elem,
  14865. function (result) {
  14866. console.log('Set recording "', state, '". Result:', result);
  14867. var recordingElem = $(result).find('>conference>recording');
  14868. var newState = recordingElem.attr('state');
  14869. recordingEnabled = newState;
  14870. callback(newState);
  14871. if (newState === 'pending' && recordingStateChangeCallback == null)
  14872. {
  14873. recordingStateChangeCallback = callback;
  14874. connection.addHandler(function(iq){
  14875. var state = $(iq).find('recording').attr('state');
  14876. if (state)
  14877. recordingStateChangeCallback(state);
  14878. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  14879. }
  14880. },
  14881. function (error) {
  14882. console.warn(error);
  14883. callback(recordingEnabled);
  14884. }
  14885. );
  14886. }
  14887. function setRecording(state, token, callback, connection) {
  14888. if (useJirecon){
  14889. setRecordingJirecon(state, token, callback, connection);
  14890. } else {
  14891. setRecordingColibri(state, token, callback, connection);
  14892. }
  14893. }
  14894. var Recording = {
  14895. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  14896. if (!Moderator.isModerator()) {
  14897. console.log(
  14898. 'non-focus, or conference not yet organized:' +
  14899. ' not enabling recording');
  14900. return;
  14901. }
  14902. var self = this;
  14903. // Jirecon does not (currently) support a token.
  14904. if (!recordingToken && !useJirecon) {
  14905. tokenEmptyCallback(function (value) {
  14906. setRecordingToken(value);
  14907. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  14908. });
  14909. return;
  14910. }
  14911. var oldState = recordingEnabled;
  14912. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  14913. setRecording(newState,
  14914. recordingToken,
  14915. function (state) {
  14916. console.log("New recording state: ", state);
  14917. if (state === oldState) {
  14918. // FIXME: new focus:
  14919. // this will not work when moderator changes
  14920. // during active session. Then it will assume that
  14921. // recording status has changed to true, but it might have
  14922. // been already true(and we only received actual status from
  14923. // the focus).
  14924. //
  14925. // SO we start with status null, so that it is initialized
  14926. // here and will fail only after second click, so if invalid
  14927. // token was used we have to press the button twice before
  14928. // current status will be fetched and token will be reset.
  14929. //
  14930. // Reliable way would be to return authentication error.
  14931. // Or status update when moderator connects.
  14932. // Or we have to stop recording session when current
  14933. // moderator leaves the room.
  14934. // Failed to change, reset the token because it might
  14935. // have been wrong
  14936. setRecordingToken(null);
  14937. }
  14938. recordingStateChangeCallback(state);
  14939. },
  14940. connection
  14941. );
  14942. }
  14943. };
  14944. module.exports = Recording;
  14945. },{"./moderator":59}],61:[function(require,module,exports){
  14946. /* jshint -W117 */
  14947. /* a simple MUC connection plugin
  14948. * can only handle a single MUC room
  14949. */
  14950. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14951. var Moderator = require("./moderator");
  14952. module.exports = function(XMPP, eventEmitter) {
  14953. Strophe.addConnectionPlugin('emuc', {
  14954. connection: null,
  14955. roomjid: null,
  14956. myroomjid: null,
  14957. members: {},
  14958. list_members: [], // so we can elect a new focus
  14959. presMap: {},
  14960. preziMap: {},
  14961. joined: false,
  14962. isOwner: false,
  14963. role: null,
  14964. focusMucJid: null,
  14965. bridgeIsDown: false,
  14966. init: function (conn) {
  14967. this.connection = conn;
  14968. },
  14969. initPresenceMap: function (myroomjid) {
  14970. this.presMap['to'] = myroomjid;
  14971. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14972. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  14973. this.addAudioInfoToPresence(true);
  14974. }
  14975. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  14976. this.addVideoInfoToPresence(true);
  14977. }
  14978. },
  14979. doJoin: function (jid, password) {
  14980. this.myroomjid = jid;
  14981. console.info("Joined MUC as " + this.myroomjid);
  14982. this.initPresenceMap(this.myroomjid);
  14983. if (!this.roomjid) {
  14984. this.roomjid = Strophe.getBareJidFromJid(jid);
  14985. // add handlers (just once)
  14986. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14987. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14988. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14989. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14990. }
  14991. if (password !== undefined) {
  14992. this.presMap['password'] = password;
  14993. }
  14994. this.sendPresence();
  14995. },
  14996. doLeave: function () {
  14997. console.log("do leave", this.myroomjid);
  14998. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14999. this.presMap.length = 0;
  15000. this.connection.send(pres);
  15001. },
  15002. createNonAnonymousRoom: function () {
  15003. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15004. var getForm = $iq({type: 'get', to: this.roomjid})
  15005. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15006. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15007. var self = this;
  15008. this.connection.sendIQ(getForm, function (form) {
  15009. if (!$(form).find(
  15010. '>query>x[xmlns="jabber:x:data"]' +
  15011. '>field[var="muc#roomconfig_whois"]').length) {
  15012. console.error('non-anonymous rooms not supported');
  15013. return;
  15014. }
  15015. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15016. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15017. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15018. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15019. .c('value')
  15020. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15021. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15022. .c('value').t('anyone').up().up();
  15023. self.connection.sendIQ(formSubmit);
  15024. }, function (error) {
  15025. console.error("Error getting room configuration form");
  15026. });
  15027. },
  15028. onPresence: function (pres) {
  15029. var from = pres.getAttribute('from');
  15030. // What is this for? A workaround for something?
  15031. if (pres.getAttribute('type')) {
  15032. return true;
  15033. }
  15034. // Parse etherpad tag.
  15035. var etherpad = $(pres).find('>etherpad');
  15036. if (etherpad.length) {
  15037. if (config.etherpad_base) {
  15038. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15039. }
  15040. }
  15041. // Parse prezi tag.
  15042. var presentation = $(pres).find('>prezi');
  15043. if (presentation.length) {
  15044. var url = presentation.attr('url');
  15045. var current = presentation.find('>current').text();
  15046. console.log('presentation info received from', from, url);
  15047. if (this.preziMap[from] == null) {
  15048. this.preziMap[from] = url;
  15049. $(document).trigger('presentationadded.muc', [from, url, current]);
  15050. }
  15051. else {
  15052. $(document).trigger('gotoslide.muc', [from, url, current]);
  15053. }
  15054. }
  15055. else if (this.preziMap[from] != null) {
  15056. var url = this.preziMap[from];
  15057. delete this.preziMap[from];
  15058. $(document).trigger('presentationremoved.muc', [from, url]);
  15059. }
  15060. // Parse audio info tag.
  15061. var audioMuted = $(pres).find('>audiomuted');
  15062. if (audioMuted.length) {
  15063. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  15064. from, (audioMuted.text() === "true"));
  15065. }
  15066. // Parse video info tag.
  15067. var videoMuted = $(pres).find('>videomuted');
  15068. if (videoMuted.length) {
  15069. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  15070. from, (videoMuted.text() === "true"));
  15071. }
  15072. var startMuted = $(pres).find('>startmuted');
  15073. if (startMuted.length)
  15074. {
  15075. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15076. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  15077. }
  15078. var devices = $(pres).find('>devices');
  15079. if(devices.length)
  15080. {
  15081. var audio = devices.find('>audio');
  15082. var video = devices.find('>video');
  15083. var devicesValues = {audio: false, video: false};
  15084. if(audio.length && audio.text() === "true")
  15085. {
  15086. devicesValues.audio = true;
  15087. }
  15088. if(video.length && video.text() === "true")
  15089. {
  15090. devicesValues.video = true;
  15091. }
  15092. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15093. Strophe.getResourceFromJid(from), devicesValues);
  15094. }
  15095. var videoType = $(pres).find('>videoType');
  15096. if (videoType.length)
  15097. {
  15098. if (videoType.text().length)
  15099. {
  15100. eventEmitter.emit(XMPPEvents.VIDEO_TYPE,
  15101. Strophe.getResourceFromJid(from), videoType.text());
  15102. }
  15103. }
  15104. var stats = $(pres).find('>stats');
  15105. if (stats.length) {
  15106. var statsObj = {};
  15107. Strophe.forEachChild(stats[0], "stat", function (el) {
  15108. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15109. });
  15110. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15111. }
  15112. // Parse status.
  15113. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15114. this.isOwner = true;
  15115. this.createNonAnonymousRoom();
  15116. }
  15117. // Parse roles.
  15118. var member = {};
  15119. member.show = $(pres).find('>show').text();
  15120. member.status = $(pres).find('>status').text();
  15121. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15122. member.affiliation = tmp.attr('affiliation');
  15123. member.role = tmp.attr('role');
  15124. // Focus recognition
  15125. member.jid = tmp.attr('jid');
  15126. member.isFocus = false;
  15127. if (member.jid
  15128. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15129. member.isFocus = true;
  15130. }
  15131. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15132. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  15133. if (from == this.myroomjid) {
  15134. if (member.affiliation == 'owner') this.isOwner = true;
  15135. if (this.role !== member.role) {
  15136. this.role = member.role;
  15137. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15138. from, member, pres, Moderator.isModerator());
  15139. }
  15140. if (!this.joined) {
  15141. this.joined = true;
  15142. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15143. this.list_members.push(from);
  15144. }
  15145. } else if (this.members[from] === undefined) {
  15146. // new participant
  15147. this.members[from] = member;
  15148. this.list_members.push(from);
  15149. console.log('entered', from, member);
  15150. if (member.isFocus) {
  15151. this.focusMucJid = from;
  15152. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15153. }
  15154. else {
  15155. var id = $(pres).find('>userId').text();
  15156. var email = $(pres).find('>email');
  15157. if (email.length > 0) {
  15158. id = email.text();
  15159. }
  15160. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15161. }
  15162. } else {
  15163. // Presence update for existing participant
  15164. // Watch role change:
  15165. if (this.members[from].role != member.role) {
  15166. this.members[from].role = member.role;
  15167. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15168. member.role, member.displayName);
  15169. }
  15170. }
  15171. // Always trigger presence to update bindings
  15172. this.parsePresence(from, member, pres);
  15173. // Trigger status message update
  15174. if (member.status) {
  15175. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15176. }
  15177. return true;
  15178. },
  15179. onPresenceUnavailable: function (pres) {
  15180. var from = pres.getAttribute('from');
  15181. // room destroyed ?
  15182. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15183. '>destroy').length) {
  15184. var reason;
  15185. var reasonSelect = $(pres).find(
  15186. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15187. '>destroy>reason');
  15188. if (reasonSelect.length) {
  15189. reason = reasonSelect.text();
  15190. }
  15191. XMPP.disposeConference(false);
  15192. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15193. return true;
  15194. }
  15195. // Status code 110 indicates that this notification is "self-presence".
  15196. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15197. delete this.members[from];
  15198. this.list_members.splice(this.list_members.indexOf(from), 1);
  15199. this.onParticipantLeft(from);
  15200. }
  15201. // If the status code is 110 this means we're leaving and we would like
  15202. // to remove everyone else from our view, so we trigger the event.
  15203. else if (this.list_members.length > 1) {
  15204. for (var i = 0; i < this.list_members.length; i++) {
  15205. var member = this.list_members[i];
  15206. delete this.members[i];
  15207. this.list_members.splice(i, 1);
  15208. this.onParticipantLeft(member);
  15209. }
  15210. }
  15211. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15212. $(document).trigger('kicked.muc', [from]);
  15213. if (this.myroomjid === from) {
  15214. XMPP.disposeConference(false);
  15215. eventEmitter.emit(XMPPEvents.KICKED);
  15216. }
  15217. }
  15218. return true;
  15219. },
  15220. onPresenceError: function (pres) {
  15221. var from = pres.getAttribute('from');
  15222. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15223. console.log('on password required', from);
  15224. var self = this;
  15225. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15226. self.doJoin(from, value);
  15227. });
  15228. } else if ($(pres).find(
  15229. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15230. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15231. if (toDomain === config.hosts.anonymousdomain) {
  15232. // enter the room by replying with 'not-authorized'. This would
  15233. // result in reconnection from authorized domain.
  15234. // We're either missing Jicofo/Prosody config for anonymous
  15235. // domains or something is wrong.
  15236. // XMPP.promptLogin();
  15237. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15238. } else {
  15239. console.warn('onPresError ', pres);
  15240. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15241. }
  15242. } else {
  15243. console.warn('onPresError ', pres);
  15244. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15245. }
  15246. return true;
  15247. },
  15248. sendMessage: function (body, nickname) {
  15249. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15250. msg.c('body', body).up();
  15251. if (nickname) {
  15252. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15253. }
  15254. this.connection.send(msg);
  15255. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15256. },
  15257. setSubject: function (subject) {
  15258. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15259. msg.c('subject', subject);
  15260. this.connection.send(msg);
  15261. console.log("topic changed to " + subject);
  15262. },
  15263. onMessage: function (msg) {
  15264. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15265. var from = msg.getAttribute('from');
  15266. var nick =
  15267. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15268. .text() ||
  15269. Strophe.getResourceFromJid(from);
  15270. var txt = $(msg).find('>body').text();
  15271. var type = msg.getAttribute("type");
  15272. if (type == "error") {
  15273. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15274. $(msg).find('>text').text(), txt);
  15275. return true;
  15276. }
  15277. var subject = $(msg).find('>subject');
  15278. if (subject.length) {
  15279. var subjectText = subject.text();
  15280. if (subjectText || subjectText == "") {
  15281. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15282. console.log("Subject is changed to " + subjectText);
  15283. }
  15284. }
  15285. // xep-0203 delay
  15286. var stamp = $(msg).find('>delay').attr('stamp');
  15287. if (!stamp) {
  15288. // or xep-0091 delay, UTC timestamp
  15289. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15290. if (stamp) {
  15291. // the format is CCYYMMDDThh:mm:ss
  15292. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15293. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15294. }
  15295. }
  15296. if (txt) {
  15297. console.log('chat', nick, txt);
  15298. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15299. from, nick, txt, this.myroomjid, stamp);
  15300. }
  15301. return true;
  15302. },
  15303. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15304. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15305. var ob = this;
  15306. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15307. function (res) {
  15308. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15309. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15310. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15311. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15312. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15313. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15314. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15315. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15316. ob.connection.sendIQ(formsubmit,
  15317. onSuccess,
  15318. onError);
  15319. } else {
  15320. onNotSupported();
  15321. }
  15322. }, onError);
  15323. },
  15324. kick: function (jid) {
  15325. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15326. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15327. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15328. .c('reason').t('You have been kicked.').up().up().up();
  15329. this.connection.sendIQ(
  15330. kickIQ,
  15331. function (result) {
  15332. console.log('Kick participant with jid: ', jid, result);
  15333. },
  15334. function (error) {
  15335. console.log('Kick participant error: ', error);
  15336. });
  15337. },
  15338. sendPresence: function () {
  15339. if (!this.presMap['to']) {
  15340. // Too early to send presence - not initialized
  15341. return;
  15342. }
  15343. var pres = $pres({to: this.presMap['to'] });
  15344. pres.c('x', {xmlns: this.presMap['xns']});
  15345. if (this.presMap['password']) {
  15346. pres.c('password').t(this.presMap['password']).up();
  15347. }
  15348. pres.up();
  15349. // Send XEP-0115 'c' stanza that contains our capabilities info
  15350. if (this.connection.caps) {
  15351. this.connection.caps.node = config.clientNode;
  15352. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15353. }
  15354. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15355. .t(navigator.userAgent).up();
  15356. if (this.presMap['bridgeIsDown']) {
  15357. pres.c('bridgeIsDown').up();
  15358. }
  15359. if (this.presMap['email']) {
  15360. pres.c('email').t(this.presMap['email']).up();
  15361. }
  15362. if (this.presMap['userId']) {
  15363. pres.c('userId').t(this.presMap['userId']).up();
  15364. }
  15365. if (this.presMap['displayName']) {
  15366. // XEP-0172
  15367. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15368. .t(this.presMap['displayName']).up();
  15369. }
  15370. if(this.presMap["devices"])
  15371. {
  15372. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15373. .c('video').t(this.presMap['devices'].video).up().up();
  15374. }
  15375. if (this.presMap['audions']) {
  15376. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15377. .t(this.presMap['audiomuted']).up();
  15378. }
  15379. if (this.presMap['videons']) {
  15380. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15381. .t(this.presMap['videomuted']).up();
  15382. }
  15383. if (this.presMap['videoTypeNs']) {
  15384. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  15385. .t(this.presMap['videoType']).up();
  15386. }
  15387. if (this.presMap['statsns']) {
  15388. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15389. for (var stat in this.presMap["stats"])
  15390. if (this.presMap["stats"][stat] != null)
  15391. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15392. pres.up();
  15393. }
  15394. if (this.presMap['prezins']) {
  15395. pres.c('prezi',
  15396. {xmlns: this.presMap['prezins'],
  15397. 'url': this.presMap['preziurl']})
  15398. .c('current').t(this.presMap['prezicurrent']).up().up();
  15399. }
  15400. if(this.presMap["startMuted"] !== undefined)
  15401. {
  15402. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15403. video: this.presMap["startMuted"].video,
  15404. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15405. delete this.presMap["startMuted"];
  15406. }
  15407. pres.up();
  15408. this.connection.send(pres);
  15409. },
  15410. addDisplayNameToPresence: function (displayName) {
  15411. this.presMap['displayName'] = displayName;
  15412. },
  15413. addDevicesToPresence: function (devices) {
  15414. this.presMap['devices'] = devices;
  15415. },
  15416. /**
  15417. * Adds the info about the type of our video stream.
  15418. * @param videoType 'camera' or 'screen'
  15419. */
  15420. addVideoTypeToPresence: function (videoType) {
  15421. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  15422. this.presMap['videoType'] = videoType;
  15423. },
  15424. addPreziToPresence: function (url, currentSlide) {
  15425. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15426. this.presMap['preziurl'] = url;
  15427. this.presMap['prezicurrent'] = currentSlide;
  15428. },
  15429. removePreziFromPresence: function () {
  15430. delete this.presMap['prezins'];
  15431. delete this.presMap['preziurl'];
  15432. delete this.presMap['prezicurrent'];
  15433. },
  15434. addCurrentSlideToPresence: function (currentSlide) {
  15435. this.presMap['prezicurrent'] = currentSlide;
  15436. },
  15437. getPrezi: function (roomjid) {
  15438. return this.preziMap[roomjid];
  15439. },
  15440. addAudioInfoToPresence: function (isMuted) {
  15441. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15442. this.presMap['audiomuted'] = isMuted.toString();
  15443. },
  15444. addVideoInfoToPresence: function (isMuted) {
  15445. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15446. this.presMap['videomuted'] = isMuted.toString();
  15447. },
  15448. addConnectionInfoToPresence: function (stats) {
  15449. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15450. this.presMap['stats'] = stats;
  15451. },
  15452. findJidFromResource: function (resourceJid) {
  15453. if (resourceJid &&
  15454. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15455. return this.myroomjid;
  15456. }
  15457. var peerJid = null;
  15458. Object.keys(this.members).some(function (jid) {
  15459. peerJid = jid;
  15460. return Strophe.getResourceFromJid(jid) === resourceJid;
  15461. });
  15462. return peerJid;
  15463. },
  15464. addBridgeIsDownToPresence: function () {
  15465. this.presMap['bridgeIsDown'] = true;
  15466. },
  15467. addEmailToPresence: function (email) {
  15468. this.presMap['email'] = email;
  15469. },
  15470. addUserIdToPresence: function (userId) {
  15471. this.presMap['userId'] = userId;
  15472. },
  15473. addStartMutedToPresence: function (audio, video) {
  15474. this.presMap["startMuted"] = {audio: audio, video: video};
  15475. },
  15476. isModerator: function () {
  15477. return this.role === 'moderator';
  15478. },
  15479. getMemberRole: function (peerJid) {
  15480. if (this.members[peerJid]) {
  15481. return this.members[peerJid].role;
  15482. }
  15483. return null;
  15484. },
  15485. onParticipantLeft: function (jid) {
  15486. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15487. this.connection.jingle.terminateByJid(jid);
  15488. if (this.getPrezi(jid)) {
  15489. $(document).trigger('presentationremoved.muc',
  15490. [jid, this.getPrezi(jid)]);
  15491. }
  15492. Moderator.onMucMemberLeft(jid);
  15493. },
  15494. parsePresence: function (from, member, pres) {
  15495. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  15496. this.bridgeIsDown = true;
  15497. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15498. }
  15499. if(member.isFocus)
  15500. return;
  15501. var displayName = !config.displayJids
  15502. ? member.displayName : Strophe.getResourceFromJid(from);
  15503. if (displayName && displayName.length > 0) {
  15504. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15505. }
  15506. var id = $(pres).find('>userID').text();
  15507. var email = $(pres).find('>email');
  15508. if (email.length > 0) {
  15509. id = email.text();
  15510. }
  15511. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15512. }
  15513. });
  15514. };
  15515. },{"../../service/xmpp/XMPPEvents":117,"./moderator":59}],62:[function(require,module,exports){
  15516. /* jshint -W117 */
  15517. var JingleSession = require("./JingleSession");
  15518. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15519. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15520. module.exports = function(XMPP, eventEmitter) {
  15521. function CallIncomingJingle(sid, connection) {
  15522. var sess = connection.jingle.sessions[sid];
  15523. // TODO: do we check activecall == null?
  15524. connection.jingle.activecall = sess;
  15525. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15526. // TODO: check affiliation and/or role
  15527. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15528. sess.usedrip = true; // not-so-naive trickle ice
  15529. sess.sendAnswer();
  15530. sess.accept();
  15531. }
  15532. Strophe.addConnectionPlugin('jingle', {
  15533. connection: null,
  15534. sessions: {},
  15535. jid2session: {},
  15536. ice_config: {iceServers: []},
  15537. pc_constraints: {},
  15538. activecall: null,
  15539. media_constraints: {
  15540. mandatory: {
  15541. 'OfferToReceiveAudio': true,
  15542. 'OfferToReceiveVideo': true
  15543. }
  15544. // MozDontOfferDataChannel: true when this is firefox
  15545. },
  15546. init: function (conn) {
  15547. this.connection = conn;
  15548. if (this.connection.disco) {
  15549. // http://xmpp.org/extensions/xep-0167.html#support
  15550. // http://xmpp.org/extensions/xep-0176.html#support
  15551. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15552. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15553. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15554. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15555. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15556. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15557. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15558. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15559. || RTCBrowserType.isTemasysPluginUsed()) {
  15560. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15561. }
  15562. // this is dealt with by SDP O/A so we don't need to announce this
  15563. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15564. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15565. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15566. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15567. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15568. }
  15569. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15570. },
  15571. onJingle: function (iq) {
  15572. var sid = $(iq).find('jingle').attr('sid');
  15573. var action = $(iq).find('jingle').attr('action');
  15574. var fromJid = iq.getAttribute('from');
  15575. // send ack first
  15576. var ack = $iq({type: 'result',
  15577. to: fromJid,
  15578. id: iq.getAttribute('id')
  15579. });
  15580. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15581. var sess = this.sessions[sid];
  15582. if ('session-initiate' != action) {
  15583. if (sess === null) {
  15584. ack.type = 'error';
  15585. ack.c('error', {type: 'cancel'})
  15586. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15587. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15588. this.connection.send(ack);
  15589. return true;
  15590. }
  15591. // local jid is not checked
  15592. if (fromJid != sess.peerjid) {
  15593. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15594. ack.type = 'error';
  15595. ack.c('error', {type: 'cancel'})
  15596. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15597. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15598. this.connection.send(ack);
  15599. return true;
  15600. }
  15601. } else if (sess !== undefined) {
  15602. // existing session with same session id
  15603. // this might be out-of-order if the sess.peerjid is the same as from
  15604. ack.type = 'error';
  15605. ack.c('error', {type: 'cancel'})
  15606. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15607. console.warn('duplicate session id', sid);
  15608. this.connection.send(ack);
  15609. return true;
  15610. }
  15611. // FIXME: check for a defined action
  15612. this.connection.send(ack);
  15613. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15614. switch (action) {
  15615. case 'session-initiate':
  15616. var startMuted = $(iq).find('jingle>startmuted');
  15617. if (startMuted && startMuted.length > 0) {
  15618. var audioMuted = startMuted.attr("audio");
  15619. var videoMuted = startMuted.attr("video");
  15620. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15621. audioMuted === "true", videoMuted === "true");
  15622. }
  15623. sess = new JingleSession(
  15624. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15625. this.connection, XMPP, eventEmitter);
  15626. // configure session
  15627. sess.media_constraints = this.media_constraints;
  15628. sess.pc_constraints = this.pc_constraints;
  15629. sess.ice_config = this.ice_config;
  15630. sess.initiate(fromJid, false);
  15631. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15632. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15633. this.sessions[sess.sid] = sess;
  15634. this.jid2session[sess.peerjid] = sess;
  15635. // the callback should either
  15636. // .sendAnswer and .accept
  15637. // or .sendTerminate -- not necessarily synchronus
  15638. CallIncomingJingle(sess.sid, this.connection);
  15639. break;
  15640. case 'session-accept':
  15641. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15642. sess.accept();
  15643. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15644. break;
  15645. case 'session-terminate':
  15646. // If this is not the focus sending the terminate, we have
  15647. // nothing more to do here.
  15648. if (Object.keys(this.sessions).length < 1
  15649. || !(this.sessions[Object.keys(this.sessions)[0]]
  15650. instanceof JingleSession))
  15651. {
  15652. break;
  15653. }
  15654. console.log('terminating...', sess.sid);
  15655. sess.terminate();
  15656. this.terminate(sess.sid);
  15657. if ($(iq).find('>jingle>reason').length) {
  15658. $(document).trigger('callterminated.jingle', [
  15659. sess.sid,
  15660. sess.peerjid,
  15661. $(iq).find('>jingle>reason>:first')[0].tagName,
  15662. $(iq).find('>jingle>reason>text').text()
  15663. ]);
  15664. } else {
  15665. $(document).trigger('callterminated.jingle',
  15666. [sess.sid, sess.peerjid]);
  15667. }
  15668. break;
  15669. case 'transport-info':
  15670. sess.addIceCandidate($(iq).find('>jingle>content'));
  15671. break;
  15672. case 'session-info':
  15673. var affected;
  15674. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15675. $(document).trigger('ringing.jingle', [sess.sid]);
  15676. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15677. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15678. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15679. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15680. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15681. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15682. }
  15683. break;
  15684. case 'addsource': // FIXME: proprietary, un-jingleish
  15685. case 'source-add': // FIXME: proprietary
  15686. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15687. break;
  15688. case 'removesource': // FIXME: proprietary, un-jingleish
  15689. case 'source-remove': // FIXME: proprietary
  15690. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15691. break;
  15692. default:
  15693. console.warn('jingle action not implemented', action);
  15694. break;
  15695. }
  15696. return true;
  15697. },
  15698. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15699. var sess = new JingleSession(myjid || this.connection.jid,
  15700. Math.random().toString(36).substr(2, 12), // random string
  15701. this.connection, XMPP, eventEmitter);
  15702. // configure session
  15703. sess.media_constraints = this.media_constraints;
  15704. sess.pc_constraints = this.pc_constraints;
  15705. sess.ice_config = this.ice_config;
  15706. sess.initiate(peerjid, true);
  15707. this.sessions[sess.sid] = sess;
  15708. this.jid2session[sess.peerjid] = sess;
  15709. sess.sendOffer();
  15710. return sess;
  15711. },
  15712. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15713. if (sid === null || sid === undefined) {
  15714. for (sid in this.sessions) {
  15715. if (this.sessions[sid].state != 'ended') {
  15716. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15717. this.sessions[sid].terminate();
  15718. }
  15719. delete this.jid2session[this.sessions[sid].peerjid];
  15720. delete this.sessions[sid];
  15721. }
  15722. } else if (this.sessions.hasOwnProperty(sid)) {
  15723. if (this.sessions[sid].state != 'ended') {
  15724. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15725. this.sessions[sid].terminate();
  15726. }
  15727. delete this.jid2session[this.sessions[sid].peerjid];
  15728. delete this.sessions[sid];
  15729. }
  15730. },
  15731. // Used to terminate a session when an unavailable presence is received.
  15732. terminateByJid: function (jid) {
  15733. if (this.jid2session.hasOwnProperty(jid)) {
  15734. var sess = this.jid2session[jid];
  15735. if (sess) {
  15736. sess.terminate();
  15737. console.log('peer went away silently', jid);
  15738. delete this.sessions[sess.sid];
  15739. delete this.jid2session[jid];
  15740. $(document).trigger('callterminated.jingle',
  15741. [sess.sid, jid], 'gone');
  15742. }
  15743. }
  15744. },
  15745. terminateRemoteByJid: function (jid, reason) {
  15746. if (this.jid2session.hasOwnProperty(jid)) {
  15747. var sess = this.jid2session[jid];
  15748. if (sess) {
  15749. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15750. sess.terminate();
  15751. console.log('terminate peer with jid', sess.sid, jid);
  15752. delete this.sessions[sess.sid];
  15753. delete this.jid2session[jid];
  15754. $(document).trigger('callterminated.jingle',
  15755. [sess.sid, jid, 'kicked']);
  15756. }
  15757. }
  15758. },
  15759. getStunAndTurnCredentials: function () {
  15760. // get stun and turn configuration from server via xep-0215
  15761. // uses time-limited credentials as described in
  15762. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15763. //
  15764. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15765. // for a prosody module which implements this
  15766. //
  15767. // currently, this doesn't work with updateIce and therefore credentials with a long
  15768. // validity have to be fetched before creating the peerconnection
  15769. // TODO: implement refresh via updateIce as described in
  15770. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15771. var self = this;
  15772. this.connection.sendIQ(
  15773. $iq({type: 'get', to: this.connection.domain})
  15774. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15775. function (res) {
  15776. var iceservers = [];
  15777. $(res).find('>services>service').each(function (idx, el) {
  15778. el = $(el);
  15779. var dict = {};
  15780. var type = el.attr('type');
  15781. switch (type) {
  15782. case 'stun':
  15783. dict.url = 'stun:' + el.attr('host');
  15784. if (el.attr('port')) {
  15785. dict.url += ':' + el.attr('port');
  15786. }
  15787. iceservers.push(dict);
  15788. break;
  15789. case 'turn':
  15790. case 'turns':
  15791. dict.url = type + ':';
  15792. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15793. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15794. dict.url += el.attr('username') + '@';
  15795. } else {
  15796. dict.username = el.attr('username'); // only works in M28
  15797. }
  15798. }
  15799. dict.url += el.attr('host');
  15800. if (el.attr('port') && el.attr('port') != '3478') {
  15801. dict.url += ':' + el.attr('port');
  15802. }
  15803. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15804. dict.url += '?transport=' + el.attr('transport');
  15805. }
  15806. if (el.attr('password')) {
  15807. dict.credential = el.attr('password');
  15808. }
  15809. iceservers.push(dict);
  15810. break;
  15811. }
  15812. });
  15813. self.ice_config.iceServers = iceservers;
  15814. },
  15815. function (err) {
  15816. console.warn('getting turn credentials failed', err);
  15817. console.warn('is mod_turncredentials or similar installed?');
  15818. }
  15819. );
  15820. // implement push?
  15821. },
  15822. /**
  15823. * Returns the data saved in 'updateLog' in a format to be logged.
  15824. */
  15825. getLog: function () {
  15826. var data = {};
  15827. var self = this;
  15828. Object.keys(this.sessions).forEach(function (sid) {
  15829. var session = self.sessions[sid];
  15830. if (session.peerconnection && session.peerconnection.updateLog) {
  15831. // FIXME: should probably be a .dump call
  15832. data["jingle_" + session.sid] = {
  15833. updateLog: session.peerconnection.updateLog,
  15834. stats: session.peerconnection.stats,
  15835. url: window.location.href
  15836. };
  15837. }
  15838. });
  15839. return data;
  15840. }
  15841. });
  15842. };
  15843. },{"../../service/xmpp/XMPPEvents":117,"../RTC/RTCBrowserType":8,"./JingleSession":53}],63:[function(require,module,exports){
  15844. /* global Strophe */
  15845. module.exports = function () {
  15846. Strophe.addConnectionPlugin('logger', {
  15847. // logs raw stanzas and makes them available for download as JSON
  15848. connection: null,
  15849. log: [],
  15850. init: function (conn) {
  15851. this.connection = conn;
  15852. this.connection.rawInput = this.log_incoming.bind(this);
  15853. this.connection.rawOutput = this.log_outgoing.bind(this);
  15854. },
  15855. log_incoming: function (stanza) {
  15856. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15857. },
  15858. log_outgoing: function (stanza) {
  15859. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15860. }
  15861. });
  15862. };
  15863. },{}],64:[function(require,module,exports){
  15864. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15865. setAudioMuted, Strophe */
  15866. /**
  15867. * Moderate connection plugin.
  15868. */
  15869. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15870. module.exports = function (XMPP, eventEmitter) {
  15871. Strophe.addConnectionPlugin('moderate', {
  15872. connection: null,
  15873. init: function (conn) {
  15874. this.connection = conn;
  15875. this.connection.addHandler(this.onMute.bind(this),
  15876. 'http://jitsi.org/jitmeet/audio',
  15877. 'iq',
  15878. 'set',
  15879. null,
  15880. null);
  15881. },
  15882. setMute: function (jid, mute) {
  15883. console.info("set mute", mute);
  15884. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15885. .c('mute', {
  15886. xmlns: 'http://jitsi.org/jitmeet/audio',
  15887. jid: jid
  15888. })
  15889. .t(mute.toString())
  15890. .up();
  15891. this.connection.sendIQ(
  15892. iqToFocus,
  15893. function (result) {
  15894. console.log('set mute', result);
  15895. },
  15896. function (error) {
  15897. console.log('set mute error', error);
  15898. });
  15899. },
  15900. onMute: function (iq) {
  15901. var from = iq.getAttribute('from');
  15902. if (from !== this.connection.emuc.focusMucJid) {
  15903. console.warn("Ignored mute from non focus peer");
  15904. return false;
  15905. }
  15906. var mute = $(iq).find('mute');
  15907. if (mute.length) {
  15908. var doMuteAudio = mute.text() === "true";
  15909. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  15910. XMPP.forceMuted = doMuteAudio;
  15911. }
  15912. return true;
  15913. },
  15914. eject: function (jid) {
  15915. // We're not the focus, so can't terminate
  15916. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15917. this.connection.emuc.kick(jid);
  15918. }
  15919. });
  15920. }
  15921. },{"../../service/xmpp/XMPPEvents":117}],65:[function(require,module,exports){
  15922. /* jshint -W117 */
  15923. module.exports = function() {
  15924. Strophe.addConnectionPlugin('rayo',
  15925. {
  15926. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15927. connection: null,
  15928. init: function (conn) {
  15929. this.connection = conn;
  15930. if (this.connection.disco) {
  15931. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15932. }
  15933. this.connection.addHandler(
  15934. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15935. },
  15936. onRayo: function (iq) {
  15937. console.info("Rayo IQ", iq);
  15938. },
  15939. dial: function (to, from, roomName, roomPass) {
  15940. var self = this;
  15941. var req = $iq(
  15942. {
  15943. type: 'set',
  15944. to: this.connection.emuc.focusMucJid
  15945. }
  15946. );
  15947. req.c('dial',
  15948. {
  15949. xmlns: this.RAYO_XMLNS,
  15950. to: to,
  15951. from: from
  15952. });
  15953. req.c('header',
  15954. {
  15955. name: 'JvbRoomName',
  15956. value: roomName
  15957. }).up();
  15958. if (roomPass !== null && roomPass.length) {
  15959. req.c('header',
  15960. {
  15961. name: 'JvbRoomPassword',
  15962. value: roomPass
  15963. }).up();
  15964. }
  15965. this.connection.sendIQ(
  15966. req,
  15967. function (result) {
  15968. console.info('Dial result ', result);
  15969. var resource = $(result).find('ref').attr('uri');
  15970. this.call_resource = resource.substr('xmpp:'.length);
  15971. console.info(
  15972. "Received call resource: " + this.call_resource);
  15973. },
  15974. function (error) {
  15975. console.info('Dial error ', error);
  15976. }
  15977. );
  15978. },
  15979. hang_up: function () {
  15980. if (!this.call_resource) {
  15981. console.warn("No call in progress");
  15982. return;
  15983. }
  15984. var self = this;
  15985. var req = $iq(
  15986. {
  15987. type: 'set',
  15988. to: this.call_resource
  15989. }
  15990. );
  15991. req.c('hangup',
  15992. {
  15993. xmlns: this.RAYO_XMLNS
  15994. });
  15995. this.connection.sendIQ(
  15996. req,
  15997. function (result) {
  15998. console.info('Hangup result ', result);
  15999. self.call_resource = null;
  16000. },
  16001. function (error) {
  16002. console.info('Hangup error ', error);
  16003. self.call_resource = null;
  16004. }
  16005. );
  16006. }
  16007. }
  16008. );
  16009. };
  16010. },{}],66:[function(require,module,exports){
  16011. /**
  16012. * Strophe logger implementation. Logs from level WARN and above.
  16013. */
  16014. module.exports = function () {
  16015. Strophe.log = function (level, msg) {
  16016. switch (level) {
  16017. case Strophe.LogLevel.WARN:
  16018. console.warn("Strophe: " + msg);
  16019. break;
  16020. case Strophe.LogLevel.ERROR:
  16021. case Strophe.LogLevel.FATAL:
  16022. console.error("Strophe: " + msg);
  16023. break;
  16024. }
  16025. };
  16026. Strophe.getStatusString = function (status) {
  16027. switch (status) {
  16028. case Strophe.Status.ERROR:
  16029. return "ERROR";
  16030. case Strophe.Status.CONNECTING:
  16031. return "CONNECTING";
  16032. case Strophe.Status.CONNFAIL:
  16033. return "CONNFAIL";
  16034. case Strophe.Status.AUTHENTICATING:
  16035. return "AUTHENTICATING";
  16036. case Strophe.Status.AUTHFAIL:
  16037. return "AUTHFAIL";
  16038. case Strophe.Status.CONNECTED:
  16039. return "CONNECTED";
  16040. case Strophe.Status.DISCONNECTED:
  16041. return "DISCONNECTED";
  16042. case Strophe.Status.DISCONNECTING:
  16043. return "DISCONNECTING";
  16044. case Strophe.Status.ATTACHED:
  16045. return "ATTACHED";
  16046. default:
  16047. return "unknown";
  16048. }
  16049. };
  16050. };
  16051. },{}],67:[function(require,module,exports){
  16052. /* global $, APP, config, Strophe*/
  16053. var Moderator = require("./moderator");
  16054. var EventEmitter = require("events");
  16055. var Recording = require("./recording");
  16056. var SDP = require("./SDP");
  16057. var Settings = require("../settings/Settings");
  16058. var Pako = require("pako");
  16059. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16060. var RTCEvents = require("../../service/RTC/RTCEvents");
  16061. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16062. var retry = require('retry');
  16063. var eventEmitter = new EventEmitter();
  16064. var connection = null;
  16065. var authenticatedUser = false;
  16066. function connect(jid, password) {
  16067. var faultTolerantConnect = retry.operation({
  16068. retries: 3
  16069. });
  16070. // fault tolerant connect
  16071. faultTolerantConnect.attempt(function () {
  16072. connection = XMPP.createConnection();
  16073. Moderator.setConnection(connection);
  16074. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16075. if (config.useIPv6) {
  16076. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16077. if (!connection.jingle.pc_constraints.optional)
  16078. connection.jingle.pc_constraints.optional = [];
  16079. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16080. }
  16081. // Include user info in MUC presence
  16082. var settings = Settings.getSettings();
  16083. if (settings.email) {
  16084. connection.emuc.addEmailToPresence(settings.email);
  16085. }
  16086. if (settings.uid) {
  16087. connection.emuc.addUserIdToPresence(settings.uid);
  16088. }
  16089. if (settings.displayName) {
  16090. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16091. }
  16092. // connection.connect() starts the connection process.
  16093. //
  16094. // As the connection process proceeds, the user supplied callback will
  16095. // be triggered multiple times with status updates. The callback should
  16096. // take two arguments - the status code and the error condition.
  16097. //
  16098. // The status code will be one of the values in the Strophe.Status
  16099. // constants. The error condition will be one of the conditions defined
  16100. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16101. //
  16102. // The Parameters wait, hold and route are optional and only relevant
  16103. // for BOSH connections. Please see XEP 124 for a more detailed
  16104. // explanation of the optional parameters.
  16105. //
  16106. // Connection status constants for use by the connection handler
  16107. // callback.
  16108. //
  16109. // Status.ERROR - An error has occurred (websockets specific)
  16110. // Status.CONNECTING - The connection is currently being made
  16111. // Status.CONNFAIL - The connection attempt failed
  16112. // Status.AUTHENTICATING - The connection is authenticating
  16113. // Status.AUTHFAIL - The authentication attempt failed
  16114. // Status.CONNECTED - The connection has succeeded
  16115. // Status.DISCONNECTED - The connection has been terminated
  16116. // Status.DISCONNECTING - The connection is currently being terminated
  16117. // Status.ATTACHED - The connection has been attached
  16118. var anonymousConnectionFailed = false;
  16119. var connectionFailed = false;
  16120. var lastErrorMsg;
  16121. connection.connect(jid, password, function (status, msg) {
  16122. console.log('Strophe status changed to',
  16123. Strophe.getStatusString(status), msg);
  16124. if (status === Strophe.Status.CONNECTED) {
  16125. if (config.useStunTurn) {
  16126. connection.jingle.getStunAndTurnCredentials();
  16127. }
  16128. console.info("My Jabber ID: " + connection.jid);
  16129. if (password)
  16130. authenticatedUser = true;
  16131. maybeDoJoin();
  16132. } else if (status === Strophe.Status.CONNFAIL) {
  16133. if (msg === 'x-strophe-bad-non-anon-jid') {
  16134. anonymousConnectionFailed = true;
  16135. } else {
  16136. connectionFailed = true;
  16137. }
  16138. lastErrorMsg = msg;
  16139. } else if (status === Strophe.Status.DISCONNECTED) {
  16140. if (anonymousConnectionFailed) {
  16141. // prompt user for username and password
  16142. XMPP.promptLogin();
  16143. } else {
  16144. // Strophe already has built-in HTTP/BOSH error handling and
  16145. // request retry logic. Requests are resent automatically
  16146. // until their error count reaches 5. Strophe.js disconnects
  16147. // if the error count is > 5. We are not replicating this
  16148. // here.
  16149. //
  16150. // The "problem" is that failed HTTP/BOSH requests don't
  16151. // trigger a callback with a status update, so when a
  16152. // callback with status Strophe.Status.DISCONNECTED arrives,
  16153. // we can't be sure if it's a graceful disconnect or if it's
  16154. // triggered by some HTTP/BOSH error.
  16155. //
  16156. // But that's a minor issue in Jitsi Meet as we never
  16157. // disconnect anyway, not even when the user closes the
  16158. // browser window (which is kind of wrong, but the point is
  16159. // that we should never ever get disconnected).
  16160. //
  16161. // On the other hand, failed connections due to XMPP layer
  16162. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16163. //
  16164. // Here we implement retry logic for failed connections due
  16165. // to XMPP layer errors and we display an error to the user
  16166. // if we get disconnected from the XMPP server permanently.
  16167. // If the connection failed, retry.
  16168. if (connectionFailed &&
  16169. faultTolerantConnect.retry("connection-failed")) {
  16170. return;
  16171. }
  16172. // If we failed to connect to the XMPP server, fire an event
  16173. // to let all the interested module now about it.
  16174. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16175. msg ? msg : lastErrorMsg);
  16176. }
  16177. } else if (status === Strophe.Status.AUTHFAIL) {
  16178. // wrong password or username, prompt user
  16179. XMPP.promptLogin();
  16180. }
  16181. });
  16182. });
  16183. }
  16184. function maybeDoJoin() {
  16185. if (connection && connection.connected &&
  16186. Strophe.getResourceFromJid(connection.jid) &&
  16187. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16188. // .connected is true while connecting?
  16189. doJoin();
  16190. }
  16191. }
  16192. function doJoin() {
  16193. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16194. }
  16195. function initStrophePlugins()
  16196. {
  16197. require("./strophe.emuc")(XMPP, eventEmitter);
  16198. require("./strophe.jingle")(XMPP, eventEmitter);
  16199. require("./strophe.moderate")(XMPP, eventEmitter);
  16200. require("./strophe.util")();
  16201. require("./strophe.rayo")();
  16202. require("./strophe.logger")();
  16203. }
  16204. /**
  16205. * If given <tt>localStream</tt> is video one this method will advertise it's
  16206. * video type in MUC presence.
  16207. * @param localStream new or modified <tt>LocalStream</tt>.
  16208. */
  16209. function broadcastLocalVideoType(localStream) {
  16210. if (localStream.videoType)
  16211. XMPP.addToPresence('videoType', localStream.videoType);
  16212. }
  16213. function registerListeners() {
  16214. APP.RTC.addStreamListener(
  16215. function (localStream) {
  16216. maybeDoJoin();
  16217. broadcastLocalVideoType(localStream);
  16218. },
  16219. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16220. );
  16221. APP.RTC.addStreamListener(
  16222. broadcastLocalVideoType,
  16223. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16224. );
  16225. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16226. XMPP.addToPresence("devices", devices);
  16227. });
  16228. }
  16229. var unload = (function () {
  16230. var unloaded = false;
  16231. return function () {
  16232. if (unloaded) { return; }
  16233. unloaded = true;
  16234. if (connection && connection.connected) {
  16235. // ensure signout
  16236. $.ajax({
  16237. type: 'POST',
  16238. url: config.bosh,
  16239. async: false,
  16240. cache: false,
  16241. contentType: 'application/xml',
  16242. data: "<body rid='" +
  16243. (connection.rid || connection._proto.rid) +
  16244. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16245. (connection.sid || connection._proto.sid) +
  16246. "' type='terminate'>" +
  16247. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16248. "</body>",
  16249. success: function (data) {
  16250. console.log('signed out');
  16251. console.log(data);
  16252. },
  16253. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16254. console.log('signout error',
  16255. textStatus + ' (' + errorThrown + ')');
  16256. }
  16257. });
  16258. }
  16259. XMPP.disposeConference(true);
  16260. };
  16261. })();
  16262. function setupEvents() {
  16263. // In recent versions of FF the 'beforeunload' event is not fired when the
  16264. // window or the tab is closed. It is only fired when we leave the page
  16265. // (change URL). If this participant doesn't unload properly, then it
  16266. // becomes a ghost for the rest of the participants that stay in the
  16267. // conference. Thankfully handling the 'unload' event in addition to the
  16268. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16269. // method at least once.
  16270. //
  16271. // The 'unload' method can safely be run multiple times, it will actually do
  16272. // something only the first time that it's run, so we're don't have to worry
  16273. // about browsers that fire both events.
  16274. $(window).bind('beforeunload', unload);
  16275. $(window).bind('unload', unload);
  16276. }
  16277. var XMPP = {
  16278. getConnection: function(){ return connection; },
  16279. sessionTerminated: false,
  16280. /**
  16281. * XMPP connection status
  16282. */
  16283. Status: Strophe.Status,
  16284. /**
  16285. * Remembers if we were muted by the focus.
  16286. * @type {boolean}
  16287. */
  16288. forceMuted: false,
  16289. start: function () {
  16290. setupEvents();
  16291. initStrophePlugins();
  16292. registerListeners();
  16293. Moderator.init(this, eventEmitter);
  16294. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16295. // Force authenticated domain if room is appended with '?login=true'
  16296. if (config.hosts.anonymousdomain &&
  16297. window.location.search.indexOf("login=true") !== -1) {
  16298. configDomain = config.hosts.domain;
  16299. }
  16300. var jid = configDomain || window.location.hostname;
  16301. connect(jid, null);
  16302. },
  16303. createConnection: function () {
  16304. var bosh = config.bosh || '/http-bind';
  16305. return new Strophe.Connection(bosh);
  16306. },
  16307. getStatusString: function (status) {
  16308. return Strophe.getStatusString(status);
  16309. },
  16310. promptLogin: function () {
  16311. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16312. },
  16313. joinRoom: function(roomName, useNicks, nick) {
  16314. var roomjid = roomName;
  16315. if (useNicks) {
  16316. if (nick) {
  16317. roomjid += '/' + nick;
  16318. } else {
  16319. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16320. }
  16321. } else {
  16322. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16323. if(!authenticatedUser)
  16324. tmpJid = tmpJid.substr(0, 8);
  16325. roomjid += '/' + tmpJid;
  16326. }
  16327. connection.emuc.doJoin(roomjid);
  16328. },
  16329. myJid: function () {
  16330. if(!connection)
  16331. return null;
  16332. return connection.emuc.myroomjid;
  16333. },
  16334. myResource: function () {
  16335. if(!connection || ! connection.emuc.myroomjid)
  16336. return null;
  16337. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16338. },
  16339. disposeConference: function (onUnload) {
  16340. var handler = connection.jingle.activecall;
  16341. if (handler && handler.peerconnection) {
  16342. // FIXME: probably removing streams is not required and close() should
  16343. // be enough
  16344. if (APP.RTC.localAudio) {
  16345. handler.peerconnection.removeStream(
  16346. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16347. }
  16348. if (APP.RTC.localVideo) {
  16349. handler.peerconnection.removeStream(
  16350. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16351. }
  16352. handler.peerconnection.close();
  16353. }
  16354. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16355. connection.jingle.activecall = null;
  16356. if (!onUnload) {
  16357. this.sessionTerminated = true;
  16358. connection.emuc.doLeave();
  16359. }
  16360. },
  16361. addListener: function(type, listener) {
  16362. eventEmitter.on(type, listener);
  16363. },
  16364. removeListener: function (type, listener) {
  16365. eventEmitter.removeListener(type, listener);
  16366. },
  16367. allocateConferenceFocus: function(roomName, callback) {
  16368. Moderator.allocateConferenceFocus(roomName, callback);
  16369. },
  16370. getLoginUrl: function (roomName, callback) {
  16371. Moderator.getLoginUrl(roomName, callback);
  16372. },
  16373. getPopupLoginUrl: function (roomName, callback) {
  16374. Moderator.getPopupLoginUrl(roomName, callback);
  16375. },
  16376. isModerator: function () {
  16377. return Moderator.isModerator();
  16378. },
  16379. isSipGatewayEnabled: function () {
  16380. return Moderator.isSipGatewayEnabled();
  16381. },
  16382. isExternalAuthEnabled: function () {
  16383. return Moderator.isExternalAuthEnabled();
  16384. },
  16385. isConferenceInProgress: function () {
  16386. return connection && connection.jingle.activecall &&
  16387. connection.jingle.activecall.peerconnection;
  16388. },
  16389. switchStreams: function (stream, oldStream, callback, isAudio) {
  16390. if (this.isConferenceInProgress()) {
  16391. // FIXME: will block switchInProgress on true value in case of exception
  16392. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16393. } else {
  16394. // We are done immediately
  16395. console.warn("No conference handler or conference not started yet");
  16396. callback();
  16397. }
  16398. },
  16399. sendVideoInfoPresence: function (mute) {
  16400. if(!connection)
  16401. return;
  16402. connection.emuc.addVideoInfoToPresence(mute);
  16403. connection.emuc.sendPresence();
  16404. },
  16405. setVideoMute: function (mute, callback, options) {
  16406. if(!connection)
  16407. return;
  16408. var self = this;
  16409. var localCallback = function (mute) {
  16410. self.sendVideoInfoPresence(mute);
  16411. return callback(mute);
  16412. };
  16413. if(connection.jingle.activecall)
  16414. {
  16415. connection.jingle.activecall.setVideoMute(
  16416. mute, localCallback, options);
  16417. }
  16418. else {
  16419. localCallback(mute);
  16420. }
  16421. },
  16422. setAudioMute: function (mute, callback) {
  16423. if (!(connection && APP.RTC.localAudio)) {
  16424. return false;
  16425. }
  16426. if (this.forceMuted && !mute) {
  16427. console.info("Asking focus for unmute");
  16428. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16429. // FIXME: wait for result before resetting muted status
  16430. this.forceMuted = false;
  16431. }
  16432. if (mute == APP.RTC.localAudio.isMuted()) {
  16433. // Nothing to do
  16434. return true;
  16435. }
  16436. APP.RTC.localAudio.setMute(mute);
  16437. this.sendAudioInfoPresence(mute, callback);
  16438. return true;
  16439. },
  16440. sendAudioInfoPresence: function(mute, callback) {
  16441. if(connection) {
  16442. connection.emuc.addAudioInfoToPresence(mute);
  16443. connection.emuc.sendPresence();
  16444. }
  16445. callback();
  16446. return true;
  16447. },
  16448. toggleRecording: function (tokenEmptyCallback,
  16449. recordingStateChangeCallback) {
  16450. Recording.toggleRecording(tokenEmptyCallback,
  16451. recordingStateChangeCallback, connection);
  16452. },
  16453. addToPresence: function (name, value, dontSend) {
  16454. switch (name) {
  16455. case "displayName":
  16456. connection.emuc.addDisplayNameToPresence(value);
  16457. break;
  16458. case "prezi":
  16459. connection.emuc.addPreziToPresence(value, 0);
  16460. break;
  16461. case "preziSlide":
  16462. connection.emuc.addCurrentSlideToPresence(value);
  16463. break;
  16464. case "connectionQuality":
  16465. connection.emuc.addConnectionInfoToPresence(value);
  16466. break;
  16467. case "email":
  16468. connection.emuc.addEmailToPresence(value);
  16469. break;
  16470. case "devices":
  16471. connection.emuc.addDevicesToPresence(value);
  16472. break;
  16473. case "videoType":
  16474. connection.emuc.addVideoTypeToPresence(value);
  16475. break;
  16476. case "startMuted":
  16477. if(!Moderator.isModerator())
  16478. return;
  16479. connection.emuc.addStartMutedToPresence(value[0],
  16480. value[1]);
  16481. break;
  16482. default :
  16483. console.log("Unknown tag for presence: " + name);
  16484. return;
  16485. }
  16486. if (!dontSend)
  16487. connection.emuc.sendPresence();
  16488. },
  16489. /**
  16490. * Sends 'data' as a log message to the focus. Returns true iff a message
  16491. * was sent.
  16492. * @param data
  16493. * @returns {boolean} true iff a message was sent.
  16494. */
  16495. sendLogs: function (data) {
  16496. if(!connection.emuc.focusMucJid)
  16497. return false;
  16498. var deflate = true;
  16499. var content = JSON.stringify(data);
  16500. if (deflate) {
  16501. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16502. }
  16503. content = Base64.encode(content);
  16504. // XEP-0337-ish
  16505. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16506. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16507. id: 'PeerConnectionStats'});
  16508. message.c('message').t(content).up();
  16509. if (deflate) {
  16510. message.c('tag', {name: "deflated", value: "true"}).up();
  16511. }
  16512. message.up();
  16513. connection.send(message);
  16514. return true;
  16515. },
  16516. // Gets the logs from strophe.jingle.
  16517. getJingleLog: function () {
  16518. return connection.jingle ? connection.jingle.getLog() : {};
  16519. },
  16520. // Gets the logs from strophe.
  16521. getXmppLog: function () {
  16522. return connection.logger ? connection.logger.log : null;
  16523. },
  16524. getPrezi: function () {
  16525. return connection.emuc.getPrezi(this.myJid());
  16526. },
  16527. removePreziFromPresence: function () {
  16528. connection.emuc.removePreziFromPresence();
  16529. connection.emuc.sendPresence();
  16530. },
  16531. sendChatMessage: function (message, nickname) {
  16532. connection.emuc.sendMessage(message, nickname);
  16533. },
  16534. setSubject: function (topic) {
  16535. connection.emuc.setSubject(topic);
  16536. },
  16537. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16538. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16539. },
  16540. dial: function (to, from, roomName,roomPass) {
  16541. connection.rayo.dial(to, from, roomName,roomPass);
  16542. },
  16543. setMute: function (jid, mute) {
  16544. connection.moderate.setMute(jid, mute);
  16545. },
  16546. eject: function (jid) {
  16547. connection.moderate.eject(jid);
  16548. },
  16549. logout: function (callback) {
  16550. Moderator.logout(callback);
  16551. },
  16552. findJidFromResource: function (resource) {
  16553. return connection.emuc.findJidFromResource(resource);
  16554. },
  16555. getMembers: function () {
  16556. return connection.emuc.members;
  16557. },
  16558. getJidFromSSRC: function (ssrc) {
  16559. if (!this.isConferenceInProgress())
  16560. return null;
  16561. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16562. },
  16563. // Returns true iff we have joined the MUC.
  16564. isMUCJoined: function () {
  16565. return connection.emuc.joined;
  16566. },
  16567. getSessions: function () {
  16568. return connection.jingle.sessions;
  16569. },
  16570. removeStream: function (stream) {
  16571. if (!this.isConferenceInProgress())
  16572. return;
  16573. connection.jingle.activecall.peerconnection.removeStream(stream);
  16574. }
  16575. };
  16576. module.exports = XMPP;
  16577. },{"../../service/RTC/RTCEvents":108,"../../service/RTC/StreamEventTypes":110,"../../service/xmpp/XMPPEvents":117,"../settings/Settings":47,"./SDP":54,"./moderator":59,"./recording":60,"./strophe.emuc":61,"./strophe.jingle":62,"./strophe.logger":63,"./strophe.moderate":64,"./strophe.rayo":65,"./strophe.util":66,"events":118,"pako":70,"retry":86}],68:[function(require,module,exports){
  16578. (function (process){
  16579. /*!
  16580. * async
  16581. * https://github.com/caolan/async
  16582. *
  16583. * Copyright 2010-2014 Caolan McMahon
  16584. * Released under the MIT license
  16585. */
  16586. /*jshint onevar: false, indent:4 */
  16587. /*global setImmediate: false, setTimeout: false, console: false */
  16588. (function () {
  16589. var async = {};
  16590. // global on the server, window in the browser
  16591. var root, previous_async;
  16592. root = this;
  16593. if (root != null) {
  16594. previous_async = root.async;
  16595. }
  16596. async.noConflict = function () {
  16597. root.async = previous_async;
  16598. return async;
  16599. };
  16600. function only_once(fn) {
  16601. var called = false;
  16602. return function() {
  16603. if (called) throw new Error("Callback was already called.");
  16604. called = true;
  16605. fn.apply(root, arguments);
  16606. }
  16607. }
  16608. //// cross-browser compatiblity functions ////
  16609. var _toString = Object.prototype.toString;
  16610. var _isArray = Array.isArray || function (obj) {
  16611. return _toString.call(obj) === '[object Array]';
  16612. };
  16613. var _each = function (arr, iterator) {
  16614. if (arr.forEach) {
  16615. return arr.forEach(iterator);
  16616. }
  16617. for (var i = 0; i < arr.length; i += 1) {
  16618. iterator(arr[i], i, arr);
  16619. }
  16620. };
  16621. var _map = function (arr, iterator) {
  16622. if (arr.map) {
  16623. return arr.map(iterator);
  16624. }
  16625. var results = [];
  16626. _each(arr, function (x, i, a) {
  16627. results.push(iterator(x, i, a));
  16628. });
  16629. return results;
  16630. };
  16631. var _reduce = function (arr, iterator, memo) {
  16632. if (arr.reduce) {
  16633. return arr.reduce(iterator, memo);
  16634. }
  16635. _each(arr, function (x, i, a) {
  16636. memo = iterator(memo, x, i, a);
  16637. });
  16638. return memo;
  16639. };
  16640. var _keys = function (obj) {
  16641. if (Object.keys) {
  16642. return Object.keys(obj);
  16643. }
  16644. var keys = [];
  16645. for (var k in obj) {
  16646. if (obj.hasOwnProperty(k)) {
  16647. keys.push(k);
  16648. }
  16649. }
  16650. return keys;
  16651. };
  16652. //// exported async module functions ////
  16653. //// nextTick implementation with browser-compatible fallback ////
  16654. if (typeof process === 'undefined' || !(process.nextTick)) {
  16655. if (typeof setImmediate === 'function') {
  16656. async.nextTick = function (fn) {
  16657. // not a direct alias for IE10 compatibility
  16658. setImmediate(fn);
  16659. };
  16660. async.setImmediate = async.nextTick;
  16661. }
  16662. else {
  16663. async.nextTick = function (fn) {
  16664. setTimeout(fn, 0);
  16665. };
  16666. async.setImmediate = async.nextTick;
  16667. }
  16668. }
  16669. else {
  16670. async.nextTick = process.nextTick;
  16671. if (typeof setImmediate !== 'undefined') {
  16672. async.setImmediate = function (fn) {
  16673. // not a direct alias for IE10 compatibility
  16674. setImmediate(fn);
  16675. };
  16676. }
  16677. else {
  16678. async.setImmediate = async.nextTick;
  16679. }
  16680. }
  16681. async.each = function (arr, iterator, callback) {
  16682. callback = callback || function () {};
  16683. if (!arr.length) {
  16684. return callback();
  16685. }
  16686. var completed = 0;
  16687. _each(arr, function (x) {
  16688. iterator(x, only_once(done) );
  16689. });
  16690. function done(err) {
  16691. if (err) {
  16692. callback(err);
  16693. callback = function () {};
  16694. }
  16695. else {
  16696. completed += 1;
  16697. if (completed >= arr.length) {
  16698. callback();
  16699. }
  16700. }
  16701. }
  16702. };
  16703. async.forEach = async.each;
  16704. async.eachSeries = function (arr, iterator, callback) {
  16705. callback = callback || function () {};
  16706. if (!arr.length) {
  16707. return callback();
  16708. }
  16709. var completed = 0;
  16710. var iterate = function () {
  16711. iterator(arr[completed], function (err) {
  16712. if (err) {
  16713. callback(err);
  16714. callback = function () {};
  16715. }
  16716. else {
  16717. completed += 1;
  16718. if (completed >= arr.length) {
  16719. callback();
  16720. }
  16721. else {
  16722. iterate();
  16723. }
  16724. }
  16725. });
  16726. };
  16727. iterate();
  16728. };
  16729. async.forEachSeries = async.eachSeries;
  16730. async.eachLimit = function (arr, limit, iterator, callback) {
  16731. var fn = _eachLimit(limit);
  16732. fn.apply(null, [arr, iterator, callback]);
  16733. };
  16734. async.forEachLimit = async.eachLimit;
  16735. var _eachLimit = function (limit) {
  16736. return function (arr, iterator, callback) {
  16737. callback = callback || function () {};
  16738. if (!arr.length || limit <= 0) {
  16739. return callback();
  16740. }
  16741. var completed = 0;
  16742. var started = 0;
  16743. var running = 0;
  16744. (function replenish () {
  16745. if (completed >= arr.length) {
  16746. return callback();
  16747. }
  16748. while (running < limit && started < arr.length) {
  16749. started += 1;
  16750. running += 1;
  16751. iterator(arr[started - 1], function (err) {
  16752. if (err) {
  16753. callback(err);
  16754. callback = function () {};
  16755. }
  16756. else {
  16757. completed += 1;
  16758. running -= 1;
  16759. if (completed >= arr.length) {
  16760. callback();
  16761. }
  16762. else {
  16763. replenish();
  16764. }
  16765. }
  16766. });
  16767. }
  16768. })();
  16769. };
  16770. };
  16771. var doParallel = function (fn) {
  16772. return function () {
  16773. var args = Array.prototype.slice.call(arguments);
  16774. return fn.apply(null, [async.each].concat(args));
  16775. };
  16776. };
  16777. var doParallelLimit = function(limit, fn) {
  16778. return function () {
  16779. var args = Array.prototype.slice.call(arguments);
  16780. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16781. };
  16782. };
  16783. var doSeries = function (fn) {
  16784. return function () {
  16785. var args = Array.prototype.slice.call(arguments);
  16786. return fn.apply(null, [async.eachSeries].concat(args));
  16787. };
  16788. };
  16789. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16790. arr = _map(arr, function (x, i) {
  16791. return {index: i, value: x};
  16792. });
  16793. if (!callback) {
  16794. eachfn(arr, function (x, callback) {
  16795. iterator(x.value, function (err) {
  16796. callback(err);
  16797. });
  16798. });
  16799. } else {
  16800. var results = [];
  16801. eachfn(arr, function (x, callback) {
  16802. iterator(x.value, function (err, v) {
  16803. results[x.index] = v;
  16804. callback(err);
  16805. });
  16806. }, function (err) {
  16807. callback(err, results);
  16808. });
  16809. }
  16810. };
  16811. async.map = doParallel(_asyncMap);
  16812. async.mapSeries = doSeries(_asyncMap);
  16813. async.mapLimit = function (arr, limit, iterator, callback) {
  16814. return _mapLimit(limit)(arr, iterator, callback);
  16815. };
  16816. var _mapLimit = function(limit) {
  16817. return doParallelLimit(limit, _asyncMap);
  16818. };
  16819. // reduce only has a series version, as doing reduce in parallel won't
  16820. // work in many situations.
  16821. async.reduce = function (arr, memo, iterator, callback) {
  16822. async.eachSeries(arr, function (x, callback) {
  16823. iterator(memo, x, function (err, v) {
  16824. memo = v;
  16825. callback(err);
  16826. });
  16827. }, function (err) {
  16828. callback(err, memo);
  16829. });
  16830. };
  16831. // inject alias
  16832. async.inject = async.reduce;
  16833. // foldl alias
  16834. async.foldl = async.reduce;
  16835. async.reduceRight = function (arr, memo, iterator, callback) {
  16836. var reversed = _map(arr, function (x) {
  16837. return x;
  16838. }).reverse();
  16839. async.reduce(reversed, memo, iterator, callback);
  16840. };
  16841. // foldr alias
  16842. async.foldr = async.reduceRight;
  16843. var _filter = function (eachfn, arr, iterator, callback) {
  16844. var results = [];
  16845. arr = _map(arr, function (x, i) {
  16846. return {index: i, value: x};
  16847. });
  16848. eachfn(arr, function (x, callback) {
  16849. iterator(x.value, function (v) {
  16850. if (v) {
  16851. results.push(x);
  16852. }
  16853. callback();
  16854. });
  16855. }, function (err) {
  16856. callback(_map(results.sort(function (a, b) {
  16857. return a.index - b.index;
  16858. }), function (x) {
  16859. return x.value;
  16860. }));
  16861. });
  16862. };
  16863. async.filter = doParallel(_filter);
  16864. async.filterSeries = doSeries(_filter);
  16865. // select alias
  16866. async.select = async.filter;
  16867. async.selectSeries = async.filterSeries;
  16868. var _reject = function (eachfn, arr, iterator, callback) {
  16869. var results = [];
  16870. arr = _map(arr, function (x, i) {
  16871. return {index: i, value: x};
  16872. });
  16873. eachfn(arr, function (x, callback) {
  16874. iterator(x.value, function (v) {
  16875. if (!v) {
  16876. results.push(x);
  16877. }
  16878. callback();
  16879. });
  16880. }, function (err) {
  16881. callback(_map(results.sort(function (a, b) {
  16882. return a.index - b.index;
  16883. }), function (x) {
  16884. return x.value;
  16885. }));
  16886. });
  16887. };
  16888. async.reject = doParallel(_reject);
  16889. async.rejectSeries = doSeries(_reject);
  16890. var _detect = function (eachfn, arr, iterator, main_callback) {
  16891. eachfn(arr, function (x, callback) {
  16892. iterator(x, function (result) {
  16893. if (result) {
  16894. main_callback(x);
  16895. main_callback = function () {};
  16896. }
  16897. else {
  16898. callback();
  16899. }
  16900. });
  16901. }, function (err) {
  16902. main_callback();
  16903. });
  16904. };
  16905. async.detect = doParallel(_detect);
  16906. async.detectSeries = doSeries(_detect);
  16907. async.some = function (arr, iterator, main_callback) {
  16908. async.each(arr, function (x, callback) {
  16909. iterator(x, function (v) {
  16910. if (v) {
  16911. main_callback(true);
  16912. main_callback = function () {};
  16913. }
  16914. callback();
  16915. });
  16916. }, function (err) {
  16917. main_callback(false);
  16918. });
  16919. };
  16920. // any alias
  16921. async.any = async.some;
  16922. async.every = function (arr, iterator, main_callback) {
  16923. async.each(arr, function (x, callback) {
  16924. iterator(x, function (v) {
  16925. if (!v) {
  16926. main_callback(false);
  16927. main_callback = function () {};
  16928. }
  16929. callback();
  16930. });
  16931. }, function (err) {
  16932. main_callback(true);
  16933. });
  16934. };
  16935. // all alias
  16936. async.all = async.every;
  16937. async.sortBy = function (arr, iterator, callback) {
  16938. async.map(arr, function (x, callback) {
  16939. iterator(x, function (err, criteria) {
  16940. if (err) {
  16941. callback(err);
  16942. }
  16943. else {
  16944. callback(null, {value: x, criteria: criteria});
  16945. }
  16946. });
  16947. }, function (err, results) {
  16948. if (err) {
  16949. return callback(err);
  16950. }
  16951. else {
  16952. var fn = function (left, right) {
  16953. var a = left.criteria, b = right.criteria;
  16954. return a < b ? -1 : a > b ? 1 : 0;
  16955. };
  16956. callback(null, _map(results.sort(fn), function (x) {
  16957. return x.value;
  16958. }));
  16959. }
  16960. });
  16961. };
  16962. async.auto = function (tasks, callback) {
  16963. callback = callback || function () {};
  16964. var keys = _keys(tasks);
  16965. var remainingTasks = keys.length
  16966. if (!remainingTasks) {
  16967. return callback();
  16968. }
  16969. var results = {};
  16970. var listeners = [];
  16971. var addListener = function (fn) {
  16972. listeners.unshift(fn);
  16973. };
  16974. var removeListener = function (fn) {
  16975. for (var i = 0; i < listeners.length; i += 1) {
  16976. if (listeners[i] === fn) {
  16977. listeners.splice(i, 1);
  16978. return;
  16979. }
  16980. }
  16981. };
  16982. var taskComplete = function () {
  16983. remainingTasks--
  16984. _each(listeners.slice(0), function (fn) {
  16985. fn();
  16986. });
  16987. };
  16988. addListener(function () {
  16989. if (!remainingTasks) {
  16990. var theCallback = callback;
  16991. // prevent final callback from calling itself if it errors
  16992. callback = function () {};
  16993. theCallback(null, results);
  16994. }
  16995. });
  16996. _each(keys, function (k) {
  16997. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  16998. var taskCallback = function (err) {
  16999. var args = Array.prototype.slice.call(arguments, 1);
  17000. if (args.length <= 1) {
  17001. args = args[0];
  17002. }
  17003. if (err) {
  17004. var safeResults = {};
  17005. _each(_keys(results), function(rkey) {
  17006. safeResults[rkey] = results[rkey];
  17007. });
  17008. safeResults[k] = args;
  17009. callback(err, safeResults);
  17010. // stop subsequent errors hitting callback multiple times
  17011. callback = function () {};
  17012. }
  17013. else {
  17014. results[k] = args;
  17015. async.setImmediate(taskComplete);
  17016. }
  17017. };
  17018. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17019. var ready = function () {
  17020. return _reduce(requires, function (a, x) {
  17021. return (a && results.hasOwnProperty(x));
  17022. }, true) && !results.hasOwnProperty(k);
  17023. };
  17024. if (ready()) {
  17025. task[task.length - 1](taskCallback, results);
  17026. }
  17027. else {
  17028. var listener = function () {
  17029. if (ready()) {
  17030. removeListener(listener);
  17031. task[task.length - 1](taskCallback, results);
  17032. }
  17033. };
  17034. addListener(listener);
  17035. }
  17036. });
  17037. };
  17038. async.retry = function(times, task, callback) {
  17039. var DEFAULT_TIMES = 5;
  17040. var attempts = [];
  17041. // Use defaults if times not passed
  17042. if (typeof times === 'function') {
  17043. callback = task;
  17044. task = times;
  17045. times = DEFAULT_TIMES;
  17046. }
  17047. // Make sure times is a number
  17048. times = parseInt(times, 10) || DEFAULT_TIMES;
  17049. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17050. var retryAttempt = function(task, finalAttempt) {
  17051. return function(seriesCallback) {
  17052. task(function(err, result){
  17053. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17054. }, wrappedResults);
  17055. };
  17056. };
  17057. while (times) {
  17058. attempts.push(retryAttempt(task, !(times-=1)));
  17059. }
  17060. async.series(attempts, function(done, data){
  17061. data = data[data.length - 1];
  17062. (wrappedCallback || callback)(data.err, data.result);
  17063. });
  17064. }
  17065. // If a callback is passed, run this as a controll flow
  17066. return callback ? wrappedTask() : wrappedTask
  17067. };
  17068. async.waterfall = function (tasks, callback) {
  17069. callback = callback || function () {};
  17070. if (!_isArray(tasks)) {
  17071. var err = new Error('First argument to waterfall must be an array of functions');
  17072. return callback(err);
  17073. }
  17074. if (!tasks.length) {
  17075. return callback();
  17076. }
  17077. var wrapIterator = function (iterator) {
  17078. return function (err) {
  17079. if (err) {
  17080. callback.apply(null, arguments);
  17081. callback = function () {};
  17082. }
  17083. else {
  17084. var args = Array.prototype.slice.call(arguments, 1);
  17085. var next = iterator.next();
  17086. if (next) {
  17087. args.push(wrapIterator(next));
  17088. }
  17089. else {
  17090. args.push(callback);
  17091. }
  17092. async.setImmediate(function () {
  17093. iterator.apply(null, args);
  17094. });
  17095. }
  17096. };
  17097. };
  17098. wrapIterator(async.iterator(tasks))();
  17099. };
  17100. var _parallel = function(eachfn, tasks, callback) {
  17101. callback = callback || function () {};
  17102. if (_isArray(tasks)) {
  17103. eachfn.map(tasks, function (fn, callback) {
  17104. if (fn) {
  17105. fn(function (err) {
  17106. var args = Array.prototype.slice.call(arguments, 1);
  17107. if (args.length <= 1) {
  17108. args = args[0];
  17109. }
  17110. callback.call(null, err, args);
  17111. });
  17112. }
  17113. }, callback);
  17114. }
  17115. else {
  17116. var results = {};
  17117. eachfn.each(_keys(tasks), function (k, callback) {
  17118. tasks[k](function (err) {
  17119. var args = Array.prototype.slice.call(arguments, 1);
  17120. if (args.length <= 1) {
  17121. args = args[0];
  17122. }
  17123. results[k] = args;
  17124. callback(err);
  17125. });
  17126. }, function (err) {
  17127. callback(err, results);
  17128. });
  17129. }
  17130. };
  17131. async.parallel = function (tasks, callback) {
  17132. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17133. };
  17134. async.parallelLimit = function(tasks, limit, callback) {
  17135. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17136. };
  17137. async.series = function (tasks, callback) {
  17138. callback = callback || function () {};
  17139. if (_isArray(tasks)) {
  17140. async.mapSeries(tasks, function (fn, callback) {
  17141. if (fn) {
  17142. fn(function (err) {
  17143. var args = Array.prototype.slice.call(arguments, 1);
  17144. if (args.length <= 1) {
  17145. args = args[0];
  17146. }
  17147. callback.call(null, err, args);
  17148. });
  17149. }
  17150. }, callback);
  17151. }
  17152. else {
  17153. var results = {};
  17154. async.eachSeries(_keys(tasks), function (k, callback) {
  17155. tasks[k](function (err) {
  17156. var args = Array.prototype.slice.call(arguments, 1);
  17157. if (args.length <= 1) {
  17158. args = args[0];
  17159. }
  17160. results[k] = args;
  17161. callback(err);
  17162. });
  17163. }, function (err) {
  17164. callback(err, results);
  17165. });
  17166. }
  17167. };
  17168. async.iterator = function (tasks) {
  17169. var makeCallback = function (index) {
  17170. var fn = function () {
  17171. if (tasks.length) {
  17172. tasks[index].apply(null, arguments);
  17173. }
  17174. return fn.next();
  17175. };
  17176. fn.next = function () {
  17177. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17178. };
  17179. return fn;
  17180. };
  17181. return makeCallback(0);
  17182. };
  17183. async.apply = function (fn) {
  17184. var args = Array.prototype.slice.call(arguments, 1);
  17185. return function () {
  17186. return fn.apply(
  17187. null, args.concat(Array.prototype.slice.call(arguments))
  17188. );
  17189. };
  17190. };
  17191. var _concat = function (eachfn, arr, fn, callback) {
  17192. var r = [];
  17193. eachfn(arr, function (x, cb) {
  17194. fn(x, function (err, y) {
  17195. r = r.concat(y || []);
  17196. cb(err);
  17197. });
  17198. }, function (err) {
  17199. callback(err, r);
  17200. });
  17201. };
  17202. async.concat = doParallel(_concat);
  17203. async.concatSeries = doSeries(_concat);
  17204. async.whilst = function (test, iterator, callback) {
  17205. if (test()) {
  17206. iterator(function (err) {
  17207. if (err) {
  17208. return callback(err);
  17209. }
  17210. async.whilst(test, iterator, callback);
  17211. });
  17212. }
  17213. else {
  17214. callback();
  17215. }
  17216. };
  17217. async.doWhilst = function (iterator, test, callback) {
  17218. iterator(function (err) {
  17219. if (err) {
  17220. return callback(err);
  17221. }
  17222. var args = Array.prototype.slice.call(arguments, 1);
  17223. if (test.apply(null, args)) {
  17224. async.doWhilst(iterator, test, callback);
  17225. }
  17226. else {
  17227. callback();
  17228. }
  17229. });
  17230. };
  17231. async.until = function (test, iterator, callback) {
  17232. if (!test()) {
  17233. iterator(function (err) {
  17234. if (err) {
  17235. return callback(err);
  17236. }
  17237. async.until(test, iterator, callback);
  17238. });
  17239. }
  17240. else {
  17241. callback();
  17242. }
  17243. };
  17244. async.doUntil = function (iterator, test, callback) {
  17245. iterator(function (err) {
  17246. if (err) {
  17247. return callback(err);
  17248. }
  17249. var args = Array.prototype.slice.call(arguments, 1);
  17250. if (!test.apply(null, args)) {
  17251. async.doUntil(iterator, test, callback);
  17252. }
  17253. else {
  17254. callback();
  17255. }
  17256. });
  17257. };
  17258. async.queue = function (worker, concurrency) {
  17259. if (concurrency === undefined) {
  17260. concurrency = 1;
  17261. }
  17262. function _insert(q, data, pos, callback) {
  17263. if (!q.started){
  17264. q.started = true;
  17265. }
  17266. if (!_isArray(data)) {
  17267. data = [data];
  17268. }
  17269. if(data.length == 0) {
  17270. // call drain immediately if there are no tasks
  17271. return async.setImmediate(function() {
  17272. if (q.drain) {
  17273. q.drain();
  17274. }
  17275. });
  17276. }
  17277. _each(data, function(task) {
  17278. var item = {
  17279. data: task,
  17280. callback: typeof callback === 'function' ? callback : null
  17281. };
  17282. if (pos) {
  17283. q.tasks.unshift(item);
  17284. } else {
  17285. q.tasks.push(item);
  17286. }
  17287. if (q.saturated && q.tasks.length === q.concurrency) {
  17288. q.saturated();
  17289. }
  17290. async.setImmediate(q.process);
  17291. });
  17292. }
  17293. var workers = 0;
  17294. var q = {
  17295. tasks: [],
  17296. concurrency: concurrency,
  17297. saturated: null,
  17298. empty: null,
  17299. drain: null,
  17300. started: false,
  17301. paused: false,
  17302. push: function (data, callback) {
  17303. _insert(q, data, false, callback);
  17304. },
  17305. kill: function () {
  17306. q.drain = null;
  17307. q.tasks = [];
  17308. },
  17309. unshift: function (data, callback) {
  17310. _insert(q, data, true, callback);
  17311. },
  17312. process: function () {
  17313. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17314. var task = q.tasks.shift();
  17315. if (q.empty && q.tasks.length === 0) {
  17316. q.empty();
  17317. }
  17318. workers += 1;
  17319. var next = function () {
  17320. workers -= 1;
  17321. if (task.callback) {
  17322. task.callback.apply(task, arguments);
  17323. }
  17324. if (q.drain && q.tasks.length + workers === 0) {
  17325. q.drain();
  17326. }
  17327. q.process();
  17328. };
  17329. var cb = only_once(next);
  17330. worker(task.data, cb);
  17331. }
  17332. },
  17333. length: function () {
  17334. return q.tasks.length;
  17335. },
  17336. running: function () {
  17337. return workers;
  17338. },
  17339. idle: function() {
  17340. return q.tasks.length + workers === 0;
  17341. },
  17342. pause: function () {
  17343. if (q.paused === true) { return; }
  17344. q.paused = true;
  17345. q.process();
  17346. },
  17347. resume: function () {
  17348. if (q.paused === false) { return; }
  17349. q.paused = false;
  17350. q.process();
  17351. }
  17352. };
  17353. return q;
  17354. };
  17355. async.priorityQueue = function (worker, concurrency) {
  17356. function _compareTasks(a, b){
  17357. return a.priority - b.priority;
  17358. };
  17359. function _binarySearch(sequence, item, compare) {
  17360. var beg = -1,
  17361. end = sequence.length - 1;
  17362. while (beg < end) {
  17363. var mid = beg + ((end - beg + 1) >>> 1);
  17364. if (compare(item, sequence[mid]) >= 0) {
  17365. beg = mid;
  17366. } else {
  17367. end = mid - 1;
  17368. }
  17369. }
  17370. return beg;
  17371. }
  17372. function _insert(q, data, priority, callback) {
  17373. if (!q.started){
  17374. q.started = true;
  17375. }
  17376. if (!_isArray(data)) {
  17377. data = [data];
  17378. }
  17379. if(data.length == 0) {
  17380. // call drain immediately if there are no tasks
  17381. return async.setImmediate(function() {
  17382. if (q.drain) {
  17383. q.drain();
  17384. }
  17385. });
  17386. }
  17387. _each(data, function(task) {
  17388. var item = {
  17389. data: task,
  17390. priority: priority,
  17391. callback: typeof callback === 'function' ? callback : null
  17392. };
  17393. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17394. if (q.saturated && q.tasks.length === q.concurrency) {
  17395. q.saturated();
  17396. }
  17397. async.setImmediate(q.process);
  17398. });
  17399. }
  17400. // Start with a normal queue
  17401. var q = async.queue(worker, concurrency);
  17402. // Override push to accept second parameter representing priority
  17403. q.push = function (data, priority, callback) {
  17404. _insert(q, data, priority, callback);
  17405. };
  17406. // Remove unshift function
  17407. delete q.unshift;
  17408. return q;
  17409. };
  17410. async.cargo = function (worker, payload) {
  17411. var working = false,
  17412. tasks = [];
  17413. var cargo = {
  17414. tasks: tasks,
  17415. payload: payload,
  17416. saturated: null,
  17417. empty: null,
  17418. drain: null,
  17419. drained: true,
  17420. push: function (data, callback) {
  17421. if (!_isArray(data)) {
  17422. data = [data];
  17423. }
  17424. _each(data, function(task) {
  17425. tasks.push({
  17426. data: task,
  17427. callback: typeof callback === 'function' ? callback : null
  17428. });
  17429. cargo.drained = false;
  17430. if (cargo.saturated && tasks.length === payload) {
  17431. cargo.saturated();
  17432. }
  17433. });
  17434. async.setImmediate(cargo.process);
  17435. },
  17436. process: function process() {
  17437. if (working) return;
  17438. if (tasks.length === 0) {
  17439. if(cargo.drain && !cargo.drained) cargo.drain();
  17440. cargo.drained = true;
  17441. return;
  17442. }
  17443. var ts = typeof payload === 'number'
  17444. ? tasks.splice(0, payload)
  17445. : tasks.splice(0, tasks.length);
  17446. var ds = _map(ts, function (task) {
  17447. return task.data;
  17448. });
  17449. if(cargo.empty) cargo.empty();
  17450. working = true;
  17451. worker(ds, function () {
  17452. working = false;
  17453. var args = arguments;
  17454. _each(ts, function (data) {
  17455. if (data.callback) {
  17456. data.callback.apply(null, args);
  17457. }
  17458. });
  17459. process();
  17460. });
  17461. },
  17462. length: function () {
  17463. return tasks.length;
  17464. },
  17465. running: function () {
  17466. return working;
  17467. }
  17468. };
  17469. return cargo;
  17470. };
  17471. var _console_fn = function (name) {
  17472. return function (fn) {
  17473. var args = Array.prototype.slice.call(arguments, 1);
  17474. fn.apply(null, args.concat([function (err) {
  17475. var args = Array.prototype.slice.call(arguments, 1);
  17476. if (typeof console !== 'undefined') {
  17477. if (err) {
  17478. if (console.error) {
  17479. console.error(err);
  17480. }
  17481. }
  17482. else if (console[name]) {
  17483. _each(args, function (x) {
  17484. console[name](x);
  17485. });
  17486. }
  17487. }
  17488. }]));
  17489. };
  17490. };
  17491. async.log = _console_fn('log');
  17492. async.dir = _console_fn('dir');
  17493. /*async.info = _console_fn('info');
  17494. async.warn = _console_fn('warn');
  17495. async.error = _console_fn('error');*/
  17496. async.memoize = function (fn, hasher) {
  17497. var memo = {};
  17498. var queues = {};
  17499. hasher = hasher || function (x) {
  17500. return x;
  17501. };
  17502. var memoized = function () {
  17503. var args = Array.prototype.slice.call(arguments);
  17504. var callback = args.pop();
  17505. var key = hasher.apply(null, args);
  17506. if (key in memo) {
  17507. async.nextTick(function () {
  17508. callback.apply(null, memo[key]);
  17509. });
  17510. }
  17511. else if (key in queues) {
  17512. queues[key].push(callback);
  17513. }
  17514. else {
  17515. queues[key] = [callback];
  17516. fn.apply(null, args.concat([function () {
  17517. memo[key] = arguments;
  17518. var q = queues[key];
  17519. delete queues[key];
  17520. for (var i = 0, l = q.length; i < l; i++) {
  17521. q[i].apply(null, arguments);
  17522. }
  17523. }]));
  17524. }
  17525. };
  17526. memoized.memo = memo;
  17527. memoized.unmemoized = fn;
  17528. return memoized;
  17529. };
  17530. async.unmemoize = function (fn) {
  17531. return function () {
  17532. return (fn.unmemoized || fn).apply(null, arguments);
  17533. };
  17534. };
  17535. async.times = function (count, iterator, callback) {
  17536. var counter = [];
  17537. for (var i = 0; i < count; i++) {
  17538. counter.push(i);
  17539. }
  17540. return async.map(counter, iterator, callback);
  17541. };
  17542. async.timesSeries = function (count, iterator, callback) {
  17543. var counter = [];
  17544. for (var i = 0; i < count; i++) {
  17545. counter.push(i);
  17546. }
  17547. return async.mapSeries(counter, iterator, callback);
  17548. };
  17549. async.seq = function (/* functions... */) {
  17550. var fns = arguments;
  17551. return function () {
  17552. var that = this;
  17553. var args = Array.prototype.slice.call(arguments);
  17554. var callback = args.pop();
  17555. async.reduce(fns, args, function (newargs, fn, cb) {
  17556. fn.apply(that, newargs.concat([function () {
  17557. var err = arguments[0];
  17558. var nextargs = Array.prototype.slice.call(arguments, 1);
  17559. cb(err, nextargs);
  17560. }]))
  17561. },
  17562. function (err, results) {
  17563. callback.apply(that, [err].concat(results));
  17564. });
  17565. };
  17566. };
  17567. async.compose = function (/* functions... */) {
  17568. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17569. };
  17570. var _applyEach = function (eachfn, fns /*args...*/) {
  17571. var go = function () {
  17572. var that = this;
  17573. var args = Array.prototype.slice.call(arguments);
  17574. var callback = args.pop();
  17575. return eachfn(fns, function (fn, cb) {
  17576. fn.apply(that, args.concat([cb]));
  17577. },
  17578. callback);
  17579. };
  17580. if (arguments.length > 2) {
  17581. var args = Array.prototype.slice.call(arguments, 2);
  17582. return go.apply(this, args);
  17583. }
  17584. else {
  17585. return go;
  17586. }
  17587. };
  17588. async.applyEach = doParallel(_applyEach);
  17589. async.applyEachSeries = doSeries(_applyEach);
  17590. async.forever = function (fn, callback) {
  17591. function next(err) {
  17592. if (err) {
  17593. if (callback) {
  17594. return callback(err);
  17595. }
  17596. throw err;
  17597. }
  17598. fn(next);
  17599. }
  17600. next();
  17601. };
  17602. // Node.js
  17603. if (typeof module !== 'undefined' && module.exports) {
  17604. module.exports = async;
  17605. }
  17606. // AMD / RequireJS
  17607. else if (typeof define !== 'undefined' && define.amd) {
  17608. define([], function () {
  17609. return async;
  17610. });
  17611. }
  17612. // included directly via <script> tag
  17613. else {
  17614. root.async = async;
  17615. }
  17616. }());
  17617. }).call(this,require('_process'))
  17618. },{"_process":119}],69:[function(require,module,exports){
  17619. // i18next, v1.7.7
  17620. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17621. // Distributed under MIT license
  17622. // http://i18next.com
  17623. (function() {
  17624. // add indexOf to non ECMA-262 standard compliant browsers
  17625. if (!Array.prototype.indexOf) {
  17626. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17627. "use strict";
  17628. if (this == null) {
  17629. throw new TypeError();
  17630. }
  17631. var t = Object(this);
  17632. var len = t.length >>> 0;
  17633. if (len === 0) {
  17634. return -1;
  17635. }
  17636. var n = 0;
  17637. if (arguments.length > 0) {
  17638. n = Number(arguments[1]);
  17639. if (n != n) { // shortcut for verifying if it's NaN
  17640. n = 0;
  17641. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17642. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17643. }
  17644. }
  17645. if (n >= len) {
  17646. return -1;
  17647. }
  17648. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17649. for (; k < len; k++) {
  17650. if (k in t && t[k] === searchElement) {
  17651. return k;
  17652. }
  17653. }
  17654. return -1;
  17655. }
  17656. }
  17657. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17658. if (!Array.prototype.lastIndexOf) {
  17659. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17660. "use strict";
  17661. if (this == null) {
  17662. throw new TypeError();
  17663. }
  17664. var t = Object(this);
  17665. var len = t.length >>> 0;
  17666. if (len === 0) {
  17667. return -1;
  17668. }
  17669. var n = len;
  17670. if (arguments.length > 1) {
  17671. n = Number(arguments[1]);
  17672. if (n != n) {
  17673. n = 0;
  17674. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17675. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17676. }
  17677. }
  17678. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17679. for (; k >= 0; k--) {
  17680. if (k in t && t[k] === searchElement) {
  17681. return k;
  17682. }
  17683. }
  17684. return -1;
  17685. };
  17686. }
  17687. // Add string trim for IE8.
  17688. if (typeof String.prototype.trim !== 'function') {
  17689. String.prototype.trim = function() {
  17690. return this.replace(/^\s+|\s+$/g, '');
  17691. }
  17692. }
  17693. var root = this
  17694. , $ = root.jQuery || root.Zepto
  17695. , i18n = {}
  17696. , resStore = {}
  17697. , currentLng
  17698. , replacementCounter = 0
  17699. , languages = []
  17700. , initialized = false
  17701. , sync = {};
  17702. // Export the i18next object for **CommonJS**.
  17703. // If we're not in CommonJS, add `i18n` to the
  17704. // global object or to jquery.
  17705. if (typeof module !== 'undefined' && module.exports) {
  17706. if (!$) {
  17707. try {
  17708. $ = require('jquery');
  17709. } catch(e) {
  17710. // just ignore
  17711. }
  17712. }
  17713. if ($) {
  17714. $.i18n = $.i18n || i18n;
  17715. }
  17716. module.exports = i18n;
  17717. } else {
  17718. if ($) {
  17719. $.i18n = $.i18n || i18n;
  17720. }
  17721. root.i18n = root.i18n || i18n;
  17722. }
  17723. sync = {
  17724. load: function(lngs, options, cb) {
  17725. if (options.useLocalStorage) {
  17726. sync._loadLocal(lngs, options, function(err, store) {
  17727. var missingLngs = [];
  17728. for (var i = 0, len = lngs.length; i < len; i++) {
  17729. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17730. }
  17731. if (missingLngs.length > 0) {
  17732. sync._fetch(missingLngs, options, function(err, fetched) {
  17733. f.extend(store, fetched);
  17734. sync._storeLocal(fetched);
  17735. cb(null, store);
  17736. });
  17737. } else {
  17738. cb(null, store);
  17739. }
  17740. });
  17741. } else {
  17742. sync._fetch(lngs, options, function(err, store){
  17743. cb(null, store);
  17744. });
  17745. }
  17746. },
  17747. _loadLocal: function(lngs, options, cb) {
  17748. var store = {}
  17749. , nowMS = new Date().getTime();
  17750. if(window.localStorage) {
  17751. var todo = lngs.length;
  17752. f.each(lngs, function(key, lng) {
  17753. var local = window.localStorage.getItem('res_' + lng);
  17754. if (local) {
  17755. local = JSON.parse(local);
  17756. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17757. store[lng] = local;
  17758. }
  17759. }
  17760. todo--; // wait for all done befor callback
  17761. if (todo === 0) cb(null, store);
  17762. });
  17763. }
  17764. },
  17765. _storeLocal: function(store) {
  17766. if(window.localStorage) {
  17767. for (var m in store) {
  17768. store[m].i18nStamp = new Date().getTime();
  17769. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17770. }
  17771. }
  17772. return;
  17773. },
  17774. _fetch: function(lngs, options, cb) {
  17775. var ns = options.ns
  17776. , store = {};
  17777. if (!options.dynamicLoad) {
  17778. var todo = ns.namespaces.length * lngs.length
  17779. , errors;
  17780. // load each file individual
  17781. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17782. f.each(lngs, function(lngIndex, lngValue) {
  17783. // Call this once our translation has returned.
  17784. var loadComplete = function(err, data) {
  17785. if (err) {
  17786. errors = errors || [];
  17787. errors.push(err);
  17788. }
  17789. store[lngValue] = store[lngValue] || {};
  17790. store[lngValue][nsValue] = data;
  17791. todo--; // wait for all done befor callback
  17792. if (todo === 0) cb(errors, store);
  17793. };
  17794. if(typeof options.customLoad == 'function'){
  17795. // Use the specified custom callback.
  17796. options.customLoad(lngValue, nsValue, options, loadComplete);
  17797. } else {
  17798. //~ // Use our inbuilt sync.
  17799. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17800. }
  17801. });
  17802. });
  17803. } else {
  17804. // Call this once our translation has returned.
  17805. var loadComplete = function(err, data) {
  17806. cb(null, data);
  17807. };
  17808. if(typeof options.customLoad == 'function'){
  17809. // Use the specified custom callback.
  17810. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17811. } else {
  17812. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17813. // load all needed stuff once
  17814. f.ajax({
  17815. url: url,
  17816. success: function(data, status, xhr) {
  17817. f.log('loaded: ' + url);
  17818. loadComplete(null, data);
  17819. },
  17820. error : function(xhr, status, error) {
  17821. f.log('failed loading: ' + url);
  17822. loadComplete('failed loading resource.json error: ' + error);
  17823. },
  17824. dataType: "json",
  17825. async : options.getAsync
  17826. });
  17827. }
  17828. }
  17829. },
  17830. _fetchOne: function(lng, ns, options, done) {
  17831. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17832. f.ajax({
  17833. url: url,
  17834. success: function(data, status, xhr) {
  17835. f.log('loaded: ' + url);
  17836. done(null, data);
  17837. },
  17838. error : function(xhr, status, error) {
  17839. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17840. // file loaded but invalid json, stop waste time !
  17841. f.error('There is a typo in: ' + url);
  17842. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17843. f.log('Does not exist: ' + url);
  17844. } else {
  17845. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17846. f.log(theStatus + ' when loading ' + url);
  17847. }
  17848. done(error, {});
  17849. },
  17850. dataType: "json",
  17851. async : options.getAsync
  17852. });
  17853. },
  17854. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17855. var payload = {};
  17856. payload[key] = defaultValue;
  17857. var urls = [];
  17858. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17859. for (var i = 0; i < o.fallbackLng.length; i++) {
  17860. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17861. }
  17862. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17863. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17864. } else if (o.sendMissingTo === 'all') {
  17865. for (var i = 0, l = lngs.length; i < l; i++) {
  17866. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17867. }
  17868. }
  17869. for (var y = 0, len = urls.length; y < len; y++) {
  17870. var item = urls[y];
  17871. f.ajax({
  17872. url: item.url,
  17873. type: o.sendType,
  17874. data: payload,
  17875. success: function(data, status, xhr) {
  17876. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17877. // add key to resStore
  17878. var keys = key.split('.');
  17879. var x = 0;
  17880. var value = resStore[item.lng][ns];
  17881. while (keys[x]) {
  17882. if (x === keys.length - 1) {
  17883. value = value[keys[x]] = defaultValue;
  17884. } else {
  17885. value = value[keys[x]] = value[keys[x]] || {};
  17886. }
  17887. x++;
  17888. }
  17889. },
  17890. error : function(xhr, status, error) {
  17891. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17892. },
  17893. dataType: "json",
  17894. async : o.postAsync
  17895. });
  17896. }
  17897. },
  17898. reload: reload
  17899. };
  17900. // defaults
  17901. var o = {
  17902. lng: undefined,
  17903. load: 'all',
  17904. preload: [],
  17905. lowerCaseLng: false,
  17906. returnObjectTrees: false,
  17907. fallbackLng: ['dev'],
  17908. fallbackNS: [],
  17909. detectLngQS: 'setLng',
  17910. detectLngFromLocalStorage: false,
  17911. ns: 'translation',
  17912. fallbackOnNull: true,
  17913. fallbackOnEmpty: false,
  17914. fallbackToDefaultNS: false,
  17915. nsseparator: ':',
  17916. keyseparator: '.',
  17917. selectorAttr: 'data-i18n',
  17918. debug: false,
  17919. resGetPath: 'locales/__lng__/__ns__.json',
  17920. resPostPath: 'locales/add/__lng__/__ns__',
  17921. getAsync: true,
  17922. postAsync: true,
  17923. resStore: undefined,
  17924. useLocalStorage: false,
  17925. localStorageExpirationTime: 7*24*60*60*1000,
  17926. dynamicLoad: false,
  17927. sendMissing: false,
  17928. sendMissingTo: 'fallback', // current | all
  17929. sendType: 'POST',
  17930. interpolationPrefix: '__',
  17931. interpolationSuffix: '__',
  17932. defaultVariables: false,
  17933. reusePrefix: '$t(',
  17934. reuseSuffix: ')',
  17935. pluralSuffix: '_plural',
  17936. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17937. contextNotFound: ['context_not_found', Math.random()].join(''),
  17938. escapeInterpolation: false,
  17939. indefiniteSuffix: '_indefinite',
  17940. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17941. setJqueryExt: true,
  17942. defaultValueFromContent: true,
  17943. useDataAttrOptions: false,
  17944. cookieExpirationTime: undefined,
  17945. useCookie: true,
  17946. cookieName: 'i18next',
  17947. cookieDomain: undefined,
  17948. objectTreeKeyHandler: undefined,
  17949. postProcess: undefined,
  17950. parseMissingKey: undefined,
  17951. missingKeyHandler: sync.postMissing,
  17952. shortcutFunction: 'sprintf' // or: defaultValue
  17953. };
  17954. function _extend(target, source) {
  17955. if (!source || typeof source === 'function') {
  17956. return target;
  17957. }
  17958. for (var attr in source) { target[attr] = source[attr]; }
  17959. return target;
  17960. }
  17961. function _deepExtend(target, source) {
  17962. for (var prop in source)
  17963. if (prop in target)
  17964. _deepExtend(target[prop], source[prop]);
  17965. else
  17966. target[prop] = source[prop];
  17967. return target;
  17968. }
  17969. function _each(object, callback, args) {
  17970. var name, i = 0,
  17971. length = object.length,
  17972. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17973. if (args) {
  17974. if (isObj) {
  17975. for (name in object) {
  17976. if (callback.apply(object[name], args) === false) {
  17977. break;
  17978. }
  17979. }
  17980. } else {
  17981. for ( ; i < length; ) {
  17982. if (callback.apply(object[i++], args) === false) {
  17983. break;
  17984. }
  17985. }
  17986. }
  17987. // A special, fast, case for the most common use of each
  17988. } else {
  17989. if (isObj) {
  17990. for (name in object) {
  17991. if (callback.call(object[name], name, object[name]) === false) {
  17992. break;
  17993. }
  17994. }
  17995. } else {
  17996. for ( ; i < length; ) {
  17997. if (callback.call(object[i], i, object[i++]) === false) {
  17998. break;
  17999. }
  18000. }
  18001. }
  18002. }
  18003. return object;
  18004. }
  18005. var _entityMap = {
  18006. "&": "&amp;",
  18007. "<": "&lt;",
  18008. ">": "&gt;",
  18009. '"': '&quot;',
  18010. "'": '&#39;',
  18011. "/": '&#x2F;'
  18012. };
  18013. function _escape(data) {
  18014. if (typeof data === 'string') {
  18015. return data.replace(/[&<>"'\/]/g, function (s) {
  18016. return _entityMap[s];
  18017. });
  18018. }else{
  18019. return data;
  18020. }
  18021. }
  18022. function _ajax(options) {
  18023. // v0.5.0 of https://github.com/goloroden/http.js
  18024. var getXhr = function (callback) {
  18025. // Use the native XHR object if the browser supports it.
  18026. if (window.XMLHttpRequest) {
  18027. return callback(null, new XMLHttpRequest());
  18028. } else if (window.ActiveXObject) {
  18029. // In Internet Explorer check for ActiveX versions of the XHR object.
  18030. try {
  18031. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18032. } catch (e) {
  18033. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18034. }
  18035. }
  18036. // If no XHR support was found, throw an error.
  18037. return callback(new Error());
  18038. };
  18039. var encodeUsingUrlEncoding = function (data) {
  18040. if(typeof data === 'string') {
  18041. return data;
  18042. }
  18043. var result = [];
  18044. for(var dataItem in data) {
  18045. if(data.hasOwnProperty(dataItem)) {
  18046. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18047. }
  18048. }
  18049. return result.join('&');
  18050. };
  18051. var utf8 = function (text) {
  18052. text = text.replace(/\r\n/g, '\n');
  18053. var result = '';
  18054. for(var i = 0; i < text.length; i++) {
  18055. var c = text.charCodeAt(i);
  18056. if(c < 128) {
  18057. result += String.fromCharCode(c);
  18058. } else if((c > 127) && (c < 2048)) {
  18059. result += String.fromCharCode((c >> 6) | 192);
  18060. result += String.fromCharCode((c & 63) | 128);
  18061. } else {
  18062. result += String.fromCharCode((c >> 12) | 224);
  18063. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18064. result += String.fromCharCode((c & 63) | 128);
  18065. }
  18066. }
  18067. return result;
  18068. };
  18069. var base64 = function (text) {
  18070. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18071. text = utf8(text);
  18072. var result = '',
  18073. chr1, chr2, chr3,
  18074. enc1, enc2, enc3, enc4,
  18075. i = 0;
  18076. do {
  18077. chr1 = text.charCodeAt(i++);
  18078. chr2 = text.charCodeAt(i++);
  18079. chr3 = text.charCodeAt(i++);
  18080. enc1 = chr1 >> 2;
  18081. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18082. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18083. enc4 = chr3 & 63;
  18084. if(isNaN(chr2)) {
  18085. enc3 = enc4 = 64;
  18086. } else if(isNaN(chr3)) {
  18087. enc4 = 64;
  18088. }
  18089. result +=
  18090. keyStr.charAt(enc1) +
  18091. keyStr.charAt(enc2) +
  18092. keyStr.charAt(enc3) +
  18093. keyStr.charAt(enc4);
  18094. chr1 = chr2 = chr3 = '';
  18095. enc1 = enc2 = enc3 = enc4 = '';
  18096. } while(i < text.length);
  18097. return result;
  18098. };
  18099. var mergeHeaders = function () {
  18100. // Use the first header object as base.
  18101. var result = arguments[0];
  18102. // Iterate through the remaining header objects and add them.
  18103. for(var i = 1; i < arguments.length; i++) {
  18104. var currentHeaders = arguments[i];
  18105. for(var header in currentHeaders) {
  18106. if(currentHeaders.hasOwnProperty(header)) {
  18107. result[header] = currentHeaders[header];
  18108. }
  18109. }
  18110. }
  18111. // Return the merged headers.
  18112. return result;
  18113. };
  18114. var ajax = function (method, url, options, callback) {
  18115. // Adjust parameters.
  18116. if(typeof options === 'function') {
  18117. callback = options;
  18118. options = {};
  18119. }
  18120. // Set default parameter values.
  18121. options.cache = options.cache || false;
  18122. options.data = options.data || {};
  18123. options.headers = options.headers || {};
  18124. options.jsonp = options.jsonp || false;
  18125. options.async = options.async === undefined ? true : options.async;
  18126. // Merge the various header objects.
  18127. var headers = mergeHeaders({
  18128. 'accept': '*/*',
  18129. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18130. }, ajax.headers, options.headers);
  18131. // Encode the data according to the content-type.
  18132. var payload;
  18133. if (headers['content-type'] === 'application/json') {
  18134. payload = JSON.stringify(options.data);
  18135. } else {
  18136. payload = encodeUsingUrlEncoding(options.data);
  18137. }
  18138. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18139. // if neccessary.
  18140. if(method === 'GET') {
  18141. // Setup the query string.
  18142. var queryString = [];
  18143. if(payload) {
  18144. queryString.push(payload);
  18145. payload = null;
  18146. }
  18147. // Handle caching.
  18148. if(!options.cache) {
  18149. queryString.push('_=' + (new Date()).getTime());
  18150. }
  18151. // If neccessary prepare the query string for a JSONP call.
  18152. if(options.jsonp) {
  18153. queryString.push('callback=' + options.jsonp);
  18154. queryString.push('jsonp=' + options.jsonp);
  18155. }
  18156. // Merge the query string and attach it to the url.
  18157. queryString = queryString.join('&');
  18158. if (queryString.length > 1) {
  18159. if (url.indexOf('?') > -1) {
  18160. url += '&' + queryString;
  18161. } else {
  18162. url += '?' + queryString;
  18163. }
  18164. }
  18165. // Make a JSONP call if neccessary.
  18166. if(options.jsonp) {
  18167. var head = document.getElementsByTagName('head')[0];
  18168. var script = document.createElement('script');
  18169. script.type = 'text/javascript';
  18170. script.src = url;
  18171. head.appendChild(script);
  18172. return;
  18173. }
  18174. }
  18175. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18176. getXhr(function (err, xhr) {
  18177. if(err) return callback(err);
  18178. // Open the request.
  18179. xhr.open(method, url, options.async);
  18180. // Set the request headers.
  18181. for(var header in headers) {
  18182. if(headers.hasOwnProperty(header)) {
  18183. xhr.setRequestHeader(header, headers[header]);
  18184. }
  18185. }
  18186. // Handle the request events.
  18187. xhr.onreadystatechange = function () {
  18188. if(xhr.readyState === 4) {
  18189. var data = xhr.responseText || '';
  18190. // If no callback is given, return.
  18191. if(!callback) {
  18192. return;
  18193. }
  18194. // Return an object that provides access to the data as text and JSON.
  18195. callback(xhr.status, {
  18196. text: function () {
  18197. return data;
  18198. },
  18199. json: function () {
  18200. try {
  18201. return JSON.parse(data)
  18202. } catch (e) {
  18203. f.error('Can not parse JSON. URL: ' + url);
  18204. return {};
  18205. }
  18206. }
  18207. });
  18208. }
  18209. };
  18210. // Actually send the XHR request.
  18211. xhr.send(payload);
  18212. });
  18213. };
  18214. // Define the external interface.
  18215. var http = {
  18216. authBasic: function (username, password) {
  18217. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18218. },
  18219. connect: function (url, options, callback) {
  18220. return ajax('CONNECT', url, options, callback);
  18221. },
  18222. del: function (url, options, callback) {
  18223. return ajax('DELETE', url, options, callback);
  18224. },
  18225. get: function (url, options, callback) {
  18226. return ajax('GET', url, options, callback);
  18227. },
  18228. head: function (url, options, callback) {
  18229. return ajax('HEAD', url, options, callback);
  18230. },
  18231. headers: function (headers) {
  18232. ajax.headers = headers || {};
  18233. },
  18234. isAllowed: function (url, verb, callback) {
  18235. this.options(url, function (status, data) {
  18236. callback(data.text().indexOf(verb) !== -1);
  18237. });
  18238. },
  18239. options: function (url, options, callback) {
  18240. return ajax('OPTIONS', url, options, callback);
  18241. },
  18242. patch: function (url, options, callback) {
  18243. return ajax('PATCH', url, options, callback);
  18244. },
  18245. post: function (url, options, callback) {
  18246. return ajax('POST', url, options, callback);
  18247. },
  18248. put: function (url, options, callback) {
  18249. return ajax('PUT', url, options, callback);
  18250. },
  18251. trace: function (url, options, callback) {
  18252. return ajax('TRACE', url, options, callback);
  18253. }
  18254. };
  18255. var methode = options.type ? options.type.toLowerCase() : 'get';
  18256. http[methode](options.url, options, function (status, data) {
  18257. // file: protocol always gives status code 0, so check for data
  18258. if (status === 200 || (status === 0 && data.text())) {
  18259. options.success(data.json(), status, null);
  18260. } else {
  18261. options.error(data.text(), status, null);
  18262. }
  18263. });
  18264. }
  18265. var _cookie = {
  18266. create: function(name,value,minutes,domain) {
  18267. var expires;
  18268. if (minutes) {
  18269. var date = new Date();
  18270. date.setTime(date.getTime()+(minutes*60*1000));
  18271. expires = "; expires="+date.toGMTString();
  18272. }
  18273. else expires = "";
  18274. domain = (domain)? "domain="+domain+";" : "";
  18275. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18276. },
  18277. read: function(name) {
  18278. var nameEQ = name + "=";
  18279. var ca = document.cookie.split(';');
  18280. for(var i=0;i < ca.length;i++) {
  18281. var c = ca[i];
  18282. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18283. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18284. }
  18285. return null;
  18286. },
  18287. remove: function(name) {
  18288. this.create(name,"",-1);
  18289. }
  18290. };
  18291. var cookie_noop = {
  18292. create: function(name,value,minutes,domain) {},
  18293. read: function(name) { return null; },
  18294. remove: function(name) {}
  18295. };
  18296. // move dependent functions to a container so that
  18297. // they can be overriden easier in no jquery environment (node.js)
  18298. var f = {
  18299. extend: $ ? $.extend : _extend,
  18300. deepExtend: _deepExtend,
  18301. each: $ ? $.each : _each,
  18302. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18303. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18304. detectLanguage: detectLanguage,
  18305. escape: _escape,
  18306. log: function(str) {
  18307. if (o.debug && typeof console !== "undefined") console.log(str);
  18308. },
  18309. error: function(str) {
  18310. if (typeof console !== "undefined") console.error(str);
  18311. },
  18312. getCountyIndexOfLng: function(lng) {
  18313. var lng_index = 0;
  18314. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18315. return lng_index;
  18316. },
  18317. toLanguages: function(lng) {
  18318. var log = this.log;
  18319. function applyCase(l) {
  18320. var ret = l;
  18321. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18322. var parts = l.split('-');
  18323. ret = o.lowerCaseLng ?
  18324. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18325. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18326. } else {
  18327. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18328. }
  18329. return ret;
  18330. }
  18331. var languages = [];
  18332. var whitelist = o.lngWhitelist || false;
  18333. var addLanguage = function(language){
  18334. //reject langs not whitelisted
  18335. if(!whitelist || whitelist.indexOf(language) > -1){
  18336. languages.push(language);
  18337. }else{
  18338. log('rejecting non-whitelisted language: ' + language);
  18339. }
  18340. };
  18341. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18342. var parts = lng.split('-');
  18343. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18344. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18345. } else {
  18346. addLanguage(applyCase(lng));
  18347. }
  18348. for (var i = 0; i < o.fallbackLng.length; i++) {
  18349. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18350. }
  18351. return languages;
  18352. },
  18353. regexEscape: function(str) {
  18354. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18355. },
  18356. regexReplacementEscape: function(strOrFn) {
  18357. if (typeof strOrFn === 'string') {
  18358. return strOrFn.replace(/\$/g, "$$$$");
  18359. } else {
  18360. return strOrFn;
  18361. }
  18362. },
  18363. localStorage: {
  18364. setItem: function(key, value) {
  18365. if (window.localStorage) {
  18366. try {
  18367. window.localStorage.setItem(key, value);
  18368. } catch (e) {
  18369. f.log('failed to set value for key "' + key + '" to localStorage.');
  18370. }
  18371. }
  18372. }
  18373. }
  18374. };
  18375. function init(options, cb) {
  18376. if (typeof options === 'function') {
  18377. cb = options;
  18378. options = {};
  18379. }
  18380. options = options || {};
  18381. // override defaults with passed in options
  18382. f.extend(o, options);
  18383. delete o.fixLng; /* passed in each time */
  18384. // override functions: .log(), .detectLanguage(), etc
  18385. if (o.functions) {
  18386. delete o.functions;
  18387. f.extend(f, options.functions);
  18388. }
  18389. // create namespace object if namespace is passed in as string
  18390. if (typeof o.ns == 'string') {
  18391. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18392. }
  18393. // fallback namespaces
  18394. if (typeof o.fallbackNS == 'string') {
  18395. o.fallbackNS = [o.fallbackNS];
  18396. }
  18397. // fallback languages
  18398. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18399. o.fallbackLng = [o.fallbackLng];
  18400. }
  18401. // escape prefix/suffix
  18402. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18403. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18404. if (!o.lng) o.lng = f.detectLanguage();
  18405. languages = f.toLanguages(o.lng);
  18406. currentLng = languages[0];
  18407. f.log('currentLng set to: ' + currentLng);
  18408. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18409. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18410. }
  18411. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18412. f.localStorage.setItem('i18next_lng', currentLng);
  18413. }
  18414. var lngTranslate = translate;
  18415. if (options.fixLng) {
  18416. lngTranslate = function(key, options) {
  18417. options = options || {};
  18418. options.lng = options.lng || lngTranslate.lng;
  18419. return translate(key, options);
  18420. };
  18421. lngTranslate.lng = currentLng;
  18422. }
  18423. pluralExtensions.setCurrentLng(currentLng);
  18424. // add JQuery extensions
  18425. if ($ && o.setJqueryExt) addJqueryFunct();
  18426. // jQuery deferred
  18427. var deferred;
  18428. if ($ && $.Deferred) {
  18429. deferred = $.Deferred();
  18430. }
  18431. // return immidiatly if res are passed in
  18432. if (o.resStore) {
  18433. resStore = o.resStore;
  18434. initialized = true;
  18435. if (cb) cb(lngTranslate);
  18436. if (deferred) deferred.resolve(lngTranslate);
  18437. if (deferred) return deferred.promise();
  18438. return;
  18439. }
  18440. // languages to load
  18441. var lngsToLoad = f.toLanguages(o.lng);
  18442. if (typeof o.preload === 'string') o.preload = [o.preload];
  18443. for (var i = 0, l = o.preload.length; i < l; i++) {
  18444. var pres = f.toLanguages(o.preload[i]);
  18445. for (var y = 0, len = pres.length; y < len; y++) {
  18446. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18447. lngsToLoad.push(pres[y]);
  18448. }
  18449. }
  18450. }
  18451. // else load them
  18452. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18453. resStore = store;
  18454. initialized = true;
  18455. if (cb) cb(lngTranslate);
  18456. if (deferred) deferred.resolve(lngTranslate);
  18457. });
  18458. if (deferred) return deferred.promise();
  18459. }
  18460. function preload(lngs, cb) {
  18461. if (typeof lngs === 'string') lngs = [lngs];
  18462. for (var i = 0, l = lngs.length; i < l; i++) {
  18463. if (o.preload.indexOf(lngs[i]) < 0) {
  18464. o.preload.push(lngs[i]);
  18465. }
  18466. }
  18467. return init(cb);
  18468. }
  18469. function addResourceBundle(lng, ns, resources, deep) {
  18470. if (typeof ns !== 'string') {
  18471. resources = ns;
  18472. ns = o.ns.defaultNs;
  18473. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18474. o.ns.namespaces.push(ns);
  18475. }
  18476. resStore[lng] = resStore[lng] || {};
  18477. resStore[lng][ns] = resStore[lng][ns] || {};
  18478. if (deep) {
  18479. f.deepExtend(resStore[lng][ns], resources);
  18480. } else {
  18481. f.extend(resStore[lng][ns], resources);
  18482. }
  18483. }
  18484. function hasResourceBundle(lng, ns) {
  18485. if (typeof ns !== 'string') {
  18486. ns = o.ns.defaultNs;
  18487. }
  18488. resStore[lng] = resStore[lng] || {};
  18489. var res = resStore[lng][ns] || {};
  18490. var hasValues = false;
  18491. for(var prop in res) {
  18492. if (res.hasOwnProperty(prop)) {
  18493. hasValues = true;
  18494. }
  18495. }
  18496. return hasValues;
  18497. }
  18498. function removeResourceBundle(lng, ns) {
  18499. if (typeof ns !== 'string') {
  18500. ns = o.ns.defaultNs;
  18501. }
  18502. resStore[lng] = resStore[lng] || {};
  18503. resStore[lng][ns] = {};
  18504. }
  18505. function addResource(lng, ns, key, value) {
  18506. if (typeof ns !== 'string') {
  18507. resource = ns;
  18508. ns = o.ns.defaultNs;
  18509. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18510. o.ns.namespaces.push(ns);
  18511. }
  18512. resStore[lng] = resStore[lng] || {};
  18513. resStore[lng][ns] = resStore[lng][ns] || {};
  18514. var keys = key.split(o.keyseparator);
  18515. var x = 0;
  18516. var node = resStore[lng][ns];
  18517. var origRef = node;
  18518. while (keys[x]) {
  18519. if (x == keys.length - 1)
  18520. node[keys[x]] = value;
  18521. else {
  18522. if (node[keys[x]] == null)
  18523. node[keys[x]] = {};
  18524. node = node[keys[x]];
  18525. }
  18526. x++;
  18527. }
  18528. }
  18529. function addResources(lng, ns, resources) {
  18530. if (typeof ns !== 'string') {
  18531. resource = ns;
  18532. ns = o.ns.defaultNs;
  18533. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18534. o.ns.namespaces.push(ns);
  18535. }
  18536. for (var m in resources) {
  18537. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18538. }
  18539. }
  18540. function setDefaultNamespace(ns) {
  18541. o.ns.defaultNs = ns;
  18542. }
  18543. function loadNamespace(namespace, cb) {
  18544. loadNamespaces([namespace], cb);
  18545. }
  18546. function loadNamespaces(namespaces, cb) {
  18547. var opts = {
  18548. dynamicLoad: o.dynamicLoad,
  18549. resGetPath: o.resGetPath,
  18550. getAsync: o.getAsync,
  18551. customLoad: o.customLoad,
  18552. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18553. };
  18554. // languages to load
  18555. var lngsToLoad = f.toLanguages(o.lng);
  18556. if (typeof o.preload === 'string') o.preload = [o.preload];
  18557. for (var i = 0, l = o.preload.length; i < l; i++) {
  18558. var pres = f.toLanguages(o.preload[i]);
  18559. for (var y = 0, len = pres.length; y < len; y++) {
  18560. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18561. lngsToLoad.push(pres[y]);
  18562. }
  18563. }
  18564. }
  18565. // check if we have to load
  18566. var lngNeedLoad = [];
  18567. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18568. var needLoad = false;
  18569. var resSet = resStore[lngsToLoad[a]];
  18570. if (resSet) {
  18571. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18572. if (!resSet[namespaces[b]]) needLoad = true;
  18573. }
  18574. } else {
  18575. needLoad = true;
  18576. }
  18577. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18578. }
  18579. if (lngNeedLoad.length) {
  18580. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18581. var todo = namespaces.length * lngNeedLoad.length;
  18582. // load each file individual
  18583. f.each(namespaces, function(nsIndex, nsValue) {
  18584. // append namespace to namespace array
  18585. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18586. o.ns.namespaces.push(nsValue);
  18587. }
  18588. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18589. resStore[lngValue] = resStore[lngValue] || {};
  18590. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18591. todo--; // wait for all done befor callback
  18592. if (todo === 0 && cb) {
  18593. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18594. cb();
  18595. }
  18596. });
  18597. });
  18598. });
  18599. } else {
  18600. if (cb) cb();
  18601. }
  18602. }
  18603. function setLng(lng, options, cb) {
  18604. if (typeof options === 'function') {
  18605. cb = options;
  18606. options = {};
  18607. } else if (!options) {
  18608. options = {};
  18609. }
  18610. options.lng = lng;
  18611. return init(options, cb);
  18612. }
  18613. function lng() {
  18614. return currentLng;
  18615. }
  18616. function reload(cb) {
  18617. resStore = {};
  18618. setLng(currentLng, cb);
  18619. }
  18620. function addJqueryFunct() {
  18621. // $.t shortcut
  18622. $.t = $.t || translate;
  18623. function parse(ele, key, options) {
  18624. if (key.length === 0) return;
  18625. var attr = 'text';
  18626. if (key.indexOf('[') === 0) {
  18627. var parts = key.split(']');
  18628. key = parts[1];
  18629. attr = parts[0].substr(1, parts[0].length-1);
  18630. }
  18631. if (key.indexOf(';') === key.length-1) {
  18632. key = key.substr(0, key.length-2);
  18633. }
  18634. var optionsToUse;
  18635. if (attr === 'html') {
  18636. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18637. ele.html($.t(key, optionsToUse));
  18638. } else if (attr === 'text') {
  18639. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18640. ele.text($.t(key, optionsToUse));
  18641. } else if (attr === 'prepend') {
  18642. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18643. ele.prepend($.t(key, optionsToUse));
  18644. } else if (attr === 'append') {
  18645. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18646. ele.append($.t(key, optionsToUse));
  18647. } else if (attr.indexOf("data-") === 0) {
  18648. var dataAttr = attr.substr(("data-").length);
  18649. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18650. var translated = $.t(key, optionsToUse);
  18651. //we change into the data cache
  18652. ele.data(dataAttr, translated);
  18653. //we change into the dom
  18654. ele.attr(attr, translated);
  18655. } else {
  18656. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18657. ele.attr(attr, $.t(key, optionsToUse));
  18658. }
  18659. }
  18660. function localize(ele, options) {
  18661. var key = ele.attr(o.selectorAttr);
  18662. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18663. if (!key) return;
  18664. var target = ele
  18665. , targetSelector = ele.data("i18n-target");
  18666. if (targetSelector) {
  18667. target = ele.find(targetSelector) || ele;
  18668. }
  18669. if (!options && o.useDataAttrOptions === true) {
  18670. options = ele.data("i18n-options");
  18671. }
  18672. options = options || {};
  18673. if (key.indexOf(';') >= 0) {
  18674. var keys = key.split(';');
  18675. $.each(keys, function(m, k) {
  18676. if (k !== '') parse(target, k, options);
  18677. });
  18678. } else {
  18679. parse(target, key, options);
  18680. }
  18681. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18682. }
  18683. // fn
  18684. $.fn.i18n = function (options) {
  18685. return this.each(function() {
  18686. // localize element itself
  18687. localize($(this), options);
  18688. // localize childs
  18689. var elements = $(this).find('[' + o.selectorAttr + ']');
  18690. elements.each(function() {
  18691. localize($(this), options);
  18692. });
  18693. });
  18694. };
  18695. }
  18696. function applyReplacement(str, replacementHash, nestedKey, options) {
  18697. if (!str) return str;
  18698. options = options || replacementHash; // first call uses replacement hash combined with options
  18699. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18700. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18701. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18702. , unEscapingSuffix = 'HTML'+suffix;
  18703. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18704. f.each(hash, function(key, value) {
  18705. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18706. if (typeof value === 'object' && value !== null) {
  18707. str = applyReplacement(str, value, nextKey, options);
  18708. } else {
  18709. if (options.escapeInterpolation || o.escapeInterpolation) {
  18710. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18711. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18712. } else {
  18713. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18714. }
  18715. // str = options.escapeInterpolation;
  18716. }
  18717. });
  18718. return str;
  18719. }
  18720. // append it to functions
  18721. f.applyReplacement = applyReplacement;
  18722. function applyReuse(translated, options) {
  18723. var comma = ',';
  18724. var options_open = '{';
  18725. var options_close = '}';
  18726. var opts = f.extend({}, options);
  18727. delete opts.postProcess;
  18728. while (translated.indexOf(o.reusePrefix) != -1) {
  18729. replacementCounter++;
  18730. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18731. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18732. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18733. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18734. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18735. if (index_of_end_of_closing <= index_of_opening) {
  18736. f.error('there is an missing closing in following translation value', translated);
  18737. return '';
  18738. }
  18739. if (token_without_symbols.indexOf(comma) != -1) {
  18740. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18741. 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) {
  18742. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18743. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18744. try {
  18745. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18746. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18747. } catch (e) {
  18748. }
  18749. }
  18750. }
  18751. var translated_token = _translate(token_without_symbols, opts);
  18752. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18753. }
  18754. return translated;
  18755. }
  18756. function hasContext(options) {
  18757. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18758. }
  18759. function needsPlural(options, lng) {
  18760. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18761. }
  18762. function needsIndefiniteArticle(options) {
  18763. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18764. }
  18765. function exists(key, options) {
  18766. options = options || {};
  18767. var notFound = _getDefaultValue(key, options)
  18768. , found = _find(key, options);
  18769. return found !== undefined || found === notFound;
  18770. }
  18771. function translate(key, options) {
  18772. options = options || {};
  18773. if (!initialized) {
  18774. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18775. return options.defaultValue || '';
  18776. };
  18777. replacementCounter = 0;
  18778. return _translate.apply(null, arguments);
  18779. }
  18780. function _getDefaultValue(key, options) {
  18781. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18782. }
  18783. function _injectSprintfProcessor() {
  18784. var values = [];
  18785. // mh: build array from second argument onwards
  18786. for (var i = 1; i < arguments.length; i++) {
  18787. values.push(arguments[i]);
  18788. }
  18789. return {
  18790. postProcess: 'sprintf',
  18791. sprintf: values
  18792. };
  18793. }
  18794. function _translate(potentialKeys, options) {
  18795. if (options && typeof options !== 'object') {
  18796. if (o.shortcutFunction === 'sprintf') {
  18797. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18798. options = _injectSprintfProcessor.apply(null, arguments);
  18799. } else if (o.shortcutFunction === 'defaultValue') {
  18800. options = {
  18801. defaultValue: options
  18802. }
  18803. }
  18804. } else {
  18805. options = options || {};
  18806. }
  18807. if (typeof o.defaultVariables === 'object') {
  18808. options = f.extend({}, o.defaultVariables, options);
  18809. }
  18810. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18811. if (typeof potentialKeys === 'string') {
  18812. potentialKeys = [potentialKeys];
  18813. }
  18814. var key = potentialKeys[0];
  18815. if (potentialKeys.length > 1) {
  18816. for (var i = 0; i < potentialKeys.length; i++) {
  18817. key = potentialKeys[i];
  18818. if (exists(key, options)) {
  18819. break;
  18820. }
  18821. }
  18822. }
  18823. var notFound = _getDefaultValue(key, options)
  18824. , found = _find(key, options)
  18825. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18826. , ns = options.ns || o.ns.defaultNs
  18827. , parts;
  18828. // split ns and key
  18829. if (key.indexOf(o.nsseparator) > -1) {
  18830. parts = key.split(o.nsseparator);
  18831. ns = parts[0];
  18832. key = parts[1];
  18833. }
  18834. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18835. if (options.lng) {
  18836. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18837. } else {
  18838. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18839. }
  18840. }
  18841. var postProcessor = options.postProcess || o.postProcess;
  18842. if (found !== undefined && postProcessor) {
  18843. if (postProcessors[postProcessor]) {
  18844. found = postProcessors[postProcessor](found, key, options);
  18845. }
  18846. }
  18847. // process notFound if function exists
  18848. var splitNotFound = notFound;
  18849. if (notFound.indexOf(o.nsseparator) > -1) {
  18850. parts = notFound.split(o.nsseparator);
  18851. splitNotFound = parts[1];
  18852. }
  18853. if (splitNotFound === key && o.parseMissingKey) {
  18854. notFound = o.parseMissingKey(notFound);
  18855. }
  18856. if (found === undefined) {
  18857. notFound = applyReplacement(notFound, options);
  18858. notFound = applyReuse(notFound, options);
  18859. if (postProcessor && postProcessors[postProcessor]) {
  18860. var val = _getDefaultValue(key, options);
  18861. found = postProcessors[postProcessor](val, key, options);
  18862. }
  18863. }
  18864. return (found !== undefined) ? found : notFound;
  18865. }
  18866. function _find(key, options) {
  18867. options = options || {};
  18868. var optionWithoutCount, translated
  18869. , notFound = _getDefaultValue(key, options)
  18870. , lngs = languages;
  18871. if (!resStore) { return notFound; } // no resStore to translate from
  18872. // CI mode
  18873. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18874. // passed in lng
  18875. if (options.lngs) lngs = options.lngs;
  18876. if (options.lng) {
  18877. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18878. if (!resStore[lngs[0]]) {
  18879. var oldAsync = o.getAsync;
  18880. o.getAsync = false;
  18881. i18n.sync.load(lngs, o, function(err, store) {
  18882. f.extend(resStore, store);
  18883. o.getAsync = oldAsync;
  18884. });
  18885. }
  18886. }
  18887. var ns = options.ns || o.ns.defaultNs;
  18888. if (key.indexOf(o.nsseparator) > -1) {
  18889. var parts = key.split(o.nsseparator);
  18890. ns = parts[0];
  18891. key = parts[1];
  18892. }
  18893. if (hasContext(options)) {
  18894. optionWithoutCount = f.extend({}, options);
  18895. delete optionWithoutCount.context;
  18896. optionWithoutCount.defaultValue = o.contextNotFound;
  18897. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18898. translated = translate(contextKey, optionWithoutCount);
  18899. if (translated != o.contextNotFound) {
  18900. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18901. } // else continue translation with original/nonContext key
  18902. }
  18903. if (needsPlural(options, lngs[0])) {
  18904. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18905. delete optionWithoutCount.count;
  18906. delete optionWithoutCount.lng;
  18907. optionWithoutCount.defaultValue = o.pluralNotFound;
  18908. var pluralKey;
  18909. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18910. pluralKey = ns + o.nsseparator + key;
  18911. } else {
  18912. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18913. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18914. if (pluralExtension >= 0) {
  18915. pluralKey = pluralKey + '_' + pluralExtension;
  18916. } else if (pluralExtension === 1) {
  18917. pluralKey = ns + o.nsseparator + key; // singular
  18918. }
  18919. }
  18920. translated = translate(pluralKey, optionWithoutCount);
  18921. if (translated != o.pluralNotFound) {
  18922. return applyReplacement(translated, {
  18923. count: options.count,
  18924. interpolationPrefix: options.interpolationPrefix,
  18925. interpolationSuffix: options.interpolationSuffix
  18926. }); // apply replacement for count only
  18927. } else if (lngs.length > 1) {
  18928. // remove failed lng
  18929. var clone = lngs.slice();
  18930. clone.shift();
  18931. options = f.extend(options, { lngs: clone });
  18932. delete options.lng;
  18933. // retry with fallbacks
  18934. translated = translate(ns + o.nsseparator + key, options);
  18935. if (translated != o.pluralNotFound) return translated;
  18936. } else {
  18937. return translated;
  18938. }
  18939. }
  18940. if (needsIndefiniteArticle(options)) {
  18941. var optionsWithoutIndef = f.extend({}, options);
  18942. delete optionsWithoutIndef.indefinite_article;
  18943. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18944. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18945. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18946. translated = translate(indefiniteKey, optionsWithoutIndef);
  18947. if (translated != o.indefiniteNotFound) {
  18948. return translated;
  18949. }
  18950. }
  18951. var found;
  18952. var keys = key.split(o.keyseparator);
  18953. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18954. if (found !== undefined) break;
  18955. var l = lngs[i];
  18956. var x = 0;
  18957. var value = resStore[l] && resStore[l][ns];
  18958. while (keys[x]) {
  18959. value = value && value[keys[x]];
  18960. x++;
  18961. }
  18962. if (value !== undefined) {
  18963. var valueType = Object.prototype.toString.apply(value);
  18964. if (typeof value === 'string') {
  18965. value = applyReplacement(value, options);
  18966. value = applyReuse(value, options);
  18967. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18968. value = value.join('\n');
  18969. value = applyReplacement(value, options);
  18970. value = applyReuse(value, options);
  18971. } else if (value === null && o.fallbackOnNull === true) {
  18972. value = undefined;
  18973. } else if (value !== null) {
  18974. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18975. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18976. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18977. } else {
  18978. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18979. 'returned an object instead of string.';
  18980. f.log(value);
  18981. }
  18982. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18983. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18984. f.each(value, function(m) {
  18985. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18986. });
  18987. value = copy;
  18988. }
  18989. }
  18990. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18991. value = undefined;
  18992. found = value;
  18993. }
  18994. }
  18995. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18996. // set flag for fallback lookup - avoid recursion
  18997. options.isFallbackLookup = true;
  18998. if (o.fallbackNS.length) {
  18999. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19000. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19001. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19002. /* compare value without namespace */
  19003. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19004. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19005. if (foundValue !== notFoundValue) break;
  19006. }
  19007. }
  19008. } else {
  19009. found = _find(key, options); // fallback to default NS
  19010. }
  19011. options.isFallbackLookup = false;
  19012. }
  19013. return found;
  19014. }
  19015. function detectLanguage() {
  19016. var detectedLng;
  19017. var whitelist = o.lngWhitelist || [];
  19018. var userLngChoices = [];
  19019. // get from qs
  19020. var qsParm = [];
  19021. if (typeof window !== 'undefined') {
  19022. (function() {
  19023. var query = window.location.search.substring(1);
  19024. var params = query.split('&');
  19025. for (var i=0; i<params.length; i++) {
  19026. var pos = params[i].indexOf('=');
  19027. if (pos > 0) {
  19028. var key = params[i].substring(0,pos);
  19029. if (key == o.detectLngQS) {
  19030. userLngChoices.push(params[i].substring(pos+1));
  19031. }
  19032. }
  19033. }
  19034. })();
  19035. }
  19036. // get from cookie
  19037. if (o.useCookie && typeof document !== 'undefined') {
  19038. var c = f.cookie.read(o.cookieName);
  19039. if (c) userLngChoices.push(c);
  19040. }
  19041. // get from localStorage
  19042. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19043. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19044. }
  19045. // get from navigator
  19046. if (typeof navigator !== 'undefined') {
  19047. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19048. for (var i=0;i<navigator.languages.length;i++) {
  19049. userLngChoices.push(navigator.languages[i]);
  19050. }
  19051. }
  19052. if (navigator.userLanguage) {
  19053. userLngChoices.push(navigator.userLanguage);
  19054. }
  19055. if (navigator.language) {
  19056. userLngChoices.push(navigator.language);
  19057. }
  19058. }
  19059. (function() {
  19060. for (var i=0;i<userLngChoices.length;i++) {
  19061. var lng = userLngChoices[i];
  19062. if (lng.indexOf('-') > -1) {
  19063. var parts = lng.split('-');
  19064. lng = o.lowerCaseLng ?
  19065. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19066. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19067. }
  19068. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19069. detectedLng = lng;
  19070. break;
  19071. }
  19072. }
  19073. })();
  19074. //fallback
  19075. if (!detectedLng){
  19076. detectedLng = o.fallbackLng[0];
  19077. }
  19078. return detectedLng;
  19079. }
  19080. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19081. /* [code, name, numbers, pluralsType] */
  19082. var _rules = [
  19083. ["ach", "Acholi", [1,2], 1],
  19084. ["af", "Afrikaans",[1,2], 2],
  19085. ["ak", "Akan", [1,2], 1],
  19086. ["am", "Amharic", [1,2], 1],
  19087. ["an", "Aragonese",[1,2], 2],
  19088. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19089. ["arn", "Mapudungun",[1,2], 1],
  19090. ["ast", "Asturian", [1,2], 2],
  19091. ["ay", "Aymará", [1], 3],
  19092. ["az", "Azerbaijani",[1,2],2],
  19093. ["be", "Belarusian",[1,2,5],4],
  19094. ["bg", "Bulgarian",[1,2], 2],
  19095. ["bn", "Bengali", [1,2], 2],
  19096. ["bo", "Tibetan", [1], 3],
  19097. ["br", "Breton", [1,2], 1],
  19098. ["bs", "Bosnian", [1,2,5],4],
  19099. ["ca", "Catalan", [1,2], 2],
  19100. ["cgg", "Chiga", [1], 3],
  19101. ["cs", "Czech", [1,2,5],6],
  19102. ["csb", "Kashubian",[1,2,5],7],
  19103. ["cy", "Welsh", [1,2,3,8],8],
  19104. ["da", "Danish", [1,2], 2],
  19105. ["de", "German", [1,2], 2],
  19106. ["dev", "Development Fallback", [1,2], 2],
  19107. ["dz", "Dzongkha", [1], 3],
  19108. ["el", "Greek", [1,2], 2],
  19109. ["en", "English", [1,2], 2],
  19110. ["eo", "Esperanto",[1,2], 2],
  19111. ["es", "Spanish", [1,2], 2],
  19112. ["es_ar","Argentinean Spanish", [1,2], 2],
  19113. ["et", "Estonian", [1,2], 2],
  19114. ["eu", "Basque", [1,2], 2],
  19115. ["fa", "Persian", [1], 3],
  19116. ["fi", "Finnish", [1,2], 2],
  19117. ["fil", "Filipino", [1,2], 1],
  19118. ["fo", "Faroese", [1,2], 2],
  19119. ["fr", "French", [1,2], 9],
  19120. ["fur", "Friulian", [1,2], 2],
  19121. ["fy", "Frisian", [1,2], 2],
  19122. ["ga", "Irish", [1,2,3,7,11],10],
  19123. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19124. ["gl", "Galician", [1,2], 2],
  19125. ["gu", "Gujarati", [1,2], 2],
  19126. ["gun", "Gun", [1,2], 1],
  19127. ["ha", "Hausa", [1,2], 2],
  19128. ["he", "Hebrew", [1,2], 2],
  19129. ["hi", "Hindi", [1,2], 2],
  19130. ["hr", "Croatian", [1,2,5],4],
  19131. ["hu", "Hungarian",[1,2], 2],
  19132. ["hy", "Armenian", [1,2], 2],
  19133. ["ia", "Interlingua",[1,2],2],
  19134. ["id", "Indonesian",[1], 3],
  19135. ["is", "Icelandic",[1,2], 12],
  19136. ["it", "Italian", [1,2], 2],
  19137. ["ja", "Japanese", [1], 3],
  19138. ["jbo", "Lojban", [1], 3],
  19139. ["jv", "Javanese", [0,1], 13],
  19140. ["ka", "Georgian", [1], 3],
  19141. ["kk", "Kazakh", [1], 3],
  19142. ["km", "Khmer", [1], 3],
  19143. ["kn", "Kannada", [1,2], 2],
  19144. ["ko", "Korean", [1], 3],
  19145. ["ku", "Kurdish", [1,2], 2],
  19146. ["kw", "Cornish", [1,2,3,4],14],
  19147. ["ky", "Kyrgyz", [1], 3],
  19148. ["lb", "Letzeburgesch",[1,2],2],
  19149. ["ln", "Lingala", [1,2], 1],
  19150. ["lo", "Lao", [1], 3],
  19151. ["lt", "Lithuanian",[1,2,10],15],
  19152. ["lv", "Latvian", [1,2,0],16],
  19153. ["mai", "Maithili", [1,2], 2],
  19154. ["mfe", "Mauritian Creole",[1,2],1],
  19155. ["mg", "Malagasy", [1,2], 1],
  19156. ["mi", "Maori", [1,2], 1],
  19157. ["mk", "Macedonian",[1,2],17],
  19158. ["ml", "Malayalam",[1,2], 2],
  19159. ["mn", "Mongolian",[1,2], 2],
  19160. ["mnk", "Mandinka", [0,1,2],18],
  19161. ["mr", "Marathi", [1,2], 2],
  19162. ["ms", "Malay", [1], 3],
  19163. ["mt", "Maltese", [1,2,11,20],19],
  19164. ["nah", "Nahuatl", [1,2], 2],
  19165. ["nap", "Neapolitan",[1,2], 2],
  19166. ["nb", "Norwegian Bokmal",[1,2],2],
  19167. ["ne", "Nepali", [1,2], 2],
  19168. ["nl", "Dutch", [1,2], 2],
  19169. ["nn", "Norwegian Nynorsk",[1,2],2],
  19170. ["no", "Norwegian",[1,2], 2],
  19171. ["nso", "Northern Sotho",[1,2],2],
  19172. ["oc", "Occitan", [1,2], 1],
  19173. ["or", "Oriya", [2,1], 2],
  19174. ["pa", "Punjabi", [1,2], 2],
  19175. ["pap", "Papiamento",[1,2], 2],
  19176. ["pl", "Polish", [1,2,5],7],
  19177. ["pms", "Piemontese",[1,2], 2],
  19178. ["ps", "Pashto", [1,2], 2],
  19179. ["pt", "Portuguese",[1,2], 2],
  19180. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19181. ["rm", "Romansh", [1,2], 2],
  19182. ["ro", "Romanian", [1,2,20],20],
  19183. ["ru", "Russian", [1,2,5],4],
  19184. ["sah", "Yakut", [1], 3],
  19185. ["sco", "Scots", [1,2], 2],
  19186. ["se", "Northern Sami",[1,2], 2],
  19187. ["si", "Sinhala", [1,2], 2],
  19188. ["sk", "Slovak", [1,2,5],6],
  19189. ["sl", "Slovenian",[5,1,2,3],21],
  19190. ["so", "Somali", [1,2], 2],
  19191. ["son", "Songhay", [1,2], 2],
  19192. ["sq", "Albanian", [1,2], 2],
  19193. ["sr", "Serbian", [1,2,5],4],
  19194. ["su", "Sundanese",[1], 3],
  19195. ["sv", "Swedish", [1,2], 2],
  19196. ["sw", "Swahili", [1,2], 2],
  19197. ["ta", "Tamil", [1,2], 2],
  19198. ["te", "Telugu", [1,2], 2],
  19199. ["tg", "Tajik", [1,2], 1],
  19200. ["th", "Thai", [1], 3],
  19201. ["ti", "Tigrinya", [1,2], 1],
  19202. ["tk", "Turkmen", [1,2], 2],
  19203. ["tr", "Turkish", [1,2], 1],
  19204. ["tt", "Tatar", [1], 3],
  19205. ["ug", "Uyghur", [1], 3],
  19206. ["uk", "Ukrainian",[1,2,5],4],
  19207. ["ur", "Urdu", [1,2], 2],
  19208. ["uz", "Uzbek", [1,2], 1],
  19209. ["vi", "Vietnamese",[1], 3],
  19210. ["wa", "Walloon", [1,2], 1],
  19211. ["wo", "Wolof", [1], 3],
  19212. ["yo", "Yoruba", [1,2], 2],
  19213. ["zh", "Chinese", [1], 3]
  19214. ];
  19215. var _rulesPluralsTypes = {
  19216. 1: function(n) {return Number(n > 1);},
  19217. 2: function(n) {return Number(n != 1);},
  19218. 3: function(n) {return 0;},
  19219. 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);},
  19220. 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);},
  19221. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19222. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19223. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19224. 9: function(n) {return Number(n >= 2);},
  19225. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19226. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19227. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19228. 13: function(n) {return Number(n !== 0);},
  19229. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19230. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19231. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19232. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19233. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19234. 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);},
  19235. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19236. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19237. };
  19238. var pluralExtensions = {
  19239. rules: (function () {
  19240. var l, rules = {};
  19241. for (l=_rules.length; l-- ;) {
  19242. rules[_rules[l][0]] = {
  19243. name: _rules[l][1],
  19244. numbers: _rules[l][2],
  19245. plurals: _rulesPluralsTypes[_rules[l][3]]
  19246. }
  19247. }
  19248. return rules;
  19249. }()),
  19250. // you can add your own pluralExtensions
  19251. addRule: function(lng, obj) {
  19252. pluralExtensions.rules[lng] = obj;
  19253. },
  19254. setCurrentLng: function(lng) {
  19255. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19256. var parts = lng.split('-');
  19257. pluralExtensions.currentRule = {
  19258. lng: lng,
  19259. rule: pluralExtensions.rules[parts[0]]
  19260. };
  19261. }
  19262. },
  19263. needsPlural: function(lng, count) {
  19264. var parts = lng.split('-');
  19265. var ext;
  19266. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19267. ext = pluralExtensions.currentRule.rule;
  19268. } else {
  19269. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19270. }
  19271. if (ext && ext.numbers.length <= 1) {
  19272. return false;
  19273. } else {
  19274. return this.get(lng, count) !== 1;
  19275. }
  19276. },
  19277. get: function(lng, count) {
  19278. var parts = lng.split('-');
  19279. function getResult(l, c) {
  19280. var ext;
  19281. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19282. ext = pluralExtensions.currentRule.rule;
  19283. } else {
  19284. ext = pluralExtensions.rules[l];
  19285. }
  19286. if (ext) {
  19287. var i;
  19288. if (ext.noAbs) {
  19289. i = ext.plurals(c);
  19290. } else {
  19291. i = ext.plurals(Math.abs(c));
  19292. }
  19293. var number = ext.numbers[i];
  19294. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19295. if (number === 2) {
  19296. number = -1; // regular plural
  19297. } else if (number === 1) {
  19298. number = 1; // singular
  19299. }
  19300. }//console.log(count + '-' + number);
  19301. return number;
  19302. } else {
  19303. return c === 1 ? '1' : '-1';
  19304. }
  19305. }
  19306. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19307. }
  19308. };
  19309. var postProcessors = {};
  19310. var addPostProcessor = function(name, fc) {
  19311. postProcessors[name] = fc;
  19312. };
  19313. // sprintf support
  19314. var sprintf = (function() {
  19315. function get_type(variable) {
  19316. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19317. }
  19318. function str_repeat(input, multiplier) {
  19319. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19320. return output.join('');
  19321. }
  19322. var str_format = function() {
  19323. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19324. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19325. }
  19326. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19327. };
  19328. str_format.format = function(parse_tree, argv) {
  19329. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19330. for (i = 0; i < tree_length; i++) {
  19331. node_type = get_type(parse_tree[i]);
  19332. if (node_type === 'string') {
  19333. output.push(parse_tree[i]);
  19334. }
  19335. else if (node_type === 'array') {
  19336. match = parse_tree[i]; // convenience purposes only
  19337. if (match[2]) { // keyword argument
  19338. arg = argv[cursor];
  19339. for (k = 0; k < match[2].length; k++) {
  19340. if (!arg.hasOwnProperty(match[2][k])) {
  19341. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19342. }
  19343. arg = arg[match[2][k]];
  19344. }
  19345. }
  19346. else if (match[1]) { // positional argument (explicit)
  19347. arg = argv[match[1]];
  19348. }
  19349. else { // positional argument (implicit)
  19350. arg = argv[cursor++];
  19351. }
  19352. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19353. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19354. }
  19355. switch (match[8]) {
  19356. case 'b': arg = arg.toString(2); break;
  19357. case 'c': arg = String.fromCharCode(arg); break;
  19358. case 'd': arg = parseInt(arg, 10); break;
  19359. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19360. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19361. case 'o': arg = arg.toString(8); break;
  19362. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19363. case 'u': arg = Math.abs(arg); break;
  19364. case 'x': arg = arg.toString(16); break;
  19365. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19366. }
  19367. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19368. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19369. pad_length = match[6] - String(arg).length;
  19370. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19371. output.push(match[5] ? arg + pad : pad + arg);
  19372. }
  19373. }
  19374. return output.join('');
  19375. };
  19376. str_format.cache = {};
  19377. str_format.parse = function(fmt) {
  19378. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19379. while (_fmt) {
  19380. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19381. parse_tree.push(match[0]);
  19382. }
  19383. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19384. parse_tree.push('%');
  19385. }
  19386. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19387. if (match[2]) {
  19388. arg_names |= 1;
  19389. var field_list = [], replacement_field = match[2], field_match = [];
  19390. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19391. field_list.push(field_match[1]);
  19392. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19393. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19394. field_list.push(field_match[1]);
  19395. }
  19396. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19397. field_list.push(field_match[1]);
  19398. }
  19399. else {
  19400. throw('[sprintf] huh?');
  19401. }
  19402. }
  19403. }
  19404. else {
  19405. throw('[sprintf] huh?');
  19406. }
  19407. match[2] = field_list;
  19408. }
  19409. else {
  19410. arg_names |= 2;
  19411. }
  19412. if (arg_names === 3) {
  19413. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19414. }
  19415. parse_tree.push(match);
  19416. }
  19417. else {
  19418. throw('[sprintf] huh?');
  19419. }
  19420. _fmt = _fmt.substring(match[0].length);
  19421. }
  19422. return parse_tree;
  19423. };
  19424. return str_format;
  19425. })();
  19426. var vsprintf = function(fmt, argv) {
  19427. argv.unshift(fmt);
  19428. return sprintf.apply(null, argv);
  19429. };
  19430. addPostProcessor("sprintf", function(val, key, opts) {
  19431. if (!opts.sprintf) return val;
  19432. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19433. return vsprintf(val, opts.sprintf);
  19434. } else if (typeof opts.sprintf === 'object') {
  19435. return sprintf(val, opts.sprintf);
  19436. }
  19437. return val;
  19438. });
  19439. // public api interface
  19440. i18n.init = init;
  19441. i18n.setLng = setLng;
  19442. i18n.preload = preload;
  19443. i18n.addResourceBundle = addResourceBundle;
  19444. i18n.hasResourceBundle = hasResourceBundle;
  19445. i18n.addResource = addResource;
  19446. i18n.addResources = addResources;
  19447. i18n.removeResourceBundle = removeResourceBundle;
  19448. i18n.loadNamespace = loadNamespace;
  19449. i18n.loadNamespaces = loadNamespaces;
  19450. i18n.setDefaultNamespace = setDefaultNamespace;
  19451. i18n.t = translate;
  19452. i18n.translate = translate;
  19453. i18n.exists = exists;
  19454. i18n.detectLanguage = f.detectLanguage;
  19455. i18n.pluralExtensions = pluralExtensions;
  19456. i18n.sync = sync;
  19457. i18n.functions = f;
  19458. i18n.lng = lng;
  19459. i18n.addPostProcessor = addPostProcessor;
  19460. i18n.options = o;
  19461. })();
  19462. },{"jquery":"jquery"}],70:[function(require,module,exports){
  19463. // Top level file is just a mixin of submodules & constants
  19464. 'use strict';
  19465. var assign = require('./lib/utils/common').assign;
  19466. var deflate = require('./lib/deflate');
  19467. var inflate = require('./lib/inflate');
  19468. var constants = require('./lib/zlib/constants');
  19469. var pako = {};
  19470. assign(pako, deflate, inflate, constants);
  19471. module.exports = pako;
  19472. },{"./lib/deflate":71,"./lib/inflate":72,"./lib/utils/common":73,"./lib/zlib/constants":76}],71:[function(require,module,exports){
  19473. 'use strict';
  19474. var zlib_deflate = require('./zlib/deflate.js');
  19475. var utils = require('./utils/common');
  19476. var strings = require('./utils/strings');
  19477. var msg = require('./zlib/messages');
  19478. var zstream = require('./zlib/zstream');
  19479. var toString = Object.prototype.toString;
  19480. /* Public constants ==========================================================*/
  19481. /* ===========================================================================*/
  19482. var Z_NO_FLUSH = 0;
  19483. var Z_FINISH = 4;
  19484. var Z_OK = 0;
  19485. var Z_STREAM_END = 1;
  19486. var Z_SYNC_FLUSH = 2;
  19487. var Z_DEFAULT_COMPRESSION = -1;
  19488. var Z_DEFAULT_STRATEGY = 0;
  19489. var Z_DEFLATED = 8;
  19490. /* ===========================================================================*/
  19491. /**
  19492. * class Deflate
  19493. *
  19494. * Generic JS-style wrapper for zlib calls. If you don't need
  19495. * streaming behaviour - use more simple functions: [[deflate]],
  19496. * [[deflateRaw]] and [[gzip]].
  19497. **/
  19498. /* internal
  19499. * Deflate.chunks -> Array
  19500. *
  19501. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19502. **/
  19503. /**
  19504. * Deflate.result -> Uint8Array|Array
  19505. *
  19506. * Compressed result, generated by default [[Deflate#onData]]
  19507. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19508. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19509. * push a chunk with explicit flush (call [[Deflate#push]] with
  19510. * `Z_SYNC_FLUSH` param).
  19511. **/
  19512. /**
  19513. * Deflate.err -> Number
  19514. *
  19515. * Error code after deflate finished. 0 (Z_OK) on success.
  19516. * You will not need it in real life, because deflate errors
  19517. * are possible only on wrong options or bad `onData` / `onEnd`
  19518. * custom handlers.
  19519. **/
  19520. /**
  19521. * Deflate.msg -> String
  19522. *
  19523. * Error message, if [[Deflate.err]] != 0
  19524. **/
  19525. /**
  19526. * new Deflate(options)
  19527. * - options (Object): zlib deflate options.
  19528. *
  19529. * Creates new deflator instance with specified params. Throws exception
  19530. * on bad params. Supported options:
  19531. *
  19532. * - `level`
  19533. * - `windowBits`
  19534. * - `memLevel`
  19535. * - `strategy`
  19536. *
  19537. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19538. * for more information on these.
  19539. *
  19540. * Additional options, for internal needs:
  19541. *
  19542. * - `chunkSize` - size of generated data chunks (16K by default)
  19543. * - `raw` (Boolean) - do raw deflate
  19544. * - `gzip` (Boolean) - create gzip wrapper
  19545. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19546. * (each char code [0..255])
  19547. * - `header` (Object) - custom header for gzip
  19548. * - `text` (Boolean) - true if compressed data believed to be text
  19549. * - `time` (Number) - modification time, unix timestamp
  19550. * - `os` (Number) - operation system code
  19551. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19552. * - `name` (String) - file name (binary string)
  19553. * - `comment` (String) - comment (binary string)
  19554. * - `hcrc` (Boolean) - true if header crc should be added
  19555. *
  19556. * ##### Example:
  19557. *
  19558. * ```javascript
  19559. * var pako = require('pako')
  19560. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19561. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19562. *
  19563. * var deflate = new pako.Deflate({ level: 3});
  19564. *
  19565. * deflate.push(chunk1, false);
  19566. * deflate.push(chunk2, true); // true -> last chunk
  19567. *
  19568. * if (deflate.err) { throw new Error(deflate.err); }
  19569. *
  19570. * console.log(deflate.result);
  19571. * ```
  19572. **/
  19573. var Deflate = function(options) {
  19574. this.options = utils.assign({
  19575. level: Z_DEFAULT_COMPRESSION,
  19576. method: Z_DEFLATED,
  19577. chunkSize: 16384,
  19578. windowBits: 15,
  19579. memLevel: 8,
  19580. strategy: Z_DEFAULT_STRATEGY,
  19581. to: ''
  19582. }, options || {});
  19583. var opt = this.options;
  19584. if (opt.raw && (opt.windowBits > 0)) {
  19585. opt.windowBits = -opt.windowBits;
  19586. }
  19587. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19588. opt.windowBits += 16;
  19589. }
  19590. this.err = 0; // error code, if happens (0 = Z_OK)
  19591. this.msg = ''; // error message
  19592. this.ended = false; // used to avoid multiple onEnd() calls
  19593. this.chunks = []; // chunks of compressed data
  19594. this.strm = new zstream();
  19595. this.strm.avail_out = 0;
  19596. var status = zlib_deflate.deflateInit2(
  19597. this.strm,
  19598. opt.level,
  19599. opt.method,
  19600. opt.windowBits,
  19601. opt.memLevel,
  19602. opt.strategy
  19603. );
  19604. if (status !== Z_OK) {
  19605. throw new Error(msg[status]);
  19606. }
  19607. if (opt.header) {
  19608. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19609. }
  19610. };
  19611. /**
  19612. * Deflate#push(data[, mode]) -> Boolean
  19613. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19614. * converted to utf8 byte sequence.
  19615. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19616. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19617. *
  19618. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19619. * new compressed chunks. Returns `true` on success. The last data block must have
  19620. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19621. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19622. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19623. *
  19624. * On fail call [[Deflate#onEnd]] with error code and return false.
  19625. *
  19626. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19627. * array format is detected automatically). Also, don't skip last param and always
  19628. * use the same type in your code (boolean or number). That will improve JS speed.
  19629. *
  19630. * For regular `Array`-s make sure all elements are [0..255].
  19631. *
  19632. * ##### Example
  19633. *
  19634. * ```javascript
  19635. * push(chunk, false); // push one of data chunks
  19636. * ...
  19637. * push(chunk, true); // push last chunk
  19638. * ```
  19639. **/
  19640. Deflate.prototype.push = function(data, mode) {
  19641. var strm = this.strm;
  19642. var chunkSize = this.options.chunkSize;
  19643. var status, _mode;
  19644. if (this.ended) { return false; }
  19645. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19646. // Convert data if needed
  19647. if (typeof data === 'string') {
  19648. // If we need to compress text, change encoding to utf8.
  19649. strm.input = strings.string2buf(data);
  19650. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19651. strm.input = new Uint8Array(data);
  19652. } else {
  19653. strm.input = data;
  19654. }
  19655. strm.next_in = 0;
  19656. strm.avail_in = strm.input.length;
  19657. do {
  19658. if (strm.avail_out === 0) {
  19659. strm.output = new utils.Buf8(chunkSize);
  19660. strm.next_out = 0;
  19661. strm.avail_out = chunkSize;
  19662. }
  19663. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19664. if (status !== Z_STREAM_END && status !== Z_OK) {
  19665. this.onEnd(status);
  19666. this.ended = true;
  19667. return false;
  19668. }
  19669. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19670. if (this.options.to === 'string') {
  19671. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19672. } else {
  19673. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19674. }
  19675. }
  19676. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19677. // Finalize on the last chunk.
  19678. if (_mode === Z_FINISH) {
  19679. status = zlib_deflate.deflateEnd(this.strm);
  19680. this.onEnd(status);
  19681. this.ended = true;
  19682. return status === Z_OK;
  19683. }
  19684. // callback interim results if Z_SYNC_FLUSH.
  19685. if (_mode === Z_SYNC_FLUSH) {
  19686. this.onEnd(Z_OK);
  19687. strm.avail_out = 0;
  19688. return true;
  19689. }
  19690. return true;
  19691. };
  19692. /**
  19693. * Deflate#onData(chunk) -> Void
  19694. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19695. * on js engine support. When string output requested, each chunk
  19696. * will be string.
  19697. *
  19698. * By default, stores data blocks in `chunks[]` property and glue
  19699. * those in `onEnd`. Override this handler, if you need another behaviour.
  19700. **/
  19701. Deflate.prototype.onData = function(chunk) {
  19702. this.chunks.push(chunk);
  19703. };
  19704. /**
  19705. * Deflate#onEnd(status) -> Void
  19706. * - status (Number): deflate status. 0 (Z_OK) on success,
  19707. * other if not.
  19708. *
  19709. * Called once after you tell deflate that the input stream is
  19710. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19711. * or if an error happened. By default - join collected chunks,
  19712. * free memory and fill `results` / `err` properties.
  19713. **/
  19714. Deflate.prototype.onEnd = function(status) {
  19715. // On success - join
  19716. if (status === Z_OK) {
  19717. if (this.options.to === 'string') {
  19718. this.result = this.chunks.join('');
  19719. } else {
  19720. this.result = utils.flattenChunks(this.chunks);
  19721. }
  19722. }
  19723. this.chunks = [];
  19724. this.err = status;
  19725. this.msg = this.strm.msg;
  19726. };
  19727. /**
  19728. * deflate(data[, options]) -> Uint8Array|Array|String
  19729. * - data (Uint8Array|Array|String): input data to compress.
  19730. * - options (Object): zlib deflate options.
  19731. *
  19732. * Compress `data` with deflate alrorythm and `options`.
  19733. *
  19734. * Supported options are:
  19735. *
  19736. * - level
  19737. * - windowBits
  19738. * - memLevel
  19739. * - strategy
  19740. *
  19741. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19742. * for more information on these.
  19743. *
  19744. * Sugar (options):
  19745. *
  19746. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19747. * negative windowBits implicitly.
  19748. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19749. * (each char code [0..255])
  19750. *
  19751. * ##### Example:
  19752. *
  19753. * ```javascript
  19754. * var pako = require('pako')
  19755. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19756. *
  19757. * console.log(pako.deflate(data));
  19758. * ```
  19759. **/
  19760. function deflate(input, options) {
  19761. var deflator = new Deflate(options);
  19762. deflator.push(input, true);
  19763. // That will never happens, if you don't cheat with options :)
  19764. if (deflator.err) { throw deflator.msg; }
  19765. return deflator.result;
  19766. }
  19767. /**
  19768. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19769. * - data (Uint8Array|Array|String): input data to compress.
  19770. * - options (Object): zlib deflate options.
  19771. *
  19772. * The same as [[deflate]], but creates raw data, without wrapper
  19773. * (header and adler32 crc).
  19774. **/
  19775. function deflateRaw(input, options) {
  19776. options = options || {};
  19777. options.raw = true;
  19778. return deflate(input, options);
  19779. }
  19780. /**
  19781. * gzip(data[, options]) -> Uint8Array|Array|String
  19782. * - data (Uint8Array|Array|String): input data to compress.
  19783. * - options (Object): zlib deflate options.
  19784. *
  19785. * The same as [[deflate]], but create gzip wrapper instead of
  19786. * deflate one.
  19787. **/
  19788. function gzip(input, options) {
  19789. options = options || {};
  19790. options.gzip = true;
  19791. return deflate(input, options);
  19792. }
  19793. exports.Deflate = Deflate;
  19794. exports.deflate = deflate;
  19795. exports.deflateRaw = deflateRaw;
  19796. exports.gzip = gzip;
  19797. },{"./utils/common":73,"./utils/strings":74,"./zlib/deflate.js":78,"./zlib/messages":83,"./zlib/zstream":85}],72:[function(require,module,exports){
  19798. 'use strict';
  19799. var zlib_inflate = require('./zlib/inflate.js');
  19800. var utils = require('./utils/common');
  19801. var strings = require('./utils/strings');
  19802. var c = require('./zlib/constants');
  19803. var msg = require('./zlib/messages');
  19804. var zstream = require('./zlib/zstream');
  19805. var gzheader = require('./zlib/gzheader');
  19806. var toString = Object.prototype.toString;
  19807. /**
  19808. * class Inflate
  19809. *
  19810. * Generic JS-style wrapper for zlib calls. If you don't need
  19811. * streaming behaviour - use more simple functions: [[inflate]]
  19812. * and [[inflateRaw]].
  19813. **/
  19814. /* internal
  19815. * inflate.chunks -> Array
  19816. *
  19817. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19818. **/
  19819. /**
  19820. * Inflate.result -> Uint8Array|Array|String
  19821. *
  19822. * Uncompressed result, generated by default [[Inflate#onData]]
  19823. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19824. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19825. * push a chunk with explicit flush (call [[Inflate#push]] with
  19826. * `Z_SYNC_FLUSH` param).
  19827. **/
  19828. /**
  19829. * Inflate.err -> Number
  19830. *
  19831. * Error code after inflate finished. 0 (Z_OK) on success.
  19832. * Should be checked if broken data possible.
  19833. **/
  19834. /**
  19835. * Inflate.msg -> String
  19836. *
  19837. * Error message, if [[Inflate.err]] != 0
  19838. **/
  19839. /**
  19840. * new Inflate(options)
  19841. * - options (Object): zlib inflate options.
  19842. *
  19843. * Creates new inflator instance with specified params. Throws exception
  19844. * on bad params. Supported options:
  19845. *
  19846. * - `windowBits`
  19847. *
  19848. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19849. * for more information on these.
  19850. *
  19851. * Additional options, for internal needs:
  19852. *
  19853. * - `chunkSize` - size of generated data chunks (16K by default)
  19854. * - `raw` (Boolean) - do raw inflate
  19855. * - `to` (String) - if equal to 'string', then result will be converted
  19856. * from utf8 to utf16 (javascript) string. When string output requested,
  19857. * chunk length can differ from `chunkSize`, depending on content.
  19858. *
  19859. * By default, when no options set, autodetect deflate/gzip data format via
  19860. * wrapper header.
  19861. *
  19862. * ##### Example:
  19863. *
  19864. * ```javascript
  19865. * var pako = require('pako')
  19866. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19867. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19868. *
  19869. * var inflate = new pako.Inflate({ level: 3});
  19870. *
  19871. * inflate.push(chunk1, false);
  19872. * inflate.push(chunk2, true); // true -> last chunk
  19873. *
  19874. * if (inflate.err) { throw new Error(inflate.err); }
  19875. *
  19876. * console.log(inflate.result);
  19877. * ```
  19878. **/
  19879. var Inflate = function(options) {
  19880. this.options = utils.assign({
  19881. chunkSize: 16384,
  19882. windowBits: 0,
  19883. to: ''
  19884. }, options || {});
  19885. var opt = this.options;
  19886. // Force window size for `raw` data, if not set directly,
  19887. // because we have no header for autodetect.
  19888. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19889. opt.windowBits = -opt.windowBits;
  19890. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19891. }
  19892. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19893. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19894. !(options && options.windowBits)) {
  19895. opt.windowBits += 32;
  19896. }
  19897. // Gzip header has no info about windows size, we can do autodetect only
  19898. // for deflate. So, if window size not set, force it to max when gzip possible
  19899. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19900. // bit 3 (16) -> gzipped data
  19901. // bit 4 (32) -> autodetect gzip/deflate
  19902. if ((opt.windowBits & 15) === 0) {
  19903. opt.windowBits |= 15;
  19904. }
  19905. }
  19906. this.err = 0; // error code, if happens (0 = Z_OK)
  19907. this.msg = ''; // error message
  19908. this.ended = false; // used to avoid multiple onEnd() calls
  19909. this.chunks = []; // chunks of compressed data
  19910. this.strm = new zstream();
  19911. this.strm.avail_out = 0;
  19912. var status = zlib_inflate.inflateInit2(
  19913. this.strm,
  19914. opt.windowBits
  19915. );
  19916. if (status !== c.Z_OK) {
  19917. throw new Error(msg[status]);
  19918. }
  19919. this.header = new gzheader();
  19920. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19921. };
  19922. /**
  19923. * Inflate#push(data[, mode]) -> Boolean
  19924. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19925. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19926. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19927. *
  19928. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19929. * new output chunks. Returns `true` on success. The last data block must have
  19930. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19931. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19932. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  19933. *
  19934. * On fail call [[Inflate#onEnd]] with error code and return false.
  19935. *
  19936. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19937. * format is detected automatically). Also, don't skip last param and always
  19938. * use the same type in your code (boolean or number). That will improve JS speed.
  19939. *
  19940. * For regular `Array`-s make sure all elements are [0..255].
  19941. *
  19942. * ##### Example
  19943. *
  19944. * ```javascript
  19945. * push(chunk, false); // push one of data chunks
  19946. * ...
  19947. * push(chunk, true); // push last chunk
  19948. * ```
  19949. **/
  19950. Inflate.prototype.push = function(data, mode) {
  19951. var strm = this.strm;
  19952. var chunkSize = this.options.chunkSize;
  19953. var status, _mode;
  19954. var next_out_utf8, tail, utf8str;
  19955. if (this.ended) { return false; }
  19956. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19957. // Convert data if needed
  19958. if (typeof data === 'string') {
  19959. // Only binary strings can be decompressed on practice
  19960. strm.input = strings.binstring2buf(data);
  19961. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19962. strm.input = new Uint8Array(data);
  19963. } else {
  19964. strm.input = data;
  19965. }
  19966. strm.next_in = 0;
  19967. strm.avail_in = strm.input.length;
  19968. do {
  19969. if (strm.avail_out === 0) {
  19970. strm.output = new utils.Buf8(chunkSize);
  19971. strm.next_out = 0;
  19972. strm.avail_out = chunkSize;
  19973. }
  19974. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19975. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19976. this.onEnd(status);
  19977. this.ended = true;
  19978. return false;
  19979. }
  19980. if (strm.next_out) {
  19981. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  19982. if (this.options.to === 'string') {
  19983. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19984. tail = strm.next_out - next_out_utf8;
  19985. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19986. // move tail
  19987. strm.next_out = tail;
  19988. strm.avail_out = chunkSize - tail;
  19989. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19990. this.onData(utf8str);
  19991. } else {
  19992. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19993. }
  19994. }
  19995. }
  19996. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19997. if (status === c.Z_STREAM_END) {
  19998. _mode = c.Z_FINISH;
  19999. }
  20000. // Finalize on the last chunk.
  20001. if (_mode === c.Z_FINISH) {
  20002. status = zlib_inflate.inflateEnd(this.strm);
  20003. this.onEnd(status);
  20004. this.ended = true;
  20005. return status === c.Z_OK;
  20006. }
  20007. // callback interim results if Z_SYNC_FLUSH.
  20008. if (_mode === c.Z_SYNC_FLUSH) {
  20009. this.onEnd(c.Z_OK);
  20010. strm.avail_out = 0;
  20011. return true;
  20012. }
  20013. return true;
  20014. };
  20015. /**
  20016. * Inflate#onData(chunk) -> Void
  20017. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20018. * on js engine support. When string output requested, each chunk
  20019. * will be string.
  20020. *
  20021. * By default, stores data blocks in `chunks[]` property and glue
  20022. * those in `onEnd`. Override this handler, if you need another behaviour.
  20023. **/
  20024. Inflate.prototype.onData = function(chunk) {
  20025. this.chunks.push(chunk);
  20026. };
  20027. /**
  20028. * Inflate#onEnd(status) -> Void
  20029. * - status (Number): inflate status. 0 (Z_OK) on success,
  20030. * other if not.
  20031. *
  20032. * Called either after you tell inflate that the input stream is
  20033. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20034. * or if an error happened. By default - join collected chunks,
  20035. * free memory and fill `results` / `err` properties.
  20036. **/
  20037. Inflate.prototype.onEnd = function(status) {
  20038. // On success - join
  20039. if (status === c.Z_OK) {
  20040. if (this.options.to === 'string') {
  20041. // Glue & convert here, until we teach pako to send
  20042. // utf8 alligned strings to onData
  20043. this.result = this.chunks.join('');
  20044. } else {
  20045. this.result = utils.flattenChunks(this.chunks);
  20046. }
  20047. }
  20048. this.chunks = [];
  20049. this.err = status;
  20050. this.msg = this.strm.msg;
  20051. };
  20052. /**
  20053. * inflate(data[, options]) -> Uint8Array|Array|String
  20054. * - data (Uint8Array|Array|String): input data to decompress.
  20055. * - options (Object): zlib inflate options.
  20056. *
  20057. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20058. * format via wrapper header by default. That's why we don't provide
  20059. * separate `ungzip` method.
  20060. *
  20061. * Supported options are:
  20062. *
  20063. * - windowBits
  20064. *
  20065. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20066. * for more information.
  20067. *
  20068. * Sugar (options):
  20069. *
  20070. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20071. * negative windowBits implicitly.
  20072. * - `to` (String) - if equal to 'string', then result will be converted
  20073. * from utf8 to utf16 (javascript) string. When string output requested,
  20074. * chunk length can differ from `chunkSize`, depending on content.
  20075. *
  20076. *
  20077. * ##### Example:
  20078. *
  20079. * ```javascript
  20080. * var pako = require('pako')
  20081. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20082. * , output;
  20083. *
  20084. * try {
  20085. * output = pako.inflate(input);
  20086. * } catch (err)
  20087. * console.log(err);
  20088. * }
  20089. * ```
  20090. **/
  20091. function inflate(input, options) {
  20092. var inflator = new Inflate(options);
  20093. inflator.push(input, true);
  20094. // That will never happens, if you don't cheat with options :)
  20095. if (inflator.err) { throw inflator.msg; }
  20096. return inflator.result;
  20097. }
  20098. /**
  20099. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20100. * - data (Uint8Array|Array|String): input data to decompress.
  20101. * - options (Object): zlib inflate options.
  20102. *
  20103. * The same as [[inflate]], but creates raw data, without wrapper
  20104. * (header and adler32 crc).
  20105. **/
  20106. function inflateRaw(input, options) {
  20107. options = options || {};
  20108. options.raw = true;
  20109. return inflate(input, options);
  20110. }
  20111. /**
  20112. * ungzip(data[, options]) -> Uint8Array|Array|String
  20113. * - data (Uint8Array|Array|String): input data to decompress.
  20114. * - options (Object): zlib inflate options.
  20115. *
  20116. * Just shortcut to [[inflate]], because it autodetects format
  20117. * by header.content. Done for convenience.
  20118. **/
  20119. exports.Inflate = Inflate;
  20120. exports.inflate = inflate;
  20121. exports.inflateRaw = inflateRaw;
  20122. exports.ungzip = inflate;
  20123. },{"./utils/common":73,"./utils/strings":74,"./zlib/constants":76,"./zlib/gzheader":79,"./zlib/inflate.js":81,"./zlib/messages":83,"./zlib/zstream":85}],73:[function(require,module,exports){
  20124. 'use strict';
  20125. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20126. (typeof Uint16Array !== 'undefined') &&
  20127. (typeof Int32Array !== 'undefined');
  20128. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20129. var sources = Array.prototype.slice.call(arguments, 1);
  20130. while (sources.length) {
  20131. var source = sources.shift();
  20132. if (!source) { continue; }
  20133. if (typeof source !== 'object') {
  20134. throw new TypeError(source + 'must be non-object');
  20135. }
  20136. for (var p in source) {
  20137. if (source.hasOwnProperty(p)) {
  20138. obj[p] = source[p];
  20139. }
  20140. }
  20141. }
  20142. return obj;
  20143. };
  20144. // reduce buffer size, avoiding mem copy
  20145. exports.shrinkBuf = function (buf, size) {
  20146. if (buf.length === size) { return buf; }
  20147. if (buf.subarray) { return buf.subarray(0, size); }
  20148. buf.length = size;
  20149. return buf;
  20150. };
  20151. var fnTyped = {
  20152. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20153. if (src.subarray && dest.subarray) {
  20154. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20155. return;
  20156. }
  20157. // Fallback to ordinary array
  20158. for (var i=0; i<len; i++) {
  20159. dest[dest_offs + i] = src[src_offs + i];
  20160. }
  20161. },
  20162. // Join array of chunks to single array.
  20163. flattenChunks: function(chunks) {
  20164. var i, l, len, pos, chunk, result;
  20165. // calculate data length
  20166. len = 0;
  20167. for (i=0, l=chunks.length; i<l; i++) {
  20168. len += chunks[i].length;
  20169. }
  20170. // join chunks
  20171. result = new Uint8Array(len);
  20172. pos = 0;
  20173. for (i=0, l=chunks.length; i<l; i++) {
  20174. chunk = chunks[i];
  20175. result.set(chunk, pos);
  20176. pos += chunk.length;
  20177. }
  20178. return result;
  20179. }
  20180. };
  20181. var fnUntyped = {
  20182. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20183. for (var i=0; i<len; i++) {
  20184. dest[dest_offs + i] = src[src_offs + i];
  20185. }
  20186. },
  20187. // Join array of chunks to single array.
  20188. flattenChunks: function(chunks) {
  20189. return [].concat.apply([], chunks);
  20190. }
  20191. };
  20192. // Enable/Disable typed arrays use, for testing
  20193. //
  20194. exports.setTyped = function (on) {
  20195. if (on) {
  20196. exports.Buf8 = Uint8Array;
  20197. exports.Buf16 = Uint16Array;
  20198. exports.Buf32 = Int32Array;
  20199. exports.assign(exports, fnTyped);
  20200. } else {
  20201. exports.Buf8 = Array;
  20202. exports.Buf16 = Array;
  20203. exports.Buf32 = Array;
  20204. exports.assign(exports, fnUntyped);
  20205. }
  20206. };
  20207. exports.setTyped(TYPED_OK);
  20208. },{}],74:[function(require,module,exports){
  20209. // String encode/decode helpers
  20210. 'use strict';
  20211. var utils = require('./common');
  20212. // Quick check if we can use fast array to bin string conversion
  20213. //
  20214. // - apply(Array) can fail on Android 2.2
  20215. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20216. //
  20217. var STR_APPLY_OK = true;
  20218. var STR_APPLY_UIA_OK = true;
  20219. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20220. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20221. // Table with utf8 lengths (calculated by first byte of sequence)
  20222. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20223. // because max possible codepoint is 0x10ffff
  20224. var _utf8len = new utils.Buf8(256);
  20225. for (var q=0; q<256; q++) {
  20226. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20227. }
  20228. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20229. // convert string to array (typed, when possible)
  20230. exports.string2buf = function (str) {
  20231. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20232. // count binary size
  20233. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20234. c = str.charCodeAt(m_pos);
  20235. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20236. c2 = str.charCodeAt(m_pos+1);
  20237. if ((c2 & 0xfc00) === 0xdc00) {
  20238. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20239. m_pos++;
  20240. }
  20241. }
  20242. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20243. }
  20244. // allocate buffer
  20245. buf = new utils.Buf8(buf_len);
  20246. // convert
  20247. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20248. c = str.charCodeAt(m_pos);
  20249. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20250. c2 = str.charCodeAt(m_pos+1);
  20251. if ((c2 & 0xfc00) === 0xdc00) {
  20252. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20253. m_pos++;
  20254. }
  20255. }
  20256. if (c < 0x80) {
  20257. /* one byte */
  20258. buf[i++] = c;
  20259. } else if (c < 0x800) {
  20260. /* two bytes */
  20261. buf[i++] = 0xC0 | (c >>> 6);
  20262. buf[i++] = 0x80 | (c & 0x3f);
  20263. } else if (c < 0x10000) {
  20264. /* three bytes */
  20265. buf[i++] = 0xE0 | (c >>> 12);
  20266. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20267. buf[i++] = 0x80 | (c & 0x3f);
  20268. } else {
  20269. /* four bytes */
  20270. buf[i++] = 0xf0 | (c >>> 18);
  20271. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20272. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20273. buf[i++] = 0x80 | (c & 0x3f);
  20274. }
  20275. }
  20276. return buf;
  20277. };
  20278. // Helper (used in 2 places)
  20279. function buf2binstring(buf, len) {
  20280. // use fallback for big arrays to avoid stack overflow
  20281. if (len < 65537) {
  20282. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20283. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20284. }
  20285. }
  20286. var result = '';
  20287. for (var i=0; i < len; i++) {
  20288. result += String.fromCharCode(buf[i]);
  20289. }
  20290. return result;
  20291. }
  20292. // Convert byte array to binary string
  20293. exports.buf2binstring = function(buf) {
  20294. return buf2binstring(buf, buf.length);
  20295. };
  20296. // Convert binary string (typed, when possible)
  20297. exports.binstring2buf = function(str) {
  20298. var buf = new utils.Buf8(str.length);
  20299. for (var i=0, len=buf.length; i < len; i++) {
  20300. buf[i] = str.charCodeAt(i);
  20301. }
  20302. return buf;
  20303. };
  20304. // convert array to string
  20305. exports.buf2string = function (buf, max) {
  20306. var i, out, c, c_len;
  20307. var len = max || buf.length;
  20308. // Reserve max possible length (2 words per char)
  20309. // NB: by unknown reasons, Array is significantly faster for
  20310. // String.fromCharCode.apply than Uint16Array.
  20311. var utf16buf = new Array(len*2);
  20312. for (out=0, i=0; i<len;) {
  20313. c = buf[i++];
  20314. // quick process ascii
  20315. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20316. c_len = _utf8len[c];
  20317. // skip 5 & 6 byte codes
  20318. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20319. // apply mask on first byte
  20320. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20321. // join the rest
  20322. while (c_len > 1 && i < len) {
  20323. c = (c << 6) | (buf[i++] & 0x3f);
  20324. c_len--;
  20325. }
  20326. // terminated by end of string?
  20327. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20328. if (c < 0x10000) {
  20329. utf16buf[out++] = c;
  20330. } else {
  20331. c -= 0x10000;
  20332. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20333. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20334. }
  20335. }
  20336. return buf2binstring(utf16buf, out);
  20337. };
  20338. // Calculate max possible position in utf8 buffer,
  20339. // that will not break sequence. If that's not possible
  20340. // - (very small limits) return max size as is.
  20341. //
  20342. // buf[] - utf8 bytes array
  20343. // max - length limit (mandatory);
  20344. exports.utf8border = function(buf, max) {
  20345. var pos;
  20346. max = max || buf.length;
  20347. if (max > buf.length) { max = buf.length; }
  20348. // go back from last position, until start of sequence found
  20349. pos = max-1;
  20350. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20351. // Fuckup - very small and broken sequence,
  20352. // return max, because we should return something anyway.
  20353. if (pos < 0) { return max; }
  20354. // If we came to start of buffer - that means vuffer is too small,
  20355. // return max too.
  20356. if (pos === 0) { return max; }
  20357. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20358. };
  20359. },{"./common":73}],75:[function(require,module,exports){
  20360. 'use strict';
  20361. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20362. // It doesn't worth to make additional optimizationa as in original.
  20363. // Small size is preferable.
  20364. function adler32(adler, buf, len, pos) {
  20365. var s1 = (adler & 0xffff) |0,
  20366. s2 = ((adler >>> 16) & 0xffff) |0,
  20367. n = 0;
  20368. while (len !== 0) {
  20369. // Set limit ~ twice less than 5552, to keep
  20370. // s2 in 31-bits, because we force signed ints.
  20371. // in other case %= will fail.
  20372. n = len > 2000 ? 2000 : len;
  20373. len -= n;
  20374. do {
  20375. s1 = (s1 + buf[pos++]) |0;
  20376. s2 = (s2 + s1) |0;
  20377. } while (--n);
  20378. s1 %= 65521;
  20379. s2 %= 65521;
  20380. }
  20381. return (s1 | (s2 << 16)) |0;
  20382. }
  20383. module.exports = adler32;
  20384. },{}],76:[function(require,module,exports){
  20385. module.exports = {
  20386. /* Allowed flush values; see deflate() and inflate() below for details */
  20387. Z_NO_FLUSH: 0,
  20388. Z_PARTIAL_FLUSH: 1,
  20389. Z_SYNC_FLUSH: 2,
  20390. Z_FULL_FLUSH: 3,
  20391. Z_FINISH: 4,
  20392. Z_BLOCK: 5,
  20393. Z_TREES: 6,
  20394. /* Return codes for the compression/decompression functions. Negative values
  20395. * are errors, positive values are used for special but normal events.
  20396. */
  20397. Z_OK: 0,
  20398. Z_STREAM_END: 1,
  20399. Z_NEED_DICT: 2,
  20400. Z_ERRNO: -1,
  20401. Z_STREAM_ERROR: -2,
  20402. Z_DATA_ERROR: -3,
  20403. //Z_MEM_ERROR: -4,
  20404. Z_BUF_ERROR: -5,
  20405. //Z_VERSION_ERROR: -6,
  20406. /* compression levels */
  20407. Z_NO_COMPRESSION: 0,
  20408. Z_BEST_SPEED: 1,
  20409. Z_BEST_COMPRESSION: 9,
  20410. Z_DEFAULT_COMPRESSION: -1,
  20411. Z_FILTERED: 1,
  20412. Z_HUFFMAN_ONLY: 2,
  20413. Z_RLE: 3,
  20414. Z_FIXED: 4,
  20415. Z_DEFAULT_STRATEGY: 0,
  20416. /* Possible values of the data_type field (though see inflate()) */
  20417. Z_BINARY: 0,
  20418. Z_TEXT: 1,
  20419. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20420. Z_UNKNOWN: 2,
  20421. /* The deflate compression method */
  20422. Z_DEFLATED: 8
  20423. //Z_NULL: null // Use -1 or null inline, depending on var type
  20424. };
  20425. },{}],77:[function(require,module,exports){
  20426. 'use strict';
  20427. // Note: we can't get significant speed boost here.
  20428. // So write code to minimize size - no pregenerated tables
  20429. // and array tools dependencies.
  20430. // Use ordinary array, since untyped makes no boost here
  20431. function makeTable() {
  20432. var c, table = [];
  20433. for (var n =0; n < 256; n++) {
  20434. c = n;
  20435. for (var k =0; k < 8; k++) {
  20436. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20437. }
  20438. table[n] = c;
  20439. }
  20440. return table;
  20441. }
  20442. // Create table on load. Just 255 signed longs. Not a problem.
  20443. var crcTable = makeTable();
  20444. function crc32(crc, buf, len, pos) {
  20445. var t = crcTable,
  20446. end = pos + len;
  20447. crc = crc ^ (-1);
  20448. for (var i = pos; i < end; i++) {
  20449. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20450. }
  20451. return (crc ^ (-1)); // >>> 0;
  20452. }
  20453. module.exports = crc32;
  20454. },{}],78:[function(require,module,exports){
  20455. 'use strict';
  20456. var utils = require('../utils/common');
  20457. var trees = require('./trees');
  20458. var adler32 = require('./adler32');
  20459. var crc32 = require('./crc32');
  20460. var msg = require('./messages');
  20461. /* Public constants ==========================================================*/
  20462. /* ===========================================================================*/
  20463. /* Allowed flush values; see deflate() and inflate() below for details */
  20464. var Z_NO_FLUSH = 0;
  20465. var Z_PARTIAL_FLUSH = 1;
  20466. //var Z_SYNC_FLUSH = 2;
  20467. var Z_FULL_FLUSH = 3;
  20468. var Z_FINISH = 4;
  20469. var Z_BLOCK = 5;
  20470. //var Z_TREES = 6;
  20471. /* Return codes for the compression/decompression functions. Negative values
  20472. * are errors, positive values are used for special but normal events.
  20473. */
  20474. var Z_OK = 0;
  20475. var Z_STREAM_END = 1;
  20476. //var Z_NEED_DICT = 2;
  20477. //var Z_ERRNO = -1;
  20478. var Z_STREAM_ERROR = -2;
  20479. var Z_DATA_ERROR = -3;
  20480. //var Z_MEM_ERROR = -4;
  20481. var Z_BUF_ERROR = -5;
  20482. //var Z_VERSION_ERROR = -6;
  20483. /* compression levels */
  20484. //var Z_NO_COMPRESSION = 0;
  20485. //var Z_BEST_SPEED = 1;
  20486. //var Z_BEST_COMPRESSION = 9;
  20487. var Z_DEFAULT_COMPRESSION = -1;
  20488. var Z_FILTERED = 1;
  20489. var Z_HUFFMAN_ONLY = 2;
  20490. var Z_RLE = 3;
  20491. var Z_FIXED = 4;
  20492. var Z_DEFAULT_STRATEGY = 0;
  20493. /* Possible values of the data_type field (though see inflate()) */
  20494. //var Z_BINARY = 0;
  20495. //var Z_TEXT = 1;
  20496. //var Z_ASCII = 1; // = Z_TEXT
  20497. var Z_UNKNOWN = 2;
  20498. /* The deflate compression method */
  20499. var Z_DEFLATED = 8;
  20500. /*============================================================================*/
  20501. var MAX_MEM_LEVEL = 9;
  20502. /* Maximum value for memLevel in deflateInit2 */
  20503. var MAX_WBITS = 15;
  20504. /* 32K LZ77 window */
  20505. var DEF_MEM_LEVEL = 8;
  20506. var LENGTH_CODES = 29;
  20507. /* number of length codes, not counting the special END_BLOCK code */
  20508. var LITERALS = 256;
  20509. /* number of literal bytes 0..255 */
  20510. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20511. /* number of Literal or Length codes, including the END_BLOCK code */
  20512. var D_CODES = 30;
  20513. /* number of distance codes */
  20514. var BL_CODES = 19;
  20515. /* number of codes used to transfer the bit lengths */
  20516. var HEAP_SIZE = 2*L_CODES + 1;
  20517. /* maximum heap size */
  20518. var MAX_BITS = 15;
  20519. /* All codes must not exceed MAX_BITS bits */
  20520. var MIN_MATCH = 3;
  20521. var MAX_MATCH = 258;
  20522. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20523. var PRESET_DICT = 0x20;
  20524. var INIT_STATE = 42;
  20525. var EXTRA_STATE = 69;
  20526. var NAME_STATE = 73;
  20527. var COMMENT_STATE = 91;
  20528. var HCRC_STATE = 103;
  20529. var BUSY_STATE = 113;
  20530. var FINISH_STATE = 666;
  20531. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20532. var BS_BLOCK_DONE = 2; /* block flush performed */
  20533. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20534. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20535. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20536. function err(strm, errorCode) {
  20537. strm.msg = msg[errorCode];
  20538. return errorCode;
  20539. }
  20540. function rank(f) {
  20541. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20542. }
  20543. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20544. /* =========================================================================
  20545. * Flush as much pending output as possible. All deflate() output goes
  20546. * through this function so some applications may wish to modify it
  20547. * to avoid allocating a large strm->output buffer and copying into it.
  20548. * (See also read_buf()).
  20549. */
  20550. function flush_pending(strm) {
  20551. var s = strm.state;
  20552. //_tr_flush_bits(s);
  20553. var len = s.pending;
  20554. if (len > strm.avail_out) {
  20555. len = strm.avail_out;
  20556. }
  20557. if (len === 0) { return; }
  20558. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20559. strm.next_out += len;
  20560. s.pending_out += len;
  20561. strm.total_out += len;
  20562. strm.avail_out -= len;
  20563. s.pending -= len;
  20564. if (s.pending === 0) {
  20565. s.pending_out = 0;
  20566. }
  20567. }
  20568. function flush_block_only (s, last) {
  20569. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20570. s.block_start = s.strstart;
  20571. flush_pending(s.strm);
  20572. }
  20573. function put_byte(s, b) {
  20574. s.pending_buf[s.pending++] = b;
  20575. }
  20576. /* =========================================================================
  20577. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20578. * IN assertion: the stream state is correct and there is enough room in
  20579. * pending_buf.
  20580. */
  20581. function putShortMSB(s, b) {
  20582. // put_byte(s, (Byte)(b >> 8));
  20583. // put_byte(s, (Byte)(b & 0xff));
  20584. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20585. s.pending_buf[s.pending++] = b & 0xff;
  20586. }
  20587. /* ===========================================================================
  20588. * Read a new buffer from the current input stream, update the adler32
  20589. * and total number of bytes read. All deflate() input goes through
  20590. * this function so some applications may wish to modify it to avoid
  20591. * allocating a large strm->input buffer and copying from it.
  20592. * (See also flush_pending()).
  20593. */
  20594. function read_buf(strm, buf, start, size) {
  20595. var len = strm.avail_in;
  20596. if (len > size) { len = size; }
  20597. if (len === 0) { return 0; }
  20598. strm.avail_in -= len;
  20599. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20600. if (strm.state.wrap === 1) {
  20601. strm.adler = adler32(strm.adler, buf, len, start);
  20602. }
  20603. else if (strm.state.wrap === 2) {
  20604. strm.adler = crc32(strm.adler, buf, len, start);
  20605. }
  20606. strm.next_in += len;
  20607. strm.total_in += len;
  20608. return len;
  20609. }
  20610. /* ===========================================================================
  20611. * Set match_start to the longest match starting at the given string and
  20612. * return its length. Matches shorter or equal to prev_length are discarded,
  20613. * in which case the result is equal to prev_length and match_start is
  20614. * garbage.
  20615. * IN assertions: cur_match is the head of the hash chain for the current
  20616. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20617. * OUT assertion: the match length is not greater than s->lookahead.
  20618. */
  20619. function longest_match(s, cur_match) {
  20620. var chain_length = s.max_chain_length; /* max hash chain length */
  20621. var scan = s.strstart; /* current string */
  20622. var match; /* matched string */
  20623. var len; /* length of current match */
  20624. var best_len = s.prev_length; /* best match length so far */
  20625. var nice_match = s.nice_match; /* stop if match long enough */
  20626. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20627. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20628. var _win = s.window; // shortcut
  20629. var wmask = s.w_mask;
  20630. var prev = s.prev;
  20631. /* Stop when cur_match becomes <= limit. To simplify the code,
  20632. * we prevent matches with the string of window index 0.
  20633. */
  20634. var strend = s.strstart + MAX_MATCH;
  20635. var scan_end1 = _win[scan + best_len - 1];
  20636. var scan_end = _win[scan + best_len];
  20637. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20638. * It is easy to get rid of this optimization if necessary.
  20639. */
  20640. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20641. /* Do not waste too much time if we already have a good match: */
  20642. if (s.prev_length >= s.good_match) {
  20643. chain_length >>= 2;
  20644. }
  20645. /* Do not look for matches beyond the end of the input. This is necessary
  20646. * to make deflate deterministic.
  20647. */
  20648. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20649. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20650. do {
  20651. // Assert(cur_match < s->strstart, "no future");
  20652. match = cur_match;
  20653. /* Skip to next match if the match length cannot increase
  20654. * or if the match length is less than 2. Note that the checks below
  20655. * for insufficient lookahead only occur occasionally for performance
  20656. * reasons. Therefore uninitialized memory will be accessed, and
  20657. * conditional jumps will be made that depend on those values.
  20658. * However the length of the match is limited to the lookahead, so
  20659. * the output of deflate is not affected by the uninitialized values.
  20660. */
  20661. if (_win[match + best_len] !== scan_end ||
  20662. _win[match + best_len - 1] !== scan_end1 ||
  20663. _win[match] !== _win[scan] ||
  20664. _win[++match] !== _win[scan + 1]) {
  20665. continue;
  20666. }
  20667. /* The check at best_len-1 can be removed because it will be made
  20668. * again later. (This heuristic is not always a win.)
  20669. * It is not necessary to compare scan[2] and match[2] since they
  20670. * are always equal when the other bytes match, given that
  20671. * the hash keys are equal and that HASH_BITS >= 8.
  20672. */
  20673. scan += 2;
  20674. match++;
  20675. // Assert(*scan == *match, "match[2]?");
  20676. /* We check for insufficient lookahead only every 8th comparison;
  20677. * the 256th check will be made at strstart+258.
  20678. */
  20679. do {
  20680. /*jshint noempty:false*/
  20681. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20682. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20683. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20684. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20685. scan < strend);
  20686. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20687. len = MAX_MATCH - (strend - scan);
  20688. scan = strend - MAX_MATCH;
  20689. if (len > best_len) {
  20690. s.match_start = cur_match;
  20691. best_len = len;
  20692. if (len >= nice_match) {
  20693. break;
  20694. }
  20695. scan_end1 = _win[scan + best_len - 1];
  20696. scan_end = _win[scan + best_len];
  20697. }
  20698. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20699. if (best_len <= s.lookahead) {
  20700. return best_len;
  20701. }
  20702. return s.lookahead;
  20703. }
  20704. /* ===========================================================================
  20705. * Fill the window when the lookahead becomes insufficient.
  20706. * Updates strstart and lookahead.
  20707. *
  20708. * IN assertion: lookahead < MIN_LOOKAHEAD
  20709. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20710. * At least one byte has been read, or avail_in == 0; reads are
  20711. * performed for at least two bytes (required for the zip translate_eol
  20712. * option -- not supported here).
  20713. */
  20714. function fill_window(s) {
  20715. var _w_size = s.w_size;
  20716. var p, n, m, more, str;
  20717. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20718. do {
  20719. more = s.window_size - s.lookahead - s.strstart;
  20720. // JS ints have 32 bit, block below not needed
  20721. /* Deal with !@#$% 64K limit: */
  20722. //if (sizeof(int) <= 2) {
  20723. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20724. // more = wsize;
  20725. //
  20726. // } else if (more == (unsigned)(-1)) {
  20727. // /* Very unlikely, but possible on 16 bit machine if
  20728. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20729. // */
  20730. // more--;
  20731. // }
  20732. //}
  20733. /* If the window is almost full and there is insufficient lookahead,
  20734. * move the upper half to the lower one to make room in the upper half.
  20735. */
  20736. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20737. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20738. s.match_start -= _w_size;
  20739. s.strstart -= _w_size;
  20740. /* we now have strstart >= MAX_DIST */
  20741. s.block_start -= _w_size;
  20742. /* Slide the hash table (could be avoided with 32 bit values
  20743. at the expense of memory usage). We slide even when level == 0
  20744. to keep the hash table consistent if we switch back to level > 0
  20745. later. (Using level 0 permanently is not an optimal usage of
  20746. zlib, so we don't care about this pathological case.)
  20747. */
  20748. n = s.hash_size;
  20749. p = n;
  20750. do {
  20751. m = s.head[--p];
  20752. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20753. } while (--n);
  20754. n = _w_size;
  20755. p = n;
  20756. do {
  20757. m = s.prev[--p];
  20758. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20759. /* If n is not on any hash chain, prev[n] is garbage but
  20760. * its value will never be used.
  20761. */
  20762. } while (--n);
  20763. more += _w_size;
  20764. }
  20765. if (s.strm.avail_in === 0) {
  20766. break;
  20767. }
  20768. /* If there was no sliding:
  20769. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20770. * more == window_size - lookahead - strstart
  20771. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20772. * => more >= window_size - 2*WSIZE + 2
  20773. * In the BIG_MEM or MMAP case (not yet supported),
  20774. * window_size == input_size + MIN_LOOKAHEAD &&
  20775. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20776. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20777. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20778. */
  20779. //Assert(more >= 2, "more < 2");
  20780. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20781. s.lookahead += n;
  20782. /* Initialize the hash value now that we have some input: */
  20783. if (s.lookahead + s.insert >= MIN_MATCH) {
  20784. str = s.strstart - s.insert;
  20785. s.ins_h = s.window[str];
  20786. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20787. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20788. //#if MIN_MATCH != 3
  20789. // Call update_hash() MIN_MATCH-3 more times
  20790. //#endif
  20791. while (s.insert) {
  20792. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20793. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20794. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20795. s.head[s.ins_h] = str;
  20796. str++;
  20797. s.insert--;
  20798. if (s.lookahead + s.insert < MIN_MATCH) {
  20799. break;
  20800. }
  20801. }
  20802. }
  20803. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20804. * but this is not important since only literal bytes will be emitted.
  20805. */
  20806. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20807. /* If the WIN_INIT bytes after the end of the current data have never been
  20808. * written, then zero those bytes in order to avoid memory check reports of
  20809. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20810. * the longest match routines. Update the high water mark for the next
  20811. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20812. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20813. */
  20814. // if (s.high_water < s.window_size) {
  20815. // var curr = s.strstart + s.lookahead;
  20816. // var init = 0;
  20817. //
  20818. // if (s.high_water < curr) {
  20819. // /* Previous high water mark below current data -- zero WIN_INIT
  20820. // * bytes or up to end of window, whichever is less.
  20821. // */
  20822. // init = s.window_size - curr;
  20823. // if (init > WIN_INIT)
  20824. // init = WIN_INIT;
  20825. // zmemzero(s->window + curr, (unsigned)init);
  20826. // s->high_water = curr + init;
  20827. // }
  20828. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20829. // /* High water mark at or above current data, but below current data
  20830. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20831. // * to end of window, whichever is less.
  20832. // */
  20833. // init = (ulg)curr + WIN_INIT - s->high_water;
  20834. // if (init > s->window_size - s->high_water)
  20835. // init = s->window_size - s->high_water;
  20836. // zmemzero(s->window + s->high_water, (unsigned)init);
  20837. // s->high_water += init;
  20838. // }
  20839. // }
  20840. //
  20841. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20842. // "not enough room for search");
  20843. }
  20844. /* ===========================================================================
  20845. * Copy without compression as much as possible from the input stream, return
  20846. * the current block state.
  20847. * This function does not insert new strings in the dictionary since
  20848. * uncompressible data is probably not useful. This function is used
  20849. * only for the level=0 compression option.
  20850. * NOTE: this function should be optimized to avoid extra copying from
  20851. * window to pending_buf.
  20852. */
  20853. function deflate_stored(s, flush) {
  20854. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20855. * to pending_buf_size, and each stored block has a 5 byte header:
  20856. */
  20857. var max_block_size = 0xffff;
  20858. if (max_block_size > s.pending_buf_size - 5) {
  20859. max_block_size = s.pending_buf_size - 5;
  20860. }
  20861. /* Copy as much as possible from input to output: */
  20862. for (;;) {
  20863. /* Fill the window as much as possible: */
  20864. if (s.lookahead <= 1) {
  20865. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20866. // s->block_start >= (long)s->w_size, "slide too late");
  20867. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20868. // s.block_start >= s.w_size)) {
  20869. // throw new Error("slide too late");
  20870. // }
  20871. fill_window(s);
  20872. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20873. return BS_NEED_MORE;
  20874. }
  20875. if (s.lookahead === 0) {
  20876. break;
  20877. }
  20878. /* flush the current block */
  20879. }
  20880. //Assert(s->block_start >= 0L, "block gone");
  20881. // if (s.block_start < 0) throw new Error("block gone");
  20882. s.strstart += s.lookahead;
  20883. s.lookahead = 0;
  20884. /* Emit a stored block if pending_buf will be full: */
  20885. var max_start = s.block_start + max_block_size;
  20886. if (s.strstart === 0 || s.strstart >= max_start) {
  20887. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20888. s.lookahead = s.strstart - max_start;
  20889. s.strstart = max_start;
  20890. /*** FLUSH_BLOCK(s, 0); ***/
  20891. flush_block_only(s, false);
  20892. if (s.strm.avail_out === 0) {
  20893. return BS_NEED_MORE;
  20894. }
  20895. /***/
  20896. }
  20897. /* Flush if we may have to slide, otherwise block_start may become
  20898. * negative and the data will be gone:
  20899. */
  20900. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20901. /*** FLUSH_BLOCK(s, 0); ***/
  20902. flush_block_only(s, false);
  20903. if (s.strm.avail_out === 0) {
  20904. return BS_NEED_MORE;
  20905. }
  20906. /***/
  20907. }
  20908. }
  20909. s.insert = 0;
  20910. if (flush === Z_FINISH) {
  20911. /*** FLUSH_BLOCK(s, 1); ***/
  20912. flush_block_only(s, true);
  20913. if (s.strm.avail_out === 0) {
  20914. return BS_FINISH_STARTED;
  20915. }
  20916. /***/
  20917. return BS_FINISH_DONE;
  20918. }
  20919. if (s.strstart > s.block_start) {
  20920. /*** FLUSH_BLOCK(s, 0); ***/
  20921. flush_block_only(s, false);
  20922. if (s.strm.avail_out === 0) {
  20923. return BS_NEED_MORE;
  20924. }
  20925. /***/
  20926. }
  20927. return BS_NEED_MORE;
  20928. }
  20929. /* ===========================================================================
  20930. * Compress as much as possible from the input stream, return the current
  20931. * block state.
  20932. * This function does not perform lazy evaluation of matches and inserts
  20933. * new strings in the dictionary only for unmatched strings or for short
  20934. * matches. It is used only for the fast compression options.
  20935. */
  20936. function deflate_fast(s, flush) {
  20937. var hash_head; /* head of the hash chain */
  20938. var bflush; /* set if current block must be flushed */
  20939. for (;;) {
  20940. /* Make sure that we always have enough lookahead, except
  20941. * at the end of the input file. We need MAX_MATCH bytes
  20942. * for the next match, plus MIN_MATCH bytes to insert the
  20943. * string following the next match.
  20944. */
  20945. if (s.lookahead < MIN_LOOKAHEAD) {
  20946. fill_window(s);
  20947. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20948. return BS_NEED_MORE;
  20949. }
  20950. if (s.lookahead === 0) {
  20951. break; /* flush the current block */
  20952. }
  20953. }
  20954. /* Insert the string window[strstart .. strstart+2] in the
  20955. * dictionary, and set hash_head to the head of the hash chain:
  20956. */
  20957. hash_head = 0/*NIL*/;
  20958. if (s.lookahead >= MIN_MATCH) {
  20959. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20960. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20961. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20962. s.head[s.ins_h] = s.strstart;
  20963. /***/
  20964. }
  20965. /* Find the longest match, discarding those <= prev_length.
  20966. * At this point we have always match_length < MIN_MATCH
  20967. */
  20968. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20969. /* To simplify the code, we prevent matches with the string
  20970. * of window index 0 (in particular we have to avoid a match
  20971. * of the string with itself at the start of the input file).
  20972. */
  20973. s.match_length = longest_match(s, hash_head);
  20974. /* longest_match() sets match_start */
  20975. }
  20976. if (s.match_length >= MIN_MATCH) {
  20977. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20978. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20979. s.match_length - MIN_MATCH, bflush); ***/
  20980. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20981. s.lookahead -= s.match_length;
  20982. /* Insert new strings in the hash table only if the match length
  20983. * is not too large. This saves time but degrades compression.
  20984. */
  20985. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20986. s.match_length--; /* string at strstart already in table */
  20987. do {
  20988. s.strstart++;
  20989. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20990. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20991. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20992. s.head[s.ins_h] = s.strstart;
  20993. /***/
  20994. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20995. * always MIN_MATCH bytes ahead.
  20996. */
  20997. } while (--s.match_length !== 0);
  20998. s.strstart++;
  20999. } else
  21000. {
  21001. s.strstart += s.match_length;
  21002. s.match_length = 0;
  21003. s.ins_h = s.window[s.strstart];
  21004. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21005. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21006. //#if MIN_MATCH != 3
  21007. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21008. //#endif
  21009. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21010. * matter since it will be recomputed at next deflate call.
  21011. */
  21012. }
  21013. } else {
  21014. /* No match, output a literal byte */
  21015. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21016. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21017. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21018. s.lookahead--;
  21019. s.strstart++;
  21020. }
  21021. if (bflush) {
  21022. /*** FLUSH_BLOCK(s, 0); ***/
  21023. flush_block_only(s, false);
  21024. if (s.strm.avail_out === 0) {
  21025. return BS_NEED_MORE;
  21026. }
  21027. /***/
  21028. }
  21029. }
  21030. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21031. if (flush === Z_FINISH) {
  21032. /*** FLUSH_BLOCK(s, 1); ***/
  21033. flush_block_only(s, true);
  21034. if (s.strm.avail_out === 0) {
  21035. return BS_FINISH_STARTED;
  21036. }
  21037. /***/
  21038. return BS_FINISH_DONE;
  21039. }
  21040. if (s.last_lit) {
  21041. /*** FLUSH_BLOCK(s, 0); ***/
  21042. flush_block_only(s, false);
  21043. if (s.strm.avail_out === 0) {
  21044. return BS_NEED_MORE;
  21045. }
  21046. /***/
  21047. }
  21048. return BS_BLOCK_DONE;
  21049. }
  21050. /* ===========================================================================
  21051. * Same as above, but achieves better compression. We use a lazy
  21052. * evaluation for matches: a match is finally adopted only if there is
  21053. * no better match at the next window position.
  21054. */
  21055. function deflate_slow(s, flush) {
  21056. var hash_head; /* head of hash chain */
  21057. var bflush; /* set if current block must be flushed */
  21058. var max_insert;
  21059. /* Process the input block. */
  21060. for (;;) {
  21061. /* Make sure that we always have enough lookahead, except
  21062. * at the end of the input file. We need MAX_MATCH bytes
  21063. * for the next match, plus MIN_MATCH bytes to insert the
  21064. * string following the next match.
  21065. */
  21066. if (s.lookahead < MIN_LOOKAHEAD) {
  21067. fill_window(s);
  21068. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21069. return BS_NEED_MORE;
  21070. }
  21071. if (s.lookahead === 0) { break; } /* flush the current block */
  21072. }
  21073. /* Insert the string window[strstart .. strstart+2] in the
  21074. * dictionary, and set hash_head to the head of the hash chain:
  21075. */
  21076. hash_head = 0/*NIL*/;
  21077. if (s.lookahead >= MIN_MATCH) {
  21078. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21079. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21080. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21081. s.head[s.ins_h] = s.strstart;
  21082. /***/
  21083. }
  21084. /* Find the longest match, discarding those <= prev_length.
  21085. */
  21086. s.prev_length = s.match_length;
  21087. s.prev_match = s.match_start;
  21088. s.match_length = MIN_MATCH-1;
  21089. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21090. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21091. /* To simplify the code, we prevent matches with the string
  21092. * of window index 0 (in particular we have to avoid a match
  21093. * of the string with itself at the start of the input file).
  21094. */
  21095. s.match_length = longest_match(s, hash_head);
  21096. /* longest_match() sets match_start */
  21097. if (s.match_length <= 5 &&
  21098. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21099. /* If prev_match is also MIN_MATCH, match_start is garbage
  21100. * but we will ignore the current match anyway.
  21101. */
  21102. s.match_length = MIN_MATCH-1;
  21103. }
  21104. }
  21105. /* If there was a match at the previous step and the current
  21106. * match is not better, output the previous match:
  21107. */
  21108. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21109. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21110. /* Do not insert strings in hash table beyond this. */
  21111. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21112. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21113. s.prev_length - MIN_MATCH, bflush);***/
  21114. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21115. /* Insert in hash table all strings up to the end of the match.
  21116. * strstart-1 and strstart are already inserted. If there is not
  21117. * enough lookahead, the last two strings are not inserted in
  21118. * the hash table.
  21119. */
  21120. s.lookahead -= s.prev_length-1;
  21121. s.prev_length -= 2;
  21122. do {
  21123. if (++s.strstart <= max_insert) {
  21124. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21125. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21126. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21127. s.head[s.ins_h] = s.strstart;
  21128. /***/
  21129. }
  21130. } while (--s.prev_length !== 0);
  21131. s.match_available = 0;
  21132. s.match_length = MIN_MATCH-1;
  21133. s.strstart++;
  21134. if (bflush) {
  21135. /*** FLUSH_BLOCK(s, 0); ***/
  21136. flush_block_only(s, false);
  21137. if (s.strm.avail_out === 0) {
  21138. return BS_NEED_MORE;
  21139. }
  21140. /***/
  21141. }
  21142. } else if (s.match_available) {
  21143. /* If there was no match at the previous position, output a
  21144. * single literal. If there was a match but the current match
  21145. * is longer, truncate the previous match to a single literal.
  21146. */
  21147. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21148. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21149. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21150. if (bflush) {
  21151. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21152. flush_block_only(s, false);
  21153. /***/
  21154. }
  21155. s.strstart++;
  21156. s.lookahead--;
  21157. if (s.strm.avail_out === 0) {
  21158. return BS_NEED_MORE;
  21159. }
  21160. } else {
  21161. /* There is no previous match to compare with, wait for
  21162. * the next step to decide.
  21163. */
  21164. s.match_available = 1;
  21165. s.strstart++;
  21166. s.lookahead--;
  21167. }
  21168. }
  21169. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21170. if (s.match_available) {
  21171. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21172. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21173. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21174. s.match_available = 0;
  21175. }
  21176. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21177. if (flush === Z_FINISH) {
  21178. /*** FLUSH_BLOCK(s, 1); ***/
  21179. flush_block_only(s, true);
  21180. if (s.strm.avail_out === 0) {
  21181. return BS_FINISH_STARTED;
  21182. }
  21183. /***/
  21184. return BS_FINISH_DONE;
  21185. }
  21186. if (s.last_lit) {
  21187. /*** FLUSH_BLOCK(s, 0); ***/
  21188. flush_block_only(s, false);
  21189. if (s.strm.avail_out === 0) {
  21190. return BS_NEED_MORE;
  21191. }
  21192. /***/
  21193. }
  21194. return BS_BLOCK_DONE;
  21195. }
  21196. /* ===========================================================================
  21197. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21198. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21199. * deflate switches away from Z_RLE.)
  21200. */
  21201. function deflate_rle(s, flush) {
  21202. var bflush; /* set if current block must be flushed */
  21203. var prev; /* byte at distance one to match */
  21204. var scan, strend; /* scan goes up to strend for length of run */
  21205. var _win = s.window;
  21206. for (;;) {
  21207. /* Make sure that we always have enough lookahead, except
  21208. * at the end of the input file. We need MAX_MATCH bytes
  21209. * for the longest run, plus one for the unrolled loop.
  21210. */
  21211. if (s.lookahead <= MAX_MATCH) {
  21212. fill_window(s);
  21213. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21214. return BS_NEED_MORE;
  21215. }
  21216. if (s.lookahead === 0) { break; } /* flush the current block */
  21217. }
  21218. /* See how many times the previous byte repeats */
  21219. s.match_length = 0;
  21220. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21221. scan = s.strstart - 1;
  21222. prev = _win[scan];
  21223. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21224. strend = s.strstart + MAX_MATCH;
  21225. do {
  21226. /*jshint noempty:false*/
  21227. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21228. prev === _win[++scan] && prev === _win[++scan] &&
  21229. prev === _win[++scan] && prev === _win[++scan] &&
  21230. prev === _win[++scan] && prev === _win[++scan] &&
  21231. scan < strend);
  21232. s.match_length = MAX_MATCH - (strend - scan);
  21233. if (s.match_length > s.lookahead) {
  21234. s.match_length = s.lookahead;
  21235. }
  21236. }
  21237. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21238. }
  21239. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21240. if (s.match_length >= MIN_MATCH) {
  21241. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21242. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21243. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21244. s.lookahead -= s.match_length;
  21245. s.strstart += s.match_length;
  21246. s.match_length = 0;
  21247. } else {
  21248. /* No match, output a literal byte */
  21249. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21250. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21251. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21252. s.lookahead--;
  21253. s.strstart++;
  21254. }
  21255. if (bflush) {
  21256. /*** FLUSH_BLOCK(s, 0); ***/
  21257. flush_block_only(s, false);
  21258. if (s.strm.avail_out === 0) {
  21259. return BS_NEED_MORE;
  21260. }
  21261. /***/
  21262. }
  21263. }
  21264. s.insert = 0;
  21265. if (flush === Z_FINISH) {
  21266. /*** FLUSH_BLOCK(s, 1); ***/
  21267. flush_block_only(s, true);
  21268. if (s.strm.avail_out === 0) {
  21269. return BS_FINISH_STARTED;
  21270. }
  21271. /***/
  21272. return BS_FINISH_DONE;
  21273. }
  21274. if (s.last_lit) {
  21275. /*** FLUSH_BLOCK(s, 0); ***/
  21276. flush_block_only(s, false);
  21277. if (s.strm.avail_out === 0) {
  21278. return BS_NEED_MORE;
  21279. }
  21280. /***/
  21281. }
  21282. return BS_BLOCK_DONE;
  21283. }
  21284. /* ===========================================================================
  21285. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21286. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21287. */
  21288. function deflate_huff(s, flush) {
  21289. var bflush; /* set if current block must be flushed */
  21290. for (;;) {
  21291. /* Make sure that we have a literal to write. */
  21292. if (s.lookahead === 0) {
  21293. fill_window(s);
  21294. if (s.lookahead === 0) {
  21295. if (flush === Z_NO_FLUSH) {
  21296. return BS_NEED_MORE;
  21297. }
  21298. break; /* flush the current block */
  21299. }
  21300. }
  21301. /* Output a literal byte */
  21302. s.match_length = 0;
  21303. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21304. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21305. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21306. s.lookahead--;
  21307. s.strstart++;
  21308. if (bflush) {
  21309. /*** FLUSH_BLOCK(s, 0); ***/
  21310. flush_block_only(s, false);
  21311. if (s.strm.avail_out === 0) {
  21312. return BS_NEED_MORE;
  21313. }
  21314. /***/
  21315. }
  21316. }
  21317. s.insert = 0;
  21318. if (flush === Z_FINISH) {
  21319. /*** FLUSH_BLOCK(s, 1); ***/
  21320. flush_block_only(s, true);
  21321. if (s.strm.avail_out === 0) {
  21322. return BS_FINISH_STARTED;
  21323. }
  21324. /***/
  21325. return BS_FINISH_DONE;
  21326. }
  21327. if (s.last_lit) {
  21328. /*** FLUSH_BLOCK(s, 0); ***/
  21329. flush_block_only(s, false);
  21330. if (s.strm.avail_out === 0) {
  21331. return BS_NEED_MORE;
  21332. }
  21333. /***/
  21334. }
  21335. return BS_BLOCK_DONE;
  21336. }
  21337. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21338. * the desired pack level (0..9). The values given below have been tuned to
  21339. * exclude worst case performance for pathological files. Better values may be
  21340. * found for specific files.
  21341. */
  21342. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21343. this.good_length = good_length;
  21344. this.max_lazy = max_lazy;
  21345. this.nice_length = nice_length;
  21346. this.max_chain = max_chain;
  21347. this.func = func;
  21348. };
  21349. var configuration_table;
  21350. configuration_table = [
  21351. /* good lazy nice chain */
  21352. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21353. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21354. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21355. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21356. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21357. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21358. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21359. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21360. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21361. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21362. ];
  21363. /* ===========================================================================
  21364. * Initialize the "longest match" routines for a new zlib stream
  21365. */
  21366. function lm_init(s) {
  21367. s.window_size = 2 * s.w_size;
  21368. /*** CLEAR_HASH(s); ***/
  21369. zero(s.head); // Fill with NIL (= 0);
  21370. /* Set the default configuration parameters:
  21371. */
  21372. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21373. s.good_match = configuration_table[s.level].good_length;
  21374. s.nice_match = configuration_table[s.level].nice_length;
  21375. s.max_chain_length = configuration_table[s.level].max_chain;
  21376. s.strstart = 0;
  21377. s.block_start = 0;
  21378. s.lookahead = 0;
  21379. s.insert = 0;
  21380. s.match_length = s.prev_length = MIN_MATCH - 1;
  21381. s.match_available = 0;
  21382. s.ins_h = 0;
  21383. }
  21384. function DeflateState() {
  21385. this.strm = null; /* pointer back to this zlib stream */
  21386. this.status = 0; /* as the name implies */
  21387. this.pending_buf = null; /* output still pending */
  21388. this.pending_buf_size = 0; /* size of pending_buf */
  21389. this.pending_out = 0; /* next pending byte to output to the stream */
  21390. this.pending = 0; /* nb of bytes in the pending buffer */
  21391. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21392. this.gzhead = null; /* gzip header information to write */
  21393. this.gzindex = 0; /* where in extra, name, or comment */
  21394. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21395. this.last_flush = -1; /* value of flush param for previous deflate call */
  21396. this.w_size = 0; /* LZ77 window size (32K by default) */
  21397. this.w_bits = 0; /* log2(w_size) (8..16) */
  21398. this.w_mask = 0; /* w_size - 1 */
  21399. this.window = null;
  21400. /* Sliding window. Input bytes are read into the second half of the window,
  21401. * and move to the first half later to keep a dictionary of at least wSize
  21402. * bytes. With this organization, matches are limited to a distance of
  21403. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21404. * performed with a length multiple of the block size.
  21405. */
  21406. this.window_size = 0;
  21407. /* Actual size of window: 2*wSize, except when the user input buffer
  21408. * is directly used as sliding window.
  21409. */
  21410. this.prev = null;
  21411. /* Link to older string with same hash index. To limit the size of this
  21412. * array to 64K, this link is maintained only for the last 32K strings.
  21413. * An index in this array is thus a window index modulo 32K.
  21414. */
  21415. this.head = null; /* Heads of the hash chains or NIL. */
  21416. this.ins_h = 0; /* hash index of string to be inserted */
  21417. this.hash_size = 0; /* number of elements in hash table */
  21418. this.hash_bits = 0; /* log2(hash_size) */
  21419. this.hash_mask = 0; /* hash_size-1 */
  21420. this.hash_shift = 0;
  21421. /* Number of bits by which ins_h must be shifted at each input
  21422. * step. It must be such that after MIN_MATCH steps, the oldest
  21423. * byte no longer takes part in the hash key, that is:
  21424. * hash_shift * MIN_MATCH >= hash_bits
  21425. */
  21426. this.block_start = 0;
  21427. /* Window position at the beginning of the current output block. Gets
  21428. * negative when the window is moved backwards.
  21429. */
  21430. this.match_length = 0; /* length of best match */
  21431. this.prev_match = 0; /* previous match */
  21432. this.match_available = 0; /* set if previous match exists */
  21433. this.strstart = 0; /* start of string to insert */
  21434. this.match_start = 0; /* start of matching string */
  21435. this.lookahead = 0; /* number of valid bytes ahead in window */
  21436. this.prev_length = 0;
  21437. /* Length of the best match at previous step. Matches not greater than this
  21438. * are discarded. This is used in the lazy match evaluation.
  21439. */
  21440. this.max_chain_length = 0;
  21441. /* To speed up deflation, hash chains are never searched beyond this
  21442. * length. A higher limit improves compression ratio but degrades the
  21443. * speed.
  21444. */
  21445. this.max_lazy_match = 0;
  21446. /* Attempt to find a better match only when the current match is strictly
  21447. * smaller than this value. This mechanism is used only for compression
  21448. * levels >= 4.
  21449. */
  21450. // That's alias to max_lazy_match, don't use directly
  21451. //this.max_insert_length = 0;
  21452. /* Insert new strings in the hash table only if the match length is not
  21453. * greater than this length. This saves time but degrades compression.
  21454. * max_insert_length is used only for compression levels <= 3.
  21455. */
  21456. this.level = 0; /* compression level (1..9) */
  21457. this.strategy = 0; /* favor or force Huffman coding*/
  21458. this.good_match = 0;
  21459. /* Use a faster search when the previous match is longer than this */
  21460. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21461. /* used by trees.c: */
  21462. /* Didn't use ct_data typedef below to suppress compiler warning */
  21463. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21464. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21465. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21466. // Use flat array of DOUBLE size, with interleaved fata,
  21467. // because JS does not support effective
  21468. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21469. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21470. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21471. zero(this.dyn_ltree);
  21472. zero(this.dyn_dtree);
  21473. zero(this.bl_tree);
  21474. this.l_desc = null; /* desc. for literal tree */
  21475. this.d_desc = null; /* desc. for distance tree */
  21476. this.bl_desc = null; /* desc. for bit length tree */
  21477. //ush bl_count[MAX_BITS+1];
  21478. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21479. /* number of codes at each bit length for an optimal tree */
  21480. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21481. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21482. zero(this.heap);
  21483. this.heap_len = 0; /* number of elements in the heap */
  21484. this.heap_max = 0; /* element of largest frequency */
  21485. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21486. * The same heap array is used to build all trees.
  21487. */
  21488. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21489. zero(this.depth);
  21490. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21491. */
  21492. this.l_buf = 0; /* buffer index for literals or lengths */
  21493. this.lit_bufsize = 0;
  21494. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21495. * limiting lit_bufsize to 64K:
  21496. * - frequencies can be kept in 16 bit counters
  21497. * - if compression is not successful for the first block, all input
  21498. * data is still in the window so we can still emit a stored block even
  21499. * when input comes from standard input. (This can also be done for
  21500. * all blocks if lit_bufsize is not greater than 32K.)
  21501. * - if compression is not successful for a file smaller than 64K, we can
  21502. * even emit a stored file instead of a stored block (saving 5 bytes).
  21503. * This is applicable only for zip (not gzip or zlib).
  21504. * - creating new Huffman trees less frequently may not provide fast
  21505. * adaptation to changes in the input data statistics. (Take for
  21506. * example a binary file with poorly compressible code followed by
  21507. * a highly compressible string table.) Smaller buffer sizes give
  21508. * fast adaptation but have of course the overhead of transmitting
  21509. * trees more frequently.
  21510. * - I can't count above 4
  21511. */
  21512. this.last_lit = 0; /* running index in l_buf */
  21513. this.d_buf = 0;
  21514. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21515. * the same number of elements. To use different lengths, an extra flag
  21516. * array would be necessary.
  21517. */
  21518. this.opt_len = 0; /* bit length of current block with optimal trees */
  21519. this.static_len = 0; /* bit length of current block with static trees */
  21520. this.matches = 0; /* number of string matches in current block */
  21521. this.insert = 0; /* bytes at end of window left to insert */
  21522. this.bi_buf = 0;
  21523. /* Output buffer. bits are inserted starting at the bottom (least
  21524. * significant bits).
  21525. */
  21526. this.bi_valid = 0;
  21527. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21528. * are always zero.
  21529. */
  21530. // Used for window memory init. We safely ignore it for JS. That makes
  21531. // sense only for pointers and memory check tools.
  21532. //this.high_water = 0;
  21533. /* High water mark offset in window for initialized bytes -- bytes above
  21534. * this are set to zero in order to avoid memory check warnings when
  21535. * longest match routines access bytes past the input. This is then
  21536. * updated to the new high water mark.
  21537. */
  21538. }
  21539. function deflateResetKeep(strm) {
  21540. var s;
  21541. if (!strm || !strm.state) {
  21542. return err(strm, Z_STREAM_ERROR);
  21543. }
  21544. strm.total_in = strm.total_out = 0;
  21545. strm.data_type = Z_UNKNOWN;
  21546. s = strm.state;
  21547. s.pending = 0;
  21548. s.pending_out = 0;
  21549. if (s.wrap < 0) {
  21550. s.wrap = -s.wrap;
  21551. /* was made negative by deflate(..., Z_FINISH); */
  21552. }
  21553. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21554. strm.adler = (s.wrap === 2) ?
  21555. 0 // crc32(0, Z_NULL, 0)
  21556. :
  21557. 1; // adler32(0, Z_NULL, 0)
  21558. s.last_flush = Z_NO_FLUSH;
  21559. trees._tr_init(s);
  21560. return Z_OK;
  21561. }
  21562. function deflateReset(strm) {
  21563. var ret = deflateResetKeep(strm);
  21564. if (ret === Z_OK) {
  21565. lm_init(strm.state);
  21566. }
  21567. return ret;
  21568. }
  21569. function deflateSetHeader(strm, head) {
  21570. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21571. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21572. strm.state.gzhead = head;
  21573. return Z_OK;
  21574. }
  21575. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21576. if (!strm) { // === Z_NULL
  21577. return Z_STREAM_ERROR;
  21578. }
  21579. var wrap = 1;
  21580. if (level === Z_DEFAULT_COMPRESSION) {
  21581. level = 6;
  21582. }
  21583. if (windowBits < 0) { /* suppress zlib wrapper */
  21584. wrap = 0;
  21585. windowBits = -windowBits;
  21586. }
  21587. else if (windowBits > 15) {
  21588. wrap = 2; /* write gzip wrapper instead */
  21589. windowBits -= 16;
  21590. }
  21591. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21592. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21593. strategy < 0 || strategy > Z_FIXED) {
  21594. return err(strm, Z_STREAM_ERROR);
  21595. }
  21596. if (windowBits === 8) {
  21597. windowBits = 9;
  21598. }
  21599. /* until 256-byte window bug fixed */
  21600. var s = new DeflateState();
  21601. strm.state = s;
  21602. s.strm = strm;
  21603. s.wrap = wrap;
  21604. s.gzhead = null;
  21605. s.w_bits = windowBits;
  21606. s.w_size = 1 << s.w_bits;
  21607. s.w_mask = s.w_size - 1;
  21608. s.hash_bits = memLevel + 7;
  21609. s.hash_size = 1 << s.hash_bits;
  21610. s.hash_mask = s.hash_size - 1;
  21611. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21612. s.window = new utils.Buf8(s.w_size * 2);
  21613. s.head = new utils.Buf16(s.hash_size);
  21614. s.prev = new utils.Buf16(s.w_size);
  21615. // Don't need mem init magic for JS.
  21616. //s.high_water = 0; /* nothing written to s->window yet */
  21617. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21618. s.pending_buf_size = s.lit_bufsize * 4;
  21619. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21620. s.d_buf = s.lit_bufsize >> 1;
  21621. s.l_buf = (1 + 2) * s.lit_bufsize;
  21622. s.level = level;
  21623. s.strategy = strategy;
  21624. s.method = method;
  21625. return deflateReset(strm);
  21626. }
  21627. function deflateInit(strm, level) {
  21628. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21629. }
  21630. function deflate(strm, flush) {
  21631. var old_flush, s;
  21632. var beg, val; // for gzip header write only
  21633. if (!strm || !strm.state ||
  21634. flush > Z_BLOCK || flush < 0) {
  21635. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21636. }
  21637. s = strm.state;
  21638. if (!strm.output ||
  21639. (!strm.input && strm.avail_in !== 0) ||
  21640. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21641. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21642. }
  21643. s.strm = strm; /* just in case */
  21644. old_flush = s.last_flush;
  21645. s.last_flush = flush;
  21646. /* Write the header */
  21647. if (s.status === INIT_STATE) {
  21648. if (s.wrap === 2) { // GZIP header
  21649. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21650. put_byte(s, 31);
  21651. put_byte(s, 139);
  21652. put_byte(s, 8);
  21653. if (!s.gzhead) { // s->gzhead == Z_NULL
  21654. put_byte(s, 0);
  21655. put_byte(s, 0);
  21656. put_byte(s, 0);
  21657. put_byte(s, 0);
  21658. put_byte(s, 0);
  21659. put_byte(s, s.level === 9 ? 2 :
  21660. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21661. 4 : 0));
  21662. put_byte(s, OS_CODE);
  21663. s.status = BUSY_STATE;
  21664. }
  21665. else {
  21666. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21667. (s.gzhead.hcrc ? 2 : 0) +
  21668. (!s.gzhead.extra ? 0 : 4) +
  21669. (!s.gzhead.name ? 0 : 8) +
  21670. (!s.gzhead.comment ? 0 : 16)
  21671. );
  21672. put_byte(s, s.gzhead.time & 0xff);
  21673. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21674. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21675. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21676. put_byte(s, s.level === 9 ? 2 :
  21677. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21678. 4 : 0));
  21679. put_byte(s, s.gzhead.os & 0xff);
  21680. if (s.gzhead.extra && s.gzhead.extra.length) {
  21681. put_byte(s, s.gzhead.extra.length & 0xff);
  21682. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21683. }
  21684. if (s.gzhead.hcrc) {
  21685. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21686. }
  21687. s.gzindex = 0;
  21688. s.status = EXTRA_STATE;
  21689. }
  21690. }
  21691. else // DEFLATE header
  21692. {
  21693. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21694. var level_flags = -1;
  21695. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21696. level_flags = 0;
  21697. } else if (s.level < 6) {
  21698. level_flags = 1;
  21699. } else if (s.level === 6) {
  21700. level_flags = 2;
  21701. } else {
  21702. level_flags = 3;
  21703. }
  21704. header |= (level_flags << 6);
  21705. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21706. header += 31 - (header % 31);
  21707. s.status = BUSY_STATE;
  21708. putShortMSB(s, header);
  21709. /* Save the adler32 of the preset dictionary: */
  21710. if (s.strstart !== 0) {
  21711. putShortMSB(s, strm.adler >>> 16);
  21712. putShortMSB(s, strm.adler & 0xffff);
  21713. }
  21714. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21715. }
  21716. }
  21717. //#ifdef GZIP
  21718. if (s.status === EXTRA_STATE) {
  21719. if (s.gzhead.extra/* != Z_NULL*/) {
  21720. beg = s.pending; /* start of bytes to update crc */
  21721. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21722. if (s.pending === s.pending_buf_size) {
  21723. if (s.gzhead.hcrc && s.pending > beg) {
  21724. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21725. }
  21726. flush_pending(strm);
  21727. beg = s.pending;
  21728. if (s.pending === s.pending_buf_size) {
  21729. break;
  21730. }
  21731. }
  21732. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21733. s.gzindex++;
  21734. }
  21735. if (s.gzhead.hcrc && s.pending > beg) {
  21736. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21737. }
  21738. if (s.gzindex === s.gzhead.extra.length) {
  21739. s.gzindex = 0;
  21740. s.status = NAME_STATE;
  21741. }
  21742. }
  21743. else {
  21744. s.status = NAME_STATE;
  21745. }
  21746. }
  21747. if (s.status === NAME_STATE) {
  21748. if (s.gzhead.name/* != Z_NULL*/) {
  21749. beg = s.pending; /* start of bytes to update crc */
  21750. //int val;
  21751. do {
  21752. if (s.pending === s.pending_buf_size) {
  21753. if (s.gzhead.hcrc && s.pending > beg) {
  21754. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21755. }
  21756. flush_pending(strm);
  21757. beg = s.pending;
  21758. if (s.pending === s.pending_buf_size) {
  21759. val = 1;
  21760. break;
  21761. }
  21762. }
  21763. // JS specific: little magic to add zero terminator to end of string
  21764. if (s.gzindex < s.gzhead.name.length) {
  21765. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21766. } else {
  21767. val = 0;
  21768. }
  21769. put_byte(s, val);
  21770. } while (val !== 0);
  21771. if (s.gzhead.hcrc && s.pending > beg) {
  21772. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21773. }
  21774. if (val === 0) {
  21775. s.gzindex = 0;
  21776. s.status = COMMENT_STATE;
  21777. }
  21778. }
  21779. else {
  21780. s.status = COMMENT_STATE;
  21781. }
  21782. }
  21783. if (s.status === COMMENT_STATE) {
  21784. if (s.gzhead.comment/* != Z_NULL*/) {
  21785. beg = s.pending; /* start of bytes to update crc */
  21786. //int val;
  21787. do {
  21788. if (s.pending === s.pending_buf_size) {
  21789. if (s.gzhead.hcrc && s.pending > beg) {
  21790. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21791. }
  21792. flush_pending(strm);
  21793. beg = s.pending;
  21794. if (s.pending === s.pending_buf_size) {
  21795. val = 1;
  21796. break;
  21797. }
  21798. }
  21799. // JS specific: little magic to add zero terminator to end of string
  21800. if (s.gzindex < s.gzhead.comment.length) {
  21801. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21802. } else {
  21803. val = 0;
  21804. }
  21805. put_byte(s, val);
  21806. } while (val !== 0);
  21807. if (s.gzhead.hcrc && s.pending > beg) {
  21808. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21809. }
  21810. if (val === 0) {
  21811. s.status = HCRC_STATE;
  21812. }
  21813. }
  21814. else {
  21815. s.status = HCRC_STATE;
  21816. }
  21817. }
  21818. if (s.status === HCRC_STATE) {
  21819. if (s.gzhead.hcrc) {
  21820. if (s.pending + 2 > s.pending_buf_size) {
  21821. flush_pending(strm);
  21822. }
  21823. if (s.pending + 2 <= s.pending_buf_size) {
  21824. put_byte(s, strm.adler & 0xff);
  21825. put_byte(s, (strm.adler >> 8) & 0xff);
  21826. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21827. s.status = BUSY_STATE;
  21828. }
  21829. }
  21830. else {
  21831. s.status = BUSY_STATE;
  21832. }
  21833. }
  21834. //#endif
  21835. /* Flush as much pending output as possible */
  21836. if (s.pending !== 0) {
  21837. flush_pending(strm);
  21838. if (strm.avail_out === 0) {
  21839. /* Since avail_out is 0, deflate will be called again with
  21840. * more output space, but possibly with both pending and
  21841. * avail_in equal to zero. There won't be anything to do,
  21842. * but this is not an error situation so make sure we
  21843. * return OK instead of BUF_ERROR at next call of deflate:
  21844. */
  21845. s.last_flush = -1;
  21846. return Z_OK;
  21847. }
  21848. /* Make sure there is something to do and avoid duplicate consecutive
  21849. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21850. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21851. */
  21852. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21853. flush !== Z_FINISH) {
  21854. return err(strm, Z_BUF_ERROR);
  21855. }
  21856. /* User must not provide more input after the first FINISH: */
  21857. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21858. return err(strm, Z_BUF_ERROR);
  21859. }
  21860. /* Start a new block or continue the current one.
  21861. */
  21862. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21863. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21864. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21865. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21866. configuration_table[s.level].func(s, flush));
  21867. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21868. s.status = FINISH_STATE;
  21869. }
  21870. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21871. if (strm.avail_out === 0) {
  21872. s.last_flush = -1;
  21873. /* avoid BUF_ERROR next call, see above */
  21874. }
  21875. return Z_OK;
  21876. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21877. * of deflate should use the same flush parameter to make sure
  21878. * that the flush is complete. So we don't have to output an
  21879. * empty block here, this will be done at next call. This also
  21880. * ensures that for a very small output buffer, we emit at most
  21881. * one empty block.
  21882. */
  21883. }
  21884. if (bstate === BS_BLOCK_DONE) {
  21885. if (flush === Z_PARTIAL_FLUSH) {
  21886. trees._tr_align(s);
  21887. }
  21888. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21889. trees._tr_stored_block(s, 0, 0, false);
  21890. /* For a full flush, this empty block will be recognized
  21891. * as a special marker by inflate_sync().
  21892. */
  21893. if (flush === Z_FULL_FLUSH) {
  21894. /*** CLEAR_HASH(s); ***/ /* forget history */
  21895. zero(s.head); // Fill with NIL (= 0);
  21896. if (s.lookahead === 0) {
  21897. s.strstart = 0;
  21898. s.block_start = 0;
  21899. s.insert = 0;
  21900. }
  21901. }
  21902. }
  21903. flush_pending(strm);
  21904. if (strm.avail_out === 0) {
  21905. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21906. return Z_OK;
  21907. }
  21908. }
  21909. }
  21910. //Assert(strm->avail_out > 0, "bug2");
  21911. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21912. if (flush !== Z_FINISH) { return Z_OK; }
  21913. if (s.wrap <= 0) { return Z_STREAM_END; }
  21914. /* Write the trailer */
  21915. if (s.wrap === 2) {
  21916. put_byte(s, strm.adler & 0xff);
  21917. put_byte(s, (strm.adler >> 8) & 0xff);
  21918. put_byte(s, (strm.adler >> 16) & 0xff);
  21919. put_byte(s, (strm.adler >> 24) & 0xff);
  21920. put_byte(s, strm.total_in & 0xff);
  21921. put_byte(s, (strm.total_in >> 8) & 0xff);
  21922. put_byte(s, (strm.total_in >> 16) & 0xff);
  21923. put_byte(s, (strm.total_in >> 24) & 0xff);
  21924. }
  21925. else
  21926. {
  21927. putShortMSB(s, strm.adler >>> 16);
  21928. putShortMSB(s, strm.adler & 0xffff);
  21929. }
  21930. flush_pending(strm);
  21931. /* If avail_out is zero, the application will call deflate again
  21932. * to flush the rest.
  21933. */
  21934. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21935. /* write the trailer only once! */
  21936. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21937. }
  21938. function deflateEnd(strm) {
  21939. var status;
  21940. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21941. return Z_STREAM_ERROR;
  21942. }
  21943. status = strm.state.status;
  21944. if (status !== INIT_STATE &&
  21945. status !== EXTRA_STATE &&
  21946. status !== NAME_STATE &&
  21947. status !== COMMENT_STATE &&
  21948. status !== HCRC_STATE &&
  21949. status !== BUSY_STATE &&
  21950. status !== FINISH_STATE
  21951. ) {
  21952. return err(strm, Z_STREAM_ERROR);
  21953. }
  21954. strm.state = null;
  21955. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21956. }
  21957. /* =========================================================================
  21958. * Copy the source state to the destination state
  21959. */
  21960. //function deflateCopy(dest, source) {
  21961. //
  21962. //}
  21963. exports.deflateInit = deflateInit;
  21964. exports.deflateInit2 = deflateInit2;
  21965. exports.deflateReset = deflateReset;
  21966. exports.deflateResetKeep = deflateResetKeep;
  21967. exports.deflateSetHeader = deflateSetHeader;
  21968. exports.deflate = deflate;
  21969. exports.deflateEnd = deflateEnd;
  21970. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21971. /* Not implemented
  21972. exports.deflateBound = deflateBound;
  21973. exports.deflateCopy = deflateCopy;
  21974. exports.deflateSetDictionary = deflateSetDictionary;
  21975. exports.deflateParams = deflateParams;
  21976. exports.deflatePending = deflatePending;
  21977. exports.deflatePrime = deflatePrime;
  21978. exports.deflateTune = deflateTune;
  21979. */
  21980. },{"../utils/common":73,"./adler32":75,"./crc32":77,"./messages":83,"./trees":84}],79:[function(require,module,exports){
  21981. 'use strict';
  21982. function GZheader() {
  21983. /* true if compressed data believed to be text */
  21984. this.text = 0;
  21985. /* modification time */
  21986. this.time = 0;
  21987. /* extra flags (not used when writing a gzip file) */
  21988. this.xflags = 0;
  21989. /* operating system */
  21990. this.os = 0;
  21991. /* pointer to extra field or Z_NULL if none */
  21992. this.extra = null;
  21993. /* extra field length (valid if extra != Z_NULL) */
  21994. this.extra_len = 0; // Actually, we don't need it in JS,
  21995. // but leave for few code modifications
  21996. //
  21997. // Setup limits is not necessary because in js we should not preallocate memory
  21998. // for inflate use constant limit in 65536 bytes
  21999. //
  22000. /* space at extra (only when reading header) */
  22001. // this.extra_max = 0;
  22002. /* pointer to zero-terminated file name or Z_NULL */
  22003. this.name = '';
  22004. /* space at name (only when reading header) */
  22005. // this.name_max = 0;
  22006. /* pointer to zero-terminated comment or Z_NULL */
  22007. this.comment = '';
  22008. /* space at comment (only when reading header) */
  22009. // this.comm_max = 0;
  22010. /* true if there was or will be a header crc */
  22011. this.hcrc = 0;
  22012. /* true when done reading gzip header (not used when writing a gzip file) */
  22013. this.done = false;
  22014. }
  22015. module.exports = GZheader;
  22016. },{}],80:[function(require,module,exports){
  22017. 'use strict';
  22018. // See state defs from inflate.js
  22019. var BAD = 30; /* got a data error -- remain here until reset */
  22020. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22021. /*
  22022. Decode literal, length, and distance codes and write out the resulting
  22023. literal and match bytes until either not enough input or output is
  22024. available, an end-of-block is encountered, or a data error is encountered.
  22025. When large enough input and output buffers are supplied to inflate(), for
  22026. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22027. inflate execution time is spent in this routine.
  22028. Entry assumptions:
  22029. state.mode === LEN
  22030. strm.avail_in >= 6
  22031. strm.avail_out >= 258
  22032. start >= strm.avail_out
  22033. state.bits < 8
  22034. On return, state.mode is one of:
  22035. LEN -- ran out of enough output space or enough available input
  22036. TYPE -- reached end of block code, inflate() to interpret next block
  22037. BAD -- error in block data
  22038. Notes:
  22039. - The maximum input bits used by a length/distance pair is 15 bits for the
  22040. length code, 5 bits for the length extra, 15 bits for the distance code,
  22041. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22042. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22043. checking for available input while decoding.
  22044. - The maximum bytes that a single length/distance pair can output is 258
  22045. bytes, which is the maximum length that can be coded. inflate_fast()
  22046. requires strm.avail_out >= 258 for each loop to avoid checking for
  22047. output space.
  22048. */
  22049. module.exports = function inflate_fast(strm, start) {
  22050. var state;
  22051. var _in; /* local strm.input */
  22052. var last; /* have enough input while in < last */
  22053. var _out; /* local strm.output */
  22054. var beg; /* inflate()'s initial strm.output */
  22055. var end; /* while out < end, enough space available */
  22056. //#ifdef INFLATE_STRICT
  22057. var dmax; /* maximum distance from zlib header */
  22058. //#endif
  22059. var wsize; /* window size or zero if not using window */
  22060. var whave; /* valid bytes in the window */
  22061. var wnext; /* window write index */
  22062. var window; /* allocated sliding window, if wsize != 0 */
  22063. var hold; /* local strm.hold */
  22064. var bits; /* local strm.bits */
  22065. var lcode; /* local strm.lencode */
  22066. var dcode; /* local strm.distcode */
  22067. var lmask; /* mask for first level of length codes */
  22068. var dmask; /* mask for first level of distance codes */
  22069. var here; /* retrieved table entry */
  22070. var op; /* code bits, operation, extra bits, or */
  22071. /* window position, window bytes to copy */
  22072. var len; /* match length, unused bytes */
  22073. var dist; /* match distance */
  22074. var from; /* where to copy match from */
  22075. var from_source;
  22076. var input, output; // JS specific, because we have no pointers
  22077. /* copy state to local variables */
  22078. state = strm.state;
  22079. //here = state.here;
  22080. _in = strm.next_in;
  22081. input = strm.input;
  22082. last = _in + (strm.avail_in - 5);
  22083. _out = strm.next_out;
  22084. output = strm.output;
  22085. beg = _out - (start - strm.avail_out);
  22086. end = _out + (strm.avail_out - 257);
  22087. //#ifdef INFLATE_STRICT
  22088. dmax = state.dmax;
  22089. //#endif
  22090. wsize = state.wsize;
  22091. whave = state.whave;
  22092. wnext = state.wnext;
  22093. window = state.window;
  22094. hold = state.hold;
  22095. bits = state.bits;
  22096. lcode = state.lencode;
  22097. dcode = state.distcode;
  22098. lmask = (1 << state.lenbits) - 1;
  22099. dmask = (1 << state.distbits) - 1;
  22100. /* decode literals and length/distances until end-of-block or not enough
  22101. input data or output space */
  22102. top:
  22103. do {
  22104. if (bits < 15) {
  22105. hold += input[_in++] << bits;
  22106. bits += 8;
  22107. hold += input[_in++] << bits;
  22108. bits += 8;
  22109. }
  22110. here = lcode[hold & lmask];
  22111. dolen:
  22112. for (;;) { // Goto emulation
  22113. op = here >>> 24/*here.bits*/;
  22114. hold >>>= op;
  22115. bits -= op;
  22116. op = (here >>> 16) & 0xff/*here.op*/;
  22117. if (op === 0) { /* literal */
  22118. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22119. // "inflate: literal '%c'\n" :
  22120. // "inflate: literal 0x%02x\n", here.val));
  22121. output[_out++] = here & 0xffff/*here.val*/;
  22122. }
  22123. else if (op & 16) { /* length base */
  22124. len = here & 0xffff/*here.val*/;
  22125. op &= 15; /* number of extra bits */
  22126. if (op) {
  22127. if (bits < op) {
  22128. hold += input[_in++] << bits;
  22129. bits += 8;
  22130. }
  22131. len += hold & ((1 << op) - 1);
  22132. hold >>>= op;
  22133. bits -= op;
  22134. }
  22135. //Tracevv((stderr, "inflate: length %u\n", len));
  22136. if (bits < 15) {
  22137. hold += input[_in++] << bits;
  22138. bits += 8;
  22139. hold += input[_in++] << bits;
  22140. bits += 8;
  22141. }
  22142. here = dcode[hold & dmask];
  22143. dodist:
  22144. for (;;) { // goto emulation
  22145. op = here >>> 24/*here.bits*/;
  22146. hold >>>= op;
  22147. bits -= op;
  22148. op = (here >>> 16) & 0xff/*here.op*/;
  22149. if (op & 16) { /* distance base */
  22150. dist = here & 0xffff/*here.val*/;
  22151. op &= 15; /* number of extra bits */
  22152. if (bits < op) {
  22153. hold += input[_in++] << bits;
  22154. bits += 8;
  22155. if (bits < op) {
  22156. hold += input[_in++] << bits;
  22157. bits += 8;
  22158. }
  22159. }
  22160. dist += hold & ((1 << op) - 1);
  22161. //#ifdef INFLATE_STRICT
  22162. if (dist > dmax) {
  22163. strm.msg = 'invalid distance too far back';
  22164. state.mode = BAD;
  22165. break top;
  22166. }
  22167. //#endif
  22168. hold >>>= op;
  22169. bits -= op;
  22170. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22171. op = _out - beg; /* max distance in output */
  22172. if (dist > op) { /* see if copy from window */
  22173. op = dist - op; /* distance back in window */
  22174. if (op > whave) {
  22175. if (state.sane) {
  22176. strm.msg = 'invalid distance too far back';
  22177. state.mode = BAD;
  22178. break top;
  22179. }
  22180. // (!) This block is disabled in zlib defailts,
  22181. // don't enable it for binary compatibility
  22182. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22183. // if (len <= op - whave) {
  22184. // do {
  22185. // output[_out++] = 0;
  22186. // } while (--len);
  22187. // continue top;
  22188. // }
  22189. // len -= op - whave;
  22190. // do {
  22191. // output[_out++] = 0;
  22192. // } while (--op > whave);
  22193. // if (op === 0) {
  22194. // from = _out - dist;
  22195. // do {
  22196. // output[_out++] = output[from++];
  22197. // } while (--len);
  22198. // continue top;
  22199. // }
  22200. //#endif
  22201. }
  22202. from = 0; // window index
  22203. from_source = window;
  22204. if (wnext === 0) { /* very common case */
  22205. from += wsize - op;
  22206. if (op < len) { /* some from window */
  22207. len -= op;
  22208. do {
  22209. output[_out++] = window[from++];
  22210. } while (--op);
  22211. from = _out - dist; /* rest from output */
  22212. from_source = output;
  22213. }
  22214. }
  22215. else if (wnext < op) { /* wrap around window */
  22216. from += wsize + wnext - op;
  22217. op -= wnext;
  22218. if (op < len) { /* some from end of window */
  22219. len -= op;
  22220. do {
  22221. output[_out++] = window[from++];
  22222. } while (--op);
  22223. from = 0;
  22224. if (wnext < len) { /* some from start of window */
  22225. op = wnext;
  22226. len -= op;
  22227. do {
  22228. output[_out++] = window[from++];
  22229. } while (--op);
  22230. from = _out - dist; /* rest from output */
  22231. from_source = output;
  22232. }
  22233. }
  22234. }
  22235. else { /* contiguous in window */
  22236. from += wnext - op;
  22237. if (op < len) { /* some from window */
  22238. len -= op;
  22239. do {
  22240. output[_out++] = window[from++];
  22241. } while (--op);
  22242. from = _out - dist; /* rest from output */
  22243. from_source = output;
  22244. }
  22245. }
  22246. while (len > 2) {
  22247. output[_out++] = from_source[from++];
  22248. output[_out++] = from_source[from++];
  22249. output[_out++] = from_source[from++];
  22250. len -= 3;
  22251. }
  22252. if (len) {
  22253. output[_out++] = from_source[from++];
  22254. if (len > 1) {
  22255. output[_out++] = from_source[from++];
  22256. }
  22257. }
  22258. }
  22259. else {
  22260. from = _out - dist; /* copy direct from output */
  22261. do { /* minimum length is three */
  22262. output[_out++] = output[from++];
  22263. output[_out++] = output[from++];
  22264. output[_out++] = output[from++];
  22265. len -= 3;
  22266. } while (len > 2);
  22267. if (len) {
  22268. output[_out++] = output[from++];
  22269. if (len > 1) {
  22270. output[_out++] = output[from++];
  22271. }
  22272. }
  22273. }
  22274. }
  22275. else if ((op & 64) === 0) { /* 2nd level distance code */
  22276. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22277. continue dodist;
  22278. }
  22279. else {
  22280. strm.msg = 'invalid distance code';
  22281. state.mode = BAD;
  22282. break top;
  22283. }
  22284. break; // need to emulate goto via "continue"
  22285. }
  22286. }
  22287. else if ((op & 64) === 0) { /* 2nd level length code */
  22288. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22289. continue dolen;
  22290. }
  22291. else if (op & 32) { /* end-of-block */
  22292. //Tracevv((stderr, "inflate: end of block\n"));
  22293. state.mode = TYPE;
  22294. break top;
  22295. }
  22296. else {
  22297. strm.msg = 'invalid literal/length code';
  22298. state.mode = BAD;
  22299. break top;
  22300. }
  22301. break; // need to emulate goto via "continue"
  22302. }
  22303. } while (_in < last && _out < end);
  22304. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22305. len = bits >> 3;
  22306. _in -= len;
  22307. bits -= len << 3;
  22308. hold &= (1 << bits) - 1;
  22309. /* update state and return */
  22310. strm.next_in = _in;
  22311. strm.next_out = _out;
  22312. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22313. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22314. state.hold = hold;
  22315. state.bits = bits;
  22316. return;
  22317. };
  22318. },{}],81:[function(require,module,exports){
  22319. 'use strict';
  22320. var utils = require('../utils/common');
  22321. var adler32 = require('./adler32');
  22322. var crc32 = require('./crc32');
  22323. var inflate_fast = require('./inffast');
  22324. var inflate_table = require('./inftrees');
  22325. var CODES = 0;
  22326. var LENS = 1;
  22327. var DISTS = 2;
  22328. /* Public constants ==========================================================*/
  22329. /* ===========================================================================*/
  22330. /* Allowed flush values; see deflate() and inflate() below for details */
  22331. //var Z_NO_FLUSH = 0;
  22332. //var Z_PARTIAL_FLUSH = 1;
  22333. //var Z_SYNC_FLUSH = 2;
  22334. //var Z_FULL_FLUSH = 3;
  22335. var Z_FINISH = 4;
  22336. var Z_BLOCK = 5;
  22337. var Z_TREES = 6;
  22338. /* Return codes for the compression/decompression functions. Negative values
  22339. * are errors, positive values are used for special but normal events.
  22340. */
  22341. var Z_OK = 0;
  22342. var Z_STREAM_END = 1;
  22343. var Z_NEED_DICT = 2;
  22344. //var Z_ERRNO = -1;
  22345. var Z_STREAM_ERROR = -2;
  22346. var Z_DATA_ERROR = -3;
  22347. var Z_MEM_ERROR = -4;
  22348. var Z_BUF_ERROR = -5;
  22349. //var Z_VERSION_ERROR = -6;
  22350. /* The deflate compression method */
  22351. var Z_DEFLATED = 8;
  22352. /* STATES ====================================================================*/
  22353. /* ===========================================================================*/
  22354. var HEAD = 1; /* i: waiting for magic header */
  22355. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22356. var TIME = 3; /* i: waiting for modification time (gzip) */
  22357. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22358. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22359. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22360. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22361. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22362. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22363. var DICTID = 10; /* i: waiting for dictionary check value */
  22364. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22365. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22366. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22367. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22368. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22369. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22370. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22371. var LENLENS = 18; /* i: waiting for code length code lengths */
  22372. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22373. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22374. var LEN = 21; /* i: waiting for length/lit/eob code */
  22375. var LENEXT = 22; /* i: waiting for length extra bits */
  22376. var DIST = 23; /* i: waiting for distance code */
  22377. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22378. var MATCH = 25; /* o: waiting for output space to copy string */
  22379. var LIT = 26; /* o: waiting for output space to write literal */
  22380. var CHECK = 27; /* i: waiting for 32-bit check value */
  22381. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22382. var DONE = 29; /* finished check, done -- remain here until reset */
  22383. var BAD = 30; /* got a data error -- remain here until reset */
  22384. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22385. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22386. /* ===========================================================================*/
  22387. var ENOUGH_LENS = 852;
  22388. var ENOUGH_DISTS = 592;
  22389. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22390. var MAX_WBITS = 15;
  22391. /* 32K LZ77 window */
  22392. var DEF_WBITS = MAX_WBITS;
  22393. function ZSWAP32(q) {
  22394. return (((q >>> 24) & 0xff) +
  22395. ((q >>> 8) & 0xff00) +
  22396. ((q & 0xff00) << 8) +
  22397. ((q & 0xff) << 24));
  22398. }
  22399. function InflateState() {
  22400. this.mode = 0; /* current inflate mode */
  22401. this.last = false; /* true if processing last block */
  22402. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22403. this.havedict = false; /* true if dictionary provided */
  22404. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22405. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22406. this.check = 0; /* protected copy of check value */
  22407. this.total = 0; /* protected copy of output count */
  22408. // TODO: may be {}
  22409. this.head = null; /* where to save gzip header information */
  22410. /* sliding window */
  22411. this.wbits = 0; /* log base 2 of requested window size */
  22412. this.wsize = 0; /* window size or zero if not using window */
  22413. this.whave = 0; /* valid bytes in the window */
  22414. this.wnext = 0; /* window write index */
  22415. this.window = null; /* allocated sliding window, if needed */
  22416. /* bit accumulator */
  22417. this.hold = 0; /* input bit accumulator */
  22418. this.bits = 0; /* number of bits in "in" */
  22419. /* for string and stored block copying */
  22420. this.length = 0; /* literal or length of data to copy */
  22421. this.offset = 0; /* distance back to copy string from */
  22422. /* for table and code decoding */
  22423. this.extra = 0; /* extra bits needed */
  22424. /* fixed and dynamic code tables */
  22425. this.lencode = null; /* starting table for length/literal codes */
  22426. this.distcode = null; /* starting table for distance codes */
  22427. this.lenbits = 0; /* index bits for lencode */
  22428. this.distbits = 0; /* index bits for distcode */
  22429. /* dynamic table building */
  22430. this.ncode = 0; /* number of code length code lengths */
  22431. this.nlen = 0; /* number of length code lengths */
  22432. this.ndist = 0; /* number of distance code lengths */
  22433. this.have = 0; /* number of code lengths in lens[] */
  22434. this.next = null; /* next available space in codes[] */
  22435. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22436. this.work = new utils.Buf16(288); /* work area for code table building */
  22437. /*
  22438. because we don't have pointers in js, we use lencode and distcode directly
  22439. as buffers so we don't need codes
  22440. */
  22441. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22442. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22443. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22444. this.sane = 0; /* if false, allow invalid distance too far */
  22445. this.back = 0; /* bits back of last unprocessed length/lit */
  22446. this.was = 0; /* initial length of match */
  22447. }
  22448. function inflateResetKeep(strm) {
  22449. var state;
  22450. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22451. state = strm.state;
  22452. strm.total_in = strm.total_out = state.total = 0;
  22453. strm.msg = ''; /*Z_NULL*/
  22454. if (state.wrap) { /* to support ill-conceived Java test suite */
  22455. strm.adler = state.wrap & 1;
  22456. }
  22457. state.mode = HEAD;
  22458. state.last = 0;
  22459. state.havedict = 0;
  22460. state.dmax = 32768;
  22461. state.head = null/*Z_NULL*/;
  22462. state.hold = 0;
  22463. state.bits = 0;
  22464. //state.lencode = state.distcode = state.next = state.codes;
  22465. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22466. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22467. state.sane = 1;
  22468. state.back = -1;
  22469. //Tracev((stderr, "inflate: reset\n"));
  22470. return Z_OK;
  22471. }
  22472. function inflateReset(strm) {
  22473. var state;
  22474. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22475. state = strm.state;
  22476. state.wsize = 0;
  22477. state.whave = 0;
  22478. state.wnext = 0;
  22479. return inflateResetKeep(strm);
  22480. }
  22481. function inflateReset2(strm, windowBits) {
  22482. var wrap;
  22483. var state;
  22484. /* get the state */
  22485. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22486. state = strm.state;
  22487. /* extract wrap request from windowBits parameter */
  22488. if (windowBits < 0) {
  22489. wrap = 0;
  22490. windowBits = -windowBits;
  22491. }
  22492. else {
  22493. wrap = (windowBits >> 4) + 1;
  22494. if (windowBits < 48) {
  22495. windowBits &= 15;
  22496. }
  22497. }
  22498. /* set number of window bits, free window if different */
  22499. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22500. return Z_STREAM_ERROR;
  22501. }
  22502. if (state.window !== null && state.wbits !== windowBits) {
  22503. state.window = null;
  22504. }
  22505. /* update state and reset the rest of it */
  22506. state.wrap = wrap;
  22507. state.wbits = windowBits;
  22508. return inflateReset(strm);
  22509. }
  22510. function inflateInit2(strm, windowBits) {
  22511. var ret;
  22512. var state;
  22513. if (!strm) { return Z_STREAM_ERROR; }
  22514. //strm.msg = Z_NULL; /* in case we return an error */
  22515. state = new InflateState();
  22516. //if (state === Z_NULL) return Z_MEM_ERROR;
  22517. //Tracev((stderr, "inflate: allocated\n"));
  22518. strm.state = state;
  22519. state.window = null/*Z_NULL*/;
  22520. ret = inflateReset2(strm, windowBits);
  22521. if (ret !== Z_OK) {
  22522. strm.state = null/*Z_NULL*/;
  22523. }
  22524. return ret;
  22525. }
  22526. function inflateInit(strm) {
  22527. return inflateInit2(strm, DEF_WBITS);
  22528. }
  22529. /*
  22530. Return state with length and distance decoding tables and index sizes set to
  22531. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22532. If BUILDFIXED is defined, then instead this routine builds the tables the
  22533. first time it's called, and returns those tables the first time and
  22534. thereafter. This reduces the size of the code by about 2K bytes, in
  22535. exchange for a little execution time. However, BUILDFIXED should not be
  22536. used for threaded applications, since the rewriting of the tables and virgin
  22537. may not be thread-safe.
  22538. */
  22539. var virgin = true;
  22540. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22541. function fixedtables(state) {
  22542. /* build fixed huffman tables if first call (may not be thread safe) */
  22543. if (virgin) {
  22544. var sym;
  22545. lenfix = new utils.Buf32(512);
  22546. distfix = new utils.Buf32(32);
  22547. /* literal/length table */
  22548. sym = 0;
  22549. while (sym < 144) { state.lens[sym++] = 8; }
  22550. while (sym < 256) { state.lens[sym++] = 9; }
  22551. while (sym < 280) { state.lens[sym++] = 7; }
  22552. while (sym < 288) { state.lens[sym++] = 8; }
  22553. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22554. /* distance table */
  22555. sym = 0;
  22556. while (sym < 32) { state.lens[sym++] = 5; }
  22557. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22558. /* do this just once */
  22559. virgin = false;
  22560. }
  22561. state.lencode = lenfix;
  22562. state.lenbits = 9;
  22563. state.distcode = distfix;
  22564. state.distbits = 5;
  22565. }
  22566. /*
  22567. Update the window with the last wsize (normally 32K) bytes written before
  22568. returning. If window does not exist yet, create it. This is only called
  22569. when a window is already in use, or when output has been written during this
  22570. inflate call, but the end of the deflate stream has not been reached yet.
  22571. It is also called to create a window for dictionary data when a dictionary
  22572. is loaded.
  22573. Providing output buffers larger than 32K to inflate() should provide a speed
  22574. advantage, since only the last 32K of output is copied to the sliding window
  22575. upon return from inflate(), and since all distances after the first 32K of
  22576. output will fall in the output data, making match copies simpler and faster.
  22577. The advantage may be dependent on the size of the processor's data caches.
  22578. */
  22579. function updatewindow(strm, src, end, copy) {
  22580. var dist;
  22581. var state = strm.state;
  22582. /* if it hasn't been done already, allocate space for the window */
  22583. if (state.window === null) {
  22584. state.wsize = 1 << state.wbits;
  22585. state.wnext = 0;
  22586. state.whave = 0;
  22587. state.window = new utils.Buf8(state.wsize);
  22588. }
  22589. /* copy state->wsize or less output bytes into the circular window */
  22590. if (copy >= state.wsize) {
  22591. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22592. state.wnext = 0;
  22593. state.whave = state.wsize;
  22594. }
  22595. else {
  22596. dist = state.wsize - state.wnext;
  22597. if (dist > copy) {
  22598. dist = copy;
  22599. }
  22600. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22601. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22602. copy -= dist;
  22603. if (copy) {
  22604. //zmemcpy(state->window, end - copy, copy);
  22605. utils.arraySet(state.window,src, end - copy, copy, 0);
  22606. state.wnext = copy;
  22607. state.whave = state.wsize;
  22608. }
  22609. else {
  22610. state.wnext += dist;
  22611. if (state.wnext === state.wsize) { state.wnext = 0; }
  22612. if (state.whave < state.wsize) { state.whave += dist; }
  22613. }
  22614. }
  22615. return 0;
  22616. }
  22617. function inflate(strm, flush) {
  22618. var state;
  22619. var input, output; // input/output buffers
  22620. var next; /* next input INDEX */
  22621. var put; /* next output INDEX */
  22622. var have, left; /* available input and output */
  22623. var hold; /* bit buffer */
  22624. var bits; /* bits in bit buffer */
  22625. var _in, _out; /* save starting available input and output */
  22626. var copy; /* number of stored or match bytes to copy */
  22627. var from; /* where to copy match bytes from */
  22628. var from_source;
  22629. var here = 0; /* current decoding table entry */
  22630. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22631. //var last; /* parent table entry */
  22632. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22633. var len; /* length to copy for repeats, bits to drop */
  22634. var ret; /* return code */
  22635. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22636. var opts;
  22637. var n; // temporary var for NEED_BITS
  22638. var order = /* permutation of code lengths */
  22639. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22640. if (!strm || !strm.state || !strm.output ||
  22641. (!strm.input && strm.avail_in !== 0)) {
  22642. return Z_STREAM_ERROR;
  22643. }
  22644. state = strm.state;
  22645. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22646. //--- LOAD() ---
  22647. put = strm.next_out;
  22648. output = strm.output;
  22649. left = strm.avail_out;
  22650. next = strm.next_in;
  22651. input = strm.input;
  22652. have = strm.avail_in;
  22653. hold = state.hold;
  22654. bits = state.bits;
  22655. //---
  22656. _in = have;
  22657. _out = left;
  22658. ret = Z_OK;
  22659. inf_leave: // goto emulation
  22660. for (;;) {
  22661. switch (state.mode) {
  22662. case HEAD:
  22663. if (state.wrap === 0) {
  22664. state.mode = TYPEDO;
  22665. break;
  22666. }
  22667. //=== NEEDBITS(16);
  22668. while (bits < 16) {
  22669. if (have === 0) { break inf_leave; }
  22670. have--;
  22671. hold += input[next++] << bits;
  22672. bits += 8;
  22673. }
  22674. //===//
  22675. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22676. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22677. //=== CRC2(state.check, hold);
  22678. hbuf[0] = hold & 0xff;
  22679. hbuf[1] = (hold >>> 8) & 0xff;
  22680. state.check = crc32(state.check, hbuf, 2, 0);
  22681. //===//
  22682. //=== INITBITS();
  22683. hold = 0;
  22684. bits = 0;
  22685. //===//
  22686. state.mode = FLAGS;
  22687. break;
  22688. }
  22689. state.flags = 0; /* expect zlib header */
  22690. if (state.head) {
  22691. state.head.done = false;
  22692. }
  22693. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22694. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22695. strm.msg = 'incorrect header check';
  22696. state.mode = BAD;
  22697. break;
  22698. }
  22699. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22700. strm.msg = 'unknown compression method';
  22701. state.mode = BAD;
  22702. break;
  22703. }
  22704. //--- DROPBITS(4) ---//
  22705. hold >>>= 4;
  22706. bits -= 4;
  22707. //---//
  22708. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22709. if (state.wbits === 0) {
  22710. state.wbits = len;
  22711. }
  22712. else if (len > state.wbits) {
  22713. strm.msg = 'invalid window size';
  22714. state.mode = BAD;
  22715. break;
  22716. }
  22717. state.dmax = 1 << len;
  22718. //Tracev((stderr, "inflate: zlib header ok\n"));
  22719. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22720. state.mode = hold & 0x200 ? DICTID : TYPE;
  22721. //=== INITBITS();
  22722. hold = 0;
  22723. bits = 0;
  22724. //===//
  22725. break;
  22726. case FLAGS:
  22727. //=== NEEDBITS(16); */
  22728. while (bits < 16) {
  22729. if (have === 0) { break inf_leave; }
  22730. have--;
  22731. hold += input[next++] << bits;
  22732. bits += 8;
  22733. }
  22734. //===//
  22735. state.flags = hold;
  22736. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22737. strm.msg = 'unknown compression method';
  22738. state.mode = BAD;
  22739. break;
  22740. }
  22741. if (state.flags & 0xe000) {
  22742. strm.msg = 'unknown header flags set';
  22743. state.mode = BAD;
  22744. break;
  22745. }
  22746. if (state.head) {
  22747. state.head.text = ((hold >> 8) & 1);
  22748. }
  22749. if (state.flags & 0x0200) {
  22750. //=== CRC2(state.check, hold);
  22751. hbuf[0] = hold & 0xff;
  22752. hbuf[1] = (hold >>> 8) & 0xff;
  22753. state.check = crc32(state.check, hbuf, 2, 0);
  22754. //===//
  22755. }
  22756. //=== INITBITS();
  22757. hold = 0;
  22758. bits = 0;
  22759. //===//
  22760. state.mode = TIME;
  22761. /* falls through */
  22762. case TIME:
  22763. //=== NEEDBITS(32); */
  22764. while (bits < 32) {
  22765. if (have === 0) { break inf_leave; }
  22766. have--;
  22767. hold += input[next++] << bits;
  22768. bits += 8;
  22769. }
  22770. //===//
  22771. if (state.head) {
  22772. state.head.time = hold;
  22773. }
  22774. if (state.flags & 0x0200) {
  22775. //=== CRC4(state.check, hold)
  22776. hbuf[0] = hold & 0xff;
  22777. hbuf[1] = (hold >>> 8) & 0xff;
  22778. hbuf[2] = (hold >>> 16) & 0xff;
  22779. hbuf[3] = (hold >>> 24) & 0xff;
  22780. state.check = crc32(state.check, hbuf, 4, 0);
  22781. //===
  22782. }
  22783. //=== INITBITS();
  22784. hold = 0;
  22785. bits = 0;
  22786. //===//
  22787. state.mode = OS;
  22788. /* falls through */
  22789. case OS:
  22790. //=== NEEDBITS(16); */
  22791. while (bits < 16) {
  22792. if (have === 0) { break inf_leave; }
  22793. have--;
  22794. hold += input[next++] << bits;
  22795. bits += 8;
  22796. }
  22797. //===//
  22798. if (state.head) {
  22799. state.head.xflags = (hold & 0xff);
  22800. state.head.os = (hold >> 8);
  22801. }
  22802. if (state.flags & 0x0200) {
  22803. //=== CRC2(state.check, hold);
  22804. hbuf[0] = hold & 0xff;
  22805. hbuf[1] = (hold >>> 8) & 0xff;
  22806. state.check = crc32(state.check, hbuf, 2, 0);
  22807. //===//
  22808. }
  22809. //=== INITBITS();
  22810. hold = 0;
  22811. bits = 0;
  22812. //===//
  22813. state.mode = EXLEN;
  22814. /* falls through */
  22815. case EXLEN:
  22816. if (state.flags & 0x0400) {
  22817. //=== NEEDBITS(16); */
  22818. while (bits < 16) {
  22819. if (have === 0) { break inf_leave; }
  22820. have--;
  22821. hold += input[next++] << bits;
  22822. bits += 8;
  22823. }
  22824. //===//
  22825. state.length = hold;
  22826. if (state.head) {
  22827. state.head.extra_len = hold;
  22828. }
  22829. if (state.flags & 0x0200) {
  22830. //=== CRC2(state.check, hold);
  22831. hbuf[0] = hold & 0xff;
  22832. hbuf[1] = (hold >>> 8) & 0xff;
  22833. state.check = crc32(state.check, hbuf, 2, 0);
  22834. //===//
  22835. }
  22836. //=== INITBITS();
  22837. hold = 0;
  22838. bits = 0;
  22839. //===//
  22840. }
  22841. else if (state.head) {
  22842. state.head.extra = null/*Z_NULL*/;
  22843. }
  22844. state.mode = EXTRA;
  22845. /* falls through */
  22846. case EXTRA:
  22847. if (state.flags & 0x0400) {
  22848. copy = state.length;
  22849. if (copy > have) { copy = have; }
  22850. if (copy) {
  22851. if (state.head) {
  22852. len = state.head.extra_len - state.length;
  22853. if (!state.head.extra) {
  22854. // Use untyped array for more conveniend processing later
  22855. state.head.extra = new Array(state.head.extra_len);
  22856. }
  22857. utils.arraySet(
  22858. state.head.extra,
  22859. input,
  22860. next,
  22861. // extra field is limited to 65536 bytes
  22862. // - no need for additional size check
  22863. copy,
  22864. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22865. len
  22866. );
  22867. //zmemcpy(state.head.extra + len, next,
  22868. // len + copy > state.head.extra_max ?
  22869. // state.head.extra_max - len : copy);
  22870. }
  22871. if (state.flags & 0x0200) {
  22872. state.check = crc32(state.check, input, copy, next);
  22873. }
  22874. have -= copy;
  22875. next += copy;
  22876. state.length -= copy;
  22877. }
  22878. if (state.length) { break inf_leave; }
  22879. }
  22880. state.length = 0;
  22881. state.mode = NAME;
  22882. /* falls through */
  22883. case NAME:
  22884. if (state.flags & 0x0800) {
  22885. if (have === 0) { break inf_leave; }
  22886. copy = 0;
  22887. do {
  22888. // TODO: 2 or 1 bytes?
  22889. len = input[next + copy++];
  22890. /* use constant limit because in js we should not preallocate memory */
  22891. if (state.head && len &&
  22892. (state.length < 65536 /*state.head.name_max*/)) {
  22893. state.head.name += String.fromCharCode(len);
  22894. }
  22895. } while (len && copy < have);
  22896. if (state.flags & 0x0200) {
  22897. state.check = crc32(state.check, input, copy, next);
  22898. }
  22899. have -= copy;
  22900. next += copy;
  22901. if (len) { break inf_leave; }
  22902. }
  22903. else if (state.head) {
  22904. state.head.name = null;
  22905. }
  22906. state.length = 0;
  22907. state.mode = COMMENT;
  22908. /* falls through */
  22909. case COMMENT:
  22910. if (state.flags & 0x1000) {
  22911. if (have === 0) { break inf_leave; }
  22912. copy = 0;
  22913. do {
  22914. len = input[next + copy++];
  22915. /* use constant limit because in js we should not preallocate memory */
  22916. if (state.head && len &&
  22917. (state.length < 65536 /*state.head.comm_max*/)) {
  22918. state.head.comment += String.fromCharCode(len);
  22919. }
  22920. } while (len && copy < have);
  22921. if (state.flags & 0x0200) {
  22922. state.check = crc32(state.check, input, copy, next);
  22923. }
  22924. have -= copy;
  22925. next += copy;
  22926. if (len) { break inf_leave; }
  22927. }
  22928. else if (state.head) {
  22929. state.head.comment = null;
  22930. }
  22931. state.mode = HCRC;
  22932. /* falls through */
  22933. case HCRC:
  22934. if (state.flags & 0x0200) {
  22935. //=== NEEDBITS(16); */
  22936. while (bits < 16) {
  22937. if (have === 0) { break inf_leave; }
  22938. have--;
  22939. hold += input[next++] << bits;
  22940. bits += 8;
  22941. }
  22942. //===//
  22943. if (hold !== (state.check & 0xffff)) {
  22944. strm.msg = 'header crc mismatch';
  22945. state.mode = BAD;
  22946. break;
  22947. }
  22948. //=== INITBITS();
  22949. hold = 0;
  22950. bits = 0;
  22951. //===//
  22952. }
  22953. if (state.head) {
  22954. state.head.hcrc = ((state.flags >> 9) & 1);
  22955. state.head.done = true;
  22956. }
  22957. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22958. state.mode = TYPE;
  22959. break;
  22960. case DICTID:
  22961. //=== NEEDBITS(32); */
  22962. while (bits < 32) {
  22963. if (have === 0) { break inf_leave; }
  22964. have--;
  22965. hold += input[next++] << bits;
  22966. bits += 8;
  22967. }
  22968. //===//
  22969. strm.adler = state.check = ZSWAP32(hold);
  22970. //=== INITBITS();
  22971. hold = 0;
  22972. bits = 0;
  22973. //===//
  22974. state.mode = DICT;
  22975. /* falls through */
  22976. case DICT:
  22977. if (state.havedict === 0) {
  22978. //--- RESTORE() ---
  22979. strm.next_out = put;
  22980. strm.avail_out = left;
  22981. strm.next_in = next;
  22982. strm.avail_in = have;
  22983. state.hold = hold;
  22984. state.bits = bits;
  22985. //---
  22986. return Z_NEED_DICT;
  22987. }
  22988. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22989. state.mode = TYPE;
  22990. /* falls through */
  22991. case TYPE:
  22992. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22993. /* falls through */
  22994. case TYPEDO:
  22995. if (state.last) {
  22996. //--- BYTEBITS() ---//
  22997. hold >>>= bits & 7;
  22998. bits -= bits & 7;
  22999. //---//
  23000. state.mode = CHECK;
  23001. break;
  23002. }
  23003. //=== NEEDBITS(3); */
  23004. while (bits < 3) {
  23005. if (have === 0) { break inf_leave; }
  23006. have--;
  23007. hold += input[next++] << bits;
  23008. bits += 8;
  23009. }
  23010. //===//
  23011. state.last = (hold & 0x01)/*BITS(1)*/;
  23012. //--- DROPBITS(1) ---//
  23013. hold >>>= 1;
  23014. bits -= 1;
  23015. //---//
  23016. switch ((hold & 0x03)/*BITS(2)*/) {
  23017. case 0: /* stored block */
  23018. //Tracev((stderr, "inflate: stored block%s\n",
  23019. // state.last ? " (last)" : ""));
  23020. state.mode = STORED;
  23021. break;
  23022. case 1: /* fixed block */
  23023. fixedtables(state);
  23024. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23025. // state.last ? " (last)" : ""));
  23026. state.mode = LEN_; /* decode codes */
  23027. if (flush === Z_TREES) {
  23028. //--- DROPBITS(2) ---//
  23029. hold >>>= 2;
  23030. bits -= 2;
  23031. //---//
  23032. break inf_leave;
  23033. }
  23034. break;
  23035. case 2: /* dynamic block */
  23036. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23037. // state.last ? " (last)" : ""));
  23038. state.mode = TABLE;
  23039. break;
  23040. case 3:
  23041. strm.msg = 'invalid block type';
  23042. state.mode = BAD;
  23043. }
  23044. //--- DROPBITS(2) ---//
  23045. hold >>>= 2;
  23046. bits -= 2;
  23047. //---//
  23048. break;
  23049. case STORED:
  23050. //--- BYTEBITS() ---// /* go to byte boundary */
  23051. hold >>>= bits & 7;
  23052. bits -= bits & 7;
  23053. //---//
  23054. //=== NEEDBITS(32); */
  23055. while (bits < 32) {
  23056. if (have === 0) { break inf_leave; }
  23057. have--;
  23058. hold += input[next++] << bits;
  23059. bits += 8;
  23060. }
  23061. //===//
  23062. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23063. strm.msg = 'invalid stored block lengths';
  23064. state.mode = BAD;
  23065. break;
  23066. }
  23067. state.length = hold & 0xffff;
  23068. //Tracev((stderr, "inflate: stored length %u\n",
  23069. // state.length));
  23070. //=== INITBITS();
  23071. hold = 0;
  23072. bits = 0;
  23073. //===//
  23074. state.mode = COPY_;
  23075. if (flush === Z_TREES) { break inf_leave; }
  23076. /* falls through */
  23077. case COPY_:
  23078. state.mode = COPY;
  23079. /* falls through */
  23080. case COPY:
  23081. copy = state.length;
  23082. if (copy) {
  23083. if (copy > have) { copy = have; }
  23084. if (copy > left) { copy = left; }
  23085. if (copy === 0) { break inf_leave; }
  23086. //--- zmemcpy(put, next, copy); ---
  23087. utils.arraySet(output, input, next, copy, put);
  23088. //---//
  23089. have -= copy;
  23090. next += copy;
  23091. left -= copy;
  23092. put += copy;
  23093. state.length -= copy;
  23094. break;
  23095. }
  23096. //Tracev((stderr, "inflate: stored end\n"));
  23097. state.mode = TYPE;
  23098. break;
  23099. case TABLE:
  23100. //=== NEEDBITS(14); */
  23101. while (bits < 14) {
  23102. if (have === 0) { break inf_leave; }
  23103. have--;
  23104. hold += input[next++] << bits;
  23105. bits += 8;
  23106. }
  23107. //===//
  23108. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23109. //--- DROPBITS(5) ---//
  23110. hold >>>= 5;
  23111. bits -= 5;
  23112. //---//
  23113. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23114. //--- DROPBITS(5) ---//
  23115. hold >>>= 5;
  23116. bits -= 5;
  23117. //---//
  23118. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23119. //--- DROPBITS(4) ---//
  23120. hold >>>= 4;
  23121. bits -= 4;
  23122. //---//
  23123. //#ifndef PKZIP_BUG_WORKAROUND
  23124. if (state.nlen > 286 || state.ndist > 30) {
  23125. strm.msg = 'too many length or distance symbols';
  23126. state.mode = BAD;
  23127. break;
  23128. }
  23129. //#endif
  23130. //Tracev((stderr, "inflate: table sizes ok\n"));
  23131. state.have = 0;
  23132. state.mode = LENLENS;
  23133. /* falls through */
  23134. case LENLENS:
  23135. while (state.have < state.ncode) {
  23136. //=== NEEDBITS(3);
  23137. while (bits < 3) {
  23138. if (have === 0) { break inf_leave; }
  23139. have--;
  23140. hold += input[next++] << bits;
  23141. bits += 8;
  23142. }
  23143. //===//
  23144. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23145. //--- DROPBITS(3) ---//
  23146. hold >>>= 3;
  23147. bits -= 3;
  23148. //---//
  23149. }
  23150. while (state.have < 19) {
  23151. state.lens[order[state.have++]] = 0;
  23152. }
  23153. // We have separate tables & no pointers. 2 commented lines below not needed.
  23154. //state.next = state.codes;
  23155. //state.lencode = state.next;
  23156. // Switch to use dynamic table
  23157. state.lencode = state.lendyn;
  23158. state.lenbits = 7;
  23159. opts = {bits: state.lenbits};
  23160. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23161. state.lenbits = opts.bits;
  23162. if (ret) {
  23163. strm.msg = 'invalid code lengths set';
  23164. state.mode = BAD;
  23165. break;
  23166. }
  23167. //Tracev((stderr, "inflate: code lengths ok\n"));
  23168. state.have = 0;
  23169. state.mode = CODELENS;
  23170. /* falls through */
  23171. case CODELENS:
  23172. while (state.have < state.nlen + state.ndist) {
  23173. for (;;) {
  23174. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23175. here_bits = here >>> 24;
  23176. here_op = (here >>> 16) & 0xff;
  23177. here_val = here & 0xffff;
  23178. if ((here_bits) <= bits) { break; }
  23179. //--- PULLBYTE() ---//
  23180. if (have === 0) { break inf_leave; }
  23181. have--;
  23182. hold += input[next++] << bits;
  23183. bits += 8;
  23184. //---//
  23185. }
  23186. if (here_val < 16) {
  23187. //--- DROPBITS(here.bits) ---//
  23188. hold >>>= here_bits;
  23189. bits -= here_bits;
  23190. //---//
  23191. state.lens[state.have++] = here_val;
  23192. }
  23193. else {
  23194. if (here_val === 16) {
  23195. //=== NEEDBITS(here.bits + 2);
  23196. n = here_bits + 2;
  23197. while (bits < n) {
  23198. if (have === 0) { break inf_leave; }
  23199. have--;
  23200. hold += input[next++] << bits;
  23201. bits += 8;
  23202. }
  23203. //===//
  23204. //--- DROPBITS(here.bits) ---//
  23205. hold >>>= here_bits;
  23206. bits -= here_bits;
  23207. //---//
  23208. if (state.have === 0) {
  23209. strm.msg = 'invalid bit length repeat';
  23210. state.mode = BAD;
  23211. break;
  23212. }
  23213. len = state.lens[state.have - 1];
  23214. copy = 3 + (hold & 0x03);//BITS(2);
  23215. //--- DROPBITS(2) ---//
  23216. hold >>>= 2;
  23217. bits -= 2;
  23218. //---//
  23219. }
  23220. else if (here_val === 17) {
  23221. //=== NEEDBITS(here.bits + 3);
  23222. n = here_bits + 3;
  23223. while (bits < n) {
  23224. if (have === 0) { break inf_leave; }
  23225. have--;
  23226. hold += input[next++] << bits;
  23227. bits += 8;
  23228. }
  23229. //===//
  23230. //--- DROPBITS(here.bits) ---//
  23231. hold >>>= here_bits;
  23232. bits -= here_bits;
  23233. //---//
  23234. len = 0;
  23235. copy = 3 + (hold & 0x07);//BITS(3);
  23236. //--- DROPBITS(3) ---//
  23237. hold >>>= 3;
  23238. bits -= 3;
  23239. //---//
  23240. }
  23241. else {
  23242. //=== NEEDBITS(here.bits + 7);
  23243. n = here_bits + 7;
  23244. while (bits < n) {
  23245. if (have === 0) { break inf_leave; }
  23246. have--;
  23247. hold += input[next++] << bits;
  23248. bits += 8;
  23249. }
  23250. //===//
  23251. //--- DROPBITS(here.bits) ---//
  23252. hold >>>= here_bits;
  23253. bits -= here_bits;
  23254. //---//
  23255. len = 0;
  23256. copy = 11 + (hold & 0x7f);//BITS(7);
  23257. //--- DROPBITS(7) ---//
  23258. hold >>>= 7;
  23259. bits -= 7;
  23260. //---//
  23261. }
  23262. if (state.have + copy > state.nlen + state.ndist) {
  23263. strm.msg = 'invalid bit length repeat';
  23264. state.mode = BAD;
  23265. break;
  23266. }
  23267. while (copy--) {
  23268. state.lens[state.have++] = len;
  23269. }
  23270. }
  23271. }
  23272. /* handle error breaks in while */
  23273. if (state.mode === BAD) { break; }
  23274. /* check for end-of-block code (better have one) */
  23275. if (state.lens[256] === 0) {
  23276. strm.msg = 'invalid code -- missing end-of-block';
  23277. state.mode = BAD;
  23278. break;
  23279. }
  23280. /* build code tables -- note: do not change the lenbits or distbits
  23281. values here (9 and 6) without reading the comments in inftrees.h
  23282. concerning the ENOUGH constants, which depend on those values */
  23283. state.lenbits = 9;
  23284. opts = {bits: state.lenbits};
  23285. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23286. // We have separate tables & no pointers. 2 commented lines below not needed.
  23287. // state.next_index = opts.table_index;
  23288. state.lenbits = opts.bits;
  23289. // state.lencode = state.next;
  23290. if (ret) {
  23291. strm.msg = 'invalid literal/lengths set';
  23292. state.mode = BAD;
  23293. break;
  23294. }
  23295. state.distbits = 6;
  23296. //state.distcode.copy(state.codes);
  23297. // Switch to use dynamic table
  23298. state.distcode = state.distdyn;
  23299. opts = {bits: state.distbits};
  23300. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23301. // We have separate tables & no pointers. 2 commented lines below not needed.
  23302. // state.next_index = opts.table_index;
  23303. state.distbits = opts.bits;
  23304. // state.distcode = state.next;
  23305. if (ret) {
  23306. strm.msg = 'invalid distances set';
  23307. state.mode = BAD;
  23308. break;
  23309. }
  23310. //Tracev((stderr, 'inflate: codes ok\n'));
  23311. state.mode = LEN_;
  23312. if (flush === Z_TREES) { break inf_leave; }
  23313. /* falls through */
  23314. case LEN_:
  23315. state.mode = LEN;
  23316. /* falls through */
  23317. case LEN:
  23318. if (have >= 6 && left >= 258) {
  23319. //--- RESTORE() ---
  23320. strm.next_out = put;
  23321. strm.avail_out = left;
  23322. strm.next_in = next;
  23323. strm.avail_in = have;
  23324. state.hold = hold;
  23325. state.bits = bits;
  23326. //---
  23327. inflate_fast(strm, _out);
  23328. //--- LOAD() ---
  23329. put = strm.next_out;
  23330. output = strm.output;
  23331. left = strm.avail_out;
  23332. next = strm.next_in;
  23333. input = strm.input;
  23334. have = strm.avail_in;
  23335. hold = state.hold;
  23336. bits = state.bits;
  23337. //---
  23338. if (state.mode === TYPE) {
  23339. state.back = -1;
  23340. }
  23341. break;
  23342. }
  23343. state.back = 0;
  23344. for (;;) {
  23345. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23346. here_bits = here >>> 24;
  23347. here_op = (here >>> 16) & 0xff;
  23348. here_val = here & 0xffff;
  23349. if (here_bits <= bits) { break; }
  23350. //--- PULLBYTE() ---//
  23351. if (have === 0) { break inf_leave; }
  23352. have--;
  23353. hold += input[next++] << bits;
  23354. bits += 8;
  23355. //---//
  23356. }
  23357. if (here_op && (here_op & 0xf0) === 0) {
  23358. last_bits = here_bits;
  23359. last_op = here_op;
  23360. last_val = here_val;
  23361. for (;;) {
  23362. here = state.lencode[last_val +
  23363. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23364. here_bits = here >>> 24;
  23365. here_op = (here >>> 16) & 0xff;
  23366. here_val = here & 0xffff;
  23367. if ((last_bits + here_bits) <= bits) { break; }
  23368. //--- PULLBYTE() ---//
  23369. if (have === 0) { break inf_leave; }
  23370. have--;
  23371. hold += input[next++] << bits;
  23372. bits += 8;
  23373. //---//
  23374. }
  23375. //--- DROPBITS(last.bits) ---//
  23376. hold >>>= last_bits;
  23377. bits -= last_bits;
  23378. //---//
  23379. state.back += last_bits;
  23380. }
  23381. //--- DROPBITS(here.bits) ---//
  23382. hold >>>= here_bits;
  23383. bits -= here_bits;
  23384. //---//
  23385. state.back += here_bits;
  23386. state.length = here_val;
  23387. if (here_op === 0) {
  23388. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23389. // "inflate: literal '%c'\n" :
  23390. // "inflate: literal 0x%02x\n", here.val));
  23391. state.mode = LIT;
  23392. break;
  23393. }
  23394. if (here_op & 32) {
  23395. //Tracevv((stderr, "inflate: end of block\n"));
  23396. state.back = -1;
  23397. state.mode = TYPE;
  23398. break;
  23399. }
  23400. if (here_op & 64) {
  23401. strm.msg = 'invalid literal/length code';
  23402. state.mode = BAD;
  23403. break;
  23404. }
  23405. state.extra = here_op & 15;
  23406. state.mode = LENEXT;
  23407. /* falls through */
  23408. case LENEXT:
  23409. if (state.extra) {
  23410. //=== NEEDBITS(state.extra);
  23411. n = state.extra;
  23412. while (bits < n) {
  23413. if (have === 0) { break inf_leave; }
  23414. have--;
  23415. hold += input[next++] << bits;
  23416. bits += 8;
  23417. }
  23418. //===//
  23419. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23420. //--- DROPBITS(state.extra) ---//
  23421. hold >>>= state.extra;
  23422. bits -= state.extra;
  23423. //---//
  23424. state.back += state.extra;
  23425. }
  23426. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23427. state.was = state.length;
  23428. state.mode = DIST;
  23429. /* falls through */
  23430. case DIST:
  23431. for (;;) {
  23432. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23433. here_bits = here >>> 24;
  23434. here_op = (here >>> 16) & 0xff;
  23435. here_val = here & 0xffff;
  23436. if ((here_bits) <= bits) { break; }
  23437. //--- PULLBYTE() ---//
  23438. if (have === 0) { break inf_leave; }
  23439. have--;
  23440. hold += input[next++] << bits;
  23441. bits += 8;
  23442. //---//
  23443. }
  23444. if ((here_op & 0xf0) === 0) {
  23445. last_bits = here_bits;
  23446. last_op = here_op;
  23447. last_val = here_val;
  23448. for (;;) {
  23449. here = state.distcode[last_val +
  23450. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23451. here_bits = here >>> 24;
  23452. here_op = (here >>> 16) & 0xff;
  23453. here_val = here & 0xffff;
  23454. if ((last_bits + here_bits) <= bits) { break; }
  23455. //--- PULLBYTE() ---//
  23456. if (have === 0) { break inf_leave; }
  23457. have--;
  23458. hold += input[next++] << bits;
  23459. bits += 8;
  23460. //---//
  23461. }
  23462. //--- DROPBITS(last.bits) ---//
  23463. hold >>>= last_bits;
  23464. bits -= last_bits;
  23465. //---//
  23466. state.back += last_bits;
  23467. }
  23468. //--- DROPBITS(here.bits) ---//
  23469. hold >>>= here_bits;
  23470. bits -= here_bits;
  23471. //---//
  23472. state.back += here_bits;
  23473. if (here_op & 64) {
  23474. strm.msg = 'invalid distance code';
  23475. state.mode = BAD;
  23476. break;
  23477. }
  23478. state.offset = here_val;
  23479. state.extra = (here_op) & 15;
  23480. state.mode = DISTEXT;
  23481. /* falls through */
  23482. case DISTEXT:
  23483. if (state.extra) {
  23484. //=== NEEDBITS(state.extra);
  23485. n = state.extra;
  23486. while (bits < n) {
  23487. if (have === 0) { break inf_leave; }
  23488. have--;
  23489. hold += input[next++] << bits;
  23490. bits += 8;
  23491. }
  23492. //===//
  23493. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23494. //--- DROPBITS(state.extra) ---//
  23495. hold >>>= state.extra;
  23496. bits -= state.extra;
  23497. //---//
  23498. state.back += state.extra;
  23499. }
  23500. //#ifdef INFLATE_STRICT
  23501. if (state.offset > state.dmax) {
  23502. strm.msg = 'invalid distance too far back';
  23503. state.mode = BAD;
  23504. break;
  23505. }
  23506. //#endif
  23507. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23508. state.mode = MATCH;
  23509. /* falls through */
  23510. case MATCH:
  23511. if (left === 0) { break inf_leave; }
  23512. copy = _out - left;
  23513. if (state.offset > copy) { /* copy from window */
  23514. copy = state.offset - copy;
  23515. if (copy > state.whave) {
  23516. if (state.sane) {
  23517. strm.msg = 'invalid distance too far back';
  23518. state.mode = BAD;
  23519. break;
  23520. }
  23521. // (!) This block is disabled in zlib defailts,
  23522. // don't enable it for binary compatibility
  23523. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23524. // Trace((stderr, "inflate.c too far\n"));
  23525. // copy -= state.whave;
  23526. // if (copy > state.length) { copy = state.length; }
  23527. // if (copy > left) { copy = left; }
  23528. // left -= copy;
  23529. // state.length -= copy;
  23530. // do {
  23531. // output[put++] = 0;
  23532. // } while (--copy);
  23533. // if (state.length === 0) { state.mode = LEN; }
  23534. // break;
  23535. //#endif
  23536. }
  23537. if (copy > state.wnext) {
  23538. copy -= state.wnext;
  23539. from = state.wsize - copy;
  23540. }
  23541. else {
  23542. from = state.wnext - copy;
  23543. }
  23544. if (copy > state.length) { copy = state.length; }
  23545. from_source = state.window;
  23546. }
  23547. else { /* copy from output */
  23548. from_source = output;
  23549. from = put - state.offset;
  23550. copy = state.length;
  23551. }
  23552. if (copy > left) { copy = left; }
  23553. left -= copy;
  23554. state.length -= copy;
  23555. do {
  23556. output[put++] = from_source[from++];
  23557. } while (--copy);
  23558. if (state.length === 0) { state.mode = LEN; }
  23559. break;
  23560. case LIT:
  23561. if (left === 0) { break inf_leave; }
  23562. output[put++] = state.length;
  23563. left--;
  23564. state.mode = LEN;
  23565. break;
  23566. case CHECK:
  23567. if (state.wrap) {
  23568. //=== NEEDBITS(32);
  23569. while (bits < 32) {
  23570. if (have === 0) { break inf_leave; }
  23571. have--;
  23572. // Use '|' insdead of '+' to make sure that result is signed
  23573. hold |= input[next++] << bits;
  23574. bits += 8;
  23575. }
  23576. //===//
  23577. _out -= left;
  23578. strm.total_out += _out;
  23579. state.total += _out;
  23580. if (_out) {
  23581. strm.adler = state.check =
  23582. /*UPDATE(state.check, put - _out, _out);*/
  23583. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23584. }
  23585. _out = left;
  23586. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23587. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23588. strm.msg = 'incorrect data check';
  23589. state.mode = BAD;
  23590. break;
  23591. }
  23592. //=== INITBITS();
  23593. hold = 0;
  23594. bits = 0;
  23595. //===//
  23596. //Tracev((stderr, "inflate: check matches trailer\n"));
  23597. }
  23598. state.mode = LENGTH;
  23599. /* falls through */
  23600. case LENGTH:
  23601. if (state.wrap && state.flags) {
  23602. //=== NEEDBITS(32);
  23603. while (bits < 32) {
  23604. if (have === 0) { break inf_leave; }
  23605. have--;
  23606. hold += input[next++] << bits;
  23607. bits += 8;
  23608. }
  23609. //===//
  23610. if (hold !== (state.total & 0xffffffff)) {
  23611. strm.msg = 'incorrect length check';
  23612. state.mode = BAD;
  23613. break;
  23614. }
  23615. //=== INITBITS();
  23616. hold = 0;
  23617. bits = 0;
  23618. //===//
  23619. //Tracev((stderr, "inflate: length matches trailer\n"));
  23620. }
  23621. state.mode = DONE;
  23622. /* falls through */
  23623. case DONE:
  23624. ret = Z_STREAM_END;
  23625. break inf_leave;
  23626. case BAD:
  23627. ret = Z_DATA_ERROR;
  23628. break inf_leave;
  23629. case MEM:
  23630. return Z_MEM_ERROR;
  23631. case SYNC:
  23632. /* falls through */
  23633. default:
  23634. return Z_STREAM_ERROR;
  23635. }
  23636. }
  23637. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23638. /*
  23639. Return from inflate(), updating the total counts and the check value.
  23640. If there was no progress during the inflate() call, return a buffer
  23641. error. Call updatewindow() to create and/or update the window state.
  23642. Note: a memory error from inflate() is non-recoverable.
  23643. */
  23644. //--- RESTORE() ---
  23645. strm.next_out = put;
  23646. strm.avail_out = left;
  23647. strm.next_in = next;
  23648. strm.avail_in = have;
  23649. state.hold = hold;
  23650. state.bits = bits;
  23651. //---
  23652. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23653. (state.mode < CHECK || flush !== Z_FINISH))) {
  23654. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23655. state.mode = MEM;
  23656. return Z_MEM_ERROR;
  23657. }
  23658. }
  23659. _in -= strm.avail_in;
  23660. _out -= strm.avail_out;
  23661. strm.total_in += _in;
  23662. strm.total_out += _out;
  23663. state.total += _out;
  23664. if (state.wrap && _out) {
  23665. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23666. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23667. }
  23668. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23669. (state.mode === TYPE ? 128 : 0) +
  23670. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23671. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23672. ret = Z_BUF_ERROR;
  23673. }
  23674. return ret;
  23675. }
  23676. function inflateEnd(strm) {
  23677. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23678. return Z_STREAM_ERROR;
  23679. }
  23680. var state = strm.state;
  23681. if (state.window) {
  23682. state.window = null;
  23683. }
  23684. strm.state = null;
  23685. return Z_OK;
  23686. }
  23687. function inflateGetHeader(strm, head) {
  23688. var state;
  23689. /* check state */
  23690. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23691. state = strm.state;
  23692. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23693. /* save header structure */
  23694. state.head = head;
  23695. head.done = false;
  23696. return Z_OK;
  23697. }
  23698. exports.inflateReset = inflateReset;
  23699. exports.inflateReset2 = inflateReset2;
  23700. exports.inflateResetKeep = inflateResetKeep;
  23701. exports.inflateInit = inflateInit;
  23702. exports.inflateInit2 = inflateInit2;
  23703. exports.inflate = inflate;
  23704. exports.inflateEnd = inflateEnd;
  23705. exports.inflateGetHeader = inflateGetHeader;
  23706. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23707. /* Not implemented
  23708. exports.inflateCopy = inflateCopy;
  23709. exports.inflateGetDictionary = inflateGetDictionary;
  23710. exports.inflateMark = inflateMark;
  23711. exports.inflatePrime = inflatePrime;
  23712. exports.inflateSetDictionary = inflateSetDictionary;
  23713. exports.inflateSync = inflateSync;
  23714. exports.inflateSyncPoint = inflateSyncPoint;
  23715. exports.inflateUndermine = inflateUndermine;
  23716. */
  23717. },{"../utils/common":73,"./adler32":75,"./crc32":77,"./inffast":80,"./inftrees":82}],82:[function(require,module,exports){
  23718. 'use strict';
  23719. var utils = require('../utils/common');
  23720. var MAXBITS = 15;
  23721. var ENOUGH_LENS = 852;
  23722. var ENOUGH_DISTS = 592;
  23723. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23724. var CODES = 0;
  23725. var LENS = 1;
  23726. var DISTS = 2;
  23727. var lbase = [ /* Length codes 257..285 base */
  23728. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23729. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23730. ];
  23731. var lext = [ /* Length codes 257..285 extra */
  23732. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23733. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23734. ];
  23735. var dbase = [ /* Distance codes 0..29 base */
  23736. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23737. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23738. 8193, 12289, 16385, 24577, 0, 0
  23739. ];
  23740. var dext = [ /* Distance codes 0..29 extra */
  23741. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23742. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23743. 28, 28, 29, 29, 64, 64
  23744. ];
  23745. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23746. {
  23747. var bits = opts.bits;
  23748. //here = opts.here; /* table entry for duplication */
  23749. var len = 0; /* a code's length in bits */
  23750. var sym = 0; /* index of code symbols */
  23751. var min = 0, max = 0; /* minimum and maximum code lengths */
  23752. var root = 0; /* number of index bits for root table */
  23753. var curr = 0; /* number of index bits for current table */
  23754. var drop = 0; /* code bits to drop for sub-table */
  23755. var left = 0; /* number of prefix codes available */
  23756. var used = 0; /* code entries in table used */
  23757. var huff = 0; /* Huffman code */
  23758. var incr; /* for incrementing code, index */
  23759. var fill; /* index for replicating entries */
  23760. var low; /* low bits for current root entry */
  23761. var mask; /* mask for low root bits */
  23762. var next; /* next available space in table */
  23763. var base = null; /* base value table to use */
  23764. var base_index = 0;
  23765. // var shoextra; /* extra bits table to use */
  23766. var end; /* use base and extra for symbol > end */
  23767. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23768. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23769. var extra = null;
  23770. var extra_index = 0;
  23771. var here_bits, here_op, here_val;
  23772. /*
  23773. Process a set of code lengths to create a canonical Huffman code. The
  23774. code lengths are lens[0..codes-1]. Each length corresponds to the
  23775. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23776. symbols by length from short to long, and retaining the symbol order
  23777. for codes with equal lengths. Then the code starts with all zero bits
  23778. for the first code of the shortest length, and the codes are integer
  23779. increments for the same length, and zeros are appended as the length
  23780. increases. For the deflate format, these bits are stored backwards
  23781. from their more natural integer increment ordering, and so when the
  23782. decoding tables are built in the large loop below, the integer codes
  23783. are incremented backwards.
  23784. This routine assumes, but does not check, that all of the entries in
  23785. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23786. 1..MAXBITS is interpreted as that code length. zero means that that
  23787. symbol does not occur in this code.
  23788. The codes are sorted by computing a count of codes for each length,
  23789. creating from that a table of starting indices for each length in the
  23790. sorted table, and then entering the symbols in order in the sorted
  23791. table. The sorted table is work[], with that space being provided by
  23792. the caller.
  23793. The length counts are used for other purposes as well, i.e. finding
  23794. the minimum and maximum length codes, determining if there are any
  23795. codes at all, checking for a valid set of lengths, and looking ahead
  23796. at length counts to determine sub-table sizes when building the
  23797. decoding tables.
  23798. */
  23799. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23800. for (len = 0; len <= MAXBITS; len++) {
  23801. count[len] = 0;
  23802. }
  23803. for (sym = 0; sym < codes; sym++) {
  23804. count[lens[lens_index + sym]]++;
  23805. }
  23806. /* bound code lengths, force root to be within code lengths */
  23807. root = bits;
  23808. for (max = MAXBITS; max >= 1; max--) {
  23809. if (count[max] !== 0) { break; }
  23810. }
  23811. if (root > max) {
  23812. root = max;
  23813. }
  23814. if (max === 0) { /* no symbols to code at all */
  23815. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23816. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23817. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23818. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23819. //table.op[opts.table_index] = 64;
  23820. //table.bits[opts.table_index] = 1;
  23821. //table.val[opts.table_index++] = 0;
  23822. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23823. opts.bits = 1;
  23824. return 0; /* no symbols, but wait for decoding to report error */
  23825. }
  23826. for (min = 1; min < max; min++) {
  23827. if (count[min] !== 0) { break; }
  23828. }
  23829. if (root < min) {
  23830. root = min;
  23831. }
  23832. /* check for an over-subscribed or incomplete set of lengths */
  23833. left = 1;
  23834. for (len = 1; len <= MAXBITS; len++) {
  23835. left <<= 1;
  23836. left -= count[len];
  23837. if (left < 0) {
  23838. return -1;
  23839. } /* over-subscribed */
  23840. }
  23841. if (left > 0 && (type === CODES || max !== 1)) {
  23842. return -1; /* incomplete set */
  23843. }
  23844. /* generate offsets into symbol table for each length for sorting */
  23845. offs[1] = 0;
  23846. for (len = 1; len < MAXBITS; len++) {
  23847. offs[len + 1] = offs[len] + count[len];
  23848. }
  23849. /* sort symbols by length, by symbol order within each length */
  23850. for (sym = 0; sym < codes; sym++) {
  23851. if (lens[lens_index + sym] !== 0) {
  23852. work[offs[lens[lens_index + sym]]++] = sym;
  23853. }
  23854. }
  23855. /*
  23856. Create and fill in decoding tables. In this loop, the table being
  23857. filled is at next and has curr index bits. The code being used is huff
  23858. with length len. That code is converted to an index by dropping drop
  23859. bits off of the bottom. For codes where len is less than drop + curr,
  23860. those top drop + curr - len bits are incremented through all values to
  23861. fill the table with replicated entries.
  23862. root is the number of index bits for the root table. When len exceeds
  23863. root, sub-tables are created pointed to by the root entry with an index
  23864. of the low root bits of huff. This is saved in low to check for when a
  23865. new sub-table should be started. drop is zero when the root table is
  23866. being filled, and drop is root when sub-tables are being filled.
  23867. When a new sub-table is needed, it is necessary to look ahead in the
  23868. code lengths to determine what size sub-table is needed. The length
  23869. counts are used for this, and so count[] is decremented as codes are
  23870. entered in the tables.
  23871. used keeps track of how many table entries have been allocated from the
  23872. provided *table space. It is checked for LENS and DIST tables against
  23873. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23874. the initial root table size constants. See the comments in inftrees.h
  23875. for more information.
  23876. sym increments through all symbols, and the loop terminates when
  23877. all codes of length max, i.e. all codes, have been processed. This
  23878. routine permits incomplete codes, so another loop after this one fills
  23879. in the rest of the decoding tables with invalid code markers.
  23880. */
  23881. /* set up for code type */
  23882. // poor man optimization - use if-else instead of switch,
  23883. // to avoid deopts in old v8
  23884. if (type === CODES) {
  23885. base = extra = work; /* dummy value--not used */
  23886. end = 19;
  23887. } else if (type === LENS) {
  23888. base = lbase;
  23889. base_index -= 257;
  23890. extra = lext;
  23891. extra_index -= 257;
  23892. end = 256;
  23893. } else { /* DISTS */
  23894. base = dbase;
  23895. extra = dext;
  23896. end = -1;
  23897. }
  23898. /* initialize opts for loop */
  23899. huff = 0; /* starting code */
  23900. sym = 0; /* starting code symbol */
  23901. len = min; /* starting code length */
  23902. next = table_index; /* current table to fill in */
  23903. curr = root; /* current table index bits */
  23904. drop = 0; /* current bits to drop from code for index */
  23905. low = -1; /* trigger new sub-table when len > root */
  23906. used = 1 << root; /* use root table entries */
  23907. mask = used - 1; /* mask for comparing low */
  23908. /* check available table space */
  23909. if ((type === LENS && used > ENOUGH_LENS) ||
  23910. (type === DISTS && used > ENOUGH_DISTS)) {
  23911. return 1;
  23912. }
  23913. var i=0;
  23914. /* process all codes and make table entries */
  23915. for (;;) {
  23916. i++;
  23917. /* create table entry */
  23918. here_bits = len - drop;
  23919. if (work[sym] < end) {
  23920. here_op = 0;
  23921. here_val = work[sym];
  23922. }
  23923. else if (work[sym] > end) {
  23924. here_op = extra[extra_index + work[sym]];
  23925. here_val = base[base_index + work[sym]];
  23926. }
  23927. else {
  23928. here_op = 32 + 64; /* end of block */
  23929. here_val = 0;
  23930. }
  23931. /* replicate for those indices with low len bits equal to huff */
  23932. incr = 1 << (len - drop);
  23933. fill = 1 << curr;
  23934. min = fill; /* save offset to next table */
  23935. do {
  23936. fill -= incr;
  23937. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23938. } while (fill !== 0);
  23939. /* backwards increment the len-bit code huff */
  23940. incr = 1 << (len - 1);
  23941. while (huff & incr) {
  23942. incr >>= 1;
  23943. }
  23944. if (incr !== 0) {
  23945. huff &= incr - 1;
  23946. huff += incr;
  23947. } else {
  23948. huff = 0;
  23949. }
  23950. /* go to next symbol, update count, len */
  23951. sym++;
  23952. if (--count[len] === 0) {
  23953. if (len === max) { break; }
  23954. len = lens[lens_index + work[sym]];
  23955. }
  23956. /* create new sub-table if needed */
  23957. if (len > root && (huff & mask) !== low) {
  23958. /* if first time, transition to sub-tables */
  23959. if (drop === 0) {
  23960. drop = root;
  23961. }
  23962. /* increment past last table */
  23963. next += min; /* here min is 1 << curr */
  23964. /* determine length of next table */
  23965. curr = len - drop;
  23966. left = 1 << curr;
  23967. while (curr + drop < max) {
  23968. left -= count[curr + drop];
  23969. if (left <= 0) { break; }
  23970. curr++;
  23971. left <<= 1;
  23972. }
  23973. /* check for enough space */
  23974. used += 1 << curr;
  23975. if ((type === LENS && used > ENOUGH_LENS) ||
  23976. (type === DISTS && used > ENOUGH_DISTS)) {
  23977. return 1;
  23978. }
  23979. /* point entry in root table to sub-table */
  23980. low = huff & mask;
  23981. /*table.op[low] = curr;
  23982. table.bits[low] = root;
  23983. table.val[low] = next - opts.table_index;*/
  23984. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23985. }
  23986. }
  23987. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23988. at most one remaining entry, since if the code is incomplete, the
  23989. maximum code length that was allowed to get this far is one bit) */
  23990. if (huff !== 0) {
  23991. //table.op[next + huff] = 64; /* invalid code marker */
  23992. //table.bits[next + huff] = len - drop;
  23993. //table.val[next + huff] = 0;
  23994. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23995. }
  23996. /* set return parameters */
  23997. //opts.table_index += used;
  23998. opts.bits = root;
  23999. return 0;
  24000. };
  24001. },{"../utils/common":73}],83:[function(require,module,exports){
  24002. 'use strict';
  24003. module.exports = {
  24004. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24005. '1': 'stream end', /* Z_STREAM_END 1 */
  24006. '0': '', /* Z_OK 0 */
  24007. '-1': 'file error', /* Z_ERRNO (-1) */
  24008. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24009. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24010. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24011. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24012. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24013. };
  24014. },{}],84:[function(require,module,exports){
  24015. 'use strict';
  24016. var utils = require('../utils/common');
  24017. /* Public constants ==========================================================*/
  24018. /* ===========================================================================*/
  24019. //var Z_FILTERED = 1;
  24020. //var Z_HUFFMAN_ONLY = 2;
  24021. //var Z_RLE = 3;
  24022. var Z_FIXED = 4;
  24023. //var Z_DEFAULT_STRATEGY = 0;
  24024. /* Possible values of the data_type field (though see inflate()) */
  24025. var Z_BINARY = 0;
  24026. var Z_TEXT = 1;
  24027. //var Z_ASCII = 1; // = Z_TEXT
  24028. var Z_UNKNOWN = 2;
  24029. /*============================================================================*/
  24030. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24031. // From zutil.h
  24032. var STORED_BLOCK = 0;
  24033. var STATIC_TREES = 1;
  24034. var DYN_TREES = 2;
  24035. /* The three kinds of block type */
  24036. var MIN_MATCH = 3;
  24037. var MAX_MATCH = 258;
  24038. /* The minimum and maximum match lengths */
  24039. // From deflate.h
  24040. /* ===========================================================================
  24041. * Internal compression state.
  24042. */
  24043. var LENGTH_CODES = 29;
  24044. /* number of length codes, not counting the special END_BLOCK code */
  24045. var LITERALS = 256;
  24046. /* number of literal bytes 0..255 */
  24047. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24048. /* number of Literal or Length codes, including the END_BLOCK code */
  24049. var D_CODES = 30;
  24050. /* number of distance codes */
  24051. var BL_CODES = 19;
  24052. /* number of codes used to transfer the bit lengths */
  24053. var HEAP_SIZE = 2*L_CODES + 1;
  24054. /* maximum heap size */
  24055. var MAX_BITS = 15;
  24056. /* All codes must not exceed MAX_BITS bits */
  24057. var Buf_size = 16;
  24058. /* size of bit buffer in bi_buf */
  24059. /* ===========================================================================
  24060. * Constants
  24061. */
  24062. var MAX_BL_BITS = 7;
  24063. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24064. var END_BLOCK = 256;
  24065. /* end of block literal code */
  24066. var REP_3_6 = 16;
  24067. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24068. var REPZ_3_10 = 17;
  24069. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24070. var REPZ_11_138 = 18;
  24071. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24072. var extra_lbits = /* extra bits for each length code */
  24073. [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];
  24074. var extra_dbits = /* extra bits for each distance code */
  24075. [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];
  24076. var extra_blbits = /* extra bits for each bit length code */
  24077. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24078. var bl_order =
  24079. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24080. /* The lengths of the bit length codes are sent in order of decreasing
  24081. * probability, to avoid transmitting the lengths for unused bit length codes.
  24082. */
  24083. /* ===========================================================================
  24084. * Local data. These are initialized only once.
  24085. */
  24086. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24087. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24088. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24089. var static_ltree = new Array((L_CODES+2) * 2);
  24090. zero(static_ltree);
  24091. /* The static literal tree. Since the bit lengths are imposed, there is no
  24092. * need for the L_CODES extra codes used during heap construction. However
  24093. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24094. * below).
  24095. */
  24096. var static_dtree = new Array(D_CODES * 2);
  24097. zero(static_dtree);
  24098. /* The static distance tree. (Actually a trivial tree since all codes use
  24099. * 5 bits.)
  24100. */
  24101. var _dist_code = new Array(DIST_CODE_LEN);
  24102. zero(_dist_code);
  24103. /* Distance codes. The first 256 values correspond to the distances
  24104. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24105. * the 15 bit distances.
  24106. */
  24107. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24108. zero(_length_code);
  24109. /* length code for each normalized match length (0 == MIN_MATCH) */
  24110. var base_length = new Array(LENGTH_CODES);
  24111. zero(base_length);
  24112. /* First normalized length for each code (0 = MIN_MATCH) */
  24113. var base_dist = new Array(D_CODES);
  24114. zero(base_dist);
  24115. /* First normalized distance for each code (0 = distance of 1) */
  24116. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24117. this.static_tree = static_tree; /* static tree or NULL */
  24118. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24119. this.extra_base = extra_base; /* base index for extra_bits */
  24120. this.elems = elems; /* max number of elements in the tree */
  24121. this.max_length = max_length; /* max bit length for the codes */
  24122. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24123. this.has_stree = static_tree && static_tree.length;
  24124. };
  24125. var static_l_desc;
  24126. var static_d_desc;
  24127. var static_bl_desc;
  24128. var TreeDesc = function(dyn_tree, stat_desc) {
  24129. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24130. this.max_code = 0; /* largest code with non zero frequency */
  24131. this.stat_desc = stat_desc; /* the corresponding static tree */
  24132. };
  24133. function d_code(dist) {
  24134. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24135. }
  24136. /* ===========================================================================
  24137. * Output a short LSB first on the stream.
  24138. * IN assertion: there is enough room in pendingBuf.
  24139. */
  24140. function put_short (s, w) {
  24141. // put_byte(s, (uch)((w) & 0xff));
  24142. // put_byte(s, (uch)((ush)(w) >> 8));
  24143. s.pending_buf[s.pending++] = (w) & 0xff;
  24144. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24145. }
  24146. /* ===========================================================================
  24147. * Send a value on a given number of bits.
  24148. * IN assertion: length <= 16 and value fits in length bits.
  24149. */
  24150. function send_bits(s, value, length) {
  24151. if (s.bi_valid > (Buf_size - length)) {
  24152. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24153. put_short(s, s.bi_buf);
  24154. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24155. s.bi_valid += length - Buf_size;
  24156. } else {
  24157. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24158. s.bi_valid += length;
  24159. }
  24160. }
  24161. function send_code(s, c, tree) {
  24162. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24163. }
  24164. /* ===========================================================================
  24165. * Reverse the first len bits of a code, using straightforward code (a faster
  24166. * method would use a table)
  24167. * IN assertion: 1 <= len <= 15
  24168. */
  24169. function bi_reverse(code, len) {
  24170. var res = 0;
  24171. do {
  24172. res |= code & 1;
  24173. code >>>= 1;
  24174. res <<= 1;
  24175. } while (--len > 0);
  24176. return res >>> 1;
  24177. }
  24178. /* ===========================================================================
  24179. * Flush the bit buffer, keeping at most 7 bits in it.
  24180. */
  24181. function bi_flush(s) {
  24182. if (s.bi_valid === 16) {
  24183. put_short(s, s.bi_buf);
  24184. s.bi_buf = 0;
  24185. s.bi_valid = 0;
  24186. } else if (s.bi_valid >= 8) {
  24187. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24188. s.bi_buf >>= 8;
  24189. s.bi_valid -= 8;
  24190. }
  24191. }
  24192. /* ===========================================================================
  24193. * Compute the optimal bit lengths for a tree and update the total bit length
  24194. * for the current block.
  24195. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24196. * above are the tree nodes sorted by increasing frequency.
  24197. * OUT assertions: the field len is set to the optimal bit length, the
  24198. * array bl_count contains the frequencies for each bit length.
  24199. * The length opt_len is updated; static_len is also updated if stree is
  24200. * not null.
  24201. */
  24202. function gen_bitlen(s, desc)
  24203. // deflate_state *s;
  24204. // tree_desc *desc; /* the tree descriptor */
  24205. {
  24206. var tree = desc.dyn_tree;
  24207. var max_code = desc.max_code;
  24208. var stree = desc.stat_desc.static_tree;
  24209. var has_stree = desc.stat_desc.has_stree;
  24210. var extra = desc.stat_desc.extra_bits;
  24211. var base = desc.stat_desc.extra_base;
  24212. var max_length = desc.stat_desc.max_length;
  24213. var h; /* heap index */
  24214. var n, m; /* iterate over the tree elements */
  24215. var bits; /* bit length */
  24216. var xbits; /* extra bits */
  24217. var f; /* frequency */
  24218. var overflow = 0; /* number of elements with bit length too large */
  24219. for (bits = 0; bits <= MAX_BITS; bits++) {
  24220. s.bl_count[bits] = 0;
  24221. }
  24222. /* In a first pass, compute the optimal bit lengths (which may
  24223. * overflow in the case of the bit length tree).
  24224. */
  24225. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24226. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24227. n = s.heap[h];
  24228. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24229. if (bits > max_length) {
  24230. bits = max_length;
  24231. overflow++;
  24232. }
  24233. tree[n*2 + 1]/*.Len*/ = bits;
  24234. /* We overwrite tree[n].Dad which is no longer needed */
  24235. if (n > max_code) { continue; } /* not a leaf node */
  24236. s.bl_count[bits]++;
  24237. xbits = 0;
  24238. if (n >= base) {
  24239. xbits = extra[n-base];
  24240. }
  24241. f = tree[n * 2]/*.Freq*/;
  24242. s.opt_len += f * (bits + xbits);
  24243. if (has_stree) {
  24244. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24245. }
  24246. }
  24247. if (overflow === 0) { return; }
  24248. // Trace((stderr,"\nbit length overflow\n"));
  24249. /* This happens for example on obj2 and pic of the Calgary corpus */
  24250. /* Find the first bit length which could increase: */
  24251. do {
  24252. bits = max_length-1;
  24253. while (s.bl_count[bits] === 0) { bits--; }
  24254. s.bl_count[bits]--; /* move one leaf down the tree */
  24255. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24256. s.bl_count[max_length]--;
  24257. /* The brother of the overflow item also moves one step up,
  24258. * but this does not affect bl_count[max_length]
  24259. */
  24260. overflow -= 2;
  24261. } while (overflow > 0);
  24262. /* Now recompute all bit lengths, scanning in increasing frequency.
  24263. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24264. * lengths instead of fixing only the wrong ones. This idea is taken
  24265. * from 'ar' written by Haruhiko Okumura.)
  24266. */
  24267. for (bits = max_length; bits !== 0; bits--) {
  24268. n = s.bl_count[bits];
  24269. while (n !== 0) {
  24270. m = s.heap[--h];
  24271. if (m > max_code) { continue; }
  24272. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24273. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24274. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24275. tree[m*2 + 1]/*.Len*/ = bits;
  24276. }
  24277. n--;
  24278. }
  24279. }
  24280. }
  24281. /* ===========================================================================
  24282. * Generate the codes for a given tree and bit counts (which need not be
  24283. * optimal).
  24284. * IN assertion: the array bl_count contains the bit length statistics for
  24285. * the given tree and the field len is set for all tree elements.
  24286. * OUT assertion: the field code is set for all tree elements of non
  24287. * zero code length.
  24288. */
  24289. function gen_codes(tree, max_code, bl_count)
  24290. // ct_data *tree; /* the tree to decorate */
  24291. // int max_code; /* largest code with non zero frequency */
  24292. // ushf *bl_count; /* number of codes at each bit length */
  24293. {
  24294. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24295. var code = 0; /* running code value */
  24296. var bits; /* bit index */
  24297. var n; /* code index */
  24298. /* The distribution counts are first used to generate the code values
  24299. * without bit reversal.
  24300. */
  24301. for (bits = 1; bits <= MAX_BITS; bits++) {
  24302. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24303. }
  24304. /* Check that the bit counts in bl_count are consistent. The last code
  24305. * must be all ones.
  24306. */
  24307. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24308. // "inconsistent bit counts");
  24309. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24310. for (n = 0; n <= max_code; n++) {
  24311. var len = tree[n*2 + 1]/*.Len*/;
  24312. if (len === 0) { continue; }
  24313. /* Now reverse the bits */
  24314. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24315. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24316. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24317. }
  24318. }
  24319. /* ===========================================================================
  24320. * Initialize the various 'constant' tables.
  24321. */
  24322. function tr_static_init() {
  24323. var n; /* iterates over tree elements */
  24324. var bits; /* bit counter */
  24325. var length; /* length value */
  24326. var code; /* code value */
  24327. var dist; /* distance index */
  24328. var bl_count = new Array(MAX_BITS+1);
  24329. /* number of codes at each bit length for an optimal tree */
  24330. // do check in _tr_init()
  24331. //if (static_init_done) return;
  24332. /* For some embedded targets, global variables are not initialized: */
  24333. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24334. static_l_desc.static_tree = static_ltree;
  24335. static_l_desc.extra_bits = extra_lbits;
  24336. static_d_desc.static_tree = static_dtree;
  24337. static_d_desc.extra_bits = extra_dbits;
  24338. static_bl_desc.extra_bits = extra_blbits;
  24339. #endif*/
  24340. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24341. length = 0;
  24342. for (code = 0; code < LENGTH_CODES-1; code++) {
  24343. base_length[code] = length;
  24344. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24345. _length_code[length++] = code;
  24346. }
  24347. }
  24348. //Assert (length == 256, "tr_static_init: length != 256");
  24349. /* Note that the length 255 (match length 258) can be represented
  24350. * in two different ways: code 284 + 5 bits or code 285, so we
  24351. * overwrite length_code[255] to use the best encoding:
  24352. */
  24353. _length_code[length-1] = code;
  24354. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24355. dist = 0;
  24356. for (code = 0 ; code < 16; code++) {
  24357. base_dist[code] = dist;
  24358. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24359. _dist_code[dist++] = code;
  24360. }
  24361. }
  24362. //Assert (dist == 256, "tr_static_init: dist != 256");
  24363. dist >>= 7; /* from now on, all distances are divided by 128 */
  24364. for (; code < D_CODES; code++) {
  24365. base_dist[code] = dist << 7;
  24366. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24367. _dist_code[256 + dist++] = code;
  24368. }
  24369. }
  24370. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24371. /* Construct the codes of the static literal tree */
  24372. for (bits = 0; bits <= MAX_BITS; bits++) {
  24373. bl_count[bits] = 0;
  24374. }
  24375. n = 0;
  24376. while (n <= 143) {
  24377. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24378. n++;
  24379. bl_count[8]++;
  24380. }
  24381. while (n <= 255) {
  24382. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24383. n++;
  24384. bl_count[9]++;
  24385. }
  24386. while (n <= 279) {
  24387. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24388. n++;
  24389. bl_count[7]++;
  24390. }
  24391. while (n <= 287) {
  24392. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24393. n++;
  24394. bl_count[8]++;
  24395. }
  24396. /* Codes 286 and 287 do not exist, but we must include them in the
  24397. * tree construction to get a canonical Huffman tree (longest code
  24398. * all ones)
  24399. */
  24400. gen_codes(static_ltree, L_CODES+1, bl_count);
  24401. /* The static distance tree is trivial: */
  24402. for (n = 0; n < D_CODES; n++) {
  24403. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24404. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24405. }
  24406. // Now data ready and we can init static trees
  24407. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24408. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24409. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24410. //static_init_done = true;
  24411. }
  24412. /* ===========================================================================
  24413. * Initialize a new block.
  24414. */
  24415. function init_block(s) {
  24416. var n; /* iterates over tree elements */
  24417. /* Initialize the trees. */
  24418. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24419. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24420. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24421. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24422. s.opt_len = s.static_len = 0;
  24423. s.last_lit = s.matches = 0;
  24424. }
  24425. /* ===========================================================================
  24426. * Flush the bit buffer and align the output on a byte boundary
  24427. */
  24428. function bi_windup(s)
  24429. {
  24430. if (s.bi_valid > 8) {
  24431. put_short(s, s.bi_buf);
  24432. } else if (s.bi_valid > 0) {
  24433. //put_byte(s, (Byte)s->bi_buf);
  24434. s.pending_buf[s.pending++] = s.bi_buf;
  24435. }
  24436. s.bi_buf = 0;
  24437. s.bi_valid = 0;
  24438. }
  24439. /* ===========================================================================
  24440. * Copy a stored block, storing first the length and its
  24441. * one's complement if requested.
  24442. */
  24443. function copy_block(s, buf, len, header)
  24444. //DeflateState *s;
  24445. //charf *buf; /* the input data */
  24446. //unsigned len; /* its length */
  24447. //int header; /* true if block header must be written */
  24448. {
  24449. bi_windup(s); /* align on byte boundary */
  24450. if (header) {
  24451. put_short(s, len);
  24452. put_short(s, ~len);
  24453. }
  24454. // while (len--) {
  24455. // put_byte(s, *buf++);
  24456. // }
  24457. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24458. s.pending += len;
  24459. }
  24460. /* ===========================================================================
  24461. * Compares to subtrees, using the tree depth as tie breaker when
  24462. * the subtrees have equal frequency. This minimizes the worst case length.
  24463. */
  24464. function smaller(tree, n, m, depth) {
  24465. var _n2 = n*2;
  24466. var _m2 = m*2;
  24467. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24468. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24469. }
  24470. /* ===========================================================================
  24471. * Restore the heap property by moving down the tree starting at node k,
  24472. * exchanging a node with the smallest of its two sons if necessary, stopping
  24473. * when the heap property is re-established (each father smaller than its
  24474. * two sons).
  24475. */
  24476. function pqdownheap(s, tree, k)
  24477. // deflate_state *s;
  24478. // ct_data *tree; /* the tree to restore */
  24479. // int k; /* node to move down */
  24480. {
  24481. var v = s.heap[k];
  24482. var j = k << 1; /* left son of k */
  24483. while (j <= s.heap_len) {
  24484. /* Set j to the smallest of the two sons: */
  24485. if (j < s.heap_len &&
  24486. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24487. j++;
  24488. }
  24489. /* Exit if v is smaller than both sons */
  24490. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24491. /* Exchange v with the smallest son */
  24492. s.heap[k] = s.heap[j];
  24493. k = j;
  24494. /* And continue down the tree, setting j to the left son of k */
  24495. j <<= 1;
  24496. }
  24497. s.heap[k] = v;
  24498. }
  24499. // inlined manually
  24500. // var SMALLEST = 1;
  24501. /* ===========================================================================
  24502. * Send the block data compressed using the given Huffman trees
  24503. */
  24504. function compress_block(s, ltree, dtree)
  24505. // deflate_state *s;
  24506. // const ct_data *ltree; /* literal tree */
  24507. // const ct_data *dtree; /* distance tree */
  24508. {
  24509. var dist; /* distance of matched string */
  24510. var lc; /* match length or unmatched char (if dist == 0) */
  24511. var lx = 0; /* running index in l_buf */
  24512. var code; /* the code to send */
  24513. var extra; /* number of extra bits to send */
  24514. if (s.last_lit !== 0) {
  24515. do {
  24516. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24517. lc = s.pending_buf[s.l_buf + lx];
  24518. lx++;
  24519. if (dist === 0) {
  24520. send_code(s, lc, ltree); /* send a literal byte */
  24521. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24522. } else {
  24523. /* Here, lc is the match length - MIN_MATCH */
  24524. code = _length_code[lc];
  24525. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24526. extra = extra_lbits[code];
  24527. if (extra !== 0) {
  24528. lc -= base_length[code];
  24529. send_bits(s, lc, extra); /* send the extra length bits */
  24530. }
  24531. dist--; /* dist is now the match distance - 1 */
  24532. code = d_code(dist);
  24533. //Assert (code < D_CODES, "bad d_code");
  24534. send_code(s, code, dtree); /* send the distance code */
  24535. extra = extra_dbits[code];
  24536. if (extra !== 0) {
  24537. dist -= base_dist[code];
  24538. send_bits(s, dist, extra); /* send the extra distance bits */
  24539. }
  24540. } /* literal or match pair ? */
  24541. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24542. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24543. // "pendingBuf overflow");
  24544. } while (lx < s.last_lit);
  24545. }
  24546. send_code(s, END_BLOCK, ltree);
  24547. }
  24548. /* ===========================================================================
  24549. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24550. * Update the total bit length for the current block.
  24551. * IN assertion: the field freq is set for all tree elements.
  24552. * OUT assertions: the fields len and code are set to the optimal bit length
  24553. * and corresponding code. The length opt_len is updated; static_len is
  24554. * also updated if stree is not null. The field max_code is set.
  24555. */
  24556. function build_tree(s, desc)
  24557. // deflate_state *s;
  24558. // tree_desc *desc; /* the tree descriptor */
  24559. {
  24560. var tree = desc.dyn_tree;
  24561. var stree = desc.stat_desc.static_tree;
  24562. var has_stree = desc.stat_desc.has_stree;
  24563. var elems = desc.stat_desc.elems;
  24564. var n, m; /* iterate over heap elements */
  24565. var max_code = -1; /* largest code with non zero frequency */
  24566. var node; /* new node being created */
  24567. /* Construct the initial heap, with least frequent element in
  24568. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24569. * heap[0] is not used.
  24570. */
  24571. s.heap_len = 0;
  24572. s.heap_max = HEAP_SIZE;
  24573. for (n = 0; n < elems; n++) {
  24574. if (tree[n * 2]/*.Freq*/ !== 0) {
  24575. s.heap[++s.heap_len] = max_code = n;
  24576. s.depth[n] = 0;
  24577. } else {
  24578. tree[n*2 + 1]/*.Len*/ = 0;
  24579. }
  24580. }
  24581. /* The pkzip format requires that at least one distance code exists,
  24582. * and that at least one bit should be sent even if there is only one
  24583. * possible code. So to avoid special checks later on we force at least
  24584. * two codes of non zero frequency.
  24585. */
  24586. while (s.heap_len < 2) {
  24587. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24588. tree[node * 2]/*.Freq*/ = 1;
  24589. s.depth[node] = 0;
  24590. s.opt_len--;
  24591. if (has_stree) {
  24592. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24593. }
  24594. /* node is 0 or 1 so it does not have extra bits */
  24595. }
  24596. desc.max_code = max_code;
  24597. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24598. * establish sub-heaps of increasing lengths:
  24599. */
  24600. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24601. /* Construct the Huffman tree by repeatedly combining the least two
  24602. * frequent nodes.
  24603. */
  24604. node = elems; /* next internal node of the tree */
  24605. do {
  24606. //pqremove(s, tree, n); /* n = node of least frequency */
  24607. /*** pqremove ***/
  24608. n = s.heap[1/*SMALLEST*/];
  24609. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24610. pqdownheap(s, tree, 1/*SMALLEST*/);
  24611. /***/
  24612. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24613. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24614. s.heap[--s.heap_max] = m;
  24615. /* Create a new node father of n and m */
  24616. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24617. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24618. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24619. /* and insert the new node in the heap */
  24620. s.heap[1/*SMALLEST*/] = node++;
  24621. pqdownheap(s, tree, 1/*SMALLEST*/);
  24622. } while (s.heap_len >= 2);
  24623. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24624. /* At this point, the fields freq and dad are set. We can now
  24625. * generate the bit lengths.
  24626. */
  24627. gen_bitlen(s, desc);
  24628. /* The field len is now set, we can generate the bit codes */
  24629. gen_codes(tree, max_code, s.bl_count);
  24630. }
  24631. /* ===========================================================================
  24632. * Scan a literal or distance tree to determine the frequencies of the codes
  24633. * in the bit length tree.
  24634. */
  24635. function scan_tree(s, tree, max_code)
  24636. // deflate_state *s;
  24637. // ct_data *tree; /* the tree to be scanned */
  24638. // int max_code; /* and its largest code of non zero frequency */
  24639. {
  24640. var n; /* iterates over all tree elements */
  24641. var prevlen = -1; /* last emitted length */
  24642. var curlen; /* length of current code */
  24643. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24644. var count = 0; /* repeat count of the current code */
  24645. var max_count = 7; /* max repeat count */
  24646. var min_count = 4; /* min repeat count */
  24647. if (nextlen === 0) {
  24648. max_count = 138;
  24649. min_count = 3;
  24650. }
  24651. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24652. for (n = 0; n <= max_code; n++) {
  24653. curlen = nextlen;
  24654. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24655. if (++count < max_count && curlen === nextlen) {
  24656. continue;
  24657. } else if (count < min_count) {
  24658. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24659. } else if (curlen !== 0) {
  24660. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24661. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24662. } else if (count <= 10) {
  24663. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24664. } else {
  24665. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24666. }
  24667. count = 0;
  24668. prevlen = curlen;
  24669. if (nextlen === 0) {
  24670. max_count = 138;
  24671. min_count = 3;
  24672. } else if (curlen === nextlen) {
  24673. max_count = 6;
  24674. min_count = 3;
  24675. } else {
  24676. max_count = 7;
  24677. min_count = 4;
  24678. }
  24679. }
  24680. }
  24681. /* ===========================================================================
  24682. * Send a literal or distance tree in compressed form, using the codes in
  24683. * bl_tree.
  24684. */
  24685. function send_tree(s, tree, max_code)
  24686. // deflate_state *s;
  24687. // ct_data *tree; /* the tree to be scanned */
  24688. // int max_code; /* and its largest code of non zero frequency */
  24689. {
  24690. var n; /* iterates over all tree elements */
  24691. var prevlen = -1; /* last emitted length */
  24692. var curlen; /* length of current code */
  24693. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24694. var count = 0; /* repeat count of the current code */
  24695. var max_count = 7; /* max repeat count */
  24696. var min_count = 4; /* min repeat count */
  24697. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24698. if (nextlen === 0) {
  24699. max_count = 138;
  24700. min_count = 3;
  24701. }
  24702. for (n = 0; n <= max_code; n++) {
  24703. curlen = nextlen;
  24704. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24705. if (++count < max_count && curlen === nextlen) {
  24706. continue;
  24707. } else if (count < min_count) {
  24708. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24709. } else if (curlen !== 0) {
  24710. if (curlen !== prevlen) {
  24711. send_code(s, curlen, s.bl_tree);
  24712. count--;
  24713. }
  24714. //Assert(count >= 3 && count <= 6, " 3_6?");
  24715. send_code(s, REP_3_6, s.bl_tree);
  24716. send_bits(s, count-3, 2);
  24717. } else if (count <= 10) {
  24718. send_code(s, REPZ_3_10, s.bl_tree);
  24719. send_bits(s, count-3, 3);
  24720. } else {
  24721. send_code(s, REPZ_11_138, s.bl_tree);
  24722. send_bits(s, count-11, 7);
  24723. }
  24724. count = 0;
  24725. prevlen = curlen;
  24726. if (nextlen === 0) {
  24727. max_count = 138;
  24728. min_count = 3;
  24729. } else if (curlen === nextlen) {
  24730. max_count = 6;
  24731. min_count = 3;
  24732. } else {
  24733. max_count = 7;
  24734. min_count = 4;
  24735. }
  24736. }
  24737. }
  24738. /* ===========================================================================
  24739. * Construct the Huffman tree for the bit lengths and return the index in
  24740. * bl_order of the last bit length code to send.
  24741. */
  24742. function build_bl_tree(s) {
  24743. var max_blindex; /* index of last bit length code of non zero freq */
  24744. /* Determine the bit length frequencies for literal and distance trees */
  24745. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24746. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24747. /* Build the bit length tree: */
  24748. build_tree(s, s.bl_desc);
  24749. /* opt_len now includes the length of the tree representations, except
  24750. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24751. */
  24752. /* Determine the number of bit length codes to send. The pkzip format
  24753. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24754. * 3 but the actual value used is 4.)
  24755. */
  24756. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24757. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24758. break;
  24759. }
  24760. }
  24761. /* Update opt_len to include the bit length tree and counts */
  24762. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24763. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24764. // s->opt_len, s->static_len));
  24765. return max_blindex;
  24766. }
  24767. /* ===========================================================================
  24768. * Send the header for a block using dynamic Huffman trees: the counts, the
  24769. * lengths of the bit length codes, the literal tree and the distance tree.
  24770. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24771. */
  24772. function send_all_trees(s, lcodes, dcodes, blcodes)
  24773. // deflate_state *s;
  24774. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24775. {
  24776. var rank; /* index in bl_order */
  24777. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24778. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24779. // "too many codes");
  24780. //Tracev((stderr, "\nbl counts: "));
  24781. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24782. send_bits(s, dcodes-1, 5);
  24783. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24784. for (rank = 0; rank < blcodes; rank++) {
  24785. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24786. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24787. }
  24788. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24789. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24790. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24791. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24792. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24793. }
  24794. /* ===========================================================================
  24795. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24796. * - TEXT if the two conditions below are satisfied:
  24797. * a) There are no non-portable control characters belonging to the
  24798. * "black list" (0..6, 14..25, 28..31).
  24799. * b) There is at least one printable character belonging to the
  24800. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24801. * - BINARY otherwise.
  24802. * - The following partially-portable control characters form a
  24803. * "gray list" that is ignored in this detection algorithm:
  24804. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24805. * IN assertion: the fields Freq of dyn_ltree are set.
  24806. */
  24807. function detect_data_type(s) {
  24808. /* black_mask is the bit mask of black-listed bytes
  24809. * set bits 0..6, 14..25, and 28..31
  24810. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24811. */
  24812. var black_mask = 0xf3ffc07f;
  24813. var n;
  24814. /* Check for non-textual ("black-listed") bytes. */
  24815. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24816. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24817. return Z_BINARY;
  24818. }
  24819. }
  24820. /* Check for textual ("white-listed") bytes. */
  24821. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24822. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24823. return Z_TEXT;
  24824. }
  24825. for (n = 32; n < LITERALS; n++) {
  24826. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24827. return Z_TEXT;
  24828. }
  24829. }
  24830. /* There are no "black-listed" or "white-listed" bytes:
  24831. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24832. */
  24833. return Z_BINARY;
  24834. }
  24835. var static_init_done = false;
  24836. /* ===========================================================================
  24837. * Initialize the tree data structures for a new zlib stream.
  24838. */
  24839. function _tr_init(s)
  24840. {
  24841. if (!static_init_done) {
  24842. tr_static_init();
  24843. static_init_done = true;
  24844. }
  24845. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24846. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24847. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24848. s.bi_buf = 0;
  24849. s.bi_valid = 0;
  24850. /* Initialize the first block of the first file: */
  24851. init_block(s);
  24852. }
  24853. /* ===========================================================================
  24854. * Send a stored block
  24855. */
  24856. function _tr_stored_block(s, buf, stored_len, last)
  24857. //DeflateState *s;
  24858. //charf *buf; /* input block */
  24859. //ulg stored_len; /* length of input block */
  24860. //int last; /* one if this is the last block for a file */
  24861. {
  24862. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24863. copy_block(s, buf, stored_len, true); /* with header */
  24864. }
  24865. /* ===========================================================================
  24866. * Send one empty static block to give enough lookahead for inflate.
  24867. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24868. */
  24869. function _tr_align(s) {
  24870. send_bits(s, STATIC_TREES<<1, 3);
  24871. send_code(s, END_BLOCK, static_ltree);
  24872. bi_flush(s);
  24873. }
  24874. /* ===========================================================================
  24875. * Determine the best encoding for the current block: dynamic trees, static
  24876. * trees or store, and output the encoded block to the zip file.
  24877. */
  24878. function _tr_flush_block(s, buf, stored_len, last)
  24879. //DeflateState *s;
  24880. //charf *buf; /* input block, or NULL if too old */
  24881. //ulg stored_len; /* length of input block */
  24882. //int last; /* one if this is the last block for a file */
  24883. {
  24884. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24885. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24886. /* Build the Huffman trees unless a stored block is forced */
  24887. if (s.level > 0) {
  24888. /* Check if the file is binary or text */
  24889. if (s.strm.data_type === Z_UNKNOWN) {
  24890. s.strm.data_type = detect_data_type(s);
  24891. }
  24892. /* Construct the literal and distance trees */
  24893. build_tree(s, s.l_desc);
  24894. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24895. // s->static_len));
  24896. build_tree(s, s.d_desc);
  24897. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24898. // s->static_len));
  24899. /* At this point, opt_len and static_len are the total bit lengths of
  24900. * the compressed block data, excluding the tree representations.
  24901. */
  24902. /* Build the bit length tree for the above two trees, and get the index
  24903. * in bl_order of the last bit length code to send.
  24904. */
  24905. max_blindex = build_bl_tree(s);
  24906. /* Determine the best encoding. Compute the block lengths in bytes. */
  24907. opt_lenb = (s.opt_len+3+7) >>> 3;
  24908. static_lenb = (s.static_len+3+7) >>> 3;
  24909. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24910. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24911. // s->last_lit));
  24912. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24913. } else {
  24914. // Assert(buf != (char*)0, "lost buf");
  24915. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24916. }
  24917. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24918. /* 4: two words for the lengths */
  24919. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24920. * Otherwise we can't have processed more than WSIZE input bytes since
  24921. * the last block flush, because compression would have been
  24922. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24923. * transform a block into a stored block.
  24924. */
  24925. _tr_stored_block(s, buf, stored_len, last);
  24926. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24927. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24928. compress_block(s, static_ltree, static_dtree);
  24929. } else {
  24930. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24931. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24932. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24933. }
  24934. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24935. /* The above check is made mod 2^32, for files larger than 512 MB
  24936. * and uLong implemented on 32 bits.
  24937. */
  24938. init_block(s);
  24939. if (last) {
  24940. bi_windup(s);
  24941. }
  24942. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24943. // s->compressed_len-7*last));
  24944. }
  24945. /* ===========================================================================
  24946. * Save the match info and tally the frequency counts. Return true if
  24947. * the current block must be flushed.
  24948. */
  24949. function _tr_tally(s, dist, lc)
  24950. // deflate_state *s;
  24951. // unsigned dist; /* distance of matched string */
  24952. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24953. {
  24954. //var out_length, in_length, dcode;
  24955. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24956. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24957. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24958. s.last_lit++;
  24959. if (dist === 0) {
  24960. /* lc is the unmatched char */
  24961. s.dyn_ltree[lc*2]/*.Freq*/++;
  24962. } else {
  24963. s.matches++;
  24964. /* Here, lc is the match length - MIN_MATCH */
  24965. dist--; /* dist = match distance - 1 */
  24966. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24967. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24968. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24969. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24970. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24971. }
  24972. // (!) This block is disabled in zlib defailts,
  24973. // don't enable it for binary compatibility
  24974. //#ifdef TRUNCATE_BLOCK
  24975. // /* Try to guess if it is profitable to stop the current block here */
  24976. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24977. // /* Compute an upper bound for the compressed length */
  24978. // out_length = s.last_lit*8;
  24979. // in_length = s.strstart - s.block_start;
  24980. //
  24981. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24982. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24983. // }
  24984. // out_length >>>= 3;
  24985. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24986. // // s->last_lit, in_length, out_length,
  24987. // // 100L - out_length*100L/in_length));
  24988. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24989. // return true;
  24990. // }
  24991. // }
  24992. //#endif
  24993. return (s.last_lit === s.lit_bufsize-1);
  24994. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24995. * on 16 bit machines and because stored blocks are restricted to
  24996. * 64K-1 bytes.
  24997. */
  24998. }
  24999. exports._tr_init = _tr_init;
  25000. exports._tr_stored_block = _tr_stored_block;
  25001. exports._tr_flush_block = _tr_flush_block;
  25002. exports._tr_tally = _tr_tally;
  25003. exports._tr_align = _tr_align;
  25004. },{"../utils/common":73}],85:[function(require,module,exports){
  25005. 'use strict';
  25006. function ZStream() {
  25007. /* next input byte */
  25008. this.input = null; // JS specific, because we have no pointers
  25009. this.next_in = 0;
  25010. /* number of bytes available at input */
  25011. this.avail_in = 0;
  25012. /* total number of input bytes read so far */
  25013. this.total_in = 0;
  25014. /* next output byte should be put there */
  25015. this.output = null; // JS specific, because we have no pointers
  25016. this.next_out = 0;
  25017. /* remaining free space at output */
  25018. this.avail_out = 0;
  25019. /* total number of bytes output so far */
  25020. this.total_out = 0;
  25021. /* last error message, NULL if no error */
  25022. this.msg = ''/*Z_NULL*/;
  25023. /* not visible by applications */
  25024. this.state = null;
  25025. /* best guess about the data type: binary or text */
  25026. this.data_type = 2/*Z_UNKNOWN*/;
  25027. /* adler32 value of the uncompressed data */
  25028. this.adler = 0;
  25029. }
  25030. module.exports = ZStream;
  25031. },{}],86:[function(require,module,exports){
  25032. module.exports = require('./lib/retry');
  25033. },{"./lib/retry":87}],87:[function(require,module,exports){
  25034. var RetryOperation = require('./retry_operation');
  25035. exports.operation = function(options) {
  25036. var timeouts = exports.timeouts(options);
  25037. return new RetryOperation(timeouts);
  25038. };
  25039. exports.timeouts = function(options) {
  25040. if (options instanceof Array) {
  25041. return [].concat(options);
  25042. }
  25043. var opts = {
  25044. retries: 10,
  25045. factor: 2,
  25046. minTimeout: 1 * 1000,
  25047. maxTimeout: Infinity,
  25048. randomize: false
  25049. };
  25050. for (var key in options) {
  25051. opts[key] = options[key];
  25052. }
  25053. if (opts.minTimeout > opts.maxTimeout) {
  25054. throw new Error('minTimeout is greater than maxTimeout');
  25055. }
  25056. var timeouts = [];
  25057. for (var i = 0; i < opts.retries; i++) {
  25058. timeouts.push(this._createTimeout(i, opts));
  25059. }
  25060. // sort the array numerically ascending
  25061. timeouts.sort(function(a,b) {
  25062. return a - b;
  25063. });
  25064. return timeouts;
  25065. };
  25066. exports._createTimeout = function(attempt, opts) {
  25067. var random = (opts.randomize)
  25068. ? (Math.random() + 1)
  25069. : 1;
  25070. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25071. timeout = Math.min(timeout, opts.maxTimeout);
  25072. return timeout;
  25073. };
  25074. },{"./retry_operation":88}],88:[function(require,module,exports){
  25075. function RetryOperation(timeouts) {
  25076. this._timeouts = timeouts;
  25077. this._fn = null;
  25078. this._errors = [];
  25079. this._attempts = 1;
  25080. this._operationTimeout = null;
  25081. this._operationTimeoutCb = null;
  25082. this._timeout = null;
  25083. }
  25084. module.exports = RetryOperation;
  25085. RetryOperation.prototype.retry = function(err) {
  25086. if (this._timeout) {
  25087. clearTimeout(this._timeout);
  25088. }
  25089. if (!err) {
  25090. return false;
  25091. }
  25092. this._errors.push(err);
  25093. var timeout = this._timeouts.shift();
  25094. if (timeout === undefined) {
  25095. return false;
  25096. }
  25097. this._attempts++;
  25098. var self = this;
  25099. setTimeout(function() {
  25100. self._fn(self._attempts);
  25101. if (self._operationTimeoutCb) {
  25102. self._timeout = setTimeout(function() {
  25103. self._operationTimeoutCb(self._attempts);
  25104. }, self._operationTimeout);
  25105. }
  25106. }, timeout);
  25107. return true;
  25108. };
  25109. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25110. this._fn = fn;
  25111. if (timeoutOps) {
  25112. if (timeoutOps.timeout) {
  25113. this._operationTimeout = timeoutOps.timeout;
  25114. }
  25115. if (timeoutOps.cb) {
  25116. this._operationTimeoutCb = timeoutOps.cb;
  25117. }
  25118. }
  25119. this._fn(this._attempts);
  25120. var self = this;
  25121. if (this._operationTimeoutCb) {
  25122. this._timeout = setTimeout(function() {
  25123. self._operationTimeoutCb();
  25124. }, self._operationTimeout);
  25125. }
  25126. };
  25127. RetryOperation.prototype.try = function(fn) {
  25128. console.log('Using RetryOperation.try() is deprecated');
  25129. this.attempt(fn);
  25130. };
  25131. RetryOperation.prototype.start = function(fn) {
  25132. console.log('Using RetryOperation.start() is deprecated');
  25133. this.attempt(fn);
  25134. };
  25135. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25136. RetryOperation.prototype.errors = function() {
  25137. return this._errors;
  25138. };
  25139. RetryOperation.prototype.attempts = function() {
  25140. return this._attempts;
  25141. };
  25142. RetryOperation.prototype.mainError = function() {
  25143. if (this._errors.length === 0) {
  25144. return null;
  25145. }
  25146. var counts = {};
  25147. var mainError = null;
  25148. var mainErrorCount = 0;
  25149. for (var i = 0; i < this._errors.length; i++) {
  25150. var error = this._errors[i];
  25151. var message = error.message;
  25152. var count = (counts[message] || 0) + 1;
  25153. counts[message] = count;
  25154. if (count >= mainErrorCount) {
  25155. mainError = error;
  25156. mainErrorCount = count;
  25157. }
  25158. }
  25159. return mainError;
  25160. };
  25161. },{}],89:[function(require,module,exports){
  25162. module.exports = function arrayEquals(array) {
  25163. // if the other array is a falsy value, return
  25164. if (!array)
  25165. return false;
  25166. // compare lengths - can save a lot of time
  25167. if (this.length != array.length)
  25168. return false;
  25169. for (var i = 0, l = this.length; i < l; i++) {
  25170. // Check if we have nested arrays
  25171. if (this[i] instanceof Array && array[i] instanceof Array) {
  25172. // recurse into the nested arrays
  25173. if (!arrayEquals.apply(this[i], [array[i]]))
  25174. return false;
  25175. } else if (this[i] != array[i]) {
  25176. // Warning - two different object instances will never be equal:
  25177. // {x:20} != {x:20}
  25178. return false;
  25179. }
  25180. }
  25181. return true;
  25182. }
  25183. },{}],90:[function(require,module,exports){
  25184. exports.Interop = require('./interop');
  25185. },{"./interop":91}],91:[function(require,module,exports){
  25186. "use strict";
  25187. var transform = require('./transform');
  25188. var arrayEquals = require('./array-equals');
  25189. function Interop() {
  25190. /**
  25191. * This map holds the most recent Unified Plan offer/answer SDP that was
  25192. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25193. * the SDP string as values.
  25194. *
  25195. * @type {{}}
  25196. */
  25197. this.cache = {};
  25198. }
  25199. module.exports = Interop;
  25200. /**
  25201. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25202. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25203. * application.
  25204. *
  25205. * @param desc
  25206. * @returns {*}
  25207. */
  25208. Interop.prototype.toPlanB = function(desc) {
  25209. //#region Preliminary input validation.
  25210. if (typeof desc !== 'object' || desc === null ||
  25211. typeof desc.sdp !== 'string') {
  25212. console.warn('An empty description was passed as an argument.');
  25213. return desc;
  25214. }
  25215. // Objectify the SDP for easier manipulation.
  25216. var session = transform.parse(desc.sdp);
  25217. // If the SDP contains no media, there's nothing to transform.
  25218. if (typeof session.media === 'undefined' ||
  25219. !Array.isArray(session.media) || session.media.length === 0) {
  25220. console.warn('The description has no media.');
  25221. return desc;
  25222. }
  25223. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25224. // SDP has a video, an audio and a data "channel" at most.
  25225. if (session.media.length <= 3 && session.media.every(function(m) {
  25226. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25227. })) {
  25228. console.warn('This description does not look like Unified Plan.');
  25229. return desc;
  25230. }
  25231. //#endregion
  25232. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25233. // -> Unified Plan transformation.
  25234. this.cache[desc.type] = desc.sdp;
  25235. //#region Convert from Unified Plan to Plan B.
  25236. // We rebuild the session.media array.
  25237. var media = session.media;
  25238. session.media = [];
  25239. // Associative array that maps channel types to channel objects for fast
  25240. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25241. // obj.
  25242. var type2bl = {};
  25243. // Used to build the group:BUNDLE value after the channels construction
  25244. // loop.
  25245. var types = [];
  25246. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25247. media.forEach(function(unifiedLine) {
  25248. // rtcp-mux is required in the Plan B SDP.
  25249. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25250. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25251. unifiedLine.direction !== 'inactive') {
  25252. throw new Error('Cannot convert to Plan B because m-lines ' +
  25253. 'without the rtcp-mux attribute were found.');
  25254. }
  25255. if (unifiedLine.type === 'application') {
  25256. session.media.push(unifiedLine);
  25257. types.push(unifiedLine.mid);
  25258. return;
  25259. }
  25260. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25261. // as the channel basis.
  25262. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25263. type2bl[unifiedLine.type] = unifiedLine;
  25264. }
  25265. // Add sources to the channel and handle a=msid.
  25266. if (typeof unifiedLine.sources === 'object') {
  25267. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25268. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25269. type2bl[unifiedLine.type].sources = {};
  25270. // Assign the sources to the channel.
  25271. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25272. if (typeof unifiedLine.msid !== 'undefined') {
  25273. // In Plan B the msid is an SSRC attribute. Also, we don't
  25274. // care about the obsolete label and mslabel attributes.
  25275. //
  25276. // Note that it is not guaranteed that the unifiedLine will have
  25277. // an msid. recvonly channels in particular don't have one.
  25278. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25279. }
  25280. // NOTE ssrcs in ssrc groups will share msids, as
  25281. // draft-uberti-rtcweb-plan-00 mandates.
  25282. });
  25283. }
  25284. // Add ssrc groups to the channel.
  25285. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25286. Array.isArray(unifiedLine.ssrcGroups)) {
  25287. // Create the ssrcGroups array, if it's not defined.
  25288. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25289. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25290. type2bl[unifiedLine.type].ssrcGroups = [];
  25291. }
  25292. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25293. }
  25294. if (type2bl[unifiedLine.type] === unifiedLine) {
  25295. // Copy ICE related stuff from the principal media line.
  25296. unifiedLine.candidates = media[0].candidates;
  25297. unifiedLine.iceUfrag = media[0].iceUfrag;
  25298. unifiedLine.icePwd = media[0].icePwd;
  25299. unifiedLine.fingerprint = media[0].fingerprint;
  25300. // Plan B mids are in ['audio', 'video', 'data']
  25301. unifiedLine.mid = unifiedLine.type;
  25302. // Plan B doesn't support/need the bundle-only attribute.
  25303. delete unifiedLine.bundleOnly;
  25304. // In Plan B the msid is an SSRC attribute.
  25305. delete unifiedLine.msid;
  25306. // Used to build the group:BUNDLE value after this loop.
  25307. types.push(unifiedLine.type);
  25308. // Add the channel to the new media array.
  25309. session.media.push(unifiedLine);
  25310. }
  25311. });
  25312. // We regenerate the BUNDLE group with the new mids.
  25313. session.groups.some(function(group) {
  25314. if (group.type === 'BUNDLE') {
  25315. group.mids = types.join(' ');
  25316. return true;
  25317. }
  25318. });
  25319. // msid semantic
  25320. session.msidSemantic = {
  25321. semantic: 'WMS',
  25322. token: '*'
  25323. };
  25324. var resStr = transform.write(session);
  25325. return new RTCSessionDescription({
  25326. type: desc.type,
  25327. sdp: resStr
  25328. });
  25329. //#endregion
  25330. };
  25331. /**
  25332. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25333. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25334. * to FF.
  25335. *
  25336. * @param desc
  25337. * @returns {*}
  25338. */
  25339. Interop.prototype.toUnifiedPlan = function(desc) {
  25340. //#region Preliminary input validation.
  25341. if (typeof desc !== 'object' || desc === null ||
  25342. typeof desc.sdp !== 'string') {
  25343. console.warn('An empty description was passed as an argument.');
  25344. return desc;
  25345. }
  25346. var session = transform.parse(desc.sdp);
  25347. // If the SDP contains no media, there's nothing to transform.
  25348. if (typeof session.media === 'undefined' ||
  25349. !Array.isArray(session.media) || session.media.length === 0) {
  25350. console.warn('The description has no media.');
  25351. return desc;
  25352. }
  25353. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25354. // a video, an audio and a data "channel" at most.
  25355. if (session.media.length > 3 || !session.media.every(function(m) {
  25356. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25357. })) {
  25358. console.warn('This description does not look like Plan B.');
  25359. return desc;
  25360. }
  25361. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25362. var mids = [];
  25363. session.media.forEach(function(m) {
  25364. mids.push(m.mid);
  25365. });
  25366. var hasBundle = false;
  25367. if (typeof session.groups !== 'undefined' &&
  25368. Array.isArray(session.groups)) {
  25369. hasBundle = session.groups.every(function(g) {
  25370. return g.type !== 'BUNDLE' ||
  25371. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25372. });
  25373. }
  25374. if (!hasBundle) {
  25375. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25376. " are not bundled were found.");
  25377. }
  25378. //#endregion
  25379. //#region Convert from Plan B to Unified Plan.
  25380. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25381. // rebuild an equivalent Unified Plan offer/answer.
  25382. //
  25383. // For example, if this is a local answer (in Unified Plan style) that we
  25384. // convert to Plan B prior to handing it over to the application (the
  25385. // PeerConnection wrapper called us, for instance, after a successful
  25386. // createAnswer), we want to remember the m-line at which we've seen the
  25387. // (local) SSRC. That's because when the application wants to do call the
  25388. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25389. // Unified Plan), we need to know to which m-line to assign the (local)
  25390. // SSRC. We also need to know all the other m-lines that the original
  25391. // answer had and include them in the transformed answer as well.
  25392. //
  25393. // Another example is if this is a remote offer that we convert to Plan B
  25394. // prior to giving it to the application, we want to remember the mid at
  25395. // which we've seen the (remote) SSRC.
  25396. //
  25397. // In the iteration that follows, we use the cached Unified Plan (if it
  25398. // exists) to assign mids to ssrcs.
  25399. var cached;
  25400. if (typeof this.cache[desc.type] !== 'undefined') {
  25401. cached = transform.parse(this.cache[desc.type]);
  25402. }
  25403. // A helper map that sends mids to m-line objects. We use it later to
  25404. // rebuild the Unified Plan style session.media array.
  25405. var mid2ul = {};
  25406. session.media.forEach(function(bLine) {
  25407. if ((typeof bLine.rtcpMux !== 'string' ||
  25408. bLine.rtcpMux !== 'rtcp-mux') &&
  25409. bLine.direction !== 'inactive') {
  25410. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25411. "without the rtcp-mux attribute were found.");
  25412. }
  25413. if (bLine.type === 'application') {
  25414. mid2ul[bLine.mid] = bLine;
  25415. return;
  25416. }
  25417. // With rtcp-mux and bundle all the channels should have the same ICE
  25418. // stuff.
  25419. var sources = bLine.sources;
  25420. var ssrcGroups = bLine.ssrcGroups;
  25421. var candidates = bLine.candidates;
  25422. var iceUfrag = bLine.iceUfrag;
  25423. var icePwd = bLine.icePwd;
  25424. var fingerprint = bLine.fingerprint;
  25425. var port = bLine.port;
  25426. // We'll use the "bLine" object as a prototype for each new "mLine"
  25427. // that we create, but first we need to clean it up a bit.
  25428. delete bLine.sources;
  25429. delete bLine.ssrcGroups;
  25430. delete bLine.candidates;
  25431. delete bLine.iceUfrag;
  25432. delete bLine.icePwd;
  25433. delete bLine.fingerprint;
  25434. delete bLine.port;
  25435. delete bLine.mid;
  25436. // inverted ssrc group map
  25437. var ssrc2group = {};
  25438. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25439. ssrcGroups.forEach(function (ssrcGroup) {
  25440. // TODO(gp) find out how to receive simulcast with FF. For the
  25441. // time being, hide it.
  25442. if (ssrcGroup.semantics === 'SIM') {
  25443. return;
  25444. }
  25445. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25446. Array.isArray(ssrcGroup.ssrcs)) {
  25447. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25448. if (typeof ssrc2group[ssrc] === 'undefined') {
  25449. ssrc2group[ssrc] = [];
  25450. }
  25451. ssrc2group[ssrc].push(ssrcGroup);
  25452. });
  25453. }
  25454. });
  25455. }
  25456. // ssrc to m-line index.
  25457. var ssrc2ml = {};
  25458. if (typeof sources === 'object') {
  25459. // Explode the Plan B channel sources with one m-line per source.
  25460. Object.keys(sources).forEach(function(ssrc) {
  25461. // The (unified) m-line for this SSRC. We either create it from
  25462. // scratch or, if it's a grouped SSRC, we re-use a related
  25463. // mline. In other words, if the source is grouped with another
  25464. // source, put the two together in the same m-line.
  25465. var unifiedLine;
  25466. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25467. Array.isArray(ssrc2group[ssrc])) {
  25468. ssrc2group[ssrc].some(function (ssrcGroup) {
  25469. // ssrcGroup.ssrcs *is* an Array, no need to check
  25470. // again here.
  25471. return ssrcGroup.ssrcs.some(function (related) {
  25472. if (typeof ssrc2ml[related] === 'object') {
  25473. unifiedLine = ssrc2ml[related];
  25474. return true;
  25475. }
  25476. });
  25477. });
  25478. }
  25479. if (typeof unifiedLine === 'object') {
  25480. // the m-line already exists. Just add the source.
  25481. unifiedLine.sources[ssrc] = sources[ssrc];
  25482. delete sources[ssrc].msid;
  25483. } else {
  25484. // Use the "bLine" as a prototype for the "unifiedLine".
  25485. unifiedLine = Object.create(bLine);
  25486. ssrc2ml[ssrc] = unifiedLine;
  25487. if (typeof sources[ssrc].msid !== 'undefined') {
  25488. // Assign the msid of the source to the m-line. Note
  25489. // that it is not guaranteed that the source will have
  25490. // msid. In particular "recvonly" sources don't have an
  25491. // msid. Note that "recvonly" is a term only defined
  25492. // for m-lines.
  25493. unifiedLine.msid = sources[ssrc].msid;
  25494. delete sources[ssrc].msid;
  25495. }
  25496. // We assign one SSRC per media line.
  25497. unifiedLine.sources = {};
  25498. unifiedLine.sources[ssrc] = sources[ssrc];
  25499. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25500. // Use the cached Unified Plan SDP (if it exists) to assign
  25501. // SSRCs to mids.
  25502. if (typeof cached !== 'undefined' &&
  25503. typeof cached.media !== 'undefined' &&
  25504. Array.isArray(cached.media)) {
  25505. cached.media.forEach(function (m) {
  25506. if (typeof m.sources === 'object') {
  25507. Object.keys(m.sources).forEach(function (s) {
  25508. if (s === ssrc) {
  25509. unifiedLine.mid = m.mid;
  25510. }
  25511. });
  25512. }
  25513. });
  25514. }
  25515. if (typeof unifiedLine.mid === 'undefined') {
  25516. // If this is an SSRC that we see for the first time
  25517. // assign it a new mid. This is typically the case when
  25518. // this method is called to transform a remote
  25519. // description for the first time or when there is a
  25520. // new SSRC in the remote description because a new
  25521. // peer has joined the conference. Local SSRCs should
  25522. // have already been added to the map in the toPlanB
  25523. // method.
  25524. //
  25525. // Because FF generates answers in Unified Plan style,
  25526. // we MUST already have a cached answer with all the
  25527. // local SSRCs mapped to some m-line/mid.
  25528. if (desc.type === 'answer') {
  25529. throw new Error("An unmapped SSRC was found.");
  25530. }
  25531. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25532. }
  25533. // Include the candidates in the 1st media line.
  25534. unifiedLine.candidates = candidates;
  25535. unifiedLine.iceUfrag = iceUfrag;
  25536. unifiedLine.icePwd = icePwd;
  25537. unifiedLine.fingerprint = fingerprint;
  25538. unifiedLine.port = port;
  25539. mid2ul[unifiedLine.mid] = unifiedLine;
  25540. }
  25541. });
  25542. }
  25543. });
  25544. // Rebuild the media array in the right order and add the missing mLines
  25545. // (missing from the Plan B SDP).
  25546. session.media = [];
  25547. mids = []; // reuse
  25548. if (desc.type === 'answer') {
  25549. // The media lines in the answer must match the media lines in the
  25550. // offer. The order is important too. Here we assume that Firefox is the
  25551. // answerer, so we merely have to use the reconstructed (unified) answer
  25552. // to update the cached (unified) answer accordingly.
  25553. //
  25554. // In the general case, one would have to use the cached (unified) offer
  25555. // to find the m-lines that are missing from the reconstructed answer,
  25556. // potentially grabbing them from the cached (unified) answer. One has
  25557. // to be carefull with this approach because inactive m-lines do not
  25558. // always have an mid, making it tricky (impossible?) to find where
  25559. // exactly and which m-lines are missing from the reconstructed answer.
  25560. for (var i = 0; i < cached.media.length; i++) {
  25561. var unifiedLine = cached.media[i];
  25562. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25563. // The mid isn't in the reconstructed (unified) answer.
  25564. // This is either a (unified) m-line containing a remote
  25565. // track only, or a (unified) m-line containing a remote
  25566. // track and a local track that has been removed.
  25567. // In either case, it MUST exist in the cached
  25568. // (unified) answer.
  25569. //
  25570. // In case this is a removed local track, clean-up
  25571. // the (unified) m-line and make sure it's 'recvonly' or
  25572. // 'inactive'.
  25573. delete unifiedLine.msid;
  25574. delete unifiedLine.sources;
  25575. delete unifiedLine.ssrcGroups;
  25576. if (!unifiedLine.direction
  25577. || unifiedLine.direction === 'sendrecv')
  25578. unifiedLine.direction = 'recvonly';
  25579. if (!unifiedLine.direction
  25580. || unifiedLine.direction === 'sendonly')
  25581. unifiedLine.direction = 'inactive';
  25582. } else {
  25583. // This is an (unified) m-line/channel that contains a local
  25584. // track (sendrecv or sendonly channel) or it's a unified
  25585. // recvonly m-line/channel. In either case, since we're
  25586. // going from PlanB -> Unified Plan this m-line MUST
  25587. // exist in the cached answer.
  25588. }
  25589. session.media.push(unifiedLine);
  25590. if (typeof unifiedLine.mid === 'string') {
  25591. // inactive lines don't/may not have an mid.
  25592. mids.push(unifiedLine.mid);
  25593. }
  25594. }
  25595. } else {
  25596. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25597. // under any circumstances. If we are no longer interested in sending a
  25598. // track, we just remove the msid and ssrc attributes and set it to
  25599. // either a=recvonly (as the reofferer, we must use recvonly if the
  25600. // other side was previously sending on the m-section, but we can also
  25601. // leave the possibility open if it wasn't previously in use), or
  25602. // a=inacive.
  25603. if (typeof cached !== 'undefined' &&
  25604. typeof cached.media !== 'undefined' &&
  25605. Array.isArray(cached.media)) {
  25606. cached.media.forEach(function(unifiedLine) {
  25607. mids.push(unifiedLine.mid);
  25608. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25609. session.media.push(mid2ul[unifiedLine.mid]);
  25610. } else {
  25611. delete unifiedLine.msid;
  25612. delete unifiedLine.sources;
  25613. delete unifiedLine.ssrcGroups;
  25614. if (!unifiedLine.direction
  25615. || unifiedLine.direction === 'sendrecv')
  25616. unifiedLine.direction = 'recvonly';
  25617. if (!unifiedLine.direction
  25618. || unifiedLine.direction === 'sendonly')
  25619. unifiedLine.direction = 'inactive';
  25620. session.media.push(unifiedLine);
  25621. }
  25622. });
  25623. }
  25624. // Add all the remaining (new) m-lines of the transformed SDP.
  25625. Object.keys(mid2ul).forEach(function(mid) {
  25626. if (mids.indexOf(mid) === -1) {
  25627. mids.push(mid);
  25628. if (typeof mid2ul[mid].direction === 'recvonly') {
  25629. // This is a remote recvonly channel. Add its SSRC to the
  25630. // appropriate sendrecv or sendonly channel.
  25631. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25632. session.media.some(function (unifiedLine) {
  25633. if ((unifiedLine.direction === 'sendrecv' ||
  25634. unifiedLine.direction === 'sendonly') &&
  25635. unifiedLine.type === mid2ul[mid].type) {
  25636. // mid2ul[mid] shouldn't have any ssrc-groups
  25637. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25638. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25639. });
  25640. return true;
  25641. }
  25642. });
  25643. } else {
  25644. session.media.push(mid2ul[mid]);
  25645. }
  25646. }
  25647. });
  25648. }
  25649. // We regenerate the BUNDLE group (since we regenerated the mids)
  25650. session.groups.some(function(group) {
  25651. if (group.type === 'BUNDLE') {
  25652. group.mids = mids.join(' ');
  25653. return true;
  25654. }
  25655. });
  25656. // msid semantic
  25657. session.msidSemantic = {
  25658. semantic: 'WMS',
  25659. token: '*'
  25660. };
  25661. var resStr = transform.write(session);
  25662. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25663. // function.
  25664. this.cache[desc.type] = resStr;
  25665. return new RTCSessionDescription({
  25666. type: desc.type,
  25667. sdp: resStr
  25668. });
  25669. //#endregion
  25670. };
  25671. },{"./array-equals":89,"./transform":92}],92:[function(require,module,exports){
  25672. var transform = require('sdp-transform');
  25673. exports.write = function(session, opts) {
  25674. if (typeof session !== 'undefined' &&
  25675. typeof session.media !== 'undefined' &&
  25676. Array.isArray(session.media)) {
  25677. session.media.forEach(function (mLine) {
  25678. // expand sources to ssrcs
  25679. if (typeof mLine.sources !== 'undefined' &&
  25680. Object.keys(mLine.sources).length !== 0) {
  25681. mLine.ssrcs = [];
  25682. Object.keys(mLine.sources).forEach(function (ssrc) {
  25683. var source = mLine.sources[ssrc];
  25684. Object.keys(source).forEach(function (attribute) {
  25685. mLine.ssrcs.push({
  25686. id: ssrc,
  25687. attribute: attribute,
  25688. value: source[attribute]
  25689. });
  25690. });
  25691. });
  25692. delete mLine.sources;
  25693. }
  25694. // join ssrcs in ssrc groups
  25695. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25696. Array.isArray(mLine.ssrcGroups)) {
  25697. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25698. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25699. Array.isArray(ssrcGroup.ssrcs)) {
  25700. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25701. }
  25702. });
  25703. }
  25704. });
  25705. }
  25706. // join group mids
  25707. if (typeof session !== 'undefined' &&
  25708. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25709. session.groups.forEach(function (g) {
  25710. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25711. g.mids = g.mids.join(' ');
  25712. }
  25713. });
  25714. }
  25715. return transform.write(session, opts);
  25716. };
  25717. exports.parse = function(sdp) {
  25718. var session = transform.parse(sdp);
  25719. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25720. Array.isArray(session.media)) {
  25721. session.media.forEach(function (mLine) {
  25722. // group sources attributes by ssrc
  25723. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25724. mLine.sources = {};
  25725. mLine.ssrcs.forEach(function (ssrc) {
  25726. if (!mLine.sources[ssrc.id])
  25727. mLine.sources[ssrc.id] = {};
  25728. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25729. });
  25730. delete mLine.ssrcs;
  25731. }
  25732. // split ssrcs in ssrc groups
  25733. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25734. Array.isArray(mLine.ssrcGroups)) {
  25735. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25736. if (typeof ssrcGroup.ssrcs === 'string') {
  25737. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25738. }
  25739. });
  25740. }
  25741. });
  25742. }
  25743. // split group mids
  25744. if (typeof session !== 'undefined' &&
  25745. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25746. session.groups.forEach(function (g) {
  25747. if (typeof g.mids === 'string') {
  25748. g.mids = g.mids.split(' ');
  25749. }
  25750. });
  25751. }
  25752. return session;
  25753. };
  25754. },{"sdp-transform":94}],93:[function(require,module,exports){
  25755. var grammar = module.exports = {
  25756. v: [{
  25757. name: 'version',
  25758. reg: /^(\d*)$/
  25759. }],
  25760. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25761. // NB: sessionId will be a String in most cases because it is huge
  25762. name: 'origin',
  25763. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25764. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25765. format: "%s %s %d %s IP%d %s"
  25766. }],
  25767. // default parsing of these only (though some of these feel outdated)
  25768. s: [{ name: 'name' }],
  25769. i: [{ name: 'description' }],
  25770. u: [{ name: 'uri' }],
  25771. e: [{ name: 'email' }],
  25772. p: [{ name: 'phone' }],
  25773. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25774. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25775. //k: [{}], // outdated thing ignored
  25776. t: [{ //t=0 0
  25777. name: 'timing',
  25778. reg: /^(\d*) (\d*)/,
  25779. names: ['start', 'stop'],
  25780. format: "%d %d"
  25781. }],
  25782. c: [{ //c=IN IP4 10.47.197.26
  25783. name: 'connection',
  25784. reg: /^IN IP(\d) (\S*)/,
  25785. names: ['version', 'ip'],
  25786. format: "IN IP%d %s"
  25787. }],
  25788. b: [{ //b=AS:4000
  25789. push: 'bandwidth',
  25790. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25791. names: ['type', 'limit'],
  25792. format: "%s:%s"
  25793. }],
  25794. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25795. // NB: special - pushes to session
  25796. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25797. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25798. names: ['type', 'port', 'protocol', 'payloads'],
  25799. format: "%s %d %s %s"
  25800. }],
  25801. a: [
  25802. { //a=rtpmap:110 opus/48000/2
  25803. push: 'rtp',
  25804. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25805. names: ['payload', 'codec', 'rate', 'encoding'],
  25806. format: function (o) {
  25807. return (o.encoding) ?
  25808. "rtpmap:%d %s/%s/%s":
  25809. "rtpmap:%d %s/%s";
  25810. }
  25811. },
  25812. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25813. push: 'fmtp',
  25814. reg: /^fmtp:(\d*) (\S*)/,
  25815. names: ['payload', 'config'],
  25816. format: "fmtp:%d %s"
  25817. },
  25818. { //a=control:streamid=0
  25819. name: 'control',
  25820. reg: /^control:(.*)/,
  25821. format: "control:%s"
  25822. },
  25823. { //a=rtcp:65179 IN IP4 193.84.77.194
  25824. name: 'rtcp',
  25825. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25826. names: ['port', 'netType', 'ipVer', 'address'],
  25827. format: function (o) {
  25828. return (o.address != null) ?
  25829. "rtcp:%d %s IP%d %s":
  25830. "rtcp:%d";
  25831. }
  25832. },
  25833. { //a=rtcp-fb:98 trr-int 100
  25834. push: 'rtcpFbTrrInt',
  25835. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25836. names: ['payload', 'value'],
  25837. format: "rtcp-fb:%d trr-int %d"
  25838. },
  25839. { //a=rtcp-fb:98 nack rpsi
  25840. push: 'rtcpFb',
  25841. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25842. names: ['payload', 'type', 'subtype'],
  25843. format: function (o) {
  25844. return (o.subtype != null) ?
  25845. "rtcp-fb:%s %s %s":
  25846. "rtcp-fb:%s %s";
  25847. }
  25848. },
  25849. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25850. //a=extmap:1/recvonly URI-gps-string
  25851. push: 'ext',
  25852. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25853. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25854. format: function (o) {
  25855. return (o.config != null) ?
  25856. "extmap:%s %s %s":
  25857. "extmap:%s %s";
  25858. }
  25859. },
  25860. {
  25861. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25862. push: 'crypto',
  25863. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25864. names: ['id', 'suite', 'config', 'sessionConfig'],
  25865. format: function (o) {
  25866. return (o.sessionConfig != null) ?
  25867. "crypto:%d %s %s %s":
  25868. "crypto:%d %s %s";
  25869. }
  25870. },
  25871. { //a=setup:actpass
  25872. name: 'setup',
  25873. reg: /^setup:(\w*)/,
  25874. format: "setup:%s"
  25875. },
  25876. { //a=mid:1
  25877. name: 'mid',
  25878. reg: /^mid:([^\s]*)/,
  25879. format: "mid:%s"
  25880. },
  25881. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25882. name: 'msid',
  25883. reg: /^msid:(.*)/,
  25884. format: "msid:%s"
  25885. },
  25886. { //a=ptime:20
  25887. name: 'ptime',
  25888. reg: /^ptime:(\d*)/,
  25889. format: "ptime:%d"
  25890. },
  25891. { //a=maxptime:60
  25892. name: 'maxptime',
  25893. reg: /^maxptime:(\d*)/,
  25894. format: "maxptime:%d"
  25895. },
  25896. { //a=sendrecv
  25897. name: 'direction',
  25898. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25899. },
  25900. { //a=ice-lite
  25901. name: 'icelite',
  25902. reg: /^(ice-lite)/
  25903. },
  25904. { //a=ice-ufrag:F7gI
  25905. name: 'iceUfrag',
  25906. reg: /^ice-ufrag:(\S*)/,
  25907. format: "ice-ufrag:%s"
  25908. },
  25909. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25910. name: 'icePwd',
  25911. reg: /^ice-pwd:(\S*)/,
  25912. format: "ice-pwd:%s"
  25913. },
  25914. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25915. name: 'fingerprint',
  25916. reg: /^fingerprint:(\S*) (\S*)/,
  25917. names: ['type', 'hash'],
  25918. format: "fingerprint:%s %s"
  25919. },
  25920. {
  25921. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25922. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25923. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25924. push:'candidates',
  25925. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  25926. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  25927. format: function (o) {
  25928. var str = "candidate:%s %d %s %d %s %d typ %s";
  25929. // NB: candidate has two optional chunks, so %void middle one if it's missing
  25930. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25931. if (o.generation != null) {
  25932. str += " generation %d";
  25933. }
  25934. return str;
  25935. }
  25936. },
  25937. { //a=end-of-candidates (keep after the candidates line for readability)
  25938. name: 'endOfCandidates',
  25939. reg: /^(end-of-candidates)/
  25940. },
  25941. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25942. name: 'remoteCandidates',
  25943. reg: /^remote-candidates:(.*)/,
  25944. format: "remote-candidates:%s"
  25945. },
  25946. { //a=ice-options:google-ice
  25947. name: 'iceOptions',
  25948. reg: /^ice-options:(\S*)/,
  25949. format: "ice-options:%s"
  25950. },
  25951. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25952. push: "ssrcs",
  25953. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25954. names: ['id', 'attribute', 'value'],
  25955. format: "ssrc:%d %s:%s"
  25956. },
  25957. { //a=ssrc-group:FEC 1 2
  25958. push: "ssrcGroups",
  25959. reg: /^ssrc-group:(\w*) (.*)/,
  25960. names: ['semantics', 'ssrcs'],
  25961. format: "ssrc-group:%s %s"
  25962. },
  25963. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25964. name: "msidSemantic",
  25965. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25966. names: ['semantic', 'token'],
  25967. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25968. },
  25969. { //a=group:BUNDLE audio video
  25970. push: 'groups',
  25971. reg: /^group:(\w*) (.*)/,
  25972. names: ['type', 'mids'],
  25973. format: "group:%s %s"
  25974. },
  25975. { //a=rtcp-mux
  25976. name: 'rtcpMux',
  25977. reg: /^(rtcp-mux)/
  25978. },
  25979. { //a=rtcp-rsize
  25980. name: 'rtcpRsize',
  25981. reg: /^(rtcp-rsize)/
  25982. },
  25983. { // any a= that we don't understand is kepts verbatim on media.invalid
  25984. push: 'invalid',
  25985. names: ["value"]
  25986. }
  25987. ]
  25988. };
  25989. // set sensible defaults to avoid polluting the grammar with boring details
  25990. Object.keys(grammar).forEach(function (key) {
  25991. var objs = grammar[key];
  25992. objs.forEach(function (obj) {
  25993. if (!obj.reg) {
  25994. obj.reg = /(.*)/;
  25995. }
  25996. if (!obj.format) {
  25997. obj.format = "%s";
  25998. }
  25999. });
  26000. });
  26001. },{}],94:[function(require,module,exports){
  26002. var parser = require('./parser');
  26003. var writer = require('./writer');
  26004. exports.write = writer;
  26005. exports.parse = parser.parse;
  26006. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26007. exports.parsePayloads = parser.parsePayloads;
  26008. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26009. },{"./parser":95,"./writer":96}],95:[function(require,module,exports){
  26010. var toIntIfInt = function (v) {
  26011. return String(Number(v)) === v ? Number(v) : v;
  26012. };
  26013. var attachProperties = function (match, location, names, rawName) {
  26014. if (rawName && !names) {
  26015. location[rawName] = toIntIfInt(match[1]);
  26016. }
  26017. else {
  26018. for (var i = 0; i < names.length; i += 1) {
  26019. if (match[i+1] != null) {
  26020. location[names[i]] = toIntIfInt(match[i+1]);
  26021. }
  26022. }
  26023. }
  26024. };
  26025. var parseReg = function (obj, location, content) {
  26026. var needsBlank = obj.name && obj.names;
  26027. if (obj.push && !location[obj.push]) {
  26028. location[obj.push] = [];
  26029. }
  26030. else if (needsBlank && !location[obj.name]) {
  26031. location[obj.name] = {};
  26032. }
  26033. var keyLocation = obj.push ?
  26034. {} : // blank object that will be pushed
  26035. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26036. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26037. if (obj.push) {
  26038. location[obj.push].push(keyLocation);
  26039. }
  26040. };
  26041. var grammar = require('./grammar');
  26042. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26043. exports.parse = function (sdp) {
  26044. var session = {}
  26045. , media = []
  26046. , location = session; // points at where properties go under (one of the above)
  26047. // parse lines we understand
  26048. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26049. var type = l[0];
  26050. var content = l.slice(2);
  26051. if (type === 'm') {
  26052. media.push({rtp: [], fmtp: []});
  26053. location = media[media.length-1]; // point at latest media line
  26054. }
  26055. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26056. var obj = grammar[type][j];
  26057. if (obj.reg.test(content)) {
  26058. return parseReg(obj, location, content);
  26059. }
  26060. }
  26061. });
  26062. session.media = media; // link it up
  26063. return session;
  26064. };
  26065. var fmtpReducer = function (acc, expr) {
  26066. var s = expr.split('=');
  26067. if (s.length === 2) {
  26068. acc[s[0]] = toIntIfInt(s[1]);
  26069. }
  26070. return acc;
  26071. };
  26072. exports.parseFmtpConfig = function (str) {
  26073. return str.split(';').reduce(fmtpReducer, {});
  26074. };
  26075. exports.parsePayloads = function (str) {
  26076. return str.split(' ').map(Number);
  26077. };
  26078. exports.parseRemoteCandidates = function (str) {
  26079. var candidates = [];
  26080. var parts = str.split(' ').map(toIntIfInt);
  26081. for (var i = 0; i < parts.length; i += 3) {
  26082. candidates.push({
  26083. component: parts[i],
  26084. ip: parts[i + 1],
  26085. port: parts[i + 2]
  26086. });
  26087. }
  26088. return candidates;
  26089. };
  26090. },{"./grammar":93}],96:[function(require,module,exports){
  26091. var grammar = require('./grammar');
  26092. // customized util.format - discards excess arguments and can void middle ones
  26093. var formatRegExp = /%[sdv%]/g;
  26094. var format = function (formatStr) {
  26095. var i = 1;
  26096. var args = arguments;
  26097. var len = args.length;
  26098. return formatStr.replace(formatRegExp, function (x) {
  26099. if (i >= len) {
  26100. return x; // missing argument
  26101. }
  26102. var arg = args[i];
  26103. i += 1;
  26104. switch (x) {
  26105. case '%%':
  26106. return '%';
  26107. case '%s':
  26108. return String(arg);
  26109. case '%d':
  26110. return Number(arg);
  26111. case '%v':
  26112. return '';
  26113. }
  26114. });
  26115. // NB: we discard excess arguments - they are typically undefined from makeLine
  26116. };
  26117. var makeLine = function (type, obj, location) {
  26118. var str = obj.format instanceof Function ?
  26119. (obj.format(obj.push ? location : location[obj.name])) :
  26120. obj.format;
  26121. var args = [type + '=' + str];
  26122. if (obj.names) {
  26123. for (var i = 0; i < obj.names.length; i += 1) {
  26124. var n = obj.names[i];
  26125. if (obj.name) {
  26126. args.push(location[obj.name][n]);
  26127. }
  26128. else { // for mLine and push attributes
  26129. args.push(location[obj.names[i]]);
  26130. }
  26131. }
  26132. }
  26133. else {
  26134. args.push(location[obj.name]);
  26135. }
  26136. return format.apply(null, args);
  26137. };
  26138. // RFC specified order
  26139. // TODO: extend this with all the rest
  26140. var defaultOuterOrder = [
  26141. 'v', 'o', 's', 'i',
  26142. 'u', 'e', 'p', 'c',
  26143. 'b', 't', 'r', 'z', 'a'
  26144. ];
  26145. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26146. module.exports = function (session, opts) {
  26147. opts = opts || {};
  26148. // ensure certain properties exist
  26149. if (session.version == null) {
  26150. session.version = 0; // "v=0" must be there (only defined version atm)
  26151. }
  26152. if (session.name == null) {
  26153. session.name = " "; // "s= " must be there if no meaningful name set
  26154. }
  26155. session.media.forEach(function (mLine) {
  26156. if (mLine.payloads == null) {
  26157. mLine.payloads = "";
  26158. }
  26159. });
  26160. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26161. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26162. var sdp = [];
  26163. // loop through outerOrder for matching properties on session
  26164. outerOrder.forEach(function (type) {
  26165. grammar[type].forEach(function (obj) {
  26166. if (obj.name in session && session[obj.name] != null) {
  26167. sdp.push(makeLine(type, obj, session));
  26168. }
  26169. else if (obj.push in session && session[obj.push] != null) {
  26170. session[obj.push].forEach(function (el) {
  26171. sdp.push(makeLine(type, obj, el));
  26172. });
  26173. }
  26174. });
  26175. });
  26176. // then for each media line, follow the innerOrder
  26177. session.media.forEach(function (mLine) {
  26178. sdp.push(makeLine('m', grammar.m[0], mLine));
  26179. innerOrder.forEach(function (type) {
  26180. grammar[type].forEach(function (obj) {
  26181. if (obj.name in mLine && mLine[obj.name] != null) {
  26182. sdp.push(makeLine(type, obj, mLine));
  26183. }
  26184. else if (obj.push in mLine && mLine[obj.push] != null) {
  26185. mLine[obj.push].forEach(function (el) {
  26186. sdp.push(makeLine(type, obj, el));
  26187. });
  26188. }
  26189. });
  26190. });
  26191. });
  26192. return sdp.join('\r\n') + '\r\n';
  26193. };
  26194. },{"./grammar":93}],97:[function(require,module,exports){
  26195. var transform = require('sdp-transform');
  26196. var transformUtils = require('./transform-utils');
  26197. var parseSsrcs = transformUtils.parseSsrcs;
  26198. var writeSsrcs = transformUtils.writeSsrcs;
  26199. //region Constants
  26200. var DEFAULT_NUM_OF_LAYERS = 3;
  26201. //endregion
  26202. //region Ctor
  26203. function Simulcast(options) {
  26204. this.options = options ? options : {};
  26205. if (!this.options.numOfLayers) {
  26206. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26207. }
  26208. this.layers = [];
  26209. }
  26210. //endregion
  26211. //region Stateless private utility functions
  26212. /**
  26213. * Returns a random integer between min (included) and max (excluded)
  26214. * Using Math.round() gives a non-uniform distribution!
  26215. * @returns {number}
  26216. */
  26217. function generateSSRC() {
  26218. var min = 0, max = 0xffffffff;
  26219. return Math.floor(Math.random() * (max - min)) + min;
  26220. };
  26221. function processVideo(session, action) {
  26222. if (session == null || !Array.isArray(session.media)) {
  26223. return;
  26224. }
  26225. session.media.forEach(function (mLine) {
  26226. if (mLine.type === 'video') {
  26227. action(mLine);
  26228. }
  26229. });
  26230. }
  26231. function validateDescription(desc)
  26232. {
  26233. return desc && desc != null
  26234. && desc.type && desc.type != ''
  26235. && desc.sdp && desc.sdp != '';
  26236. }
  26237. function explodeRemoteSimulcast(mLine) {
  26238. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26239. return;
  26240. }
  26241. var sources = parseSsrcs(mLine);
  26242. var order = [];
  26243. // Find the SIM group and explode its sources.
  26244. var j = mLine.ssrcGroups.length;
  26245. while (j--) {
  26246. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26247. continue;
  26248. }
  26249. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26250. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26251. var ssrc = simulcastSsrcs[i];
  26252. order.push(ssrc);
  26253. var parts = sources[ssrc].msid.split(' ');
  26254. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26255. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26256. // Remove all the groups that this SSRC participates in.
  26257. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26258. if (relatedGroup.semantics === 'SIM') {
  26259. return;
  26260. }
  26261. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26262. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26263. return;
  26264. }
  26265. // Nuke all the related SSRCs.
  26266. relatedSsrcs.forEach(function (relatedSSRC) {
  26267. sources[relatedSSRC].msid = sources[ssrc].msid;
  26268. sources[relatedSSRC].cname = sources[ssrc].cname;
  26269. if (relatedSSRC !== ssrc) {
  26270. order.push(relatedSSRC);
  26271. }
  26272. });
  26273. // Schedule the related group for nuking.
  26274. })
  26275. }
  26276. mLine.ssrcs = writeSsrcs(sources, order);
  26277. mLine.ssrcGroups.splice(j, 1);
  26278. };
  26279. }
  26280. function squeezeRemoteSimulcast(mLine) {
  26281. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26282. return;
  26283. }
  26284. var sources = parseSsrcs(mLine);
  26285. // Find the SIM group and nuke it.
  26286. mLine.ssrcGroups.some(function (simulcastGroup) {
  26287. if (simulcastGroup.semantics !== 'SIM') {
  26288. return false;
  26289. }
  26290. // Schedule the SIM group for nuking.
  26291. simulcastGroup.nuke = true;
  26292. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26293. // Nuke all the higher layer SSRCs.
  26294. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26295. var ssrc = simulcastSsrcs[i];
  26296. delete sources[ssrc];
  26297. // Remove all the groups that this SSRC participates in.
  26298. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26299. if (relatedGroup.semantics === 'SIM') {
  26300. return;
  26301. }
  26302. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26303. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26304. return;
  26305. }
  26306. // Nuke all the related SSRCs.
  26307. relatedSsrcs.forEach(function (relatedSSRC) {
  26308. delete sources[relatedSSRC];
  26309. });
  26310. // Schedule the related group for nuking.
  26311. relatedGroup.nuke = true;
  26312. })
  26313. }
  26314. return true;
  26315. });
  26316. mLine.ssrcs = writeSsrcs(sources);
  26317. // Nuke all the scheduled groups.
  26318. var i = mLine.ssrcGroups.length;
  26319. while (i--) {
  26320. if (mLine.ssrcGroups[i].nuke) {
  26321. mLine.ssrcGroups.splice(i, 1);
  26322. }
  26323. }
  26324. }
  26325. function removeGoogConference(mLine) {
  26326. if (!mLine || !Array.isArray(mLine.invalid)) {
  26327. return;
  26328. }
  26329. var i = mLine.invalid.length;
  26330. while (i--) {
  26331. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26332. mLine.invalid.splice(i, 1);
  26333. }
  26334. }
  26335. }
  26336. function assertGoogConference(mLine) {
  26337. if (!mLine) {
  26338. return;
  26339. }
  26340. if (!Array.isArray(mLine.invalid)) {
  26341. mLine.invalid = [];
  26342. }
  26343. if (!mLine.invalid.some(
  26344. function (i) { return i.value === 'x-google-flag:conference' })) {
  26345. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26346. }
  26347. }
  26348. //endregion
  26349. //region "Private" functions
  26350. /**
  26351. *
  26352. * @param mLine
  26353. * @private
  26354. */
  26355. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26356. if (!mLine || mLine.type !== 'video') {
  26357. return;
  26358. }
  26359. var sources = parseSsrcs(mLine);
  26360. if (Object.keys(sources).length === 0) {
  26361. // no sources, disable simulcast.
  26362. if (this.layers.length !== 0) {
  26363. this.layers = [];
  26364. }
  26365. return;
  26366. }
  26367. // find the base layer (we'll reuse its msid and cname).
  26368. var baseLayerSSRC = Object.keys(sources)[0];
  26369. var baseLayer = sources[baseLayerSSRC];
  26370. // todo(gp) handle screen sharing.
  26371. // check if base CNAME has changed and reinitialise layers.
  26372. if (this.layers.length > 0
  26373. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26374. this.layers = [];
  26375. }
  26376. // (re)initialise layers
  26377. if (this.layers.length < 1) {
  26378. // first push the base layer.
  26379. this.layers.push({
  26380. ssrc: baseLayerSSRC,
  26381. msid: baseLayer.msid,
  26382. cname: baseLayer.cname
  26383. });
  26384. var rtx = false; // RFC 4588
  26385. if (Array.isArray(mLine.rtp)) {
  26386. rtx = mLine.rtp.some(
  26387. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26388. }
  26389. if (rtx) {
  26390. this.layers[0].rtx = generateSSRC();
  26391. }
  26392. // now push additional layers.
  26393. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26394. var layer = { ssrc: generateSSRC() };
  26395. if (rtx) {
  26396. layer.rtx = generateSSRC();
  26397. }
  26398. this.layers.push(layer);
  26399. }
  26400. }
  26401. };
  26402. /**
  26403. *
  26404. * @param mLine
  26405. * @private
  26406. */
  26407. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26408. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26409. var sources = {};
  26410. var msid = this.layers[0].msid;
  26411. var cname = this.layers[0].cname;
  26412. var simulcastSsrcs = [];
  26413. var ssrcGroups = [];
  26414. for (var i = 0; i < this.layers.length; i++) {
  26415. var layer = this.layers[i];
  26416. sources[layer.ssrc] = { msid: msid, cname: cname };
  26417. simulcastSsrcs.push(layer.ssrc);
  26418. if (layer.rtx) {
  26419. sources[layer.rtx] = {
  26420. msid: msid,
  26421. cname: cname
  26422. }
  26423. ssrcGroups.push({
  26424. semantics: 'FID',
  26425. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26426. });
  26427. }
  26428. }
  26429. ssrcGroups.push({
  26430. semantics: 'SIM',
  26431. ssrcs: simulcastSsrcs.join(' ')
  26432. });
  26433. mLine.ssrcGroups = ssrcGroups;
  26434. mLine.ssrcs = writeSsrcs(sources);
  26435. }
  26436. }
  26437. //endregion
  26438. //region "Public" functions
  26439. Simulcast.prototype.isSupported = function () {
  26440. return window.chrome;
  26441. // TODO this needs improvements. For example I doubt that Chrome in Android
  26442. // has simulcast support. Also, only recent versions of Chromium have native
  26443. // simulcast support.
  26444. }
  26445. /**
  26446. *
  26447. * @param desc
  26448. * @returns {RTCSessionDescription}
  26449. */
  26450. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26451. if (!validateDescription(desc)) {
  26452. return desc;
  26453. }
  26454. var session = transform.parse(desc.sdp);
  26455. var self = this;
  26456. processVideo(session, function (mLine) {
  26457. // Handle simulcast reception.
  26458. if (self.options.explodeRemoteSimulcast) {
  26459. explodeRemoteSimulcast(mLine);
  26460. } else {
  26461. squeezeRemoteSimulcast(mLine);
  26462. }
  26463. // If native simulcast is enabled, we must append the x-goog-conference
  26464. // attribute to the SDP.
  26465. if (self.layers.length < 1) {
  26466. removeGoogConference(mLine);
  26467. } else {
  26468. assertGoogConference(mLine);
  26469. }
  26470. });
  26471. return new RTCSessionDescription({
  26472. type: desc.type,
  26473. sdp: transform.write(session)
  26474. });
  26475. };
  26476. /**
  26477. *
  26478. * @param desc
  26479. * @returns {RTCSessionDescription}
  26480. */
  26481. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26482. if (!validateDescription(desc) || !this.isSupported()) {
  26483. return desc;
  26484. }
  26485. var session = transform.parse(desc.sdp);
  26486. var self = this;
  26487. processVideo(session, function (mLine) {
  26488. // Initialize native simulcast layers, if not already done.
  26489. self._maybeInitializeLayers(mLine);
  26490. // Update the SDP with the simulcast layers.
  26491. self._restoreSimulcastView(mLine);
  26492. });
  26493. return new RTCSessionDescription({
  26494. type: desc.type,
  26495. sdp: transform.write(session)
  26496. });
  26497. };
  26498. //endregion
  26499. module.exports = Simulcast;
  26500. },{"./transform-utils":98,"sdp-transform":100}],98:[function(require,module,exports){
  26501. exports.writeSsrcs = function(sources, order) {
  26502. var ssrcs = [];
  26503. // expand sources to ssrcs
  26504. if (typeof sources !== 'undefined' &&
  26505. Object.keys(sources).length !== 0) {
  26506. if (Array.isArray(order)) {
  26507. for (var i = 0; i < order.length; i++) {
  26508. var ssrc = order[i];
  26509. var source = sources[ssrc];
  26510. Object.keys(source).forEach(function (attribute) {
  26511. ssrcs.push({
  26512. id: ssrc,
  26513. attribute: attribute,
  26514. value: source[attribute]
  26515. });
  26516. });
  26517. }
  26518. } else {
  26519. Object.keys(sources).forEach(function (ssrc) {
  26520. var source = sources[ssrc];
  26521. Object.keys(source).forEach(function (attribute) {
  26522. ssrcs.push({
  26523. id: ssrc,
  26524. attribute: attribute,
  26525. value: source[attribute]
  26526. });
  26527. });
  26528. });
  26529. }
  26530. }
  26531. return ssrcs;
  26532. };
  26533. exports.parseSsrcs = function (mLine) {
  26534. var sources = {};
  26535. // group sources attributes by ssrc.
  26536. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26537. mLine.ssrcs.forEach(function (ssrc) {
  26538. if (!sources[ssrc.id])
  26539. sources[ssrc.id] = {};
  26540. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26541. });
  26542. }
  26543. return sources;
  26544. };
  26545. },{}],99:[function(require,module,exports){
  26546. arguments[4][93][0].apply(exports,arguments)
  26547. },{"dup":93}],100:[function(require,module,exports){
  26548. arguments[4][94][0].apply(exports,arguments)
  26549. },{"./parser":101,"./writer":102,"dup":94}],101:[function(require,module,exports){
  26550. arguments[4][95][0].apply(exports,arguments)
  26551. },{"./grammar":99,"dup":95}],102:[function(require,module,exports){
  26552. arguments[4][96][0].apply(exports,arguments)
  26553. },{"./grammar":99,"dup":96}],103:[function(require,module,exports){
  26554. arguments[4][93][0].apply(exports,arguments)
  26555. },{"dup":93}],104:[function(require,module,exports){
  26556. arguments[4][94][0].apply(exports,arguments)
  26557. },{"./parser":105,"./writer":106,"dup":94}],105:[function(require,module,exports){
  26558. arguments[4][95][0].apply(exports,arguments)
  26559. },{"./grammar":103,"dup":95}],106:[function(require,module,exports){
  26560. arguments[4][96][0].apply(exports,arguments)
  26561. },{"./grammar":103,"dup":96}],107:[function(require,module,exports){
  26562. var MediaStreamType = {
  26563. VIDEO_TYPE: "Video",
  26564. AUDIO_TYPE: "Audio"
  26565. };
  26566. module.exports = MediaStreamType;
  26567. },{}],108:[function(require,module,exports){
  26568. var RTCEvents = {
  26569. RTC_READY: "rtc.ready",
  26570. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  26571. LASTN_CHANGED: "rtc.lastn_changed",
  26572. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26573. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26574. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26575. AUDIO_MUTE: "rtc.audio_mute",
  26576. VIDEO_MUTE: "rtc.video_mute"
  26577. };
  26578. module.exports = RTCEvents;
  26579. },{}],109:[function(require,module,exports){
  26580. var Resolutions = {
  26581. "1080": {
  26582. width: 1920,
  26583. height: 1080,
  26584. order: 7
  26585. },
  26586. "fullhd": {
  26587. width: 1920,
  26588. height: 1080,
  26589. order: 7
  26590. },
  26591. "720": {
  26592. width: 1280,
  26593. height: 720,
  26594. order: 6
  26595. },
  26596. "hd": {
  26597. width: 1280,
  26598. height: 720,
  26599. order: 6
  26600. },
  26601. "960": {
  26602. width: 960,
  26603. height: 720,
  26604. order: 5
  26605. },
  26606. "640": {
  26607. width: 640,
  26608. height: 480,
  26609. order: 4
  26610. },
  26611. "vga": {
  26612. width: 640,
  26613. height: 480,
  26614. order: 4
  26615. },
  26616. "360": {
  26617. width: 640,
  26618. height: 360,
  26619. order: 3
  26620. },
  26621. "320": {
  26622. width: 320,
  26623. height: 240,
  26624. order: 2
  26625. },
  26626. "180": {
  26627. width: 320,
  26628. height: 180,
  26629. order: 1
  26630. }
  26631. };
  26632. module.exports = Resolutions;
  26633. },{}],110:[function(require,module,exports){
  26634. var StreamEventTypes = {
  26635. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26636. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26637. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26638. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26639. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  26640. };
  26641. module.exports = StreamEventTypes;
  26642. },{}],111:[function(require,module,exports){
  26643. var UIEvents = {
  26644. NICKNAME_CHANGED: "UI.nickname_changed",
  26645. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26646. PINNED_ENDPOINT: "UI.pinned_endpoint",
  26647. LARGEVIDEO_INIT: "UI.largevideo_init"
  26648. };
  26649. module.exports = UIEvents;
  26650. },{}],112:[function(require,module,exports){
  26651. var AuthenticationEvents = {
  26652. /**
  26653. * Event callback arguments:
  26654. * function(authenticationEnabled, userIdentity)
  26655. * authenticationEnabled - indicates whether authentication has been enabled
  26656. * in this session
  26657. * userIdentity - if user has been logged in then it contains user name. If
  26658. * contains 'null' or 'undefined' then user is not logged in.
  26659. */
  26660. IDENTITY_UPDATED: "authentication.identity_updated"
  26661. };
  26662. module.exports = AuthenticationEvents;
  26663. },{}],113:[function(require,module,exports){
  26664. var CQEvents = {
  26665. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26666. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26667. STOP: "cq.stop"
  26668. };
  26669. module.exports = CQEvents;
  26670. },{}],114:[function(require,module,exports){
  26671. var DesktopSharingEventTypes = {
  26672. INIT: "ds.init",
  26673. SWITCHING_DONE: "ds.switching_done",
  26674. NEW_STREAM_CREATED: "ds.new_stream_created"
  26675. };
  26676. module.exports = DesktopSharingEventTypes;
  26677. },{}],115:[function(require,module,exports){
  26678. var Events = {
  26679. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26680. };
  26681. module.exports = Events;
  26682. },{}],116:[function(require,module,exports){
  26683. module.exports = {
  26684. getLanguages : function () {
  26685. var languages = [];
  26686. for(var lang in this)
  26687. {
  26688. if(typeof this[lang] === "string")
  26689. languages.push(this[lang]);
  26690. }
  26691. return languages;
  26692. },
  26693. EN: "en",
  26694. BG: "bg",
  26695. DE: "de",
  26696. TR: "tr",
  26697. FR: "fr"
  26698. }
  26699. },{}],117:[function(require,module,exports){
  26700. var XMPPEvents = {
  26701. CONNECTION_FAILED: "xmpp.connection.failed",
  26702. // Indicates an interrupted connection event.
  26703. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  26704. // Indicates a restored connection event.
  26705. CONNECTION_RESTORED: "xmpp.connection.restored",
  26706. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26707. CALL_INCOMING: "xmpp.callincoming.jingle",
  26708. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26709. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26710. KICKED: "xmpp.kicked",
  26711. BRIDGE_DOWN: "xmpp.bridge_down",
  26712. USER_ID_CHANGED: "xmpp.user_id_changed",
  26713. // We joined the MUC
  26714. MUC_JOINED: "xmpp.muc_joined",
  26715. // A member joined the MUC
  26716. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26717. // A member left the MUC
  26718. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26719. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26720. MUC_DESTROYED: "xmpp.muc_destroyed",
  26721. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26722. REMOTE_STATS: "xmpp.remote_stats",
  26723. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26724. PRESENCE_STATUS: "xmpp.presence_status",
  26725. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26726. SUBJECT_CHANGED: "xmpp.subject_changed",
  26727. MESSAGE_RECEIVED: "xmpp.message_received",
  26728. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26729. PASSWORD_REQUIRED: "xmpp.password_required",
  26730. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26731. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26732. ETHERPAD: "xmpp.etherpad",
  26733. DEVICE_AVAILABLE: "xmpp.device_available",
  26734. VIDEO_TYPE: "xmpp.video_type",
  26735. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  26736. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  26737. AUDIO_MUTED: "xmpp.audio_muted",
  26738. VIDEO_MUTED: "xmpp.video_muted",
  26739. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  26740. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  26741. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  26742. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  26743. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  26744. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  26745. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  26746. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  26747. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  26748. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  26749. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  26750. // xmpp is connected and obtained user media
  26751. READY_TO_JOIN: 'xmpp.ready_to_join'
  26752. };
  26753. module.exports = XMPPEvents;
  26754. },{}],118:[function(require,module,exports){
  26755. // Copyright Joyent, Inc. and other Node contributors.
  26756. //
  26757. // Permission is hereby granted, free of charge, to any person obtaining a
  26758. // copy of this software and associated documentation files (the
  26759. // "Software"), to deal in the Software without restriction, including
  26760. // without limitation the rights to use, copy, modify, merge, publish,
  26761. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26762. // persons to whom the Software is furnished to do so, subject to the
  26763. // following conditions:
  26764. //
  26765. // The above copyright notice and this permission notice shall be included
  26766. // in all copies or substantial portions of the Software.
  26767. //
  26768. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26769. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26770. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26771. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26772. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26773. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26774. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26775. function EventEmitter() {
  26776. this._events = this._events || {};
  26777. this._maxListeners = this._maxListeners || undefined;
  26778. }
  26779. module.exports = EventEmitter;
  26780. // Backwards-compat with node 0.10.x
  26781. EventEmitter.EventEmitter = EventEmitter;
  26782. EventEmitter.prototype._events = undefined;
  26783. EventEmitter.prototype._maxListeners = undefined;
  26784. // By default EventEmitters will print a warning if more than 10 listeners are
  26785. // added to it. This is a useful default which helps finding memory leaks.
  26786. EventEmitter.defaultMaxListeners = 10;
  26787. // Obviously not all Emitters should be limited to 10. This function allows
  26788. // that to be increased. Set to zero for unlimited.
  26789. EventEmitter.prototype.setMaxListeners = function(n) {
  26790. if (!isNumber(n) || n < 0 || isNaN(n))
  26791. throw TypeError('n must be a positive number');
  26792. this._maxListeners = n;
  26793. return this;
  26794. };
  26795. EventEmitter.prototype.emit = function(type) {
  26796. var er, handler, len, args, i, listeners;
  26797. if (!this._events)
  26798. this._events = {};
  26799. // If there is no 'error' event listener then throw.
  26800. if (type === 'error') {
  26801. if (!this._events.error ||
  26802. (isObject(this._events.error) && !this._events.error.length)) {
  26803. er = arguments[1];
  26804. if (er instanceof Error) {
  26805. throw er; // Unhandled 'error' event
  26806. }
  26807. throw TypeError('Uncaught, unspecified "error" event.');
  26808. }
  26809. }
  26810. handler = this._events[type];
  26811. if (isUndefined(handler))
  26812. return false;
  26813. if (isFunction(handler)) {
  26814. switch (arguments.length) {
  26815. // fast cases
  26816. case 1:
  26817. handler.call(this);
  26818. break;
  26819. case 2:
  26820. handler.call(this, arguments[1]);
  26821. break;
  26822. case 3:
  26823. handler.call(this, arguments[1], arguments[2]);
  26824. break;
  26825. // slower
  26826. default:
  26827. len = arguments.length;
  26828. args = new Array(len - 1);
  26829. for (i = 1; i < len; i++)
  26830. args[i - 1] = arguments[i];
  26831. handler.apply(this, args);
  26832. }
  26833. } else if (isObject(handler)) {
  26834. len = arguments.length;
  26835. args = new Array(len - 1);
  26836. for (i = 1; i < len; i++)
  26837. args[i - 1] = arguments[i];
  26838. listeners = handler.slice();
  26839. len = listeners.length;
  26840. for (i = 0; i < len; i++)
  26841. listeners[i].apply(this, args);
  26842. }
  26843. return true;
  26844. };
  26845. EventEmitter.prototype.addListener = function(type, listener) {
  26846. var m;
  26847. if (!isFunction(listener))
  26848. throw TypeError('listener must be a function');
  26849. if (!this._events)
  26850. this._events = {};
  26851. // To avoid recursion in the case that type === "newListener"! Before
  26852. // adding it to the listeners, first emit "newListener".
  26853. if (this._events.newListener)
  26854. this.emit('newListener', type,
  26855. isFunction(listener.listener) ?
  26856. listener.listener : listener);
  26857. if (!this._events[type])
  26858. // Optimize the case of one listener. Don't need the extra array object.
  26859. this._events[type] = listener;
  26860. else if (isObject(this._events[type]))
  26861. // If we've already got an array, just append.
  26862. this._events[type].push(listener);
  26863. else
  26864. // Adding the second element, need to change to array.
  26865. this._events[type] = [this._events[type], listener];
  26866. // Check for listener leak
  26867. if (isObject(this._events[type]) && !this._events[type].warned) {
  26868. var m;
  26869. if (!isUndefined(this._maxListeners)) {
  26870. m = this._maxListeners;
  26871. } else {
  26872. m = EventEmitter.defaultMaxListeners;
  26873. }
  26874. if (m && m > 0 && this._events[type].length > m) {
  26875. this._events[type].warned = true;
  26876. console.error('(node) warning: possible EventEmitter memory ' +
  26877. 'leak detected. %d listeners added. ' +
  26878. 'Use emitter.setMaxListeners() to increase limit.',
  26879. this._events[type].length);
  26880. if (typeof console.trace === 'function') {
  26881. // not supported in IE 10
  26882. console.trace();
  26883. }
  26884. }
  26885. }
  26886. return this;
  26887. };
  26888. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  26889. EventEmitter.prototype.once = function(type, listener) {
  26890. if (!isFunction(listener))
  26891. throw TypeError('listener must be a function');
  26892. var fired = false;
  26893. function g() {
  26894. this.removeListener(type, g);
  26895. if (!fired) {
  26896. fired = true;
  26897. listener.apply(this, arguments);
  26898. }
  26899. }
  26900. g.listener = listener;
  26901. this.on(type, g);
  26902. return this;
  26903. };
  26904. // emits a 'removeListener' event iff the listener was removed
  26905. EventEmitter.prototype.removeListener = function(type, listener) {
  26906. var list, position, length, i;
  26907. if (!isFunction(listener))
  26908. throw TypeError('listener must be a function');
  26909. if (!this._events || !this._events[type])
  26910. return this;
  26911. list = this._events[type];
  26912. length = list.length;
  26913. position = -1;
  26914. if (list === listener ||
  26915. (isFunction(list.listener) && list.listener === listener)) {
  26916. delete this._events[type];
  26917. if (this._events.removeListener)
  26918. this.emit('removeListener', type, listener);
  26919. } else if (isObject(list)) {
  26920. for (i = length; i-- > 0;) {
  26921. if (list[i] === listener ||
  26922. (list[i].listener && list[i].listener === listener)) {
  26923. position = i;
  26924. break;
  26925. }
  26926. }
  26927. if (position < 0)
  26928. return this;
  26929. if (list.length === 1) {
  26930. list.length = 0;
  26931. delete this._events[type];
  26932. } else {
  26933. list.splice(position, 1);
  26934. }
  26935. if (this._events.removeListener)
  26936. this.emit('removeListener', type, listener);
  26937. }
  26938. return this;
  26939. };
  26940. EventEmitter.prototype.removeAllListeners = function(type) {
  26941. var key, listeners;
  26942. if (!this._events)
  26943. return this;
  26944. // not listening for removeListener, no need to emit
  26945. if (!this._events.removeListener) {
  26946. if (arguments.length === 0)
  26947. this._events = {};
  26948. else if (this._events[type])
  26949. delete this._events[type];
  26950. return this;
  26951. }
  26952. // emit removeListener for all listeners on all events
  26953. if (arguments.length === 0) {
  26954. for (key in this._events) {
  26955. if (key === 'removeListener') continue;
  26956. this.removeAllListeners(key);
  26957. }
  26958. this.removeAllListeners('removeListener');
  26959. this._events = {};
  26960. return this;
  26961. }
  26962. listeners = this._events[type];
  26963. if (isFunction(listeners)) {
  26964. this.removeListener(type, listeners);
  26965. } else {
  26966. // LIFO order
  26967. while (listeners.length)
  26968. this.removeListener(type, listeners[listeners.length - 1]);
  26969. }
  26970. delete this._events[type];
  26971. return this;
  26972. };
  26973. EventEmitter.prototype.listeners = function(type) {
  26974. var ret;
  26975. if (!this._events || !this._events[type])
  26976. ret = [];
  26977. else if (isFunction(this._events[type]))
  26978. ret = [this._events[type]];
  26979. else
  26980. ret = this._events[type].slice();
  26981. return ret;
  26982. };
  26983. EventEmitter.listenerCount = function(emitter, type) {
  26984. var ret;
  26985. if (!emitter._events || !emitter._events[type])
  26986. ret = 0;
  26987. else if (isFunction(emitter._events[type]))
  26988. ret = 1;
  26989. else
  26990. ret = emitter._events[type].length;
  26991. return ret;
  26992. };
  26993. function isFunction(arg) {
  26994. return typeof arg === 'function';
  26995. }
  26996. function isNumber(arg) {
  26997. return typeof arg === 'number';
  26998. }
  26999. function isObject(arg) {
  27000. return typeof arg === 'object' && arg !== null;
  27001. }
  27002. function isUndefined(arg) {
  27003. return arg === void 0;
  27004. }
  27005. },{}],119:[function(require,module,exports){
  27006. // shim for using process in browser
  27007. var process = module.exports = {};
  27008. var queue = [];
  27009. var draining = false;
  27010. var currentQueue;
  27011. var queueIndex = -1;
  27012. function cleanUpNextTick() {
  27013. draining = false;
  27014. if (currentQueue.length) {
  27015. queue = currentQueue.concat(queue);
  27016. } else {
  27017. queueIndex = -1;
  27018. }
  27019. if (queue.length) {
  27020. drainQueue();
  27021. }
  27022. }
  27023. function drainQueue() {
  27024. if (draining) {
  27025. return;
  27026. }
  27027. var timeout = setTimeout(cleanUpNextTick);
  27028. draining = true;
  27029. var len = queue.length;
  27030. while(len) {
  27031. currentQueue = queue;
  27032. queue = [];
  27033. while (++queueIndex < len) {
  27034. currentQueue[queueIndex].run();
  27035. }
  27036. queueIndex = -1;
  27037. len = queue.length;
  27038. }
  27039. currentQueue = null;
  27040. draining = false;
  27041. clearTimeout(timeout);
  27042. }
  27043. process.nextTick = function (fun) {
  27044. var args = new Array(arguments.length - 1);
  27045. if (arguments.length > 1) {
  27046. for (var i = 1; i < arguments.length; i++) {
  27047. args[i - 1] = arguments[i];
  27048. }
  27049. }
  27050. queue.push(new Item(fun, args));
  27051. if (queue.length === 1 && !draining) {
  27052. setTimeout(drainQueue, 0);
  27053. }
  27054. };
  27055. // v8 likes predictible objects
  27056. function Item(fun, array) {
  27057. this.fun = fun;
  27058. this.array = array;
  27059. }
  27060. Item.prototype.run = function () {
  27061. this.fun.apply(null, this.array);
  27062. };
  27063. process.title = 'browser';
  27064. process.browser = true;
  27065. process.env = {};
  27066. process.argv = [];
  27067. process.version = ''; // empty string to avoid regexp issues
  27068. process.versions = {};
  27069. function noop() {}
  27070. process.on = noop;
  27071. process.addListener = noop;
  27072. process.once = noop;
  27073. process.off = noop;
  27074. process.removeListener = noop;
  27075. process.removeAllListeners = noop;
  27076. process.emit = noop;
  27077. process.binding = function (name) {
  27078. throw new Error('process.binding is not supported');
  27079. };
  27080. // TODO(shtylman)
  27081. process.cwd = function () { return '/' };
  27082. process.chdir = function (dir) {
  27083. throw new Error('process.chdir is not supported');
  27084. };
  27085. process.umask = function() { return 0; };
  27086. },{}]},{},[1])(1)
  27087. });