Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

app.bundle.js 1.0MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142
  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":68}],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":110}],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":101}],5:[function(require,module,exports){
  456. /* global APP */
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. var RTCEvents = require("../../service/RTC/RTCEvents");
  459. var RTCBrowserType = require("./RTCBrowserType");
  460. /**
  461. * This implements 'onended' callback normally fired by WebRTC after the stream
  462. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  463. * @param stream original WebRTC stream object to which 'onended' handling
  464. * will be added.
  465. */
  466. function implementOnEndedHandling(stream) {
  467. var originalStop = stream.stop;
  468. stream.stop = function () {
  469. originalStop.apply(stream);
  470. if (!stream.ended) {
  471. stream.ended = true;
  472. stream.onended();
  473. }
  474. };
  475. }
  476. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  477. this.stream = stream;
  478. this.eventEmitter = eventEmitter;
  479. this.type = type;
  480. this.videoType = videoType;
  481. this.isGUMStream = true;
  482. if(isGUMStream === false)
  483. this.isGUMStream = isGUMStream;
  484. var self = this;
  485. if(type == "audio") {
  486. this.getTracks = function () {
  487. return self.stream.getAudioTracks();
  488. };
  489. } else {
  490. this.getTracks = function () {
  491. return self.stream.getVideoTracks();
  492. };
  493. }
  494. this.stream.onended = function () {
  495. self.streamEnded();
  496. };
  497. if (RTCBrowserType.isFirefox()) {
  498. implementOnEndedHandling(this.stream);
  499. }
  500. }
  501. LocalStream.prototype.streamEnded = function () {
  502. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  503. };
  504. LocalStream.prototype.getOriginalStream = function()
  505. {
  506. return this.stream;
  507. };
  508. LocalStream.prototype.isAudioStream = function () {
  509. return this.type === "audio";
  510. };
  511. LocalStream.prototype.setMute = function (mute)
  512. {
  513. var isAudio = this.isAudioStream();
  514. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  515. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  516. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  517. // FIXME FF does not support 'removeStream' method used to mute
  518. RTCBrowserType.isFirefox()) {
  519. var tracks = this.getTracks();
  520. for (var idx = 0; idx < tracks.length; idx++) {
  521. tracks[idx].enabled = !mute;
  522. }
  523. this.eventEmitter.emit(eventType, mute);
  524. } else {
  525. if (mute) {
  526. APP.xmpp.removeStream(this.stream);
  527. this.stream.stop();
  528. this.eventEmitter.emit(eventType, true);
  529. } else {
  530. var self = this;
  531. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  532. (this.isAudioStream() ? ["audio"] : ["video"]),
  533. function (stream) {
  534. if (isAudio) {
  535. APP.RTC.changeLocalAudio(stream,
  536. function () {
  537. self.eventEmitter.emit(eventType, false);
  538. });
  539. } else {
  540. APP.RTC.changeLocalVideo(stream, false,
  541. function () {
  542. self.eventEmitter.emit(eventType, false);
  543. });
  544. }
  545. });
  546. }
  547. }
  548. };
  549. LocalStream.prototype.isMuted = function () {
  550. var tracks = [];
  551. if (this.isAudioStream()) {
  552. tracks = this.stream.getAudioTracks();
  553. } else {
  554. if (this.stream.ended)
  555. return true;
  556. tracks = this.stream.getVideoTracks();
  557. }
  558. for (var idx = 0; idx < tracks.length; idx++) {
  559. if(tracks[idx].enabled)
  560. return false;
  561. }
  562. return true;
  563. };
  564. LocalStream.prototype.getId = function () {
  565. return this.stream.getTracks()[0].id;
  566. };
  567. module.exports = LocalStream;
  568. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes.js":103,"./RTCBrowserType":8}],6:[function(require,module,exports){
  569. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  570. /**
  571. * Creates a MediaStream object for the given data, session id and ssrc.
  572. * It is a wrapper class for the MediaStream.
  573. *
  574. * @param data the data object from which we obtain the stream,
  575. * the peerjid, etc.
  576. * @param sid the session id
  577. * @param ssrc the ssrc corresponding to this MediaStream
  578. *
  579. * @constructor
  580. */
  581. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  582. // XXX(gp) to minimize headaches in the future, we should build our
  583. // abstractions around tracks and not streams. ORTC is track based API.
  584. // Mozilla expects m-lines to represent media tracks.
  585. //
  586. // Practically, what I'm saying is that we should have a MediaTrack class
  587. // and not a MediaStream class.
  588. //
  589. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  590. // a track might have an associated RTX and FEC sources.
  591. this.sid = sid;
  592. this.stream = data.stream;
  593. this.peerjid = data.peerjid;
  594. this.videoType = data.videoType;
  595. this.ssrc = ssrc;
  596. this.type = (this.stream.getVideoTracks().length > 0)?
  597. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  598. this.muted = false;
  599. this.eventEmitter = eventEmitter;
  600. }
  601. MediaStream.prototype.getOriginalStream = function() {
  602. return this.stream;
  603. };
  604. MediaStream.prototype.setMute = function (value) {
  605. this.stream.muted = value;
  606. this.muted = value;
  607. };
  608. module.exports = MediaStream;
  609. },{"../../service/RTC/MediaStreamTypes":100}],7:[function(require,module,exports){
  610. /* global APP */
  611. var EventEmitter = require("events");
  612. var RTCBrowserType = require("./RTCBrowserType");
  613. var RTCUtils = require("./RTCUtils.js");
  614. var LocalStream = require("./LocalStream.js");
  615. var DataChannels = require("./DataChannels");
  616. var MediaStream = require("./MediaStream.js");
  617. var DesktopSharingEventTypes
  618. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  619. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  620. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  621. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  622. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  623. var UIEvents = require("../../service/UI/UIEvents");
  624. var eventEmitter = new EventEmitter();
  625. function getMediaStreamUsage()
  626. {
  627. var result = {
  628. audio: true,
  629. video: true
  630. };
  631. /** There are some issues with the desktop sharing
  632. * when this property is enabled.
  633. * WARNING: We must change the implementation to start video/audio if we
  634. * receive from the focus that the peer is not muted.
  635. var isSecureConnection = window.location.protocol == "https:";
  636. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  637. {
  638. result = {
  639. audio: false,
  640. video: false
  641. };
  642. }
  643. **/
  644. return result;
  645. }
  646. var RTC = {
  647. rtcUtils: null,
  648. devices: {
  649. audio: true,
  650. video: true
  651. },
  652. localStreams: [],
  653. remoteStreams: {},
  654. localAudio: null,
  655. localVideo: null,
  656. addStreamListener: function (listener, eventType) {
  657. eventEmitter.on(eventType, listener);
  658. },
  659. addListener: function (type, listener) {
  660. eventEmitter.on(type, listener);
  661. },
  662. removeStreamListener: function (listener, eventType) {
  663. if(!(eventType instanceof StreamEventTypes))
  664. throw "Illegal argument";
  665. eventEmitter.removeListener(eventType, listener);
  666. },
  667. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  668. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  669. //in firefox we have only one stream object
  670. if(this.localStreams.length == 0 ||
  671. this.localStreams[0].getOriginalStream() != stream)
  672. this.localStreams.push(localStream);
  673. if(isMuted === true)
  674. localStream.setMute(true);
  675. if(type == "audio") {
  676. this.localAudio = localStream;
  677. } else {
  678. this.localVideo = localStream;
  679. }
  680. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  681. if(change)
  682. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  683. eventEmitter.emit(eventType, localStream, isMuted);
  684. return localStream;
  685. },
  686. removeLocalStream: function (stream) {
  687. for(var i = 0; i < this.localStreams.length; i++) {
  688. if(this.localStreams[i].getOriginalStream() === stream) {
  689. delete this.localStreams[i];
  690. return;
  691. }
  692. }
  693. },
  694. createRemoteStream: function (data, sid, thessrc) {
  695. var remoteStream = new MediaStream(data, sid, thessrc,
  696. RTCBrowserType.getBrowserType(), eventEmitter);
  697. var jid = data.peerjid || APP.xmpp.myJid();
  698. if(!this.remoteStreams[jid]) {
  699. this.remoteStreams[jid] = {};
  700. }
  701. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  702. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  703. return remoteStream;
  704. },
  705. getPCConstraints: function () {
  706. return this.rtcUtils.pc_constraints;
  707. },
  708. getUserMediaWithConstraints:function(um, success_callback,
  709. failure_callback, resolution,
  710. bandwidth, fps, desktopStream)
  711. {
  712. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  713. failure_callback, resolution, bandwidth, fps, desktopStream);
  714. },
  715. attachMediaStream: function (elSelector, stream) {
  716. this.rtcUtils.attachMediaStream(elSelector, stream);
  717. },
  718. getStreamID: function (stream) {
  719. return this.rtcUtils.getStreamID(stream);
  720. },
  721. getVideoSrc: function (element) {
  722. return this.rtcUtils.getVideoSrc(element);
  723. },
  724. setVideoSrc: function (element, src) {
  725. this.rtcUtils.setVideoSrc(element, src);
  726. },
  727. getVideoElementName: function () {
  728. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  729. },
  730. dispose: function() {
  731. if (this.rtcUtils) {
  732. this.rtcUtils = null;
  733. }
  734. },
  735. stop: function () {
  736. this.dispose();
  737. },
  738. start: function () {
  739. var self = this;
  740. APP.desktopsharing.addListener(
  741. function (stream, isUsingScreenStream, callback) {
  742. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  743. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  744. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  745. DataChannels.init(event.peerconnection, eventEmitter);
  746. });
  747. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  748. DataChannels.handleSelectedEndpointEvent);
  749. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  750. DataChannels.handlePinnedEndpointEvent);
  751. // In case of IE we continue from 'onReady' callback
  752. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  753. // once it is initialized.
  754. var onReady = function () {
  755. eventEmitter.emit(RTCEvents.RTC_READY, true);
  756. self.rtcUtils.obtainAudioAndVideoPermissions(
  757. null, null, getMediaStreamUsage());
  758. };
  759. this.rtcUtils = new RTCUtils(this, onReady);
  760. // Call onReady() if Temasys plugin is not used
  761. if (!RTCBrowserType.isTemasysPluginUsed()) {
  762. onReady();
  763. }
  764. },
  765. muteRemoteVideoStream: function (jid, value) {
  766. var stream;
  767. if(this.remoteStreams[jid] &&
  768. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  769. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  770. }
  771. if(!stream)
  772. return true;
  773. if (value != stream.muted) {
  774. stream.setMute(value);
  775. return true;
  776. }
  777. return false;
  778. },
  779. switchVideoStreams: function (new_stream) {
  780. this.localVideo.stream = new_stream;
  781. this.localStreams = [];
  782. //in firefox we have only one stream object
  783. if (this.localAudio.getOriginalStream() != new_stream)
  784. this.localStreams.push(this.localAudio);
  785. this.localStreams.push(this.localVideo);
  786. },
  787. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  788. var oldStream = this.localVideo.getOriginalStream();
  789. var type = (isUsingScreenStream ? "screen" : "camera");
  790. var localCallback = callback;
  791. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  792. localCallback = function() {
  793. APP.xmpp.setVideoMute(false, function(mute) {
  794. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  795. });
  796. callback();
  797. };
  798. }
  799. // FIXME: Workaround for FF/IE/Safari
  800. if (stream && stream.videoStream) {
  801. stream = stream.videoStream;
  802. }
  803. var videoStream = this.rtcUtils.createStream(stream, true);
  804. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  805. // Stop the stream to trigger onended event for old stream
  806. oldStream.stop();
  807. this.switchVideoStreams(videoStream, oldStream);
  808. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  809. },
  810. changeLocalAudio: function (stream, callback) {
  811. var oldStream = this.localAudio.getOriginalStream();
  812. var newStream = this.rtcUtils.createStream(stream);
  813. this.localAudio = this.createLocalStream(newStream, "audio", true);
  814. // Stop the stream to trigger onended event for old stream
  815. oldStream.stop();
  816. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  817. },
  818. isVideoMuted: function (jid) {
  819. if (jid === APP.xmpp.myJid()) {
  820. var localVideo = APP.RTC.localVideo;
  821. return (!localVideo || localVideo.isMuted());
  822. } else {
  823. if (!APP.RTC.remoteStreams[jid] ||
  824. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  825. return null;
  826. }
  827. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  828. }
  829. },
  830. setVideoMute: function (mute, callback, options) {
  831. if (!this.localVideo)
  832. return;
  833. if (mute == APP.RTC.localVideo.isMuted())
  834. {
  835. APP.xmpp.sendVideoInfoPresence(mute);
  836. if (callback)
  837. callback(mute);
  838. }
  839. else
  840. {
  841. APP.RTC.localVideo.setMute(mute);
  842. APP.xmpp.setVideoMute(
  843. mute,
  844. callback,
  845. options);
  846. }
  847. },
  848. setDeviceAvailability: function (devices) {
  849. if(!devices)
  850. return;
  851. if(devices.audio === true || devices.audio === false)
  852. this.devices.audio = devices.audio;
  853. if(devices.video === true || devices.video === false)
  854. this.devices.video = devices.video;
  855. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  856. }
  857. };
  858. module.exports = RTC;
  859. },{"../../service/RTC/MediaStreamTypes":100,"../../service/RTC/RTCEvents.js":101,"../../service/RTC/StreamEventTypes.js":103,"../../service/UI/UIEvents":104,"../../service/desktopsharing/DesktopSharingEventTypes":107,"../../service/xmpp/XMPPEvents":110,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":111}],8:[function(require,module,exports){
  860. var currentBrowser;
  861. var browserVersion;
  862. var RTCBrowserType = {
  863. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  864. RTC_BROWSER_OPERA: "rtc_browser.opera",
  865. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  866. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  867. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  868. getBrowserType: function () {
  869. return currentBrowser;
  870. },
  871. isChrome: function () {
  872. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  873. },
  874. isOpera: function () {
  875. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  876. },
  877. isFirefox: function () {
  878. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  879. },
  880. isIExplorer: function () {
  881. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  882. },
  883. isSafari: function () {
  884. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  885. },
  886. isTemasysPluginUsed: function () {
  887. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  888. },
  889. getFirefoxVersion: function () {
  890. return RTCBrowserType.isFirefox() ? browserVersion : null;
  891. },
  892. getChromeVersion: function () {
  893. return RTCBrowserType.isChrome() ? browserVersion : null;
  894. },
  895. usesPlanB: function() {
  896. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  897. RTCBrowserType.isTemasysPluginUsed();
  898. },
  899. usesUnifiedPlan: function() {
  900. return RTCBrowserType.isFirefox();
  901. }
  902. // Add version getters for other browsers when needed
  903. };
  904. // detectOpera() must be called before detectChrome() !!!
  905. // otherwise Opera wil be detected as Chrome
  906. function detectChrome() {
  907. if (navigator.webkitGetUserMedia) {
  908. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  909. var userAgent = navigator.userAgent.toLowerCase();
  910. // We can assume that user agent is chrome, because it's
  911. // enforced when 'ext' streaming method is set
  912. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  913. console.log("This appears to be Chrome, ver: " + ver);
  914. return ver;
  915. }
  916. return null;
  917. }
  918. function detectOpera() {
  919. var userAgent = navigator.userAgent;
  920. if (userAgent.match(/Opera|OPR/)) {
  921. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  922. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  923. console.info("This appears to be Opera, ver: " + version);
  924. return version;
  925. }
  926. return null;
  927. }
  928. function detectFirefox() {
  929. if (navigator.mozGetUserMedia) {
  930. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  931. var version = parseInt(
  932. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  933. console.log('This appears to be Firefox, ver: ' + version);
  934. return version;
  935. }
  936. return null;
  937. }
  938. function detectSafari() {
  939. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  940. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  941. console.info("This appears to be Safari");
  942. // FIXME detect Safari version when needed
  943. return 1;
  944. }
  945. return null;
  946. }
  947. function detectIE() {
  948. var version;
  949. var ua = window.navigator.userAgent;
  950. var msie = ua.indexOf('MSIE ');
  951. if (msie > 0) {
  952. // IE 10 or older => return version number
  953. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  954. }
  955. var trident = ua.indexOf('Trident/');
  956. if (!version && trident > 0) {
  957. // IE 11 => return version number
  958. var rv = ua.indexOf('rv:');
  959. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  960. }
  961. var edge = ua.indexOf('Edge/');
  962. if (!version && edge > 0) {
  963. // IE 12 => return version number
  964. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  965. }
  966. if (version) {
  967. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  968. console.info("This appears to be IExplorer, ver: " + version);
  969. }
  970. return version;
  971. }
  972. function detectBrowser() {
  973. var version;
  974. var detectors = [
  975. detectOpera,
  976. detectChrome,
  977. detectFirefox,
  978. detectIE,
  979. detectSafari
  980. ];
  981. // Try all browser detectors
  982. for (var i = 0; i < detectors.length; i++) {
  983. version = detectors[i]();
  984. if (version)
  985. return version;
  986. }
  987. console.error("Failed to detect browser type");
  988. return undefined;
  989. }
  990. browserVersion = detectBrowser();
  991. module.exports = RTCBrowserType;
  992. },{}],9:[function(require,module,exports){
  993. /* global config, require, attachMediaStream, getUserMedia */
  994. var RTCBrowserType = require("./RTCBrowserType");
  995. var Resolutions = require("../../service/RTC/Resolutions");
  996. var AdapterJS = require("./adapter.screenshare");
  997. var SDPUtil = require("../xmpp/SDPUtil");
  998. var currentResolution = null;
  999. function getPreviousResolution(resolution) {
  1000. if(!Resolutions[resolution])
  1001. return null;
  1002. var order = Resolutions[resolution].order;
  1003. var res = null;
  1004. var resName = null;
  1005. for(var i in Resolutions) {
  1006. var tmp = Resolutions[i];
  1007. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1008. resName = i;
  1009. res = tmp;
  1010. }
  1011. }
  1012. return resName;
  1013. }
  1014. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1015. if (Resolutions[resolution]) {
  1016. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1017. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1018. }
  1019. else if (isAndroid) {
  1020. // FIXME can't remember if the purpose of this was to always request
  1021. // low resolution on Android ? if yes it should be moved up front
  1022. constraints.video.mandatory.minWidth = 320;
  1023. constraints.video.mandatory.minHeight = 240;
  1024. constraints.video.mandatory.maxFrameRate = 15;
  1025. }
  1026. if (constraints.video.mandatory.minWidth)
  1027. constraints.video.mandatory.maxWidth =
  1028. constraints.video.mandatory.minWidth;
  1029. if (constraints.video.mandatory.minHeight)
  1030. constraints.video.mandatory.maxHeight =
  1031. constraints.video.mandatory.minHeight;
  1032. }
  1033. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1034. {
  1035. var constraints = {audio: false, video: false};
  1036. if (um.indexOf('video') >= 0) {
  1037. // same behaviour as true
  1038. constraints.video = { mandatory: {}, optional: [] };
  1039. constraints.video.optional.push({ googLeakyBucket: true });
  1040. setResolutionConstraints(constraints, resolution, isAndroid);
  1041. }
  1042. if (um.indexOf('audio') >= 0) {
  1043. if (!RTCBrowserType.isFirefox()) {
  1044. // same behaviour as true
  1045. constraints.audio = { mandatory: {}, optional: []};
  1046. // if it is good enough for hangouts...
  1047. constraints.audio.optional.push(
  1048. {googEchoCancellation: true},
  1049. {googAutoGainControl: true},
  1050. {googNoiseSupression: true},
  1051. {googHighpassFilter: true},
  1052. {googNoisesuppression2: true},
  1053. {googEchoCancellation2: true},
  1054. {googAutoGainControl2: true}
  1055. );
  1056. } else {
  1057. constraints.audio = true;
  1058. }
  1059. }
  1060. if (um.indexOf('screen') >= 0) {
  1061. if (RTCBrowserType.isChrome()) {
  1062. constraints.video = {
  1063. mandatory: {
  1064. chromeMediaSource: "screen",
  1065. googLeakyBucket: true,
  1066. maxWidth: window.screen.width,
  1067. maxHeight: window.screen.height,
  1068. maxFrameRate: 3
  1069. },
  1070. optional: []
  1071. };
  1072. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1073. constraints.video = {
  1074. optional: [
  1075. {
  1076. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1077. }
  1078. ]
  1079. };
  1080. } else {
  1081. console.error(
  1082. "'screen' WebRTC media source is supported only in Chrome" +
  1083. " and with Temasys plugin");
  1084. }
  1085. }
  1086. if (um.indexOf('desktop') >= 0) {
  1087. constraints.video = {
  1088. mandatory: {
  1089. chromeMediaSource: "desktop",
  1090. chromeMediaSourceId: desktopStream,
  1091. googLeakyBucket: true,
  1092. maxWidth: window.screen.width,
  1093. maxHeight: window.screen.height,
  1094. maxFrameRate: 3
  1095. },
  1096. optional: []
  1097. };
  1098. }
  1099. if (bandwidth) {
  1100. if (!constraints.video) {
  1101. //same behaviour as true
  1102. constraints.video = {mandatory: {}, optional: []};
  1103. }
  1104. constraints.video.optional.push({bandwidth: bandwidth});
  1105. }
  1106. if (fps) {
  1107. // for some cameras it might be necessary to request 30fps
  1108. // so they choose 30fps mjpg over 10fps yuy2
  1109. if (!constraints.video) {
  1110. // same behaviour as true;
  1111. constraints.video = {mandatory: {}, optional: []};
  1112. }
  1113. constraints.video.mandatory.minFrameRate = fps;
  1114. }
  1115. return constraints;
  1116. }
  1117. function RTCUtils(RTCService, onTemasysPluginReady)
  1118. {
  1119. var self = this;
  1120. this.service = RTCService;
  1121. if (RTCBrowserType.isFirefox()) {
  1122. var FFversion = RTCBrowserType.getFirefoxVersion();
  1123. if (FFversion >= 40) {
  1124. this.peerconnection = mozRTCPeerConnection;
  1125. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1126. this.pc_constraints = {};
  1127. this.attachMediaStream = function (element, stream) {
  1128. // srcObject is being standardized and FF will eventually
  1129. // support that unprefixed. FF also supports the
  1130. // "element.src = URL.createObjectURL(...)" combo, but that
  1131. // will be deprecated in favour of srcObject.
  1132. //
  1133. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1134. // https://github.com/webrtc/samples/issues/302
  1135. if(!element[0])
  1136. return;
  1137. element[0].mozSrcObject = stream;
  1138. element[0].play();
  1139. };
  1140. this.getStreamID = function (stream) {
  1141. var id = stream.id;
  1142. if (!id) {
  1143. var tracks = stream.getVideoTracks();
  1144. if (!tracks || tracks.length === 0) {
  1145. tracks = stream.getAudioTracks();
  1146. }
  1147. id = tracks[0].id;
  1148. }
  1149. return SDPUtil.filter_special_chars(id);
  1150. };
  1151. this.getVideoSrc = function (element) {
  1152. if(!element)
  1153. return null;
  1154. return element.mozSrcObject;
  1155. };
  1156. this.setVideoSrc = function (element, src) {
  1157. if(element)
  1158. element.mozSrcObject = src;
  1159. };
  1160. RTCSessionDescription = mozRTCSessionDescription;
  1161. RTCIceCandidate = mozRTCIceCandidate;
  1162. } else {
  1163. console.error(
  1164. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1165. window.location.href = 'unsupported_browser.html';
  1166. return;
  1167. }
  1168. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1169. this.peerconnection = webkitRTCPeerConnection;
  1170. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1171. this.attachMediaStream = function (element, stream) {
  1172. element.attr('src', webkitURL.createObjectURL(stream));
  1173. };
  1174. this.getStreamID = function (stream) {
  1175. // streams from FF endpoints have the characters '{' and '}'
  1176. // that make jQuery choke.
  1177. return SDPUtil.filter_special_chars(stream.id);
  1178. };
  1179. this.getVideoSrc = function (element) {
  1180. if(!element)
  1181. return null;
  1182. return element.getAttribute("src");
  1183. };
  1184. this.setVideoSrc = function (element, src) {
  1185. if(element)
  1186. element.setAttribute("src", src);
  1187. };
  1188. // DTLS should now be enabled by default but..
  1189. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1190. if (navigator.userAgent.indexOf('Android') != -1) {
  1191. this.pc_constraints = {}; // disable DTLS on Android
  1192. }
  1193. if (!webkitMediaStream.prototype.getVideoTracks) {
  1194. webkitMediaStream.prototype.getVideoTracks = function () {
  1195. return this.videoTracks;
  1196. };
  1197. }
  1198. if (!webkitMediaStream.prototype.getAudioTracks) {
  1199. webkitMediaStream.prototype.getAudioTracks = function () {
  1200. return this.audioTracks;
  1201. };
  1202. }
  1203. }
  1204. // Detect IE/Safari
  1205. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1206. //AdapterJS.WebRTCPlugin.setLogLevel(
  1207. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1208. AdapterJS.webRTCReady(function (isPlugin) {
  1209. self.peerconnection = RTCPeerConnection;
  1210. self.getUserMedia = getUserMedia;
  1211. self.attachMediaStream = function (elSel, stream) {
  1212. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1213. return;
  1214. }
  1215. attachMediaStream(elSel[0], stream);
  1216. };
  1217. self.getStreamID = function (stream) {
  1218. var id = SDPUtil.filter_special_chars(stream.label);
  1219. return id;
  1220. };
  1221. self.getVideoSrc = function (element) {
  1222. if (!element) {
  1223. console.warn("Attempt to get video SRC of null element");
  1224. return null;
  1225. }
  1226. var children = element.children;
  1227. for (var i = 0; i !== children.length; ++i) {
  1228. if (children[i].name === 'streamId') {
  1229. return children[i].value;
  1230. }
  1231. }
  1232. //console.info(element.id + " SRC: " + src);
  1233. return null;
  1234. };
  1235. self.setVideoSrc = function (element, src) {
  1236. //console.info("Set video src: ", element, src);
  1237. if (!src) {
  1238. console.warn("Not attaching video stream, 'src' is null");
  1239. return;
  1240. }
  1241. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1242. var stream = AdapterJS.WebRTCPlugin.plugin
  1243. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1244. attachMediaStream(element, stream);
  1245. };
  1246. onTemasysPluginReady(isPlugin);
  1247. });
  1248. } else {
  1249. try {
  1250. console.log('Browser does not appear to be WebRTC-capable');
  1251. } catch (e) { }
  1252. window.location.href = 'unsupported_browser.html';
  1253. }
  1254. }
  1255. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1256. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1257. desktopStream) {
  1258. currentResolution = resolution;
  1259. // Check if we are running on Android device
  1260. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1261. var constraints = getConstraints(
  1262. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1263. console.info("Get media constraints", constraints);
  1264. var self = this;
  1265. try {
  1266. this.getUserMedia(constraints,
  1267. function (stream) {
  1268. console.log('onUserMediaSuccess');
  1269. self.setAvailableDevices(um, true);
  1270. success_callback(stream);
  1271. },
  1272. function (error) {
  1273. self.setAvailableDevices(um, false);
  1274. console.warn('Failed to get access to local media. Error ',
  1275. error, constraints);
  1276. if (failure_callback) {
  1277. failure_callback(error);
  1278. }
  1279. });
  1280. } catch (e) {
  1281. console.error('GUM failed: ', e);
  1282. if(failure_callback) {
  1283. failure_callback(e);
  1284. }
  1285. }
  1286. };
  1287. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1288. var devices = {};
  1289. if(um.indexOf("video") != -1) {
  1290. devices.video = available;
  1291. }
  1292. if(um.indexOf("audio") != -1) {
  1293. devices.audio = available;
  1294. }
  1295. this.service.setDeviceAvailability(devices);
  1296. };
  1297. /**
  1298. * We ask for audio and video combined stream in order to get permissions and
  1299. * not to ask twice.
  1300. */
  1301. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1302. function(devices, callback, usageOptions)
  1303. {
  1304. var self = this;
  1305. // Get AV
  1306. var successCallback = function (stream) {
  1307. if(callback)
  1308. callback(stream, usageOptions);
  1309. else
  1310. self.successCallback(stream, usageOptions);
  1311. };
  1312. if(!devices)
  1313. devices = ['audio', 'video'];
  1314. var newDevices = [];
  1315. if(usageOptions)
  1316. for(var i = 0; i < devices.length; i++) {
  1317. var device = devices[i];
  1318. if(usageOptions[device] === true)
  1319. newDevices.push(device);
  1320. }
  1321. else
  1322. newDevices = devices;
  1323. if(newDevices.length === 0) {
  1324. successCallback();
  1325. return;
  1326. }
  1327. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1328. // With FF/IE we can't split the stream into audio and video because FF
  1329. // doesn't support media stream constructors. So, we need to get the
  1330. // audio stream separately from the video stream using two distinct GUM
  1331. // calls. Not very user friendly :-( but we don't have many other
  1332. // options neither.
  1333. //
  1334. // Note that we pack those 2 streams in a single object and pass it to
  1335. // the successCallback method.
  1336. var obtainVideo = function (audioStream) {
  1337. self.getUserMediaWithConstraints(
  1338. ['video'],
  1339. function (videoStream) {
  1340. return successCallback({
  1341. audioStream: audioStream,
  1342. videoStream: videoStream
  1343. });
  1344. },
  1345. function (error) {
  1346. console.error(
  1347. 'failed to obtain video stream - stop', error);
  1348. self.errorCallback(error);
  1349. },
  1350. config.resolution || '360');
  1351. };
  1352. var obtainAudio = function () {
  1353. self.getUserMediaWithConstraints(
  1354. ['audio'],
  1355. function (audioStream) {
  1356. if (newDevices.indexOf('video') !== -1)
  1357. obtainVideo(audioStream);
  1358. },
  1359. function (error) {
  1360. console.error(
  1361. 'failed to obtain audio stream - stop', error);
  1362. self.errorCallback(error);
  1363. }
  1364. );
  1365. };
  1366. if (newDevices.indexOf('audio') !== -1) {
  1367. obtainAudio();
  1368. } else {
  1369. obtainVideo(null);
  1370. }
  1371. } else {
  1372. this.getUserMediaWithConstraints(
  1373. newDevices,
  1374. function (stream) {
  1375. successCallback(stream);
  1376. },
  1377. function (error) {
  1378. self.errorCallback(error);
  1379. },
  1380. config.resolution || '360');
  1381. }
  1382. };
  1383. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1384. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1385. // it's an object with two properties: audioStream, videoStream.
  1386. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1387. console.log('got', stream, stream.getAudioTracks().length,
  1388. stream.getVideoTracks().length);
  1389. this.handleLocalStream(stream, usageOptions);
  1390. };
  1391. RTCUtils.prototype.errorCallback = function (error) {
  1392. var self = this;
  1393. console.error('failed to obtain audio/video stream - trying audio only', error);
  1394. var resolution = getPreviousResolution(currentResolution);
  1395. if(typeof error == "object" && error.constraintName && error.name
  1396. && (error.name == "ConstraintNotSatisfiedError" ||
  1397. error.name == "OverconstrainedError") &&
  1398. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1399. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1400. && resolution != null)
  1401. {
  1402. self.getUserMediaWithConstraints(['audio', 'video'],
  1403. function (stream) {
  1404. return self.successCallback(stream);
  1405. }, function (error) {
  1406. return self.errorCallback(error);
  1407. }, resolution);
  1408. }
  1409. else {
  1410. self.getUserMediaWithConstraints(
  1411. ['audio'],
  1412. function (stream) {
  1413. return self.successCallback(stream);
  1414. },
  1415. function (error) {
  1416. console.error('failed to obtain audio/video stream - stop',
  1417. error);
  1418. return self.successCallback(null);
  1419. }
  1420. );
  1421. }
  1422. };
  1423. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1424. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1425. // an object with two properties: audioStream, videoStream.
  1426. var audioStream, videoStream;
  1427. if(window.webkitMediaStream)
  1428. {
  1429. audioStream = new webkitMediaStream();
  1430. videoStream = new webkitMediaStream();
  1431. if(stream) {
  1432. var audioTracks = stream.getAudioTracks();
  1433. for (var i = 0; i < audioTracks.length; i++) {
  1434. audioStream.addTrack(audioTracks[i]);
  1435. }
  1436. var videoTracks = stream.getVideoTracks();
  1437. for (i = 0; i < videoTracks.length; i++) {
  1438. videoStream.addTrack(videoTracks[i]);
  1439. }
  1440. }
  1441. }
  1442. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1443. { // Firefox and Temasys plugin
  1444. if (stream && stream.audioStream)
  1445. audioStream = stream.audioStream;
  1446. else
  1447. audioStream = new DummyMediaStream("dummyAudio");
  1448. if (stream && stream.videoStream)
  1449. videoStream = stream.videoStream;
  1450. else
  1451. videoStream = new DummyMediaStream("dummyVideo");
  1452. }
  1453. var audioMuted = (usageOptions && usageOptions.audio === false),
  1454. videoMuted = (usageOptions && usageOptions.video === false);
  1455. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1456. videoGUM = (!usageOptions || usageOptions.video !== false);
  1457. this.service.createLocalStream(audioStream, "audio", null, null,
  1458. audioMuted, audioGUM);
  1459. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1460. videoMuted, videoGUM);
  1461. };
  1462. function DummyMediaStream(id) {
  1463. this.id = id;
  1464. this.label = id;
  1465. this.stop = function() { };
  1466. this.getAudioTracks = function() { return []; };
  1467. this.getVideoTracks = function() { return []; };
  1468. }
  1469. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1470. var newStream = null;
  1471. if (window.webkitMediaStream) {
  1472. newStream = new webkitMediaStream();
  1473. if (newStream) {
  1474. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1475. for (var i = 0; i < tracks.length; i++) {
  1476. newStream.addTrack(tracks[i]);
  1477. }
  1478. }
  1479. }
  1480. else {
  1481. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1482. if (stream) {
  1483. newStream = stream;
  1484. } else {
  1485. newStream =
  1486. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1487. }
  1488. }
  1489. return newStream;
  1490. };
  1491. module.exports = RTCUtils;
  1492. },{"../../service/RTC/Resolutions":102,"../xmpp/SDPUtil":58,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1493. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1494. // Adapter's interface.
  1495. var AdapterJS = AdapterJS || {};
  1496. // Browserify compatibility
  1497. if(typeof exports !== 'undefined') {
  1498. module.exports = AdapterJS;
  1499. }
  1500. AdapterJS.options = AdapterJS.options || {};
  1501. // uncomment to get virtual webcams
  1502. // AdapterJS.options.getAllCams = true;
  1503. // uncomment to prevent the install prompt when the plugin in not yet installed
  1504. // AdapterJS.options.hidePluginInstallPrompt = true;
  1505. // AdapterJS version
  1506. AdapterJS.VERSION = '0.11.0';
  1507. // This function will be called when the WebRTC API is ready to be used
  1508. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1509. // the plugin
  1510. // You may Override this function to synchronise the start of your application
  1511. // with the WebRTC API being ready.
  1512. // If you decide not to override use this synchronisation, it may result in
  1513. // an extensive CPU usage on the plugin start (once per tab loaded)
  1514. // Params:
  1515. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1516. //
  1517. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1518. // The WebRTC API is ready.
  1519. // Override me and do whatever you want here
  1520. };
  1521. // Sets a callback function to be called when the WebRTC interface is ready.
  1522. // The first argument is the function to callback.\
  1523. // Throws an error if the first argument is not a function
  1524. AdapterJS.webRTCReady = function (callback) {
  1525. if (typeof callback !== 'function') {
  1526. throw new Error('Callback provided is not a function');
  1527. }
  1528. if (true === AdapterJS.onwebrtcreadyDone) {
  1529. // All WebRTC interfaces are ready, just call the callback
  1530. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1531. } else {
  1532. // will be triggered automatically when your browser/plugin is ready.
  1533. AdapterJS.onwebrtcready = callback;
  1534. }
  1535. };
  1536. // Plugin namespace
  1537. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1538. // The object to store plugin information
  1539. AdapterJS.WebRTCPlugin.pluginInfo = {
  1540. prefix : 'Tem',
  1541. plugName : 'TemWebRTCPlugin',
  1542. pluginId : 'plugin0',
  1543. type : 'application/x-temwebrtcplugin',
  1544. onload : '__TemWebRTCReady0',
  1545. portalLink : 'http://skylink.io/plugin/',
  1546. downloadLink : null, //set below
  1547. companyName: 'Temasys'
  1548. };
  1549. if(!!navigator.platform.match(/^Mac/i)) {
  1550. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1551. }
  1552. else if(!!navigator.platform.match(/^Win/i)) {
  1553. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1554. }
  1555. // Unique identifier of each opened page
  1556. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1557. // Use this whenever you want to call the plugin.
  1558. AdapterJS.WebRTCPlugin.plugin = null;
  1559. // Set log level for the plugin once it is ready.
  1560. // The different values are
  1561. // This is an asynchronous function that will run when the plugin is ready
  1562. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1563. // Defines webrtc's JS interface according to the plugin's implementation.
  1564. // Define plugin Browsers as WebRTC Interface.
  1565. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1566. // This function detects whether or not a plugin is installed.
  1567. // Checks if Not IE (firefox, for example), else if it's IE,
  1568. // we're running IE and do something. If not it is not supported.
  1569. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1570. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1571. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1572. // Inject the HTML DOM object element into the page.
  1573. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1574. // States of readiness that the plugin goes through when
  1575. // being injected and stated
  1576. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1577. NONE : 0, // no plugin use
  1578. INITIALIZING : 1, // Detected need for plugin
  1579. INJECTING : 2, // Injecting plugin
  1580. INJECTED: 3, // Plugin element injected but not usable yet
  1581. READY: 4 // Plugin ready to be used
  1582. };
  1583. // Current state of the plugin. You cannot use the plugin before this is
  1584. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1585. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1586. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1587. // Used to make sure AdapterJS.onwebrtcready is only called once
  1588. AdapterJS.onwebrtcreadyDone = false;
  1589. // Log levels for the plugin.
  1590. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1591. /*
  1592. Log outputs are prefixed in some cases.
  1593. INFO: Information reported by the plugin.
  1594. ERROR: Errors originating from within the plugin.
  1595. WEBRTC: Error originating from within the libWebRTC library
  1596. */
  1597. // From the least verbose to the most verbose
  1598. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1599. NONE : 'NONE',
  1600. ERROR : 'ERROR',
  1601. WARNING : 'WARNING',
  1602. INFO: 'INFO',
  1603. VERBOSE: 'VERBOSE',
  1604. SENSITIVE: 'SENSITIVE'
  1605. };
  1606. // Does a waiting check before proceeding to load the plugin.
  1607. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1608. // This methid will use an interval to wait for the plugin to be ready.
  1609. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1610. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1611. // This function will be called when plugin is ready. It sends necessary
  1612. // details to the plugin.
  1613. // The function will wait for the document to be ready and the set the
  1614. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1615. // indicating that it can start being requested.
  1616. // This function is not in the IE/Safari condition brackets so that
  1617. // TemPluginLoaded function might be called on Chrome/Firefox.
  1618. // This function is the only private function that is not encapsulated to
  1619. // allow the plugin method to be called.
  1620. __TemWebRTCReady0 = function () {
  1621. if (document.readyState === 'complete') {
  1622. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1623. AdapterJS.maybeThroughWebRTCReady();
  1624. } else {
  1625. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1626. if (document.readyState === 'complete') {
  1627. // TODO: update comments, we wait for the document to be ready
  1628. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1629. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1630. AdapterJS.maybeThroughWebRTCReady();
  1631. }
  1632. }, 100);
  1633. }
  1634. };
  1635. AdapterJS.maybeThroughWebRTCReady = function() {
  1636. if (!AdapterJS.onwebrtcreadyDone) {
  1637. AdapterJS.onwebrtcreadyDone = true;
  1638. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1639. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1640. }
  1641. }
  1642. };
  1643. // Text namespace
  1644. AdapterJS.TEXT = {
  1645. PLUGIN: {
  1646. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1647. 'to work on this browser.',
  1648. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1649. BUTTON: 'Install Now'
  1650. },
  1651. REFRESH: {
  1652. REQUIRE_REFRESH: 'Please refresh page',
  1653. BUTTON: 'Refresh Page'
  1654. }
  1655. };
  1656. // The result of ice connection states.
  1657. // - starting: Ice connection is starting.
  1658. // - checking: Ice connection is checking.
  1659. // - connected Ice connection is connected.
  1660. // - completed Ice connection is connected.
  1661. // - done Ice connection has been completed.
  1662. // - disconnected Ice connection has been disconnected.
  1663. // - failed Ice connection has failed.
  1664. // - closed Ice connection is closed.
  1665. AdapterJS._iceConnectionStates = {
  1666. starting : 'starting',
  1667. checking : 'checking',
  1668. connected : 'connected',
  1669. completed : 'connected',
  1670. done : 'completed',
  1671. disconnected : 'disconnected',
  1672. failed : 'failed',
  1673. closed : 'closed'
  1674. };
  1675. //The IceConnection states that has been fired for each peer.
  1676. AdapterJS._iceConnectionFiredStates = [];
  1677. // Check if WebRTC Interface is defined.
  1678. AdapterJS.isDefined = null;
  1679. // This function helps to retrieve the webrtc detected browser information.
  1680. // This sets:
  1681. // - webrtcDetectedBrowser: The browser agent name.
  1682. // - webrtcDetectedVersion: The browser version.
  1683. // - webrtcDetectedType: The types of webRTC support.
  1684. // - 'moz': Mozilla implementation of webRTC.
  1685. // - 'webkit': WebKit implementation of webRTC.
  1686. // - 'plugin': Using the plugin implementation.
  1687. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1688. var hasMatch, checkMatch = navigator.userAgent.match(
  1689. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1690. if (/trident/i.test(checkMatch[1])) {
  1691. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1692. webrtcDetectedBrowser = 'IE';
  1693. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1694. } else if (checkMatch[1] === 'Chrome') {
  1695. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1696. if (hasMatch !== null) {
  1697. webrtcDetectedBrowser = 'opera';
  1698. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1699. }
  1700. }
  1701. if (navigator.userAgent.indexOf('Safari')) {
  1702. if (typeof InstallTrigger !== 'undefined') {
  1703. webrtcDetectedBrowser = 'firefox';
  1704. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1705. webrtcDetectedBrowser = 'IE';
  1706. } else if (
  1707. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1708. webrtcDetectedBrowser = 'safari';
  1709. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1710. webrtcDetectedBrowser = 'opera';
  1711. } else if (!!window.chrome) {
  1712. webrtcDetectedBrowser = 'chrome';
  1713. }
  1714. }
  1715. if (!webrtcDetectedBrowser) {
  1716. webrtcDetectedVersion = checkMatch[1];
  1717. }
  1718. if (!webrtcDetectedVersion) {
  1719. try {
  1720. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1721. [navigator.appName, navigator.appVersion, '-?'];
  1722. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1723. checkMatch.splice(1, 1, hasMatch[1]);
  1724. }
  1725. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1726. } catch (error) { }
  1727. }
  1728. };
  1729. // To fix configuration as some browsers does not support
  1730. // the 'urls' attribute.
  1731. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1732. if (pcConfig === null) {
  1733. return;
  1734. }
  1735. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1736. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1737. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1738. delete pcConfig.iceServers[i].urls;
  1739. }
  1740. }
  1741. };
  1742. AdapterJS.addEvent = function(elem, evnt, func) {
  1743. if (elem.addEventListener) { // W3C DOM
  1744. elem.addEventListener(evnt, func, false);
  1745. } else if (elem.attachEvent) {// OLD IE DOM
  1746. elem.attachEvent('on'+evnt, func);
  1747. } else { // No much to do
  1748. elem[evnt] = func;
  1749. }
  1750. };
  1751. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1752. // only inject once the page is ready
  1753. if (document.readyState !== 'complete') {
  1754. return;
  1755. }
  1756. var w = window;
  1757. var i = document.createElement('iframe');
  1758. i.style.position = 'fixed';
  1759. i.style.top = '-41px';
  1760. i.style.left = 0;
  1761. i.style.right = 0;
  1762. i.style.width = '100%';
  1763. i.style.height = '40px';
  1764. i.style.backgroundColor = '#ffffe1';
  1765. i.style.border = 'none';
  1766. i.style.borderBottom = '1px solid #888888';
  1767. i.style.zIndex = '9999999';
  1768. if(typeof i.style.webkitTransition === 'string') {
  1769. i.style.webkitTransition = 'all .5s ease-out';
  1770. } else if(typeof i.style.transition === 'string') {
  1771. i.style.transition = 'all .5s ease-out';
  1772. }
  1773. document.body.appendChild(i);
  1774. c = (i.contentWindow) ? i.contentWindow :
  1775. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1776. c.document.open();
  1777. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1778. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1779. 'middle; cursor: default;">' + text + '</span>');
  1780. if(buttonText && buttonLink) {
  1781. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1782. c.document.close();
  1783. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1784. if (!!displayRefreshBar) {
  1785. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1786. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1787. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1788. }
  1789. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1790. e.preventDefault();
  1791. try {
  1792. event.cancelBubble = true;
  1793. } catch(error) { }
  1794. });
  1795. }
  1796. else {
  1797. c.document.close();
  1798. }
  1799. AdapterJS.addEvent(c.document, 'click', function() {
  1800. w.document.body.removeChild(i);
  1801. });
  1802. setTimeout(function() {
  1803. if(typeof i.style.webkitTransform === 'string') {
  1804. i.style.webkitTransform = 'translateY(40px)';
  1805. } else if(typeof i.style.transform === 'string') {
  1806. i.style.transform = 'translateY(40px)';
  1807. } else {
  1808. i.style.top = '0px';
  1809. }
  1810. }, 300);
  1811. };
  1812. // -----------------------------------------------------------
  1813. // Detected webrtc implementation. Types are:
  1814. // - 'moz': Mozilla implementation of webRTC.
  1815. // - 'webkit': WebKit implementation of webRTC.
  1816. // - 'plugin': Using the plugin implementation.
  1817. webrtcDetectedType = null;
  1818. // Detected webrtc datachannel support. Types are:
  1819. // - 'SCTP': SCTP datachannel support.
  1820. // - 'RTP': RTP datachannel support.
  1821. webrtcDetectedDCSupport = null;
  1822. // Set the settings for creating DataChannels, MediaStream for
  1823. // Cross-browser compability.
  1824. // - This is only for SCTP based support browsers.
  1825. // the 'urls' attribute.
  1826. checkMediaDataChannelSettings =
  1827. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1828. if (typeof callback !== 'function') {
  1829. return;
  1830. }
  1831. var beOfferer = true;
  1832. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1833. // Nightly version does not require MozDontOfferDataChannel for interop
  1834. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1835. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1836. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1837. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1838. // Resends an updated version of constraints for MozDataChannel to work
  1839. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1840. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1841. try {
  1842. delete constraints.mandatory.MozDontOfferDataChannel;
  1843. } catch (error) {
  1844. console.error('Failed deleting MozDontOfferDataChannel');
  1845. console.error(error);
  1846. }
  1847. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1848. constraints.mandatory.MozDontOfferDataChannel = true;
  1849. }
  1850. if (!isLocalFirefox) {
  1851. // temporary measure to remove Moz* constraints in non Firefox browsers
  1852. for (var prop in constraints.mandatory) {
  1853. if (constraints.mandatory.hasOwnProperty(prop)) {
  1854. if (prop.indexOf('Moz') !== -1) {
  1855. delete constraints.mandatory[prop];
  1856. }
  1857. }
  1858. }
  1859. }
  1860. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1861. // interopability of the media stream
  1862. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1863. beOfferer = false;
  1864. }
  1865. callback(beOfferer, constraints);
  1866. };
  1867. // Handles the differences for all browsers ice connection state output.
  1868. // - Tested outcomes are:
  1869. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1870. // - Chrome (answerer) : 'checking' > 'connected'
  1871. // - Firefox (offerer) : 'checking' > 'connected'
  1872. // - Firefox (answerer): 'checking' > 'connected'
  1873. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1874. if (typeof callback !== 'function') {
  1875. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1876. return;
  1877. }
  1878. peerId = (peerId) ? peerId : 'peer';
  1879. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1880. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1881. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1882. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1883. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1884. }
  1885. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1886. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1887. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1888. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1889. setTimeout(function () {
  1890. AdapterJS._iceConnectionFiredStates[peerId]
  1891. .push(AdapterJS._iceConnectionStates.done);
  1892. callback(AdapterJS._iceConnectionStates.done);
  1893. }, 1000);
  1894. }
  1895. callback(iceConnectionState);
  1896. }
  1897. return;
  1898. };
  1899. // Firefox:
  1900. // - Creates iceServer from the url for Firefox.
  1901. // - Create iceServer with stun url.
  1902. // - Create iceServer with turn url.
  1903. // - Ignore the transport parameter from TURN url for FF version <=27.
  1904. // - Return null for createIceServer if transport=tcp.
  1905. // - FF 27 and above supports transport parameters in TURN url,
  1906. // - So passing in the full url to create iceServer.
  1907. // Chrome:
  1908. // - Creates iceServer from the url for Chrome M33 and earlier.
  1909. // - Create iceServer with stun url.
  1910. // - Chrome M28 & above uses below TURN format.
  1911. // Plugin:
  1912. // - Creates Ice Server for Plugin Browsers
  1913. // - If Stun - Create iceServer with stun url.
  1914. // - Else - Create iceServer with turn url
  1915. // - This is a WebRTC Function
  1916. createIceServer = null;
  1917. // Firefox:
  1918. // - Creates IceServers for Firefox
  1919. // - Use .url for FireFox.
  1920. // - Multiple Urls support
  1921. // Chrome:
  1922. // - Creates iceServers from the urls for Chrome M34 and above.
  1923. // - .urls is supported since Chrome M34.
  1924. // - Multiple Urls support
  1925. // Plugin:
  1926. // - Creates Ice Servers for Plugin Browsers
  1927. // - Multiple Urls support
  1928. // - This is a WebRTC Function
  1929. createIceServers = null;
  1930. //------------------------------------------------------------
  1931. //The RTCPeerConnection object.
  1932. RTCPeerConnection = null;
  1933. // Creates RTCSessionDescription object for Plugin Browsers
  1934. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  1935. RTCSessionDescription : null;
  1936. // Creates RTCIceCandidate object for Plugin Browsers
  1937. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  1938. RTCIceCandidate : null;
  1939. // Get UserMedia (only difference is the prefix).
  1940. // Code from Adam Barth.
  1941. getUserMedia = null;
  1942. // Attach a media stream to an element.
  1943. attachMediaStream = null;
  1944. // Re-attach a media stream to an element.
  1945. reattachMediaStream = null;
  1946. // Detected browser agent name. Types are:
  1947. // - 'firefox': Firefox browser.
  1948. // - 'chrome': Chrome browser.
  1949. // - 'opera': Opera browser.
  1950. // - 'safari': Safari browser.
  1951. // - 'IE' - Internet Explorer browser.
  1952. webrtcDetectedBrowser = null;
  1953. // Detected browser version.
  1954. webrtcDetectedVersion = null;
  1955. // Check for browser types and react accordingly
  1956. if (navigator.mozGetUserMedia) {
  1957. webrtcDetectedBrowser = 'firefox';
  1958. webrtcDetectedVersion = parseInt(navigator
  1959. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1960. webrtcDetectedType = 'moz';
  1961. webrtcDetectedDCSupport = 'SCTP';
  1962. RTCPeerConnection = function (pcConfig, pcConstraints) {
  1963. AdapterJS.maybeFixConfiguration(pcConfig);
  1964. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  1965. };
  1966. // The RTCSessionDescription object.
  1967. RTCSessionDescription = mozRTCSessionDescription;
  1968. window.RTCSessionDescription = RTCSessionDescription;
  1969. // The RTCIceCandidate object.
  1970. RTCIceCandidate = mozRTCIceCandidate;
  1971. window.RTCIceCandidate = RTCIceCandidate;
  1972. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1973. navigator.getUserMedia = window.getUserMedia;
  1974. // Shim for MediaStreamTrack.getSources.
  1975. MediaStreamTrack.getSources = function(successCb) {
  1976. setTimeout(function() {
  1977. var infos = [
  1978. { kind: 'audio', id: 'default', label:'', facing:'' },
  1979. { kind: 'video', id: 'default', label:'', facing:'' }
  1980. ];
  1981. successCb(infos);
  1982. }, 0);
  1983. };
  1984. createIceServer = function (url, username, password) {
  1985. var iceServer = null;
  1986. var url_parts = url.split(':');
  1987. if (url_parts[0].indexOf('stun') === 0) {
  1988. iceServer = { url : url };
  1989. } else if (url_parts[0].indexOf('turn') === 0) {
  1990. if (webrtcDetectedVersion < 27) {
  1991. var turn_url_parts = url.split('?');
  1992. if (turn_url_parts.length === 1 ||
  1993. turn_url_parts[1].indexOf('transport=udp') === 0) {
  1994. iceServer = {
  1995. url : turn_url_parts[0],
  1996. credential : password,
  1997. username : username
  1998. };
  1999. }
  2000. } else {
  2001. iceServer = {
  2002. url : url,
  2003. credential : password,
  2004. username : username
  2005. };
  2006. }
  2007. }
  2008. return iceServer;
  2009. };
  2010. createIceServers = function (urls, username, password) {
  2011. var iceServers = [];
  2012. for (i = 0; i < urls.length; i++) {
  2013. var iceServer = createIceServer(urls[i], username, password);
  2014. if (iceServer !== null) {
  2015. iceServers.push(iceServer);
  2016. }
  2017. }
  2018. return iceServers;
  2019. };
  2020. attachMediaStream = function (element, stream) {
  2021. element.mozSrcObject = stream;
  2022. if (stream !== null)
  2023. element.play();
  2024. return element;
  2025. };
  2026. reattachMediaStream = function (to, from) {
  2027. to.mozSrcObject = from.mozSrcObject;
  2028. to.play();
  2029. return to;
  2030. };
  2031. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2032. if (!callback) {
  2033. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2034. ': 1 argument required, but only 0 present.');
  2035. }
  2036. return callback([]);
  2037. };
  2038. // Fake get{Video,Audio}Tracks
  2039. if (!MediaStream.prototype.getVideoTracks) {
  2040. MediaStream.prototype.getVideoTracks = function () {
  2041. return [];
  2042. };
  2043. }
  2044. if (!MediaStream.prototype.getAudioTracks) {
  2045. MediaStream.prototype.getAudioTracks = function () {
  2046. return [];
  2047. };
  2048. }
  2049. AdapterJS.maybeThroughWebRTCReady();
  2050. } else if (navigator.webkitGetUserMedia) {
  2051. webrtcDetectedBrowser = 'chrome';
  2052. webrtcDetectedType = 'webkit';
  2053. webrtcDetectedVersion = parseInt(navigator
  2054. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2055. // check if browser is opera 20+
  2056. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2057. if (checkIfOpera !== null) {
  2058. webrtcDetectedBrowser = 'opera';
  2059. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2060. }
  2061. // check browser datachannel support
  2062. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2063. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2064. webrtcDetectedDCSupport = 'SCTP';
  2065. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2066. webrtcDetectedVersion > 24) {
  2067. webrtcDetectedDCSupport = 'RTP';
  2068. } else {
  2069. webrtcDetectedDCSupport = '';
  2070. }
  2071. createIceServer = function (url, username, password) {
  2072. var iceServer = null;
  2073. var url_parts = url.split(':');
  2074. if (url_parts[0].indexOf('stun') === 0) {
  2075. iceServer = { 'url' : url };
  2076. } else if (url_parts[0].indexOf('turn') === 0) {
  2077. iceServer = {
  2078. 'url' : url,
  2079. 'credential' : password,
  2080. 'username' : username
  2081. };
  2082. }
  2083. return iceServer;
  2084. };
  2085. createIceServers = function (urls, username, password) {
  2086. var iceServers = [];
  2087. if (webrtcDetectedVersion >= 34) {
  2088. iceServers = {
  2089. 'urls' : urls,
  2090. 'credential' : password,
  2091. 'username' : username
  2092. };
  2093. } else {
  2094. for (i = 0; i < urls.length; i++) {
  2095. var iceServer = createIceServer(urls[i], username, password);
  2096. if (iceServer !== null) {
  2097. iceServers.push(iceServer);
  2098. }
  2099. }
  2100. }
  2101. return iceServers;
  2102. };
  2103. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2104. if (webrtcDetectedVersion < 34) {
  2105. AdapterJS.maybeFixConfiguration(pcConfig);
  2106. }
  2107. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2108. };
  2109. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2110. navigator.getUserMedia = window.getUserMedia;
  2111. attachMediaStream = function (element, stream) {
  2112. if (typeof element.srcObject !== 'undefined') {
  2113. element.srcObject = stream;
  2114. } else if (typeof element.mozSrcObject !== 'undefined') {
  2115. element.mozSrcObject = stream;
  2116. } else if (typeof element.src !== 'undefined') {
  2117. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2118. } else {
  2119. console.log('Error attaching stream to element.');
  2120. }
  2121. return element;
  2122. };
  2123. reattachMediaStream = function (to, from) {
  2124. to.src = from.src;
  2125. return to;
  2126. };
  2127. AdapterJS.maybeThroughWebRTCReady();
  2128. } else { // TRY TO USE PLUGIN
  2129. // IE 9 is not offering an implementation of console.log until you open a console
  2130. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2131. /* jshint -W020 */
  2132. console = {} || console;
  2133. // Implemented based on console specs from MDN
  2134. // You may override these functions
  2135. console.log = function (arg) {};
  2136. console.info = function (arg) {};
  2137. console.error = function (arg) {};
  2138. console.dir = function (arg) {};
  2139. console.exception = function (arg) {};
  2140. console.trace = function (arg) {};
  2141. console.warn = function (arg) {};
  2142. console.count = function (arg) {};
  2143. console.debug = function (arg) {};
  2144. console.count = function (arg) {};
  2145. console.time = function (arg) {};
  2146. console.timeEnd = function (arg) {};
  2147. console.group = function (arg) {};
  2148. console.groupCollapsed = function (arg) {};
  2149. console.groupEnd = function (arg) {};
  2150. /* jshint +W020 */
  2151. }
  2152. webrtcDetectedType = 'plugin';
  2153. webrtcDetectedDCSupport = 'plugin';
  2154. AdapterJS.parseWebrtcDetectedBrowser();
  2155. isIE = webrtcDetectedBrowser === 'IE';
  2156. /* jshint -W035 */
  2157. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2158. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2159. /* empty because it needs to prevent the function from running. */
  2160. }
  2161. };
  2162. /* jshint +W035 */
  2163. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2164. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2165. // Call immediately if possible
  2166. // Once the plugin is set, the code will always take this path
  2167. callback();
  2168. } else {
  2169. // otherwise start a 100ms interval
  2170. var checkPluginReadyState = setInterval(function () {
  2171. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2172. clearInterval(checkPluginReadyState);
  2173. callback();
  2174. }
  2175. }, 100);
  2176. }
  2177. };
  2178. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2179. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2180. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2181. });
  2182. };
  2183. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2184. // only inject once the page is ready
  2185. if (document.readyState !== 'complete') {
  2186. return;
  2187. }
  2188. // Prevent multiple injections
  2189. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2190. return;
  2191. }
  2192. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2193. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2194. var frag = document.createDocumentFragment();
  2195. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2196. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2197. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2198. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2199. '<param name="pluginId" value="' +
  2200. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2201. '<param name="windowless" value="false" /> ' +
  2202. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2203. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2204. '" />' +
  2205. // uncomment to be able to use virtual cams
  2206. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2207. '</object>';
  2208. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2209. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2210. }
  2211. document.body.appendChild(frag);
  2212. // Need to re-fetch the plugin
  2213. AdapterJS.WebRTCPlugin.plugin =
  2214. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2215. } else {
  2216. // Load Plugin
  2217. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2218. AdapterJS.WebRTCPlugin.plugin.id =
  2219. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2220. // IE will only start the plugin if it's ACTUALLY visible
  2221. if (isIE) {
  2222. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2223. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2224. } else { // The size of the plugin on Safari should be 0x0px
  2225. // so that the autorisation prompt is at the top
  2226. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2227. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2228. }
  2229. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2230. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2231. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2232. '<param name="pluginId" value="' +
  2233. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2234. '<param name="windowless" value="false" /> ' +
  2235. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2236. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2237. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2238. }
  2239. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2240. };
  2241. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2242. function (comName, plugName, installedCb, notInstalledCb) {
  2243. if (!isIE) {
  2244. var pluginArray = navigator.plugins;
  2245. for (var i = 0; i < pluginArray.length; i++) {
  2246. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2247. installedCb();
  2248. return;
  2249. }
  2250. }
  2251. notInstalledCb();
  2252. } else {
  2253. try {
  2254. var axo = new ActiveXObject(comName + '.' + plugName);
  2255. } catch (e) {
  2256. notInstalledCb();
  2257. return;
  2258. }
  2259. installedCb();
  2260. }
  2261. };
  2262. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2263. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2264. AdapterJS.isDefined = function (variable) {
  2265. return variable !== null && variable !== undefined;
  2266. };
  2267. createIceServer = function (url, username, password) {
  2268. var iceServer = null;
  2269. var url_parts = url.split(':');
  2270. if (url_parts[0].indexOf('stun') === 0) {
  2271. iceServer = {
  2272. 'url' : url,
  2273. 'hasCredentials' : false
  2274. };
  2275. } else if (url_parts[0].indexOf('turn') === 0) {
  2276. iceServer = {
  2277. 'url' : url,
  2278. 'hasCredentials' : true,
  2279. 'credential' : password,
  2280. 'username' : username
  2281. };
  2282. }
  2283. return iceServer;
  2284. };
  2285. createIceServers = function (urls, username, password) {
  2286. var iceServers = [];
  2287. for (var i = 0; i < urls.length; ++i) {
  2288. iceServers.push(createIceServer(urls[i], username, password));
  2289. }
  2290. return iceServers;
  2291. };
  2292. RTCSessionDescription = function (info) {
  2293. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2294. return AdapterJS.WebRTCPlugin.plugin.
  2295. ConstructSessionDescription(info.type, info.sdp);
  2296. };
  2297. RTCPeerConnection = function (servers, constraints) {
  2298. var iceServers = null;
  2299. if (servers) {
  2300. iceServers = servers.iceServers;
  2301. for (var i = 0; i < iceServers.length; i++) {
  2302. if (iceServers[i].urls && !iceServers[i].url) {
  2303. iceServers[i].url = iceServers[i].urls;
  2304. }
  2305. iceServers[i].hasCredentials = AdapterJS.
  2306. isDefined(iceServers[i].username) &&
  2307. AdapterJS.isDefined(iceServers[i].credential);
  2308. }
  2309. }
  2310. var mandatory = (constraints && constraints.mandatory) ?
  2311. constraints.mandatory : null;
  2312. var optional = (constraints && constraints.optional) ?
  2313. constraints.optional : null;
  2314. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2315. return AdapterJS.WebRTCPlugin.plugin.
  2316. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2317. iceServers, mandatory, optional);
  2318. };
  2319. MediaStreamTrack = {};
  2320. MediaStreamTrack.getSources = function (callback) {
  2321. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2322. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2323. });
  2324. };
  2325. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2326. constraints.audio = constraints.audio || false;
  2327. constraints.video = constraints.video || false;
  2328. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2329. AdapterJS.WebRTCPlugin.plugin.
  2330. getUserMedia(constraints, successCallback, failureCallback);
  2331. });
  2332. };
  2333. window.navigator.getUserMedia = window.getUserMedia;
  2334. attachMediaStream = function (element, stream) {
  2335. if (!element || !element.parentNode) {
  2336. return;
  2337. }
  2338. var streamId
  2339. if (stream === null) {
  2340. streamId = '';
  2341. }
  2342. else {
  2343. stream.enableSoundTracks(true);
  2344. streamId = stream.id;
  2345. }
  2346. if (element.nodeName.toLowerCase() !== 'audio') {
  2347. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2348. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2349. var frag = document.createDocumentFragment();
  2350. var temp = document.createElement('div');
  2351. var classHTML = '';
  2352. if (element.className) {
  2353. classHTML = 'class="' + element.className + '" ';
  2354. } else if (element.attributes && element.attributes['class']) {
  2355. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2356. }
  2357. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2358. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2359. '<param name="pluginId" value="' + elementId + '" /> ' +
  2360. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2361. '<param name="windowless" value="true" /> ' +
  2362. '<param name="streamId" value="' + streamId + '" /> ' +
  2363. '</object>';
  2364. while (temp.firstChild) {
  2365. frag.appendChild(temp.firstChild);
  2366. }
  2367. var height = '';
  2368. var width = '';
  2369. if (element.getBoundingClientRect) {
  2370. var rectObject = element.getBoundingClientRect();
  2371. width = rectObject.width + 'px';
  2372. height = rectObject.height + 'px';
  2373. }
  2374. else if (element.width) {
  2375. width = element.width;
  2376. height = element.height;
  2377. } else {
  2378. // TODO: What scenario could bring us here?
  2379. }
  2380. element.parentNode.insertBefore(frag, element);
  2381. frag = document.getElementById(elementId);
  2382. frag.width = width;
  2383. frag.height = height;
  2384. element.parentNode.removeChild(element);
  2385. } else {
  2386. var children = element.children;
  2387. for (var i = 0; i !== children.length; ++i) {
  2388. if (children[i].name === 'streamId') {
  2389. children[i].value = streamId;
  2390. break;
  2391. }
  2392. }
  2393. element.setStreamId(streamId);
  2394. }
  2395. var newElement = document.getElementById(elementId);
  2396. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2397. if (isIE) { // on IE the event needs to be plugged manually
  2398. newElement.attachEvent('onplaying', newElement.onplaying);
  2399. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2400. newElement._TemOnClick = function (id) {
  2401. var arg = {
  2402. srcElement : document.getElementById(id)
  2403. };
  2404. newElement.onclick(arg);
  2405. };
  2406. }
  2407. return newElement;
  2408. } else {
  2409. return element;
  2410. }
  2411. };
  2412. reattachMediaStream = function (to, from) {
  2413. var stream = null;
  2414. var children = from.children;
  2415. for (var i = 0; i !== children.length; ++i) {
  2416. if (children[i].name === 'streamId') {
  2417. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2418. stream = AdapterJS.WebRTCPlugin.plugin
  2419. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2420. break;
  2421. }
  2422. }
  2423. if (stream !== null) {
  2424. return attachMediaStream(to, stream);
  2425. } else {
  2426. console.log('Could not find the stream associated with this element');
  2427. }
  2428. };
  2429. RTCIceCandidate = function (candidate) {
  2430. if (!candidate.sdpMid) {
  2431. candidate.sdpMid = '';
  2432. }
  2433. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2434. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2435. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2436. );
  2437. };
  2438. // inject plugin
  2439. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2440. AdapterJS.WebRTCPlugin.injectPlugin();
  2441. };
  2442. // This function will be called if the plugin is needed (browser different
  2443. // from Chrome or Firefox), but the plugin is not installed.
  2444. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2445. function() {
  2446. AdapterJS.addEvent(document,
  2447. 'readystatechange',
  2448. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2449. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2450. };
  2451. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2452. if (AdapterJS.options.hidePluginInstallPrompt) {
  2453. return;
  2454. }
  2455. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2456. if(downloadLink) { // if download link
  2457. var popupString;
  2458. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2459. popupString = 'This website requires you to install the ' +
  2460. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2461. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2462. ' WebRTC Plugin</a>' +
  2463. ' to work on this browser.';
  2464. } else { // no portal link, just print a generic explanation
  2465. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2466. }
  2467. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2468. } else { // no download link, just print a generic explanation
  2469. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2470. }
  2471. };
  2472. // Try to detect the plugin and act accordingly
  2473. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2474. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2475. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2476. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2477. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2478. }
  2479. (function () {
  2480. 'use strict';
  2481. var baseGetUserMedia = null;
  2482. AdapterJS.TEXT.EXTENSION = {
  2483. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2484. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2485. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2486. BUTTON_FF: 'Install Now',
  2487. BUTTON_CHROME: 'Go to Chrome Web Store'
  2488. };
  2489. var clone = function(obj) {
  2490. if (null == obj || "object" != typeof obj) return obj;
  2491. var copy = obj.constructor();
  2492. for (var attr in obj) {
  2493. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2494. }
  2495. return copy;
  2496. };
  2497. if (window.navigator.mozGetUserMedia) {
  2498. baseGetUserMedia = window.navigator.getUserMedia;
  2499. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2500. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2501. // intercepting screensharing requests
  2502. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2503. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2504. }
  2505. var updatedConstraints = clone(constraints);
  2506. //constraints.video.mediaSource = constraints.video.mediaSource;
  2507. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2508. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2509. // strange but this works anyway
  2510. var checkIfReady = setInterval(function () {
  2511. if (document.readyState === 'complete') {
  2512. clearInterval(checkIfReady);
  2513. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2514. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2515. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2516. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2517. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2518. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2519. } else {
  2520. failureCb(error);
  2521. }
  2522. });
  2523. }
  2524. }, 1);
  2525. } else { // regular GetUserMediaRequest
  2526. baseGetUserMedia(constraints, successCb, failureCb);
  2527. }
  2528. };
  2529. getUserMedia = navigator.getUserMedia;
  2530. } else if (window.navigator.webkitGetUserMedia) {
  2531. baseGetUserMedia = window.navigator.getUserMedia;
  2532. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2533. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2534. if (window.webrtcDetectedBrowser !== 'chrome') {
  2535. throw new Error('Current browser does not support screensharing');
  2536. }
  2537. // would be fine since no methods
  2538. var updatedConstraints = clone(constraints);
  2539. var chromeCallback = function(error, sourceId) {
  2540. if(!error) {
  2541. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2542. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2543. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2544. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2545. if (sourceId) {
  2546. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2547. }
  2548. delete updatedConstraints.video.mediaSource;
  2549. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2550. } else {
  2551. if (error === 'permission-denied') {
  2552. throw new Error('Permission denied for screen retrieval');
  2553. } else {
  2554. throw new Error('Failed retrieving selected screen');
  2555. }
  2556. }
  2557. };
  2558. var onIFrameCallback = function (event) {
  2559. if (!event.data) {
  2560. return;
  2561. }
  2562. if (event.data.chromeMediaSourceId) {
  2563. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2564. chromeCallback('permission-denied');
  2565. } else {
  2566. chromeCallback(null, event.data.chromeMediaSourceId);
  2567. }
  2568. }
  2569. if (event.data.chromeExtensionStatus) {
  2570. if (event.data.chromeExtensionStatus === 'not-installed') {
  2571. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2572. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2573. event.data.data, true, true);
  2574. } else {
  2575. chromeCallback(event.data.chromeExtensionStatus, null);
  2576. }
  2577. }
  2578. // this event listener is no more needed
  2579. window.removeEventListener('message', onIFrameCallback);
  2580. };
  2581. window.addEventListener('message', onIFrameCallback);
  2582. postFrameMessage({
  2583. captureSourceId: true
  2584. });
  2585. } else {
  2586. baseGetUserMedia(constraints, successCb, failureCb);
  2587. }
  2588. };
  2589. getUserMedia = navigator.getUserMedia;
  2590. } else {
  2591. baseGetUserMedia = window.navigator.getUserMedia;
  2592. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2593. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2594. // would be fine since no methods
  2595. var updatedConstraints = clone(constraints);
  2596. // wait for plugin to be ready
  2597. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2598. // check if screensharing feature is available
  2599. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2600. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2601. // set the constraints
  2602. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2603. updatedConstraints.video.optional.push({
  2604. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2605. });
  2606. delete updatedConstraints.video.mediaSource;
  2607. } else {
  2608. throw new Error('Your WebRTC plugin does not support screensharing');
  2609. }
  2610. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2611. });
  2612. } else {
  2613. baseGetUserMedia(constraints, successCb, failureCb);
  2614. }
  2615. };
  2616. getUserMedia = window.navigator.getUserMedia;
  2617. }
  2618. if (window.webrtcDetectedBrowser === 'chrome') {
  2619. var iframe = document.createElement('iframe');
  2620. iframe.onload = function() {
  2621. iframe.isLoaded = true;
  2622. };
  2623. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2624. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2625. iframe.style.display = 'none';
  2626. (document.body || document.documentElement).appendChild(iframe);
  2627. var postFrameMessage = function (object) {
  2628. object = object || {};
  2629. if (!iframe.isLoaded) {
  2630. setTimeout(function () {
  2631. iframe.contentWindow.postMessage(object, '*');
  2632. }, 100);
  2633. return;
  2634. }
  2635. iframe.contentWindow.postMessage(object, '*');
  2636. };
  2637. }
  2638. })();
  2639. },{}],11:[function(require,module,exports){
  2640. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2641. var UI = {};
  2642. var VideoLayout = require("./videolayout/VideoLayout.js");
  2643. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2644. var Prezi = require("./prezi/Prezi.js");
  2645. var Etherpad = require("./etherpad/Etherpad.js");
  2646. var Chat = require("./side_pannels/chat/Chat.js");
  2647. var Toolbar = require("./toolbars/Toolbar");
  2648. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2649. var BottomToolbar = require("./toolbars/BottomToolbar");
  2650. var ContactList = require("./side_pannels/contactlist/ContactList");
  2651. var Avatar = require("./avatar/Avatar");
  2652. var EventEmitter = require("events");
  2653. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2654. var Settings = require("./../settings/Settings");
  2655. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2656. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2657. UI.messageHandler = require("./util/MessageHandler");
  2658. var messageHandler = UI.messageHandler;
  2659. var Authentication = require("./authentication/Authentication");
  2660. var UIUtil = require("./util/UIUtil");
  2661. var NicknameHandler = require("./util/NicknameHandler");
  2662. var JitsiPopover = require("./util/JitsiPopover");
  2663. var CQEvents = require("../../service/connectionquality/CQEvents");
  2664. var DesktopSharingEventTypes
  2665. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2666. var RTCEvents = require("../../service/RTC/RTCEvents");
  2667. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2668. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2669. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2670. var UIEvents = require("../../service/UI/UIEvents");
  2671. var MemberEvents = require("../../service/members/Events");
  2672. var eventEmitter = new EventEmitter();
  2673. var roomName = null;
  2674. function promptDisplayName() {
  2675. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2676. message += APP.translation.translateString(
  2677. "dialog.displayNameRequired");
  2678. message += '</h2>' +
  2679. '<input name="displayName" type="text" data-i18n=' +
  2680. '"[placeholder]defaultNickname" placeholder="' +
  2681. APP.translation.translateString(
  2682. "defaultNickname", {name: "Jane Pink"}) +
  2683. '" autofocus>';
  2684. var buttonTxt
  2685. = APP.translation.generateTranslationHTML("dialog.Ok");
  2686. var buttons = [];
  2687. buttons.push({title: buttonTxt, value: "ok"});
  2688. messageHandler.openDialog(null, message,
  2689. true,
  2690. buttons,
  2691. function (e, v, m, f) {
  2692. if (v == "ok") {
  2693. var displayName = f.displayName;
  2694. if (displayName) {
  2695. VideoLayout.inputDisplayNameHandler(displayName);
  2696. return true;
  2697. }
  2698. }
  2699. e.preventDefault();
  2700. },
  2701. function () {
  2702. var form = $.prompt.getPrompt();
  2703. var input = form.find("input[name='displayName']");
  2704. input.focus();
  2705. var button = form.find("button");
  2706. button.attr("disabled", "disabled");
  2707. input.keyup(function () {
  2708. if(!input.val())
  2709. button.attr("disabled", "disabled");
  2710. else
  2711. button.removeAttr("disabled");
  2712. });
  2713. }
  2714. );
  2715. }
  2716. function notifyForInitialMute() {
  2717. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2718. "notify.muted", null, {timeOut: 120000});
  2719. }
  2720. function setupPrezi() {
  2721. $("#reloadPresentationLink").click(function() {
  2722. Prezi.reloadPresentation();
  2723. });
  2724. }
  2725. function setupChat() {
  2726. Chat.init();
  2727. $("#toggle_smileys").click(function() {
  2728. Chat.toggleSmileys();
  2729. });
  2730. }
  2731. function setupToolbars() {
  2732. Toolbar.init(UI);
  2733. Toolbar.setupButtonsFromConfig();
  2734. BottomToolbar.init();
  2735. }
  2736. function streamHandler(stream, isMuted) {
  2737. switch (stream.type) {
  2738. case "audio":
  2739. VideoLayout.changeLocalAudio(stream, isMuted);
  2740. break;
  2741. case "video":
  2742. VideoLayout.changeLocalVideo(stream, isMuted);
  2743. break;
  2744. case "stream":
  2745. VideoLayout.changeLocalStream(stream, isMuted);
  2746. break;
  2747. }
  2748. }
  2749. function onXmppConnectionFailed(stropheErrorMsg) {
  2750. var title = APP.translation.generateTranslationHTML(
  2751. "dialog.error");
  2752. var message;
  2753. if (stropheErrorMsg) {
  2754. message = APP.translation.generateTranslationHTML(
  2755. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2756. } else {
  2757. message = APP.translation.generateTranslationHTML(
  2758. "dialog.connectError");
  2759. }
  2760. messageHandler.openDialog(
  2761. title, message, true, {}, function (e, v, m, f) { return false; });
  2762. }
  2763. function onDisposeConference(unload) {
  2764. Toolbar.showAuthenticateButton(false);
  2765. }
  2766. function onDisplayNameChanged(jid, displayName) {
  2767. ContactList.onDisplayNameChange(jid, displayName);
  2768. SettingsMenu.onDisplayNameChange(jid, displayName);
  2769. VideoLayout.onDisplayNameChanged(jid, displayName);
  2770. }
  2771. function registerListeners() {
  2772. APP.RTC.addStreamListener(streamHandler,
  2773. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2774. APP.RTC.addStreamListener(streamHandler,
  2775. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2776. APP.RTC.addStreamListener(function (stream) {
  2777. VideoLayout.onRemoteStreamAdded(stream);
  2778. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2779. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2780. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  2781. function (resourceJid) {
  2782. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2783. });
  2784. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2785. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2786. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2787. endpointsEnteringLastN, stream);
  2788. });
  2789. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2790. function (devices) {
  2791. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2792. });
  2793. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  2794. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function () {
  2795. // when the data channel becomes available, tell the bridge about video
  2796. // selections so that it can do adaptive simulcast,
  2797. // we want the notification to trigger even if userJid is undefined,
  2798. // or null.
  2799. var userJid = APP.UI.getLargeVideoJid();
  2800. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userJid);
  2801. });
  2802. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  2803. var resourceJid;
  2804. if(jid === APP.statistics.LOCAL_JID) {
  2805. resourceJid = AudioLevels.LOCAL_LEVEL;
  2806. if(APP.RTC.localAudio.isMuted()) {
  2807. audioLevel = 0;
  2808. }
  2809. } else {
  2810. resourceJid = Strophe.getResourceFromJid(jid);
  2811. }
  2812. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2813. UI.getLargeVideoJid());
  2814. });
  2815. APP.desktopsharing.addListener(function () {
  2816. ToolbarToggler.showDesktopSharingButton();
  2817. }, DesktopSharingEventTypes.INIT);
  2818. APP.desktopsharing.addListener(
  2819. Toolbar.changeDesktopSharingButtonState,
  2820. DesktopSharingEventTypes.SWITCHING_DONE);
  2821. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2822. VideoLayout.updateLocalConnectionStats);
  2823. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2824. VideoLayout.updateConnectionStats);
  2825. APP.connectionquality.addListener(CQEvents.STOP,
  2826. VideoLayout.onStatsStop);
  2827. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2828. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2829. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2830. messageHandler.openMessageDialog(
  2831. 'dialog.serviceUnavailable',
  2832. 'dialog.gracefulShutdown'
  2833. );
  2834. });
  2835. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2836. var title = APP.translation.generateTranslationHTML(
  2837. "dialog.reservationError");
  2838. var message = APP.translation.generateTranslationHTML(
  2839. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2840. messageHandler.openDialog(
  2841. title,
  2842. message,
  2843. true, {},
  2844. function (event, value, message, formVals) {
  2845. return false;
  2846. }
  2847. );
  2848. });
  2849. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2850. messageHandler.openMessageDialog("dialog.sessTerminated",
  2851. "dialog.kickMessage");
  2852. });
  2853. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2854. //FIXME: use Session Terminated from translation, but
  2855. // 'reason' text comes from XMPP packet and is not translated
  2856. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2857. messageHandler.openDialog(
  2858. title, reason, true, {},
  2859. function (event, value, message, formVals) {
  2860. return false;
  2861. }
  2862. );
  2863. });
  2864. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2865. messageHandler.showError("dialog.error",
  2866. "dialog.bridgeUnavailable");
  2867. });
  2868. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2869. Avatar.setUserAvatar(from, id);
  2870. });
  2871. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2872. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2873. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2874. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2875. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2876. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2877. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2878. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2879. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2880. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2881. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2882. onAuthenticationRequired);
  2883. APP.xmpp.addListener(XMPPEvents.VIDEO_TYPE, onPeerVideoTypeChanged);
  2884. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2885. function (resource, devices) {
  2886. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2887. });
  2888. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  2889. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  2890. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function (doMuteAudio) {
  2891. UI.setAudioMuted(doMuteAudio);
  2892. });
  2893. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2894. onDtmfSupportChanged);
  2895. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  2896. SettingsMenu.setStartMuted(audio, video);
  2897. });
  2898. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  2899. UI.setInitialMuteFromFocus(audio, video);
  2900. });
  2901. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  2902. UI.messageHandler.showError("dialog.sorry",
  2903. "dialog.internalError");
  2904. });
  2905. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function () {
  2906. messageHandler.showError("dialog.error",
  2907. "dialog.SLDFailure");
  2908. });
  2909. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function () {
  2910. messageHandler.showError("dialog.error",
  2911. "dialog.SRDFailure");
  2912. });
  2913. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function () {
  2914. messageHandler.showError();
  2915. });
  2916. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function () {
  2917. // FIXME: re-use LoginDialog which supports retries
  2918. UI.showLoginPopup(connect);
  2919. });
  2920. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focusComponent, retrySec) {
  2921. UI.messageHandler.notify(
  2922. null, "notify.focus",
  2923. 'disconnected', "notify.focusFail",
  2924. {component: focusComponent, ms: retrySec});
  2925. });
  2926. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  2927. UI.messageHandler.openReportDialog(null,
  2928. "dialog.joinError", pres);
  2929. });
  2930. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  2931. UI.messageHandler.openReportDialog(null,
  2932. "dialog.connectError", pres);
  2933. });
  2934. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function () {
  2935. var roomName = UI.generateRoomName();
  2936. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  2937. });
  2938. //NicknameHandler emits this event
  2939. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  2940. APP.xmpp.addToPresence("displayName", nickname);
  2941. });
  2942. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  2943. AudioLevels.init();
  2944. });
  2945. if (!interfaceConfig.filmStripOnly) {
  2946. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2947. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2948. // Listens for video interruption events.
  2949. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  2950. // Listens for video restores events.
  2951. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  2952. }
  2953. }
  2954. /**
  2955. * Mutes/unmutes the local video.
  2956. *
  2957. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2958. * @param options an object which specifies optional arguments such as the
  2959. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2960. * specifies whether the method was initiated in response to a user command (in
  2961. * contrast to an automatic decision taken by the application logic)
  2962. */
  2963. function setVideoMute(mute, options) {
  2964. APP.RTC.setVideoMute(mute,
  2965. UI.setVideoMuteButtonsState,
  2966. options);
  2967. }
  2968. function onResize() {
  2969. Chat.resizeChat();
  2970. VideoLayout.resizeLargeVideoContainer();
  2971. }
  2972. function bindEvents() {
  2973. /**
  2974. * Resizes and repositions videos in full screen mode.
  2975. */
  2976. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  2977. onResize);
  2978. $(window).resize(onResize);
  2979. }
  2980. UI.start = function (init) {
  2981. document.title = interfaceConfig.APP_NAME;
  2982. var setupWelcomePage = null;
  2983. if(config.enableWelcomePage && window.location.pathname == "/" &&
  2984. (!window.localStorage.welcomePageDisabled ||
  2985. window.localStorage.welcomePageDisabled == "false")) {
  2986. $("#videoconference_page").hide();
  2987. if (!setupWelcomePage)
  2988. setupWelcomePage = require("./welcome_page/WelcomePage");
  2989. setupWelcomePage();
  2990. return;
  2991. }
  2992. $("#welcome_page").hide();
  2993. // Set the defaults for prompt dialogs.
  2994. $.prompt.setDefaults({persistent: false});
  2995. registerListeners();
  2996. VideoLayout.init(eventEmitter);
  2997. NicknameHandler.init(eventEmitter);
  2998. bindEvents();
  2999. setupPrezi();
  3000. if (!interfaceConfig.filmStripOnly) {
  3001. $("#videospace").mousemove(function () {
  3002. return ToolbarToggler.showToolbar();
  3003. });
  3004. setupToolbars();
  3005. setupChat();
  3006. // Display notice message at the top of the toolbar
  3007. if (config.noticeMessage) {
  3008. $('#noticeText').text(config.noticeMessage);
  3009. $('#notice').css({display: 'block'});
  3010. }
  3011. $("#downloadlog").click(function (event) {
  3012. dump(event.target);
  3013. });
  3014. }
  3015. else
  3016. {
  3017. $("#header").css("display", "none");
  3018. $("#bottomToolbar").css("display", "none");
  3019. $("#downloadlog").css("display", "none");
  3020. $("#remoteVideos").css("padding", "0px 0px 18px 0px");
  3021. $("#remoteVideos").css("right", "0px");
  3022. messageHandler.disableNotifications();
  3023. $('body').popover("disable");
  3024. // $("[data-toggle=popover]").popover("disable");
  3025. JitsiPopover.enabled = false;
  3026. }
  3027. document.title = interfaceConfig.APP_NAME;
  3028. if(config.requireDisplayName) {
  3029. var currentSettings = Settings.getSettings();
  3030. if (!currentSettings.displayName) {
  3031. promptDisplayName();
  3032. }
  3033. }
  3034. init();
  3035. if (!interfaceConfig.filmStripOnly) {
  3036. toastr.options = {
  3037. "closeButton": true,
  3038. "debug": false,
  3039. "positionClass": "notification-bottom-right",
  3040. "onclick": null,
  3041. "showDuration": "300",
  3042. "hideDuration": "1000",
  3043. "timeOut": "2000",
  3044. "extendedTimeOut": "1000",
  3045. "showEasing": "swing",
  3046. "hideEasing": "linear",
  3047. "showMethod": "fadeIn",
  3048. "hideMethod": "fadeOut",
  3049. "reposition": function () {
  3050. if (PanelToggler.isVisible()) {
  3051. $("#toast-container").addClass("notification-bottom-right-center");
  3052. } else {
  3053. $("#toast-container").removeClass("notification-bottom-right-center");
  3054. }
  3055. },
  3056. "newestOnTop": false
  3057. };
  3058. SettingsMenu.init();
  3059. }
  3060. };
  3061. function chatAddError(errorMessage, originalText) {
  3062. return Chat.chatAddError(errorMessage, originalText);
  3063. }
  3064. function chatSetSubject(text) {
  3065. return Chat.chatSetSubject(text);
  3066. }
  3067. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3068. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3069. }
  3070. function onMucJoined(jid, info) {
  3071. Toolbar.updateRoomUrl(window.location.href);
  3072. var meHTML = APP.translation.generateTranslationHTML("me");
  3073. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3074. var settings = Settings.getSettings();
  3075. // Make sure we configure our avatar id, before creating avatar for us
  3076. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3077. // Add myself to the contact list.
  3078. ContactList.addContact(jid);
  3079. // Once we've joined the muc show the toolbar
  3080. ToolbarToggler.showToolbar();
  3081. var displayName =
  3082. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3083. if (displayName)
  3084. onDisplayNameChanged('localVideoContainer', displayName);
  3085. VideoLayout.mucJoined();
  3086. }
  3087. function initEtherpad(name) {
  3088. Etherpad.init(name);
  3089. }
  3090. function onMucMemberLeft(jid) {
  3091. console.log('left.muc', jid);
  3092. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3093. '>.displayname').html();
  3094. messageHandler.notify(displayName,'notify.somebody',
  3095. 'disconnected',
  3096. 'notify.disconnected');
  3097. if (!config.startAudioMuted ||
  3098. config.startAudioMuted > APP.members.size()) {
  3099. UIUtil.playSoundNotification('userLeft');
  3100. }
  3101. ContactList.removeContact(jid);
  3102. VideoLayout.participantLeft(jid);
  3103. }
  3104. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3105. console.info("My role changed, new role: " + info.role);
  3106. onModeratorStatusChanged(isModerator);
  3107. VideoLayout.showModeratorIndicator();
  3108. SettingsMenu.onRoleChanged();
  3109. if (isModerator) {
  3110. Authentication.closeAuthenticationWindow();
  3111. messageHandler.notify(null, "notify.me",
  3112. 'connected', "notify.moderator");
  3113. Toolbar.checkAutoRecord();
  3114. }
  3115. }
  3116. function onModeratorStatusChanged(isModerator) {
  3117. Toolbar.showSipCallButton(isModerator);
  3118. Toolbar.showRecordingButton(
  3119. isModerator); //&&
  3120. // FIXME:
  3121. // Recording visible if
  3122. // there are at least 2(+ 1 focus) participants
  3123. //Object.keys(connection.emuc.members).length >= 3);
  3124. }
  3125. function onPasswordRequired(callback) {
  3126. // password is required
  3127. Toolbar.lockLockButton();
  3128. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3129. message += APP.translation.translateString(
  3130. "dialog.passwordRequired");
  3131. message += '</h2>' +
  3132. '<input name="lockKey" type="text" data-i18n=' +
  3133. '"[placeholder]dialog.password" placeholder="' +
  3134. APP.translation.translateString("dialog.password") +
  3135. '" autofocus>';
  3136. messageHandler.openTwoButtonDialog(null, null, null, message,
  3137. true,
  3138. "dialog.Ok",
  3139. function (e, v, m, f) {},
  3140. null,
  3141. function (e, v, m, f) {
  3142. if (v) {
  3143. var lockKey = f.lockKey;
  3144. if (lockKey) {
  3145. Toolbar.setSharedKey(lockKey);
  3146. callback(lockKey);
  3147. }
  3148. }
  3149. },
  3150. ':input:first'
  3151. );
  3152. }
  3153. /**
  3154. * The dialpad button is shown iff there is at least one member that supports
  3155. * DTMF (e.g. jigasi).
  3156. */
  3157. function onDtmfSupportChanged(dtmfSupport) {
  3158. //TODO: enable when the UI is ready
  3159. //Toolbar.showDialPadButton(dtmfSupport);
  3160. }
  3161. function onMucMemberJoined(jid, id, displayName) {
  3162. messageHandler.notify(displayName,'notify.somebody',
  3163. 'connected',
  3164. 'notify.connected');
  3165. if (!config.startAudioMuted ||
  3166. config.startAudioMuted > APP.members.size())
  3167. UIUtil.playSoundNotification('userJoined');
  3168. // Configure avatar
  3169. Avatar.setUserAvatar(jid, id);
  3170. // Add Peer's container
  3171. VideoLayout.ensurePeerContainerExists(jid);
  3172. }
  3173. function onMucPresenceStatus(jid, info) {
  3174. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3175. }
  3176. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3177. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3178. }
  3179. function onMucRoleChanged(role, displayName) {
  3180. VideoLayout.showModeratorIndicator();
  3181. if (role === 'moderator') {
  3182. var messageKey, messageOptions = {};
  3183. if (!displayName) {
  3184. messageKey = "notify.grantedToUnknown";
  3185. }
  3186. else {
  3187. messageKey = "notify.grantedTo";
  3188. messageOptions = {to: displayName};
  3189. }
  3190. messageHandler.notify(
  3191. displayName,'notify.somebody',
  3192. 'connected', messageKey,
  3193. messageOptions);
  3194. }
  3195. }
  3196. function onAuthenticationRequired(intervalCallback) {
  3197. Authentication.openAuthenticationDialog(
  3198. roomName, intervalCallback, function () {
  3199. Toolbar.authenticateClicked();
  3200. });
  3201. }
  3202. function onLastNChanged(oldValue, newValue) {
  3203. if (config.muteLocalVideoIfNotInLastN) {
  3204. setVideoMute(!newValue, { 'byUser': false });
  3205. }
  3206. }
  3207. UI.toggleSmileys = function () {
  3208. Chat.toggleSmileys();
  3209. };
  3210. UI.getSettings = function () {
  3211. return Settings.getSettings();
  3212. };
  3213. UI.toggleFilmStrip = function () {
  3214. return BottomToolbar.toggleFilmStrip();
  3215. };
  3216. UI.toggleChat = function () {
  3217. return BottomToolbar.toggleChat();
  3218. };
  3219. UI.toggleContactList = function () {
  3220. return BottomToolbar.toggleContactList();
  3221. };
  3222. UI.inputDisplayNameHandler = function (value) {
  3223. VideoLayout.inputDisplayNameHandler(value);
  3224. };
  3225. UI.getLargeVideoJid = function() {
  3226. return VideoLayout.getLargeVideoJid();
  3227. };
  3228. UI.generateRoomName = function() {
  3229. if(roomName)
  3230. return roomName;
  3231. var roomnode = null;
  3232. var path = window.location.pathname;
  3233. // determinde the room node from the url
  3234. // TODO: just the roomnode or the whole bare jid?
  3235. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3236. // custom function might be responsible for doing the pushstate
  3237. roomnode = config.getroomnode(path);
  3238. } else {
  3239. /* fall back to default strategy
  3240. * this is making assumptions about how the URL->room mapping happens.
  3241. * It currently assumes deployment at root, with a rewrite like the
  3242. * following one (for nginx):
  3243. location ~ ^/([a-zA-Z0-9]+)$ {
  3244. rewrite ^/(.*)$ / break;
  3245. }
  3246. */
  3247. if (path.length > 1) {
  3248. roomnode = path.substr(1).toLowerCase();
  3249. } else {
  3250. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3251. roomnode = word.toLowerCase();
  3252. window.history.pushState('VideoChat',
  3253. 'Room: ' + word, window.location.pathname + word);
  3254. }
  3255. }
  3256. roomName = roomnode + '@' + config.hosts.muc;
  3257. return roomName;
  3258. };
  3259. UI.connectionIndicatorShowMore = function(jid) {
  3260. return VideoLayout.showMore(jid);
  3261. };
  3262. UI.showLoginPopup = function(callback) {
  3263. console.log('password is required');
  3264. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3265. message += APP.translation.translateString(
  3266. "dialog.passwordRequired");
  3267. message += '</h2>' +
  3268. '<input name="username" type="text" ' +
  3269. 'placeholder="user@domain.net" autofocus>' +
  3270. '<input name="password" ' +
  3271. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3272. ' placeholder="user password">';
  3273. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3274. true,
  3275. "dialog.Ok",
  3276. function (e, v, m, f) {
  3277. if (v) {
  3278. if (f.username !== null && f.password != null) {
  3279. callback(f.username, f.password);
  3280. }
  3281. }
  3282. },
  3283. null, null, ':input:first'
  3284. );
  3285. };
  3286. UI.checkForNicknameAndJoin = function () {
  3287. Authentication.closeAuthenticationDialog();
  3288. Authentication.stopInterval();
  3289. var nick = null;
  3290. if (config.useNicks) {
  3291. nick = window.prompt('Your nickname (optional)');
  3292. }
  3293. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3294. };
  3295. function dump(elem, filename) {
  3296. elem = elem.parentNode;
  3297. elem.download = filename || 'meetlog.json';
  3298. elem.href = 'data:application/json;charset=utf-8,\n';
  3299. var data = APP.xmpp.getJingleLog();
  3300. var metadata = {};
  3301. metadata.time = new Date();
  3302. metadata.url = window.location.href;
  3303. metadata.ua = navigator.userAgent;
  3304. var log = APP.xmpp.getXmppLog();
  3305. if (log) {
  3306. metadata.xmpp = log;
  3307. }
  3308. data.metadata = metadata;
  3309. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3310. return false;
  3311. }
  3312. UI.getRoomName = function () {
  3313. return roomName;
  3314. };
  3315. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3316. if (muteAudio || muteVideo)
  3317. notifyForInitialMute();
  3318. if (muteAudio)
  3319. UI.setAudioMuted(true);
  3320. if (muteVideo)
  3321. UI.setVideoMute(true);
  3322. };
  3323. /**
  3324. * Mutes/unmutes the local video.
  3325. */
  3326. UI.toggleVideo = function () {
  3327. setVideoMute(!APP.RTC.localVideo.isMuted());
  3328. };
  3329. /**
  3330. * Mutes / unmutes audio for the local participant.
  3331. */
  3332. UI.toggleAudio = function() {
  3333. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3334. };
  3335. /**
  3336. * Sets muted audio state for the local participant.
  3337. */
  3338. UI.setAudioMuted = function (mute, earlyMute) {
  3339. var audioMute = null;
  3340. if (earlyMute)
  3341. audioMute = function (mute, cb) {
  3342. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3343. };
  3344. else
  3345. audioMute = function (mute, cb) {
  3346. return APP.xmpp.setAudioMute(mute, cb);
  3347. };
  3348. if (!audioMute(mute, function () {
  3349. VideoLayout.showLocalAudioIndicator(mute);
  3350. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3351. })) {
  3352. // We still click the button.
  3353. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3354. return;
  3355. }
  3356. };
  3357. UI.addListener = function (type, listener) {
  3358. eventEmitter.on(type, listener);
  3359. };
  3360. UI.clickOnVideo = function (videoNumber) {
  3361. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3362. if (remoteVideos.length > videoNumber) {
  3363. remoteVideos[videoNumber].click();
  3364. }
  3365. };
  3366. //Used by torture
  3367. UI.showToolbar = function () {
  3368. return ToolbarToggler.showToolbar();
  3369. };
  3370. //Used by torture
  3371. UI.dockToolbar = function (isDock) {
  3372. return ToolbarToggler.dockToolbar(isDock);
  3373. };
  3374. UI.setVideoMuteButtonsState = function (mute) {
  3375. var video = $('#video');
  3376. var communicativeClass = "icon-camera";
  3377. var muteClass = "icon-camera icon-camera-disabled";
  3378. if (mute) {
  3379. video.removeClass(communicativeClass);
  3380. video.addClass(muteClass);
  3381. } else {
  3382. video.removeClass(muteClass);
  3383. video.addClass(communicativeClass);
  3384. }
  3385. };
  3386. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3387. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3388. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3389. if(resourceJid === APP.xmpp.myResource())
  3390. SettingsMenu.changeAvatar(thumbUrl);
  3391. };
  3392. UI.setVideoMute = setVideoMute;
  3393. module.exports = UI;
  3394. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes":103,"../../service/UI/UIEvents":104,"../../service/connectionquality/CQEvents":106,"../../service/desktopsharing/DesktopSharingEventTypes":107,"../../service/members/Events":108,"../../service/xmpp/XMPPEvents":110,"../RTC/RTCBrowserType":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/JitsiPopover":30,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":111}],12:[function(require,module,exports){
  3395. /* global APP, interfaceConfig, $, Strophe */
  3396. var CanvasUtil = require("./CanvasUtils");
  3397. var ASDrawContext = null;
  3398. function initActiveSpeakerAudioLevels() {
  3399. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3400. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3401. // Draw a circle.
  3402. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3403. // Add a shadow around the circle
  3404. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3405. ASDrawContext.shadowOffsetX = 0;
  3406. ASDrawContext.shadowOffsetY = 0;
  3407. }
  3408. /**
  3409. * The audio Levels plugin.
  3410. */
  3411. var AudioLevels = (function(my) {
  3412. var audioLevelCanvasCache = {};
  3413. my.LOCAL_LEVEL = 'local';
  3414. my.init = function () {
  3415. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3416. initActiveSpeakerAudioLevels();
  3417. };
  3418. /**
  3419. * Updates the audio level canvas for the given peerJid. If the canvas
  3420. * didn't exist we create it.
  3421. */
  3422. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3423. var resourceJid = null;
  3424. var videoSpanId = null;
  3425. if (!peerJid)
  3426. videoSpanId = 'localVideoContainer';
  3427. else {
  3428. resourceJid = Strophe.getResourceFromJid(peerJid);
  3429. videoSpanId = 'participant_' + resourceJid;
  3430. }
  3431. var videoSpan = document.getElementById(videoSpanId);
  3432. if (!videoSpan) {
  3433. if (resourceJid)
  3434. console.error("No video element for jid", resourceJid);
  3435. else
  3436. console.error("No video element for local video.");
  3437. return;
  3438. }
  3439. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3440. var videoSpaceWidth = $('#remoteVideos').width();
  3441. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3442. var thumbnailWidth = thumbnailSize[0];
  3443. var thumbnailHeight = thumbnailSize[1];
  3444. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3445. audioLevelCanvas = document.createElement('canvas');
  3446. audioLevelCanvas.className = "audiolevel";
  3447. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3448. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3449. resizeAudioLevelCanvas( audioLevelCanvas,
  3450. thumbnailWidth,
  3451. thumbnailHeight);
  3452. videoSpan.appendChild(audioLevelCanvas);
  3453. } else {
  3454. audioLevelCanvas = audioLevelCanvas.get(0);
  3455. resizeAudioLevelCanvas( audioLevelCanvas,
  3456. thumbnailWidth,
  3457. thumbnailHeight);
  3458. }
  3459. };
  3460. /**
  3461. * Updates the audio level UI for the given resourceJid.
  3462. *
  3463. * @param resourceJid the resource jid indicating the video element for
  3464. * which we draw the audio level
  3465. * @param audioLevel the newAudio level to render
  3466. */
  3467. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3468. drawAudioLevelCanvas(resourceJid, audioLevel);
  3469. var videoSpanId = getVideoSpanId(resourceJid);
  3470. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3471. if (!audioLevelCanvas)
  3472. return;
  3473. var drawContext = audioLevelCanvas.getContext('2d');
  3474. var canvasCache = audioLevelCanvasCache[resourceJid];
  3475. drawContext.clearRect (0, 0,
  3476. audioLevelCanvas.width, audioLevelCanvas.height);
  3477. drawContext.drawImage(canvasCache, 0, 0);
  3478. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3479. if(!APP.xmpp.myJid()) {
  3480. return;
  3481. }
  3482. resourceJid = APP.xmpp.myResource();
  3483. }
  3484. if(resourceJid === largeVideoResourceJid) {
  3485. window.requestAnimationFrame(function () {
  3486. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3487. });
  3488. }
  3489. };
  3490. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3491. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3492. return;
  3493. ASDrawContext.clearRect(0, 0, 300, 300);
  3494. if(audioLevel == 0)
  3495. return;
  3496. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3497. // Fill the shape.
  3498. ASDrawContext.fill();
  3499. };
  3500. /**
  3501. * Resizes the given audio level canvas to match the given thumbnail size.
  3502. */
  3503. function resizeAudioLevelCanvas(audioLevelCanvas,
  3504. thumbnailWidth,
  3505. thumbnailHeight) {
  3506. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3507. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3508. }
  3509. /**
  3510. * Draws the audio level canvas into the cached canvas object.
  3511. *
  3512. * @param resourceJid the resource jid indicating the video element for
  3513. * which we draw the audio level
  3514. * @param audioLevel the newAudio level to render
  3515. */
  3516. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3517. if (!audioLevelCanvasCache[resourceJid]) {
  3518. var videoSpanId = getVideoSpanId(resourceJid);
  3519. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3520. /*
  3521. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3522. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3523. * error. Since audio levels are frequently updated, the errors have
  3524. * been observed to pile into the console, strain the CPU.
  3525. */
  3526. if (audioLevelCanvasOrig) {
  3527. audioLevelCanvasCache[resourceJid] =
  3528. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3529. }
  3530. }
  3531. var canvas = audioLevelCanvasCache[resourceJid];
  3532. if (!canvas)
  3533. return;
  3534. var drawContext = canvas.getContext('2d');
  3535. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3536. var shadowLevel = getShadowLevel(audioLevel);
  3537. if (shadowLevel > 0) {
  3538. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3539. CanvasUtil.drawRoundRectGlow(drawContext,
  3540. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3541. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3542. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3543. interfaceConfig.CANVAS_RADIUS,
  3544. interfaceConfig.SHADOW_COLOR,
  3545. shadowLevel);
  3546. }
  3547. }
  3548. /**
  3549. * Returns the shadow/glow level for the given audio level.
  3550. *
  3551. * @param audioLevel the audio level from which we determine the shadow
  3552. * level
  3553. */
  3554. function getShadowLevel (audioLevel) {
  3555. var shadowLevel = 0;
  3556. if (audioLevel <= 0.3) {
  3557. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3558. }
  3559. else if (audioLevel <= 0.6) {
  3560. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3561. }
  3562. else {
  3563. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3564. }
  3565. return shadowLevel;
  3566. }
  3567. /**
  3568. * Returns the video span id corresponding to the given resourceJid or local
  3569. * user.
  3570. */
  3571. function getVideoSpanId(resourceJid) {
  3572. var videoSpanId = null;
  3573. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3574. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3575. videoSpanId = 'localVideoContainer';
  3576. else
  3577. videoSpanId = 'participant_' + resourceJid;
  3578. return videoSpanId;
  3579. }
  3580. /**
  3581. * Indicates that the remote video has been resized.
  3582. */
  3583. $(document).bind('remotevideo.resized', function (event, width, height) {
  3584. var resized = false;
  3585. $('#remoteVideos>span>canvas').each(function() {
  3586. var canvas = $(this).get(0);
  3587. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3588. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3589. resized = true;
  3590. }
  3591. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3592. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3593. resized = true;
  3594. }
  3595. });
  3596. if (resized)
  3597. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3598. audioLevelCanvasCache[resourceJid].width =
  3599. width + interfaceConfig.CANVAS_EXTRA;
  3600. audioLevelCanvasCache[resourceJid].height =
  3601. height + interfaceConfig.CANVAS_EXTRA;
  3602. });
  3603. });
  3604. return my;
  3605. })(AudioLevels || {});
  3606. module.exports = AudioLevels;
  3607. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3608. /**
  3609. * Utility class for drawing canvas shapes.
  3610. */
  3611. var CanvasUtil = (function(my) {
  3612. /**
  3613. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3614. * of the glow.
  3615. *
  3616. * @param drawContext the context of the canvas to draw to
  3617. * @param x the x coordinate of the round rectangle
  3618. * @param y the y coordinate of the round rectangle
  3619. * @param w the width of the round rectangle
  3620. * @param h the height of the round rectangle
  3621. * @param glowColor the color of the glow
  3622. * @param glowWidth the width of the glow
  3623. */
  3624. my.drawRoundRectGlow
  3625. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3626. // Save the previous state of the context.
  3627. drawContext.save();
  3628. if (w < 2 * r) r = w / 2;
  3629. if (h < 2 * r) r = h / 2;
  3630. // Draw a round rectangle.
  3631. drawContext.beginPath();
  3632. drawContext.moveTo(x+r, y);
  3633. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3634. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3635. drawContext.arcTo(x, y+h, x, y, r);
  3636. drawContext.arcTo(x, y, x+w, y, r);
  3637. drawContext.closePath();
  3638. // Add a shadow around the rectangle
  3639. drawContext.shadowColor = glowColor;
  3640. drawContext.shadowBlur = glowWidth;
  3641. drawContext.shadowOffsetX = 0;
  3642. drawContext.shadowOffsetY = 0;
  3643. // Fill the shape.
  3644. drawContext.fill();
  3645. drawContext.save();
  3646. drawContext.restore();
  3647. // 1) Uncomment this line to use Composite Operation, which is doing the
  3648. // same as the clip function below and is also antialiasing the round
  3649. // border, but is said to be less fast performance wise.
  3650. // drawContext.globalCompositeOperation='destination-out';
  3651. drawContext.beginPath();
  3652. drawContext.moveTo(x+r, y);
  3653. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3654. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3655. drawContext.arcTo(x, y+h, x, y, r);
  3656. drawContext.arcTo(x, y, x+w, y, r);
  3657. drawContext.closePath();
  3658. // 2) Uncomment this line to use Composite Operation, which is doing the
  3659. // same as the clip function below and is also antialiasing the round
  3660. // border, but is said to be less fast performance wise.
  3661. // drawContext.fill();
  3662. // Comment these two lines if choosing to do the same with composite
  3663. // operation above 1 and 2.
  3664. drawContext.clip();
  3665. drawContext.clearRect(0, 0, 277, 200);
  3666. // Restore the previous context state.
  3667. drawContext.restore();
  3668. };
  3669. /**
  3670. * Clones the given canvas.
  3671. *
  3672. * @return the new cloned canvas.
  3673. */
  3674. my.cloneCanvas = function (oldCanvas) {
  3675. /*
  3676. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3677. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3678. * levels are frequently updated, the errors have been observed to pile
  3679. * into the console, strain the CPU.
  3680. */
  3681. if (!oldCanvas)
  3682. return oldCanvas;
  3683. //create a new canvas
  3684. var newCanvas = document.createElement('canvas');
  3685. var context = newCanvas.getContext('2d');
  3686. //set dimensions
  3687. newCanvas.width = oldCanvas.width;
  3688. newCanvas.height = oldCanvas.height;
  3689. //apply the old canvas to the new one
  3690. context.drawImage(oldCanvas, 0, 0);
  3691. //return the new canvas
  3692. return newCanvas;
  3693. };
  3694. return my;
  3695. })(CanvasUtil || {});
  3696. module.exports = CanvasUtil;
  3697. },{}],14:[function(require,module,exports){
  3698. /* global $, APP*/
  3699. var LoginDialog = require('./LoginDialog');
  3700. var Moderator = require('../../xmpp/moderator');
  3701. /* Initial "authentication required" dialog */
  3702. var authDialog = null;
  3703. /* Loop retry ID that wits for other user to create the room */
  3704. var authRetryId = null;
  3705. var authenticationWindow = null;
  3706. var Authentication = {
  3707. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3708. // This is the loop that will wait for the room to be created by
  3709. // someone else. 'auth_required.moderator' will bring us back here.
  3710. authRetryId = window.setTimeout(intervalCallback, 5000);
  3711. // Show prompt only if it's not open
  3712. if (authDialog !== null) {
  3713. return;
  3714. }
  3715. // extract room name from 'room@muc.server.net'
  3716. var room = roomName.substr(0, roomName.indexOf('@'));
  3717. var title
  3718. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3719. var msg
  3720. = APP.translation.generateTranslationHTML(
  3721. "dialog.WaitForHostMsg", {room: room});
  3722. var buttonTxt
  3723. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3724. var buttons = [];
  3725. buttons.push({title: buttonTxt, value: "authNow"});
  3726. authDialog = APP.UI.messageHandler.openDialog(
  3727. title,
  3728. msg,
  3729. true,
  3730. buttons,
  3731. function (onSubmitEvent, submitValue) {
  3732. // Do not close the dialog yet
  3733. onSubmitEvent.preventDefault();
  3734. // Open login popup
  3735. if (submitValue === 'authNow') {
  3736. callback();
  3737. }
  3738. }
  3739. );
  3740. },
  3741. closeAuthenticationWindow: function () {
  3742. if (authenticationWindow) {
  3743. authenticationWindow.close();
  3744. authenticationWindow = null;
  3745. }
  3746. },
  3747. xmppAuthenticate: function () {
  3748. var loginDialog = LoginDialog.show(
  3749. function (connection, state) {
  3750. if (!state) {
  3751. // User cancelled
  3752. loginDialog.close();
  3753. return;
  3754. } else if (state == APP.xmpp.Status.CONNECTED) {
  3755. loginDialog.close();
  3756. Authentication.stopInterval();
  3757. Authentication.closeAuthenticationDialog();
  3758. // Close the connection as anonymous one will be used
  3759. // to create the conference. Session-id will authorize
  3760. // the request.
  3761. connection.disconnect();
  3762. var roomName = APP.UI.generateRoomName();
  3763. Moderator.allocateConferenceFocus(roomName, function () {
  3764. // If it's not "on the fly" authentication now join
  3765. // the conference room
  3766. if (!APP.xmpp.isMUCJoined()) {
  3767. APP.UI.checkForNicknameAndJoin();
  3768. }
  3769. });
  3770. }
  3771. }, true);
  3772. },
  3773. focusAuthenticationWindow: function () {
  3774. // If auth window exists just bring it to the front
  3775. if (authenticationWindow) {
  3776. authenticationWindow.focus();
  3777. return;
  3778. }
  3779. },
  3780. closeAuthenticationDialog: function () {
  3781. // Close authentication dialog if opened
  3782. if (authDialog) {
  3783. authDialog.close();
  3784. authDialog = null;
  3785. }
  3786. },
  3787. createAuthenticationWindow: function (callback, url) {
  3788. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3789. url, 910, 660,
  3790. // On closed
  3791. function () {
  3792. // Close authentication dialog if opened
  3793. Authentication.closeAuthenticationDialog();
  3794. callback();
  3795. authenticationWindow = null;
  3796. });
  3797. return authenticationWindow;
  3798. },
  3799. stopInterval: function () {
  3800. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3801. if (authRetryId) {
  3802. window.clearTimeout(authRetryId);
  3803. authRetryId = null;
  3804. }
  3805. }
  3806. };
  3807. module.exports = Authentication;
  3808. },{"../../xmpp/moderator":60,"./LoginDialog":15}],15:[function(require,module,exports){
  3809. /* global $, APP, config*/
  3810. var XMPP = require('../../xmpp/xmpp');
  3811. var Moderator = require('../../xmpp/moderator');
  3812. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3813. // anonymous domain is not enabled
  3814. /**
  3815. * Creates new <tt>Dialog</tt> instance.
  3816. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3817. * when we either fail to connect or succeed(check Strophe.Status).
  3818. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3819. * in order to create session-id after the connection is established.
  3820. * @constructor
  3821. */
  3822. function Dialog(callback, obtainSession) {
  3823. var self = this;
  3824. var stop = false;
  3825. var connection = APP.xmpp.createConnection();
  3826. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3827. message += APP.translation.translateString("dialog.passwordRequired");
  3828. message += '</h2>' +
  3829. '<input name="username" type="text" ' +
  3830. 'placeholder="user@domain.net" autofocus>' +
  3831. '<input name="password" ' +
  3832. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3833. ' placeholder="user password">';
  3834. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3835. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3836. var states = {
  3837. login: {
  3838. html: message,
  3839. buttons: [
  3840. { title: okButton, value: true},
  3841. { title: cancelButton, value: false}
  3842. ],
  3843. focus: ':input:first',
  3844. submit: function (e, v, m, f) {
  3845. e.preventDefault();
  3846. if (v) {
  3847. var jid = f.username;
  3848. var password = f.password;
  3849. if (jid && password) {
  3850. stop = false;
  3851. connection.reset();
  3852. connDialog.goToState('connecting');
  3853. connection.connect(jid, password, stateHandler);
  3854. }
  3855. } else {
  3856. // User cancelled
  3857. stop = true;
  3858. callback();
  3859. }
  3860. }
  3861. },
  3862. connecting: {
  3863. title: APP.translation.translateString('dialog.connecting'),
  3864. html: '<div id="connectionStatus"></div>',
  3865. buttons: [],
  3866. defaultButton: 0
  3867. },
  3868. finished: {
  3869. title: APP.translation.translateString('dialog.error'),
  3870. html: '<div id="errorMessage"></div>',
  3871. buttons: [
  3872. {
  3873. title: APP.translation.translateString('dialog.retry'),
  3874. value: 'retry'
  3875. },
  3876. {
  3877. title: APP.translation.translateString('dialog.Cancel'),
  3878. value: 'cancel'
  3879. },
  3880. ],
  3881. defaultButton: 0,
  3882. submit: function (e, v, m, f) {
  3883. e.preventDefault();
  3884. if (v === 'retry')
  3885. connDialog.goToState('login');
  3886. else
  3887. callback();
  3888. }
  3889. }
  3890. };
  3891. var connDialog
  3892. = APP.UI.messageHandler.openDialogWithStates(states,
  3893. { persistent: true, closeText: '' }, null);
  3894. var stateHandler = function (status, message) {
  3895. if (stop) {
  3896. return;
  3897. }
  3898. var translateKey = "connection." + XMPP.getStatusString(status);
  3899. var statusStr = APP.translation.translateString(translateKey);
  3900. // Display current state
  3901. var connectionStatus =
  3902. connDialog.getState('connecting').find('#connectionStatus');
  3903. connectionStatus.text(statusStr);
  3904. switch (status) {
  3905. case XMPP.Status.CONNECTED:
  3906. stop = true;
  3907. if (!obtainSession) {
  3908. callback(connection, status);
  3909. return;
  3910. }
  3911. // Obtaining session-id status
  3912. connectionStatus.text(
  3913. APP.translation.translateString(
  3914. 'connection.FETCH_SESSION_ID'));
  3915. // Authenticate with Jicofo and obtain session-id
  3916. var roomName = APP.UI.generateRoomName();
  3917. // Jicofo will return new session-id when connected
  3918. // from authenticated domain
  3919. connection.sendIQ(
  3920. Moderator.createConferenceIq(roomName),
  3921. function (result) {
  3922. connectionStatus.text(
  3923. APP.translation.translateString(
  3924. 'connection.GOT_SESSION_ID'));
  3925. stop = true;
  3926. // Parse session-id
  3927. Moderator.parseSessionId(result);
  3928. callback(connection, status);
  3929. },
  3930. function (error) {
  3931. console.error("Auth on the fly failed", error);
  3932. stop = true;
  3933. var errorMsg =
  3934. APP.translation.translateString(
  3935. 'connection.GET_SESSION_ID_ERROR') +
  3936. $(error).find('>error').attr('code');
  3937. self.displayError(errorMsg);
  3938. connection.disconnect();
  3939. });
  3940. break;
  3941. case XMPP.Status.AUTHFAIL:
  3942. case XMPP.Status.CONNFAIL:
  3943. case XMPP.Status.DISCONNECTED:
  3944. stop = true;
  3945. callback(connection, status);
  3946. var errorMessage = statusStr;
  3947. if (message)
  3948. {
  3949. errorMessage += ': ' + message;
  3950. }
  3951. self.displayError(errorMessage);
  3952. break;
  3953. default:
  3954. break;
  3955. }
  3956. };
  3957. /**
  3958. * Displays error message in 'finished' state which allows either to cancel
  3959. * or retry.
  3960. * @param message the final message to be displayed.
  3961. */
  3962. this.displayError = function (message) {
  3963. var finishedState = connDialog.getState('finished');
  3964. var errorMessageElem = finishedState.find('#errorMessage');
  3965. errorMessageElem.text(message);
  3966. connDialog.goToState('finished');
  3967. };
  3968. /**
  3969. * Closes LoginDialog.
  3970. */
  3971. this.close = function () {
  3972. stop = true;
  3973. connDialog.close();
  3974. };
  3975. }
  3976. var LoginDialog = {
  3977. /**
  3978. * Displays login prompt used to establish new XMPP connection. Given
  3979. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  3980. * called when we connect successfully(status === CONNECTED) or when we fail
  3981. * to do so. On connection failure program can call Dialog.close() method in
  3982. * order to cancel or do nothing to let the user retry.
  3983. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  3984. * called when we either fail to connect or succeed(check
  3985. * Strophe.Status).
  3986. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  3987. * Jicofo in order to create session-id after the connection is
  3988. * established.
  3989. * @returns {Dialog}
  3990. */
  3991. show: function (callback, obtainSession) {
  3992. return new Dialog(callback, obtainSession);
  3993. }
  3994. };
  3995. module.exports = LoginDialog;
  3996. },{"../../xmpp/moderator":60,"../../xmpp/xmpp":68}],16:[function(require,module,exports){
  3997. var Settings = require("../../settings/Settings");
  3998. var users = {};
  3999. var Avatar = {
  4000. /**
  4001. * Sets the user's avatar in the settings menu(if local user), contact list
  4002. * and thumbnail
  4003. * @param jid jid of the user
  4004. * @param id email or userID to be used as a hash
  4005. */
  4006. setUserAvatar: function (jid, id) {
  4007. if (id) {
  4008. if (users[jid] === id) {
  4009. return;
  4010. }
  4011. users[jid] = id;
  4012. }
  4013. var thumbUrl = this.getThumbUrl(jid);
  4014. var contactListUrl = this.getContactListUrl(jid);
  4015. var resourceJid = Strophe.getResourceFromJid(jid);
  4016. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4017. },
  4018. /**
  4019. * Returns image URL for the avatar to be displayed on large video area
  4020. * where current active speaker is presented.
  4021. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4022. */
  4023. getActiveSpeakerUrl: function (jid) {
  4024. return this.getGravatarUrl(jid, 100);
  4025. },
  4026. /**
  4027. * Returns image URL for the avatar to be displayed on small video thumbnail
  4028. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4029. */
  4030. getThumbUrl: function (jid) {
  4031. return this.getGravatarUrl(jid, 100);
  4032. },
  4033. /**
  4034. * Returns the URL for the avatar to be displayed as contactlist item
  4035. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4036. */
  4037. getContactListUrl: function (jid) {
  4038. return this.getGravatarUrl(jid, 30);
  4039. },
  4040. getGravatarUrl: function (jid, size) {
  4041. if (!jid) {
  4042. console.error("Get gravatar - jid is undefined");
  4043. return null;
  4044. }
  4045. var id = users[jid];
  4046. if (!id) {
  4047. console.warn(
  4048. "No avatar stored yet for " + jid + " - using JID as ID");
  4049. id = jid;
  4050. }
  4051. return 'https://www.gravatar.com/avatar/' +
  4052. MD5.hexdigest(id.trim().toLowerCase()) +
  4053. "?d=wavatar&size=" + (size || "30");
  4054. }
  4055. };
  4056. module.exports = Avatar;
  4057. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4058. /* global $, config,
  4059. setLargeVideoVisible, Util */
  4060. var VideoLayout = require("../videolayout/VideoLayout");
  4061. var Prezi = require("../prezi/Prezi");
  4062. var UIUtil = require("../util/UIUtil");
  4063. var etherpadName = null;
  4064. var etherpadIFrame = null;
  4065. var domain = null;
  4066. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4067. /**
  4068. * Resizes the etherpad.
  4069. */
  4070. function resize() {
  4071. if ($('#etherpad>iframe').length) {
  4072. var remoteVideos = $('#remoteVideos');
  4073. var availableHeight
  4074. = window.innerHeight - remoteVideos.outerHeight();
  4075. var availableWidth = UIUtil.getAvailableVideoWidth();
  4076. $('#etherpad>iframe').width(availableWidth);
  4077. $('#etherpad>iframe').height(availableHeight);
  4078. }
  4079. }
  4080. /**
  4081. * Creates the Etherpad button and adds it to the toolbar.
  4082. */
  4083. function enableEtherpadButton() {
  4084. if (!$('#etherpadButton').is(":visible"))
  4085. $('#etherpadButton').css({display: 'inline-block'});
  4086. }
  4087. /**
  4088. * Creates the IFrame for the etherpad.
  4089. */
  4090. function createIFrame() {
  4091. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4092. domain + etherpadName + options, function() {
  4093. document.domain = document.domain;
  4094. bubbleIframeMouseMove(etherpadIFrame);
  4095. setTimeout(function() {
  4096. // the iframes inside of the etherpad are
  4097. // not yet loaded when the etherpad iframe is loaded
  4098. var outer = etherpadIFrame.
  4099. contentDocument.getElementsByName("ace_outer")[0];
  4100. bubbleIframeMouseMove(outer);
  4101. var inner = outer.
  4102. contentDocument.getElementsByName("ace_inner")[0];
  4103. bubbleIframeMouseMove(inner);
  4104. }, 2000);
  4105. });
  4106. }
  4107. function bubbleIframeMouseMove(iframe){
  4108. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4109. iframe.contentWindow.onmousemove = function(e){
  4110. if(existingOnMouseMove) existingOnMouseMove(e);
  4111. var evt = document.createEvent("MouseEvents");
  4112. var boundingClientRect = iframe.getBoundingClientRect();
  4113. evt.initMouseEvent(
  4114. "mousemove",
  4115. true, // bubbles
  4116. false, // not cancelable
  4117. window,
  4118. e.detail,
  4119. e.screenX,
  4120. e.screenY,
  4121. e.clientX + boundingClientRect.left,
  4122. e.clientY + boundingClientRect.top,
  4123. e.ctrlKey,
  4124. e.altKey,
  4125. e.shiftKey,
  4126. e.metaKey,
  4127. e.button,
  4128. null // no related element
  4129. );
  4130. iframe.dispatchEvent(evt);
  4131. };
  4132. }
  4133. var Etherpad = {
  4134. /**
  4135. * Initializes the etherpad.
  4136. */
  4137. init: function (name) {
  4138. if (config.etherpad_base && !etherpadName && name) {
  4139. domain = config.etherpad_base;
  4140. etherpadName = name;
  4141. enableEtherpadButton();
  4142. /**
  4143. * Resizes the etherpad, when the window is resized.
  4144. */
  4145. $(window).resize(function () {
  4146. resize();
  4147. });
  4148. }
  4149. },
  4150. /**
  4151. * Opens/hides the Etherpad.
  4152. */
  4153. toggleEtherpad: function (isPresentation) {
  4154. if (!etherpadIFrame)
  4155. createIFrame();
  4156. if(VideoLayout.getLargeVideoState() === "etherpad")
  4157. {
  4158. VideoLayout.setLargeVideoState("video");
  4159. }
  4160. else
  4161. {
  4162. VideoLayout.setLargeVideoState("etherpad");
  4163. }
  4164. resize();
  4165. }
  4166. };
  4167. module.exports = Etherpad;
  4168. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4169. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4170. var UIUtil = require("../util/UIUtil");
  4171. var VideoLayout = require("../videolayout/VideoLayout");
  4172. var messageHandler = require("../util/MessageHandler");
  4173. var PreziPlayer = require("./PreziPlayer");
  4174. var preziPlayer = null;
  4175. /**
  4176. * Shows/hides a presentation.
  4177. */
  4178. function setPresentationVisible(visible) {
  4179. if (visible) {
  4180. VideoLayout.setLargeVideoState("prezi");
  4181. }
  4182. else {
  4183. VideoLayout.setLargeVideoState("video");
  4184. }
  4185. }
  4186. var Prezi = {
  4187. /**
  4188. * Reloads the current presentation.
  4189. */
  4190. reloadPresentation: function() {
  4191. var iframe = document.getElementById(preziPlayer.options.preziId);
  4192. iframe.src = iframe.src;
  4193. },
  4194. /**
  4195. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4196. * otherwise.
  4197. */
  4198. isPresentationVisible: function () {
  4199. return ($('#presentation>iframe') != null
  4200. && $('#presentation>iframe').css('opacity') == 1);
  4201. },
  4202. /**
  4203. * Opens the Prezi dialog, from which the user could choose a presentation
  4204. * to load.
  4205. */
  4206. openPreziDialog: function() {
  4207. var myprezi = APP.xmpp.getPrezi();
  4208. if (myprezi) {
  4209. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4210. null,
  4211. "dialog.removePreziMsg",
  4212. null,
  4213. false,
  4214. "dialog.Remove",
  4215. function(e,v,m,f) {
  4216. if(v) {
  4217. APP.xmpp.removePreziFromPresence();
  4218. }
  4219. }
  4220. );
  4221. }
  4222. else if (preziPlayer != null) {
  4223. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4224. null, "dialog.sharePreziMsg",
  4225. null,
  4226. false,
  4227. "dialog.Ok",
  4228. function(e,v,m,f) {
  4229. $.prompt.close();
  4230. }
  4231. );
  4232. }
  4233. else {
  4234. var html = APP.translation.generateTranslationHTML(
  4235. "dialog.sharePreziTitle");
  4236. var cancelButton = APP.translation.generateTranslationHTML(
  4237. "dialog.Cancel");
  4238. var shareButton = APP.translation.generateTranslationHTML(
  4239. "dialog.Share");
  4240. var backButton = APP.translation.generateTranslationHTML(
  4241. "dialog.Back");
  4242. var buttons = [];
  4243. var buttons1 = [];
  4244. // Cancel button to both states
  4245. buttons.push({title: cancelButton, value: false});
  4246. buttons1.push({title: cancelButton, value: false});
  4247. // Share button
  4248. buttons.push({title: shareButton, value: true});
  4249. // Back button
  4250. buttons1.push({title: backButton, value: true});
  4251. var linkError = APP.translation.generateTranslationHTML(
  4252. "dialog.preziLinkError");
  4253. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4254. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4255. var openPreziState = {
  4256. state0: {
  4257. html: '<h2>' + html + '</h2>' +
  4258. '<input name="preziUrl" type="text" ' +
  4259. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4260. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4261. '\' placeholder="' + defaultUrl + '" autofocus>',
  4262. persistent: false,
  4263. buttons: buttons,
  4264. focus: ':input:first',
  4265. defaultButton: 0,
  4266. submit: function (e, v, m, f) {
  4267. e.preventDefault();
  4268. if(v)
  4269. {
  4270. var preziUrl = f.preziUrl;
  4271. if (preziUrl)
  4272. {
  4273. var urlValue
  4274. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4275. if (urlValue.indexOf('http://prezi.com/') != 0
  4276. && urlValue.indexOf('https://prezi.com/') != 0)
  4277. {
  4278. $.prompt.goToState('state1');
  4279. return false;
  4280. }
  4281. else {
  4282. var presIdTmp = urlValue.substring(
  4283. urlValue.indexOf("prezi.com/") + 10);
  4284. if (!isAlphanumeric(presIdTmp)
  4285. || presIdTmp.indexOf('/') < 2) {
  4286. $.prompt.goToState('state1');
  4287. return false;
  4288. }
  4289. else {
  4290. APP.xmpp.addToPresence("prezi", urlValue);
  4291. $.prompt.close();
  4292. }
  4293. }
  4294. }
  4295. }
  4296. else
  4297. $.prompt.close();
  4298. }
  4299. },
  4300. state1: {
  4301. html: '<h2>' + html + '</h2>' +
  4302. linkError,
  4303. persistent: false,
  4304. buttons: buttons1,
  4305. focus: ':input:first',
  4306. defaultButton: 1,
  4307. submit: function (e, v, m, f) {
  4308. e.preventDefault();
  4309. if (v === 0)
  4310. $.prompt.close();
  4311. else
  4312. $.prompt.goToState('state0');
  4313. }
  4314. }
  4315. };
  4316. messageHandler.openDialogWithStates(openPreziState);
  4317. }
  4318. }
  4319. };
  4320. /**
  4321. * A new presentation has been added.
  4322. *
  4323. * @param event the event indicating the add of a presentation
  4324. * @param jid the jid from which the presentation was added
  4325. * @param presUrl url of the presentation
  4326. * @param currentSlide the current slide to which we should move
  4327. */
  4328. function presentationAdded(event, jid, presUrl, currentSlide) {
  4329. console.log("presentation added", presUrl);
  4330. var presId = getPresentationId(presUrl);
  4331. var elementId = 'participant_'
  4332. + Strophe.getResourceFromJid(jid)
  4333. + '_' + presId;
  4334. VideoLayout.addPreziContainer(elementId);
  4335. var controlsEnabled = false;
  4336. if (jid === APP.xmpp.myJid())
  4337. controlsEnabled = true;
  4338. setPresentationVisible(true);
  4339. VideoLayout.setLargeVideoHover(
  4340. function (event) {
  4341. if (Prezi.isPresentationVisible()) {
  4342. var reloadButtonRight = window.innerWidth
  4343. - $('#presentation>iframe').offset().left
  4344. - $('#presentation>iframe').width();
  4345. $('#reloadPresentation').css({ right: reloadButtonRight,
  4346. display:'inline-block'});
  4347. }
  4348. },
  4349. function (event) {
  4350. if (!Prezi.isPresentationVisible())
  4351. $('#reloadPresentation').css({display:'none'});
  4352. else {
  4353. var e = event.toElement || event.relatedTarget;
  4354. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4355. $('#reloadPresentation').css({display:'none'});
  4356. }
  4357. });
  4358. preziPlayer = new PreziPlayer(
  4359. 'presentation',
  4360. {preziId: presId,
  4361. width: getPresentationWidth(),
  4362. height: getPresentationHeihgt(),
  4363. controls: controlsEnabled,
  4364. debug: true
  4365. });
  4366. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4367. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4368. console.log("prezi status", event.value);
  4369. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4370. if (jid != APP.xmpp.myJid())
  4371. preziPlayer.flyToStep(currentSlide);
  4372. }
  4373. });
  4374. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4375. console.log("event value", event.value);
  4376. APP.xmpp.addToPresence("preziSlide", event.value);
  4377. });
  4378. $("#" + elementId).css( 'background-image',
  4379. 'url(../images/avatarprezi.png)');
  4380. $("#" + elementId).click(
  4381. function () {
  4382. setPresentationVisible(true);
  4383. }
  4384. );
  4385. };
  4386. /**
  4387. * A presentation has been removed.
  4388. *
  4389. * @param event the event indicating the remove of a presentation
  4390. * @param jid the jid for which the presentation was removed
  4391. * @param the url of the presentation
  4392. */
  4393. function presentationRemoved(event, jid, presUrl) {
  4394. console.log('presentation removed', presUrl);
  4395. var presId = getPresentationId(presUrl);
  4396. setPresentationVisible(false);
  4397. $('#participant_'
  4398. + Strophe.getResourceFromJid(jid)
  4399. + '_' + presId).remove();
  4400. $('#presentation>iframe').remove();
  4401. if (preziPlayer != null) {
  4402. preziPlayer.destroy();
  4403. preziPlayer = null;
  4404. }
  4405. };
  4406. /**
  4407. * Indicates if the given string is an alphanumeric string.
  4408. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4409. * purpose of checking URIs.
  4410. */
  4411. function isAlphanumeric(unsafeText) {
  4412. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4413. return regex.test(unsafeText);
  4414. }
  4415. /**
  4416. * Returns the presentation id from the given url.
  4417. */
  4418. function getPresentationId (presUrl) {
  4419. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4420. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4421. }
  4422. /**
  4423. * Returns the presentation width.
  4424. */
  4425. function getPresentationWidth() {
  4426. var availableWidth = UIUtil.getAvailableVideoWidth();
  4427. var availableHeight = getPresentationHeihgt();
  4428. var aspectRatio = 16.0 / 9.0;
  4429. if (availableHeight < availableWidth / aspectRatio) {
  4430. availableWidth = Math.floor(availableHeight * aspectRatio);
  4431. }
  4432. return availableWidth;
  4433. }
  4434. /**
  4435. * Returns the presentation height.
  4436. */
  4437. function getPresentationHeihgt() {
  4438. var remoteVideos = $('#remoteVideos');
  4439. return window.innerHeight - remoteVideos.outerHeight();
  4440. }
  4441. /**
  4442. * Resizes the presentation iframe.
  4443. */
  4444. function resize() {
  4445. if ($('#presentation>iframe')) {
  4446. $('#presentation>iframe').width(getPresentationWidth());
  4447. $('#presentation>iframe').height(getPresentationHeihgt());
  4448. }
  4449. }
  4450. /**
  4451. * Presentation has been removed.
  4452. */
  4453. $(document).bind('presentationremoved.muc', presentationRemoved);
  4454. /**
  4455. * Presentation has been added.
  4456. */
  4457. $(document).bind('presentationadded.muc', presentationAdded);
  4458. /*
  4459. * Indicates presentation slide change.
  4460. */
  4461. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4462. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4463. preziPlayer.flyToStep(current);
  4464. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4465. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4466. preziPlayer.flyToStep(current, i);
  4467. }
  4468. }
  4469. });
  4470. $(window).resize(function () {
  4471. resize();
  4472. });
  4473. module.exports = Prezi;
  4474. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4475. (function() {
  4476. "use strict";
  4477. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4478. window.PreziPlayer = (function() {
  4479. PreziPlayer.API_VERSION = 1;
  4480. PreziPlayer.CURRENT_STEP = 'currentStep';
  4481. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4482. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4483. PreziPlayer.STATUS_LOADING = 'loading';
  4484. PreziPlayer.STATUS_READY = 'ready';
  4485. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4486. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4487. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4488. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4489. PreziPlayer.EVENT_STATUS = "statusChange";
  4490. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4491. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4492. PreziPlayer.domain = "https://prezi.com";
  4493. PreziPlayer.path = "/player/";
  4494. PreziPlayer.players = {};
  4495. PreziPlayer.binded_methods = ['changesHandler'];
  4496. PreziPlayer.createMultiplePlayers = function(optionArray){
  4497. for(var i=0; i<optionArray.length; i++) {
  4498. var optionSet = optionArray[i];
  4499. new PreziPlayer(optionSet.id, optionSet);
  4500. };
  4501. };
  4502. PreziPlayer.messageReceived = function(event){
  4503. var message, item, player;
  4504. try {
  4505. message = JSON.parse(event.data);
  4506. if (message.id && (player = PreziPlayer.players[message.id])) {
  4507. if (player.options.debug === true) {
  4508. if (console && console.log)
  4509. console.log('received', message);
  4510. }
  4511. if (message.type === "changes") {
  4512. player.changesHandler(message);
  4513. }
  4514. for (var i = 0; i < player.callbacks.length; i++) {
  4515. item = player.callbacks[i];
  4516. if (item && message.type === item.event) {
  4517. item.callback(message);
  4518. }
  4519. }
  4520. }
  4521. } catch (e) { }
  4522. };
  4523. function PreziPlayer(id, options) {
  4524. var params, paramString = "", _this = this;
  4525. if (PreziPlayer.players[id]){
  4526. PreziPlayer.players[id].destroy();
  4527. }
  4528. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4529. var method_name = PreziPlayer.binded_methods[i];
  4530. _this[method_name] = __bind(_this[method_name], _this);
  4531. };
  4532. options = options || {};
  4533. this.options = options;
  4534. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4535. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4536. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4537. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4538. this.callbacks = [];
  4539. this.id = id;
  4540. this.embedTo = document.getElementById(id);
  4541. if (!this.embedTo) {
  4542. throw "The element id is not available.";
  4543. }
  4544. this.iframe = document.createElement('iframe');
  4545. params = [
  4546. { name: 'oid', value: options.preziId },
  4547. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4548. { name: 'controls', value: options.controls ? 1 : 0 }
  4549. ];
  4550. for(var i=0; i<params.length; i++) {
  4551. var param = params[i];
  4552. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4553. };
  4554. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4555. this.iframe.frameBorder = 0;
  4556. this.iframe.scrolling = "no";
  4557. this.iframe.width = options.width || 640;
  4558. this.iframe.height = options.height || 480;
  4559. this.embedTo.innerHTML = '';
  4560. // JITSI: IN CASE SOMETHING GOES WRONG.
  4561. try {
  4562. this.embedTo.appendChild(this.iframe);
  4563. }
  4564. catch (err) {
  4565. console.log("CATCH ERROR");
  4566. }
  4567. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4568. // crashes for us.
  4569. this.initPollInterval = setInterval(function(){
  4570. _this.sendMessage({'action': 'init'});
  4571. }, 500);
  4572. PreziPlayer.players[id] = this;
  4573. }
  4574. PreziPlayer.prototype.changesHandler = function(message) {
  4575. var key, value, j, item;
  4576. if (this.initPollInterval) {
  4577. clearInterval(this.initPollInterval);
  4578. this.initPollInterval = false;
  4579. }
  4580. for (key in message.data) {
  4581. if (message.data.hasOwnProperty(key)){
  4582. value = message.data[key];
  4583. this.values[key] = value;
  4584. for (j=0; j<this.callbacks.length; j++) {
  4585. item = this.callbacks[j];
  4586. if (item && item.event === key + "Change"){
  4587. item.callback({type: item.event, value: value});
  4588. }
  4589. }
  4590. }
  4591. }
  4592. };
  4593. PreziPlayer.prototype.destroy = function() {
  4594. if (this.initPollInterval) {
  4595. clearInterval(this.initPollInterval);
  4596. this.initPollInterval = false;
  4597. }
  4598. this.embedTo.innerHTML = '';
  4599. };
  4600. PreziPlayer.prototype.sendMessage = function(message) {
  4601. if (this.options.debug === true) {
  4602. if (console && console.log) console.log('sent', message);
  4603. }
  4604. message.version = PreziPlayer.API_VERSION;
  4605. message.id = this.id;
  4606. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4607. };
  4608. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4609. PreziPlayer.prototype.flyToNextStep = function() {
  4610. return this.sendMessage({
  4611. 'action': 'present',
  4612. 'data': ['moveToNextStep']
  4613. });
  4614. };
  4615. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4616. PreziPlayer.prototype.flyToPreviousStep = function() {
  4617. return this.sendMessage({
  4618. 'action': 'present',
  4619. 'data': ['moveToPrevStep']
  4620. });
  4621. };
  4622. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4623. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4624. var obj = this;
  4625. // check animation_step
  4626. if (animation_step > 0 &&
  4627. obj.values.animationCountOnSteps &&
  4628. obj.values.animationCountOnSteps[step] <= animation_step) {
  4629. animation_step = obj.values.animationCountOnSteps[step];
  4630. }
  4631. // jump to animation steps by calling flyToNextStep()
  4632. function doAnimationSteps() {
  4633. if (obj.values.isMoving == true) {
  4634. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4635. return;
  4636. }
  4637. while (animation_step-- > 0) {
  4638. obj.flyToNextStep(); // do the animation steps
  4639. }
  4640. }
  4641. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4642. // jump to the step
  4643. return this.sendMessage({
  4644. 'action': 'present',
  4645. 'data': ['moveToStep', step]
  4646. });
  4647. };
  4648. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4649. PreziPlayer.prototype.flyToObject = function(objectId) {
  4650. return this.sendMessage({
  4651. 'action': 'present',
  4652. 'data': ['moveToObject', objectId]
  4653. });
  4654. };
  4655. PreziPlayer.prototype.play = function(defaultDelay) {
  4656. return this.sendMessage({
  4657. 'action': 'present',
  4658. 'data': ['startAutoPlay', defaultDelay]
  4659. });
  4660. };
  4661. PreziPlayer.prototype.stop = function() {
  4662. return this.sendMessage({
  4663. 'action': 'present',
  4664. 'data': ['stopAutoPlay']
  4665. });
  4666. };
  4667. PreziPlayer.prototype.pause = function(defaultDelay) {
  4668. return this.sendMessage({
  4669. 'action': 'present',
  4670. 'data': ['pauseAutoPlay', defaultDelay]
  4671. });
  4672. };
  4673. PreziPlayer.prototype.getCurrentStep = function() {
  4674. return this.values.currentStep;
  4675. };
  4676. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4677. return this.values.currentAnimationStep;
  4678. };
  4679. PreziPlayer.prototype.getCurrentObject = function() {
  4680. return this.values.currentObject;
  4681. };
  4682. PreziPlayer.prototype.getStatus = function() {
  4683. return this.values.status;
  4684. };
  4685. PreziPlayer.prototype.isPlaying = function() {
  4686. return this.values.isAutoPlaying;
  4687. };
  4688. PreziPlayer.prototype.getStepCount = function() {
  4689. return this.values.stepCount;
  4690. };
  4691. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4692. return this.values.animationCountOnSteps;
  4693. };
  4694. PreziPlayer.prototype.getTitle = function() {
  4695. return this.values.title;
  4696. };
  4697. PreziPlayer.prototype.setDimensions = function(dims) {
  4698. for (var parameter in dims) {
  4699. this.iframe[parameter] = dims[parameter];
  4700. }
  4701. }
  4702. PreziPlayer.prototype.getDimensions = function() {
  4703. return {
  4704. width: parseInt(this.iframe.width, 10),
  4705. height: parseInt(this.iframe.height, 10)
  4706. }
  4707. }
  4708. PreziPlayer.prototype.on = function(event, callback) {
  4709. this.callbacks.push({
  4710. event: event,
  4711. callback: callback
  4712. });
  4713. };
  4714. PreziPlayer.prototype.off = function(event, callback) {
  4715. var j, item;
  4716. if (event === undefined) {
  4717. this.callbacks = [];
  4718. }
  4719. j = this.callbacks.length;
  4720. while (j--) {
  4721. item = this.callbacks[j];
  4722. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4723. this.callbacks.splice(j, 1);
  4724. }
  4725. }
  4726. };
  4727. if (window.addEventListener) {
  4728. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4729. } else {
  4730. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4731. }
  4732. return PreziPlayer;
  4733. })();
  4734. })();
  4735. module.exports = PreziPlayer;
  4736. },{}],20:[function(require,module,exports){
  4737. /* global require, $ */
  4738. var Chat = require("./chat/Chat");
  4739. var ContactList = require("./contactlist/ContactList");
  4740. var Settings = require("./../../settings/Settings");
  4741. var SettingsMenu = require("./settings/SettingsMenu");
  4742. var VideoLayout = require("../videolayout/VideoLayout");
  4743. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4744. var UIUtil = require("../util/UIUtil");
  4745. var LargeVideo = require("../videolayout/LargeVideo");
  4746. /**
  4747. * Toggler for the chat, contact list, settings menu, etc..
  4748. */
  4749. var PanelToggler = (function(my) {
  4750. var currentlyOpen = null;
  4751. var buttons = {
  4752. '#chatspace': '#chatBottomButton',
  4753. '#contactlist': '#contactListButton',
  4754. '#settingsmenu': '#settingsButton'
  4755. };
  4756. /**
  4757. * Toggles the windows in the side panel
  4758. * @param object the window that should be shown
  4759. * @param selector the selector for the element containing the panel
  4760. * @param onOpenComplete function to be called when the panel is opened
  4761. * @param onOpen function to be called if the window is going to be opened
  4762. * @param onClose function to be called if the window is going to be closed
  4763. */
  4764. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4765. UIUtil.buttonClick(buttons[selector], "active");
  4766. if (object.isVisible()) {
  4767. $("#toast-container").animate({
  4768. right: '5px'
  4769. },
  4770. {
  4771. queue: false,
  4772. duration: 500
  4773. });
  4774. $(selector).hide("slide", {
  4775. direction: "right",
  4776. queue: false,
  4777. duration: 500
  4778. });
  4779. if(typeof onClose === "function") {
  4780. onClose();
  4781. }
  4782. currentlyOpen = null;
  4783. }
  4784. else {
  4785. // Undock the toolbar when the chat is shown and if we're in a
  4786. // video mode.
  4787. if (LargeVideo.isLargeVideoVisible()) {
  4788. ToolbarToggler.dockToolbar(false);
  4789. }
  4790. if(currentlyOpen) {
  4791. var current = $(currentlyOpen);
  4792. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4793. current.css('z-index', 4);
  4794. setTimeout(function () {
  4795. current.css('display', 'none');
  4796. current.css('z-index', 5);
  4797. }, 500);
  4798. }
  4799. $("#toast-container").animate({
  4800. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4801. },
  4802. {
  4803. queue: false,
  4804. duration: 500
  4805. });
  4806. $(selector).show("slide", {
  4807. direction: "right",
  4808. queue: false,
  4809. duration: 500,
  4810. complete: onOpenComplete
  4811. });
  4812. if(typeof onOpen === "function") {
  4813. onOpen();
  4814. }
  4815. currentlyOpen = selector;
  4816. }
  4817. };
  4818. /**
  4819. * Opens / closes the chat area.
  4820. */
  4821. my.toggleChat = function() {
  4822. var chatCompleteFunction = Chat.isVisible() ?
  4823. function() {} : function () {
  4824. Chat.scrollChatToBottom();
  4825. $('#chatspace').trigger('shown');
  4826. };
  4827. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4828. toggle(Chat,
  4829. '#chatspace',
  4830. function () {
  4831. // Request the focus in the nickname field or the chat input field.
  4832. if ($('#nickname').css('visibility') === 'visible') {
  4833. $('#nickinput').focus();
  4834. } else {
  4835. $('#usermsg').focus();
  4836. }
  4837. },
  4838. null,
  4839. Chat.resizeChat,
  4840. null);
  4841. };
  4842. /**
  4843. * Opens / closes the contact list area.
  4844. */
  4845. my.toggleContactList = function () {
  4846. var completeFunction = ContactList.isVisible() ?
  4847. function() {} : function () { $('#contactlist').trigger('shown');};
  4848. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4849. toggle(ContactList,
  4850. '#contactlist',
  4851. null,
  4852. function() {
  4853. ContactList.setVisualNotification(false);
  4854. },
  4855. null);
  4856. };
  4857. /**
  4858. * Opens / closes the settings menu
  4859. */
  4860. my.toggleSettingsMenu = function() {
  4861. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4862. toggle(SettingsMenu,
  4863. '#settingsmenu',
  4864. null,
  4865. function() {
  4866. var settings = Settings.getSettings();
  4867. $('#setDisplayName').get(0).value = settings.displayName;
  4868. $('#setEmail').get(0).value = settings.email;
  4869. },
  4870. null);
  4871. };
  4872. /**
  4873. * Returns the size of the side panel.
  4874. */
  4875. my.getPanelSize = function () {
  4876. var availableHeight = window.innerHeight;
  4877. var availableWidth = window.innerWidth;
  4878. var panelWidth = 200;
  4879. if (availableWidth * 0.2 < 200) {
  4880. panelWidth = availableWidth * 0.2;
  4881. }
  4882. return [panelWidth, availableHeight];
  4883. };
  4884. my.isVisible = function() {
  4885. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4886. };
  4887. return my;
  4888. }(PanelToggler || {}));
  4889. module.exports = PanelToggler;
  4890. },{"../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){
  4891. /* global APP, $, Util, nickname:true */
  4892. var Replacement = require("./Replacement");
  4893. var CommandsProcessor = require("./Commands");
  4894. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4895. var smileys = require("./smileys.json").smileys;
  4896. var NicknameHandler = require("../../util/NicknameHandler");
  4897. var UIUtil = require("../../util/UIUtil");
  4898. var UIEvents = require("../../../../service/UI/UIEvents");
  4899. var notificationInterval = false;
  4900. var unreadMessages = 0;
  4901. /**
  4902. * Shows/hides a visual notification, indicating that a message has arrived.
  4903. */
  4904. function setVisualNotification(show) {
  4905. var unreadMsgElement = document.getElementById('unreadMessages');
  4906. var unreadMsgBottomElement
  4907. = document.getElementById('bottomUnreadMessages');
  4908. var glower = $('#chatButton');
  4909. var bottomGlower = $('#chatBottomButton');
  4910. if (unreadMessages) {
  4911. unreadMsgElement.innerHTML = unreadMessages.toString();
  4912. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4913. ToolbarToggler.dockToolbar(true);
  4914. var chatButtonElement
  4915. = document.getElementById('chatButton').parentNode;
  4916. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4917. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4918. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4919. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4920. unreadMsgElement.setAttribute(
  4921. 'style',
  4922. 'top:' + topIndent +
  4923. '; left:' + leftIndent + ';');
  4924. var chatBottomButtonElement
  4925. = document.getElementById('chatBottomButton').parentNode;
  4926. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4927. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4928. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4929. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  4930. unreadMsgBottomElement.setAttribute(
  4931. 'style',
  4932. 'top:' + bottomTopIndent +
  4933. '; left:' + bottomLeftIndent + ';');
  4934. if (!glower.hasClass('icon-chat-simple')) {
  4935. glower.removeClass('icon-chat');
  4936. glower.addClass('icon-chat-simple');
  4937. }
  4938. }
  4939. else {
  4940. unreadMsgElement.innerHTML = '';
  4941. unreadMsgBottomElement.innerHTML = '';
  4942. glower.removeClass('icon-chat-simple');
  4943. glower.addClass('icon-chat');
  4944. }
  4945. if (show && !notificationInterval) {
  4946. notificationInterval = window.setInterval(function () {
  4947. glower.toggleClass('active');
  4948. bottomGlower.toggleClass('active glowing');
  4949. }, 800);
  4950. }
  4951. else if (!show && notificationInterval) {
  4952. window.clearInterval(notificationInterval);
  4953. notificationInterval = false;
  4954. glower.removeClass('active');
  4955. bottomGlower.removeClass('glowing');
  4956. bottomGlower.addClass('active');
  4957. }
  4958. }
  4959. /**
  4960. * Returns the current time in the format it is shown to the user
  4961. * @returns {string}
  4962. */
  4963. function getCurrentTime(stamp) {
  4964. var now = (stamp? new Date(stamp): new Date());
  4965. var hour = now.getHours();
  4966. var minute = now.getMinutes();
  4967. var second = now.getSeconds();
  4968. if(hour.toString().length === 1) {
  4969. hour = '0'+hour;
  4970. }
  4971. if(minute.toString().length === 1) {
  4972. minute = '0'+minute;
  4973. }
  4974. if(second.toString().length === 1) {
  4975. second = '0'+second;
  4976. }
  4977. return hour+':'+minute+':'+second;
  4978. }
  4979. function toggleSmileys() {
  4980. var smileys = $('#smileysContainer');
  4981. if(!smileys.is(':visible')) {
  4982. smileys.show("slide", { direction: "down", duration: 300});
  4983. } else {
  4984. smileys.hide("slide", { direction: "down", duration: 300});
  4985. }
  4986. $('#usermsg').focus();
  4987. }
  4988. function addClickFunction(smiley, number) {
  4989. smiley.onclick = function addSmileyToMessage() {
  4990. var usermsg = $('#usermsg');
  4991. var message = usermsg.val();
  4992. message += smileys['smiley' + number];
  4993. usermsg.val(message);
  4994. usermsg.get(0).setSelectionRange(message.length, message.length);
  4995. toggleSmileys();
  4996. usermsg.focus();
  4997. };
  4998. }
  4999. /**
  5000. * Adds the smileys container to the chat
  5001. */
  5002. function addSmileys() {
  5003. var smileysContainer = document.createElement('div');
  5004. smileysContainer.id = 'smileysContainer';
  5005. for(var i = 1; i <= 21; i++) {
  5006. var smileyContainer = document.createElement('div');
  5007. smileyContainer.id = 'smiley' + i;
  5008. smileyContainer.className = 'smileyContainer';
  5009. var smiley = document.createElement('img');
  5010. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5011. smiley.className = 'smiley';
  5012. addClickFunction(smiley, i);
  5013. smileyContainer.appendChild(smiley);
  5014. smileysContainer.appendChild(smileyContainer);
  5015. }
  5016. $("#chatspace").append(smileysContainer);
  5017. }
  5018. /**
  5019. * Resizes the chat conversation.
  5020. */
  5021. function resizeChatConversation() {
  5022. var msgareaHeight = $('#usermsg').outerHeight();
  5023. var chatspace = $('#chatspace');
  5024. var width = chatspace.width();
  5025. var chat = $('#chatconversation');
  5026. var smileys = $('#smileysarea');
  5027. smileys.height(msgareaHeight);
  5028. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5029. $('#smileysContainer').css('bottom', msgareaHeight);
  5030. chat.width(width - 10);
  5031. chat.height(window.innerHeight - 15 - msgareaHeight);
  5032. }
  5033. /**
  5034. * Chat related user interface.
  5035. */
  5036. var Chat = (function (my) {
  5037. /**
  5038. * Initializes chat related interface.
  5039. */
  5040. my.init = function () {
  5041. if(NicknameHandler.getNickname())
  5042. Chat.setChatConversationMode(true);
  5043. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5044. function (nickname) {
  5045. Chat.setChatConversationMode(true);
  5046. });
  5047. $('#nickinput').keydown(function (event) {
  5048. if (event.keyCode === 13) {
  5049. event.preventDefault();
  5050. var val = UIUtil.escapeHtml(this.value);
  5051. this.value = '';
  5052. if (!NicknameHandler.getNickname()) {
  5053. NicknameHandler.setNickname(val);
  5054. return;
  5055. }
  5056. }
  5057. });
  5058. var usermsg = $('#usermsg');
  5059. usermsg.keydown(function (event) {
  5060. if (event.keyCode === 13) {
  5061. event.preventDefault();
  5062. var value = this.value;
  5063. usermsg.val('').trigger('autosize.resize');
  5064. this.focus();
  5065. var command = new CommandsProcessor(value);
  5066. if(command.isCommand()) {
  5067. command.processCommand();
  5068. }
  5069. else {
  5070. var message = UIUtil.escapeHtml(value);
  5071. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5072. }
  5073. }
  5074. });
  5075. var onTextAreaResize = function () {
  5076. resizeChatConversation();
  5077. Chat.scrollChatToBottom();
  5078. };
  5079. usermsg.autosize({callback: onTextAreaResize});
  5080. $("#chatspace").bind("shown",
  5081. function () {
  5082. unreadMessages = 0;
  5083. setVisualNotification(false);
  5084. });
  5085. addSmileys();
  5086. };
  5087. /**
  5088. * Appends the given message to the chat conversation.
  5089. */
  5090. my.updateChatConversation =
  5091. function (from, displayName, message, myjid, stamp) {
  5092. var divClassName = '';
  5093. if (APP.xmpp.myJid() === from) {
  5094. divClassName = "localuser";
  5095. }
  5096. else {
  5097. divClassName = "remoteuser";
  5098. if (!Chat.isVisible()) {
  5099. unreadMessages++;
  5100. UIUtil.playSoundNotification('chatNotification');
  5101. setVisualNotification(true);
  5102. }
  5103. }
  5104. // replace links and smileys
  5105. // Strophe already escapes special symbols on sending,
  5106. // so we escape here only tags to avoid double &amp;
  5107. var escMessage = message.replace(/</g, '&lt;').
  5108. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5109. var escDisplayName = UIUtil.escapeHtml(displayName);
  5110. message = Replacement.processReplacements(escMessage);
  5111. var messageContainer =
  5112. '<div class="chatmessage">'+
  5113. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5114. '<div class="username ' + divClassName +'">' + escDisplayName +
  5115. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5116. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5117. '</div>';
  5118. $('#chatconversation').append(messageContainer);
  5119. $('#chatconversation').animate(
  5120. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5121. };
  5122. /**
  5123. * Appends error message to the conversation
  5124. * @param errorMessage the received error message.
  5125. * @param originalText the original message.
  5126. */
  5127. my.chatAddError = function(errorMessage, originalText) {
  5128. errorMessage = UIUtil.escapeHtml(errorMessage);
  5129. originalText = UIUtil.escapeHtml(originalText);
  5130. $('#chatconversation').append(
  5131. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5132. (originalText? (' \"'+ originalText + '\"') : "") +
  5133. ' was not sent.' +
  5134. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5135. $('#chatconversation').animate(
  5136. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5137. };
  5138. /**
  5139. * Sets the subject to the UI
  5140. * @param subject the subject
  5141. */
  5142. my.chatSetSubject = function(subject) {
  5143. if (subject)
  5144. subject = subject.trim();
  5145. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5146. if(subject === "") {
  5147. $("#subject").css({display: "none"});
  5148. }
  5149. else {
  5150. $("#subject").css({display: "block"});
  5151. }
  5152. };
  5153. /**
  5154. * Sets the chat conversation mode.
  5155. */
  5156. my.setChatConversationMode = function (isConversationMode) {
  5157. if (isConversationMode) {
  5158. $('#nickname').css({visibility: 'hidden'});
  5159. $('#chatconversation').css({visibility: 'visible'});
  5160. $('#usermsg').css({visibility: 'visible'});
  5161. $('#smileysarea').css({visibility: 'visible'});
  5162. $('#usermsg').focus();
  5163. }
  5164. };
  5165. /**
  5166. * Resizes the chat area.
  5167. */
  5168. my.resizeChat = function () {
  5169. var chatSize = require("../SidePanelToggler").getPanelSize();
  5170. $('#chatspace').width(chatSize[0]);
  5171. $('#chatspace').height(chatSize[1]);
  5172. resizeChatConversation();
  5173. };
  5174. /**
  5175. * Indicates if the chat is currently visible.
  5176. */
  5177. my.isVisible = function () {
  5178. return $('#chatspace').is(":visible");
  5179. };
  5180. /**
  5181. * Shows and hides the window with the smileys
  5182. */
  5183. my.toggleSmileys = toggleSmileys;
  5184. /**
  5185. * Scrolls chat to the bottom.
  5186. */
  5187. my.scrollChatToBottom = function() {
  5188. setTimeout(function () {
  5189. $('#chatconversation').scrollTop(
  5190. $('#chatconversation')[0].scrollHeight);
  5191. }, 5);
  5192. };
  5193. return my;
  5194. }(Chat || {}));
  5195. module.exports = Chat;
  5196. },{"../../../../service/UI/UIEvents":104,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5197. /* global APP, require */
  5198. var UIUtil = require("../../util/UIUtil");
  5199. /**
  5200. * List with supported commands. The keys are the names of the commands and
  5201. * the value is the function that processes the message.
  5202. * @type {{String: function}}
  5203. */
  5204. var commands = {
  5205. "topic" : processTopic
  5206. };
  5207. /**
  5208. * Extracts the command from the message.
  5209. * @param message the received message
  5210. * @returns {string} the command
  5211. */
  5212. function getCommand(message) {
  5213. if(message) {
  5214. for(var command in commands) {
  5215. if(message.indexOf("/" + command) == 0)
  5216. return command;
  5217. }
  5218. }
  5219. return "";
  5220. }
  5221. /**
  5222. * Processes the data for topic command.
  5223. * @param commandArguments the arguments of the topic command.
  5224. */
  5225. function processTopic(commandArguments) {
  5226. var topic = UIUtil.escapeHtml(commandArguments);
  5227. APP.xmpp.setSubject(topic);
  5228. }
  5229. /**
  5230. * Constructs a new CommandProccessor instance from a message that
  5231. * handles commands received via chat messages.
  5232. * @param message the message
  5233. * @constructor
  5234. */
  5235. function CommandsProcessor(message) {
  5236. var command = getCommand(message);
  5237. /**
  5238. * Returns the name of the command.
  5239. * @returns {String} the command
  5240. */
  5241. this.getCommand = function() {
  5242. return command;
  5243. };
  5244. var messageArgument = message.substr(command.length + 2);
  5245. /**
  5246. * Returns the arguments of the command.
  5247. * @returns {string}
  5248. */
  5249. this.getArgument = function() {
  5250. return messageArgument;
  5251. };
  5252. }
  5253. /**
  5254. * Checks whether this instance is valid command or not.
  5255. * @returns {boolean}
  5256. */
  5257. CommandsProcessor.prototype.isCommand = function() {
  5258. if (this.getCommand())
  5259. return true;
  5260. return false;
  5261. };
  5262. /**
  5263. * Processes the command.
  5264. */
  5265. CommandsProcessor.prototype.processCommand = function() {
  5266. if(!this.isCommand())
  5267. return;
  5268. commands[this.getCommand()](this.getArgument());
  5269. };
  5270. module.exports = CommandsProcessor;
  5271. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5272. var Smileys = require("./smileys.json");
  5273. /**
  5274. * Processes links and smileys in "body"
  5275. */
  5276. function processReplacements(body)
  5277. {
  5278. //make links clickable
  5279. body = linkify(body);
  5280. //add smileys
  5281. body = smilify(body);
  5282. return body;
  5283. }
  5284. /**
  5285. * Finds and replaces all links in the links in "body"
  5286. * with their <a href=""></a>
  5287. */
  5288. function linkify(inputText)
  5289. {
  5290. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5291. //URLs starting with http://, https://, or ftp://
  5292. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5293. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5294. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5295. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5296. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5297. //Change email addresses to mailto:: links.
  5298. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5299. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5300. return replacedText;
  5301. }
  5302. /**
  5303. * Replaces common smiley strings with images
  5304. */
  5305. function smilify(body)
  5306. {
  5307. if(!body) {
  5308. return body;
  5309. }
  5310. var regexs = Smileys["regexs"];
  5311. for(var smiley in regexs) {
  5312. if(regexs.hasOwnProperty(smiley)) {
  5313. body = body.replace(regexs[smiley],
  5314. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5315. }
  5316. }
  5317. return body;
  5318. }
  5319. module.exports = {
  5320. processReplacements: processReplacements,
  5321. linkify: linkify
  5322. };
  5323. },{"./smileys.json":24}],24:[function(require,module,exports){
  5324. module.exports={
  5325. "smileys": {
  5326. "smiley1": ":)",
  5327. "smiley2": ":(",
  5328. "smiley3": ":D",
  5329. "smiley4": "(y)",
  5330. "smiley5": " :P",
  5331. "smiley6": "(wave)",
  5332. "smiley7": "(blush)",
  5333. "smiley8": "(chuckle)",
  5334. "smiley9": "(shocked)",
  5335. "smiley10": ":*",
  5336. "smiley11": "(n)",
  5337. "smiley12": "(search)",
  5338. "smiley13": " <3",
  5339. "smiley14": "(oops)",
  5340. "smiley15": "(angry)",
  5341. "smiley16": "(angel)",
  5342. "smiley17": "(sick)",
  5343. "smiley18": ";(",
  5344. "smiley19": "(bomb)",
  5345. "smiley20": "(clap)",
  5346. "smiley21": " ;)"
  5347. },
  5348. "regexs": {
  5349. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5350. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5351. "smiley1": /(:-\)|:\))/gi,
  5352. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5353. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5354. "smiley6": /(\(wave\))/gi,
  5355. "smiley7": /(\(blush\))/gi,
  5356. "smiley8": /(\(chuckle\))/gi,
  5357. "smiley9": /(:-0|\(shocked\))/gi,
  5358. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5359. "smiley11": /(\(n\))/gi,
  5360. "smiley12": /(\(search\))/g,
  5361. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5362. "smiley14": /(\(oops\))/gi,
  5363. "smiley15": /(\(angry\))/gi,
  5364. "smiley16": /(\(angel\))/gi,
  5365. "smiley17": /(\(sick\))/gi,
  5366. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5367. "smiley19": /(\(bomb\))/gi,
  5368. "smiley20": /(\(clap\))/gi,
  5369. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5370. }
  5371. }
  5372. },{}],25:[function(require,module,exports){
  5373. /* global $, APP, Strophe */
  5374. var Avatar = require('../../avatar/Avatar');
  5375. var numberOfContacts = 0;
  5376. var notificationInterval;
  5377. /**
  5378. * Updates the number of participants in the contact list button and sets
  5379. * the glow
  5380. * @param delta indicates whether a new user has joined (1) or someone has
  5381. * left(-1)
  5382. */
  5383. function updateNumberOfParticipants(delta) {
  5384. numberOfContacts += delta;
  5385. if (numberOfContacts === 1) {
  5386. // when the user is alone we don't show the number of participants
  5387. $("#numberOfParticipants").text('');
  5388. ContactList.setVisualNotification(false);
  5389. } else if (numberOfContacts > 1) {
  5390. ContactList.setVisualNotification(!ContactList.isVisible());
  5391. $("#numberOfParticipants").text(numberOfContacts);
  5392. } else {
  5393. console.error("Invalid number of participants: " + numberOfContacts);
  5394. }
  5395. }
  5396. /**
  5397. * Creates the avatar element.
  5398. *
  5399. * @return {object} the newly created avatar element
  5400. */
  5401. function createAvatar(jid) {
  5402. var avatar = document.createElement('img');
  5403. avatar.className = "icon-avatar avatar";
  5404. avatar.src = Avatar.getContactListUrl(jid);
  5405. return avatar;
  5406. }
  5407. /**
  5408. * Creates the display name paragraph.
  5409. *
  5410. * @param displayName the display name to set
  5411. */
  5412. function createDisplayNameParagraph(key, displayName) {
  5413. var p = document.createElement('p');
  5414. if(displayName)
  5415. p.innerText = displayName;
  5416. else if(key) {
  5417. p.setAttribute("data-i18n",key);
  5418. p.innerText = APP.translation.translateString(key);
  5419. }
  5420. return p;
  5421. }
  5422. function stopGlowing(glower) {
  5423. window.clearInterval(notificationInterval);
  5424. notificationInterval = false;
  5425. glower.removeClass('glowing');
  5426. if (!ContactList.isVisible()) {
  5427. glower.removeClass('active');
  5428. }
  5429. }
  5430. /**
  5431. * Contact list.
  5432. */
  5433. var ContactList = {
  5434. /**
  5435. * Indicates if the chat is currently visible.
  5436. *
  5437. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5438. * otherwise
  5439. */
  5440. isVisible: function () {
  5441. return $('#contactlist').is(":visible");
  5442. },
  5443. /**
  5444. * Adds a contact for the given peerJid if such doesn't yet exist.
  5445. *
  5446. * @param peerJid the peerJid corresponding to the contact
  5447. */
  5448. ensureAddContact: function (peerJid) {
  5449. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5450. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5451. if (!contact || contact.length <= 0)
  5452. ContactList.addContact(peerJid);
  5453. },
  5454. /**
  5455. * Adds a contact for the given peer jid.
  5456. *
  5457. * @param peerJid the jid of the contact to add
  5458. */
  5459. addContact: function (peerJid) {
  5460. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5461. var contactlist = $('#contacts');
  5462. var newContact = document.createElement('li');
  5463. newContact.id = resourceJid;
  5464. newContact.className = "clickable";
  5465. newContact.onclick = function (event) {
  5466. if (event.currentTarget.className === "clickable") {
  5467. $(ContactList).trigger('contactclicked', [peerJid]);
  5468. }
  5469. };
  5470. newContact.appendChild(createAvatar(peerJid));
  5471. newContact.appendChild(createDisplayNameParagraph("participant"));
  5472. if (resourceJid === APP.xmpp.myResource()) {
  5473. contactlist.prepend(newContact);
  5474. }
  5475. else {
  5476. contactlist.append(newContact);
  5477. }
  5478. updateNumberOfParticipants(1);
  5479. },
  5480. /**
  5481. * Removes a contact for the given peer jid.
  5482. *
  5483. * @param peerJid the peerJid corresponding to the contact to remove
  5484. */
  5485. removeContact: function (peerJid) {
  5486. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5487. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5488. if (contact && contact.length > 0) {
  5489. var contactlist = $('#contactlist>ul');
  5490. contactlist.get(0).removeChild(contact.get(0));
  5491. updateNumberOfParticipants(-1);
  5492. }
  5493. },
  5494. setVisualNotification: function (show, stopGlowingIn) {
  5495. var glower = $('#contactListButton');
  5496. if (show && !notificationInterval) {
  5497. notificationInterval = window.setInterval(function () {
  5498. glower.toggleClass('active glowing');
  5499. }, 800);
  5500. }
  5501. else if (!show && notificationInterval) {
  5502. stopGlowing(glower);
  5503. }
  5504. if (stopGlowingIn) {
  5505. setTimeout(function () {
  5506. stopGlowing(glower);
  5507. }, stopGlowingIn);
  5508. }
  5509. },
  5510. setClickable: function (resourceJid, isClickable) {
  5511. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5512. if (isClickable) {
  5513. contact.addClass('clickable');
  5514. } else {
  5515. contact.removeClass('clickable');
  5516. }
  5517. },
  5518. onDisplayNameChange: function (peerJid, displayName) {
  5519. if (peerJid === 'localVideoContainer')
  5520. peerJid = APP.xmpp.myJid();
  5521. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5522. var contactName = $('#contacts #' + resourceJid + '>p');
  5523. if (contactName && displayName && displayName.length > 0)
  5524. contactName.html(displayName);
  5525. },
  5526. userAvatarChanged: function (resourceJid, contactListUrl) {
  5527. // set the avatar in the contact list
  5528. var contact = $('#' + resourceJid + '>img');
  5529. if (contact && contact.length > 0) {
  5530. contact.get(0).src = contactListUrl;
  5531. }
  5532. }
  5533. };
  5534. module.exports = ContactList;
  5535. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5536. /* global APP, $ */
  5537. var Avatar = require("../../avatar/Avatar");
  5538. var Settings = require("./../../../settings/Settings");
  5539. var UIUtil = require("../../util/UIUtil");
  5540. var languages = require("../../../../service/translation/languages");
  5541. function generateLanguagesSelectBox() {
  5542. var currentLang = APP.translation.getCurrentLanguage();
  5543. var html = "<select id=\"languages_selectbox\">";
  5544. var langArray = languages.getLanguages();
  5545. for(var i = 0; i < langArray.length; i++) {
  5546. var lang = langArray[i];
  5547. html += "<option ";
  5548. if(lang === currentLang)
  5549. html += "selected ";
  5550. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5551. html += "</option>";
  5552. }
  5553. return html + "</select>";
  5554. }
  5555. var SettingsMenu = {
  5556. init: function () {
  5557. var startMutedSelector = $("#startMutedOptions");
  5558. startMutedSelector.before(generateLanguagesSelectBox());
  5559. APP.translation.translateElement($("#languages_selectbox"));
  5560. $('#settingsmenu>input').keyup(function(event){
  5561. if(event.keyCode === 13) {//enter
  5562. SettingsMenu.update();
  5563. }
  5564. });
  5565. if (APP.xmpp.isModerator()) {
  5566. startMutedSelector.css("display", "block");
  5567. }
  5568. else {
  5569. startMutedSelector.css("display", "none");
  5570. }
  5571. $("#updateSettings").click(function () {
  5572. SettingsMenu.update();
  5573. });
  5574. },
  5575. onRoleChanged: function () {
  5576. if(APP.xmpp.isModerator()) {
  5577. $("#startMutedOptions").css("display", "block");
  5578. }
  5579. else {
  5580. $("#startMutedOptions").css("display", "none");
  5581. }
  5582. },
  5583. setStartMuted: function (audio, video) {
  5584. $("#startAudioMuted").attr("checked", audio);
  5585. $("#startVideoMuted").attr("checked", video);
  5586. },
  5587. update: function() {
  5588. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5589. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5590. if(newDisplayName) {
  5591. var displayName = Settings.setDisplayName(newDisplayName);
  5592. APP.xmpp.addToPresence("displayName", displayName, true);
  5593. }
  5594. var language = $("#languages_selectbox").val();
  5595. APP.translation.setLanguage(language);
  5596. Settings.setLanguage(language);
  5597. APP.xmpp.addToPresence("email", newEmail);
  5598. var email = Settings.setEmail(newEmail);
  5599. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5600. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5601. APP.xmpp.addToPresence("startMuted",
  5602. [startAudioMuted, startVideoMuted]);
  5603. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5604. },
  5605. isVisible: function() {
  5606. return $('#settingsmenu').is(':visible');
  5607. },
  5608. setDisplayName: function(newDisplayName) {
  5609. var displayName = Settings.setDisplayName(newDisplayName);
  5610. $('#setDisplayName').get(0).value = displayName;
  5611. },
  5612. onDisplayNameChange: function(peerJid, newDisplayName) {
  5613. if(peerJid === 'localVideoContainer' ||
  5614. peerJid === APP.xmpp.myJid()) {
  5615. this.setDisplayName(newDisplayName);
  5616. }
  5617. },
  5618. changeAvatar: function (thumbUrl) {
  5619. $('#avatar').get(0).src = thumbUrl;
  5620. }
  5621. };
  5622. module.exports = SettingsMenu;
  5623. },{"../../../../service/translation/languages":109,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5624. /* global $ */
  5625. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5626. var buttonHandlers = {
  5627. "bottom_toolbar_contact_list": function () {
  5628. BottomToolbar.toggleContactList();
  5629. },
  5630. "bottom_toolbar_film_strip": function () {
  5631. BottomToolbar.toggleFilmStrip();
  5632. },
  5633. "bottom_toolbar_chat": function () {
  5634. BottomToolbar.toggleChat();
  5635. }
  5636. };
  5637. var BottomToolbar = (function (my) {
  5638. my.init = function () {
  5639. for(var k in buttonHandlers)
  5640. $("#" + k).click(buttonHandlers[k]);
  5641. };
  5642. my.toggleChat = function() {
  5643. PanelToggler.toggleChat();
  5644. };
  5645. my.toggleContactList = function() {
  5646. PanelToggler.toggleContactList();
  5647. };
  5648. my.toggleFilmStrip = function() {
  5649. var filmstrip = $("#remoteVideos");
  5650. filmstrip.toggleClass("hidden");
  5651. };
  5652. $(document).bind("remotevideo.resized", function (event, width, height) {
  5653. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5654. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5655. });
  5656. return my;
  5657. }(BottomToolbar || {}));
  5658. module.exports = BottomToolbar;
  5659. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5660. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5661. Util */
  5662. var messageHandler = require("../util/MessageHandler");
  5663. var BottomToolbar = require("./BottomToolbar");
  5664. var Prezi = require("../prezi/Prezi");
  5665. var Etherpad = require("../etherpad/Etherpad");
  5666. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5667. var Authentication = require("../authentication/Authentication");
  5668. var UIUtil = require("../util/UIUtil");
  5669. var AuthenticationEvents
  5670. = require("../../../service/authentication/AuthenticationEvents");
  5671. var roomUrl = null;
  5672. var sharedKey = '';
  5673. var UI = null;
  5674. var recordingToaster = null;
  5675. var buttonHandlers = {
  5676. "toolbar_button_mute": function () {
  5677. return APP.UI.toggleAudio();
  5678. },
  5679. "toolbar_button_camera": function () {
  5680. return APP.UI.toggleVideo();
  5681. },
  5682. /*"toolbar_button_authentication": function () {
  5683. return Toolbar.authenticateClicked();
  5684. },*/
  5685. "toolbar_button_record": function () {
  5686. return toggleRecording();
  5687. },
  5688. "toolbar_button_security": function () {
  5689. return Toolbar.openLockDialog();
  5690. },
  5691. "toolbar_button_link": function () {
  5692. return Toolbar.openLinkDialog();
  5693. },
  5694. "toolbar_button_chat": function () {
  5695. return BottomToolbar.toggleChat();
  5696. },
  5697. "toolbar_button_prezi": function () {
  5698. return Prezi.openPreziDialog();
  5699. },
  5700. "toolbar_button_etherpad": function () {
  5701. return Etherpad.toggleEtherpad(0);
  5702. },
  5703. "toolbar_button_desktopsharing": function () {
  5704. return APP.desktopsharing.toggleScreenSharing();
  5705. },
  5706. "toolbar_button_fullScreen": function() {
  5707. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  5708. return Toolbar.toggleFullScreen();
  5709. },
  5710. "toolbar_button_sip": function () {
  5711. return callSipButtonClicked();
  5712. },
  5713. "toolbar_button_dialpad": function () {
  5714. return dialpadButtonClicked();
  5715. },
  5716. "toolbar_button_settings": function () {
  5717. PanelToggler.toggleSettingsMenu();
  5718. },
  5719. "toolbar_button_hangup": function () {
  5720. return hangup();
  5721. },
  5722. "toolbar_button_login": function () {
  5723. Toolbar.authenticateClicked();
  5724. },
  5725. "toolbar_button_logout": function () {
  5726. // Ask for confirmation
  5727. messageHandler.openTwoButtonDialog(
  5728. "dialog.logoutTitle",
  5729. null,
  5730. "dialog.logoutQuestion",
  5731. null,
  5732. false,
  5733. "dialog.Yes",
  5734. function (evt, yes) {
  5735. if (yes) {
  5736. APP.xmpp.logout(function (url) {
  5737. if (url) {
  5738. window.location.href = url;
  5739. } else {
  5740. hangup();
  5741. }
  5742. });
  5743. }
  5744. });
  5745. }
  5746. };
  5747. function hangup() {
  5748. APP.xmpp.disposeConference();
  5749. if(config.enableWelcomePage) {
  5750. setTimeout(function() {
  5751. window.localStorage.welcomePageDisabled = false;
  5752. window.location.pathname = "/";
  5753. }, 10000);
  5754. }
  5755. var title = APP.translation.generateTranslationHTML(
  5756. "dialog.sessTerminated");
  5757. var msg = APP.translation.generateTranslationHTML(
  5758. "dialog.hungUp");
  5759. var button = APP.translation.generateTranslationHTML(
  5760. "dialog.joinAgain");
  5761. var buttons = [];
  5762. buttons.push({title: button, value: true});
  5763. UI.messageHandler.openDialog(
  5764. title,
  5765. msg,
  5766. true,
  5767. buttons,
  5768. function(event, value, message, formVals) {
  5769. window.location.reload();
  5770. return false;
  5771. }
  5772. );
  5773. }
  5774. /**
  5775. * Starts or stops the recording for the conference.
  5776. */
  5777. function toggleRecording(predefinedToken) {
  5778. APP.xmpp.toggleRecording(function (callback) {
  5779. if (predefinedToken) {
  5780. callback(UIUtil.escapeHtml(predefinedToken));
  5781. return;
  5782. }
  5783. var msg = APP.translation.generateTranslationHTML(
  5784. "dialog.recordingToken");
  5785. var token = APP.translation.translateString("dialog.token");
  5786. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5787. '<h2>' + msg + '</h2>' +
  5788. '<input name="recordingToken" type="text" ' +
  5789. ' data-i18n="[placeholder]dialog.token" ' +
  5790. 'placeholder="' + token + '" autofocus>',
  5791. false,
  5792. "dialog.Save",
  5793. function (e, v, m, f) {
  5794. if (v) {
  5795. var token = f.recordingToken;
  5796. if (token) {
  5797. callback(UIUtil.escapeHtml(token));
  5798. }
  5799. }
  5800. },
  5801. null,
  5802. function () { },
  5803. ':input:first'
  5804. );
  5805. }, Toolbar.setRecordingButtonState);
  5806. }
  5807. /**
  5808. * Locks / unlocks the room.
  5809. */
  5810. function lockRoom(lock) {
  5811. var currentSharedKey = '';
  5812. if (lock)
  5813. currentSharedKey = sharedKey;
  5814. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5815. // password is required
  5816. if (sharedKey) {
  5817. console.log('set room password');
  5818. Toolbar.lockLockButton();
  5819. }
  5820. else {
  5821. console.log('removed room password');
  5822. Toolbar.unlockLockButton();
  5823. }
  5824. }, function (err) {
  5825. console.warn('setting password failed', err);
  5826. messageHandler.showError("dialog.lockTitle",
  5827. "dialog.lockMessage");
  5828. Toolbar.setSharedKey('');
  5829. }, function () {
  5830. console.warn('room passwords not supported');
  5831. messageHandler.showError("dialog.warning",
  5832. "dialog.passwordNotSupported");
  5833. Toolbar.setSharedKey('');
  5834. });
  5835. }
  5836. /**
  5837. * Invite participants to conference.
  5838. */
  5839. function inviteParticipants() {
  5840. if (roomUrl === null)
  5841. return;
  5842. var sharedKeyText = "";
  5843. if (sharedKey && sharedKey.length > 0) {
  5844. sharedKeyText =
  5845. APP.translation.translateString("email.sharedKey",
  5846. {sharedKey: sharedKey});
  5847. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5848. }
  5849. var supportedBrowsers = "Chromium, Google Chrome " +
  5850. APP.translation.translateString("email.and") + " Opera";
  5851. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5852. var subject = APP.translation.translateString("email.subject",
  5853. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5854. var body = APP.translation.translateString("email.body",
  5855. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5856. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5857. body = body.replace(/\n/g, "%0D%0A");
  5858. if (window.localStorage.displayname) {
  5859. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5860. }
  5861. if (interfaceConfig.INVITATION_POWERED_BY) {
  5862. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5863. }
  5864. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5865. }
  5866. function dialpadButtonClicked() {
  5867. //TODO show the dialpad box
  5868. }
  5869. function callSipButtonClicked() {
  5870. var defaultNumber
  5871. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5872. var sipMsg = APP.translation.generateTranslationHTML(
  5873. "dialog.sipMsg");
  5874. messageHandler.openTwoButtonDialog(null, null, null,
  5875. '<h2>' + sipMsg + '</h2>' +
  5876. '<input name="sipNumber" type="text"' +
  5877. ' value="' + defaultNumber + '" autofocus>',
  5878. false,
  5879. "dialog.Dial",
  5880. function (e, v, m, f) {
  5881. if (v) {
  5882. var numberInput = f.sipNumber;
  5883. if (numberInput) {
  5884. APP.xmpp.dial(
  5885. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5886. }
  5887. }
  5888. },
  5889. null, null, ':input:first'
  5890. );
  5891. }
  5892. var Toolbar = (function (my) {
  5893. my.init = function (ui) {
  5894. for(var k in buttonHandlers)
  5895. $("#" + k).click(buttonHandlers[k]);
  5896. UI = ui;
  5897. // Update login info
  5898. APP.xmpp.addListener(
  5899. AuthenticationEvents.IDENTITY_UPDATED,
  5900. function (authenticationEnabled, userIdentity) {
  5901. var loggedIn = false;
  5902. if (userIdentity) {
  5903. loggedIn = true;
  5904. }
  5905. Toolbar.showAuthenticateButton(authenticationEnabled);
  5906. if (authenticationEnabled) {
  5907. Toolbar.setAuthenticatedIdentity(userIdentity);
  5908. Toolbar.showLoginButton(!loggedIn);
  5909. Toolbar.showLogoutButton(loggedIn);
  5910. }
  5911. }
  5912. );
  5913. };
  5914. /**
  5915. * Sets shared key
  5916. * @param sKey the shared key
  5917. */
  5918. my.setSharedKey = function (sKey) {
  5919. sharedKey = sKey;
  5920. };
  5921. my.authenticateClicked = function () {
  5922. Authentication.focusAuthenticationWindow();
  5923. if (!APP.xmpp.isExternalAuthEnabled()) {
  5924. Authentication.xmppAuthenticate();
  5925. return;
  5926. }
  5927. // Get authentication URL
  5928. if (!APP.xmpp.isMUCJoined()) {
  5929. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  5930. // If conference has not been started yet - redirect to login page
  5931. window.location.href = url;
  5932. });
  5933. } else {
  5934. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  5935. // Otherwise - open popup with authentication URL
  5936. var authenticationWindow = Authentication.createAuthenticationWindow(
  5937. function () {
  5938. // On popup closed - retry room allocation
  5939. APP.xmpp.allocateConferenceFocus(
  5940. APP.UI.getRoomName(),
  5941. function () { console.info("AUTH DONE"); }
  5942. );
  5943. }, url);
  5944. if (!authenticationWindow) {
  5945. messageHandler.openMessageDialog(
  5946. null, "dialog.popupError");
  5947. }
  5948. });
  5949. }
  5950. };
  5951. /**
  5952. * Updates the room invite url.
  5953. */
  5954. my.updateRoomUrl = function (newRoomUrl) {
  5955. roomUrl = newRoomUrl;
  5956. // If the invite dialog has been already opened we update the information.
  5957. var inviteLink = document.getElementById('inviteLinkRef');
  5958. if (inviteLink) {
  5959. inviteLink.value = roomUrl;
  5960. inviteLink.select();
  5961. $('#inviteLinkRef').parent()
  5962. .find('button[value=true]').prop('disabled', false);
  5963. }
  5964. };
  5965. /**
  5966. * Disables and enables some of the buttons.
  5967. */
  5968. my.setupButtonsFromConfig = function () {
  5969. if (config.disablePrezi) {
  5970. $("#prezi_button").css({display: "none"});
  5971. }
  5972. };
  5973. /**
  5974. * Opens the lock room dialog.
  5975. */
  5976. my.openLockDialog = function () {
  5977. // Only the focus is able to set a shared key.
  5978. if (!APP.xmpp.isModerator()) {
  5979. if (sharedKey) {
  5980. messageHandler.openMessageDialog(null,
  5981. "dialog.passwordError");
  5982. } else {
  5983. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  5984. }
  5985. } else {
  5986. if (sharedKey) {
  5987. messageHandler.openTwoButtonDialog(null, null,
  5988. "dialog.passwordCheck",
  5989. null,
  5990. false,
  5991. "dialog.Remove",
  5992. function (e, v) {
  5993. if (v) {
  5994. Toolbar.setSharedKey('');
  5995. lockRoom(false);
  5996. }
  5997. });
  5998. } else {
  5999. var msg = APP.translation.generateTranslationHTML(
  6000. "dialog.passwordMsg");
  6001. var yourPassword = APP.translation.translateString(
  6002. "dialog.yourPassword");
  6003. messageHandler.openTwoButtonDialog(null, null, null,
  6004. '<h2>' + msg + '</h2>' +
  6005. '<input name="lockKey" type="text"' +
  6006. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6007. 'placeholder="' + yourPassword + '" autofocus>',
  6008. false,
  6009. "dialog.Save",
  6010. function (e, v, m, f) {
  6011. if (v) {
  6012. var lockKey = f.lockKey;
  6013. if (lockKey) {
  6014. Toolbar.setSharedKey(
  6015. UIUtil.escapeHtml(lockKey));
  6016. lockRoom(true);
  6017. }
  6018. }
  6019. },
  6020. null, null, 'input:first'
  6021. );
  6022. }
  6023. }
  6024. };
  6025. /**
  6026. * Opens the invite link dialog.
  6027. */
  6028. my.openLinkDialog = function () {
  6029. var inviteAttreibutes;
  6030. if (roomUrl === null) {
  6031. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6032. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6033. } else {
  6034. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6035. }
  6036. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6037. null, null,
  6038. '<input id="inviteLinkRef" type="text" ' +
  6039. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6040. false,
  6041. "dialog.Invite",
  6042. function (e, v) {
  6043. if (v) {
  6044. if (roomUrl) {
  6045. inviteParticipants();
  6046. }
  6047. }
  6048. },
  6049. function (event) {
  6050. if (roomUrl) {
  6051. document.getElementById('inviteLinkRef').select();
  6052. } else {
  6053. if (event && event.target)
  6054. $(event.target)
  6055. .find('button[value=true]').prop('disabled', true);
  6056. }
  6057. }
  6058. );
  6059. };
  6060. /**
  6061. * Opens the settings dialog.
  6062. * FIXME: not used ?
  6063. */
  6064. my.openSettingsDialog = function () {
  6065. var settings1 = APP.translation.generateTranslationHTML(
  6066. "dialog.settings1");
  6067. var settings2 = APP.translation.generateTranslationHTML(
  6068. "dialog.settings2");
  6069. var settings3 = APP.translation.generateTranslationHTML(
  6070. "dialog.settings3");
  6071. var yourPassword = APP.translation.translateString(
  6072. "dialog.yourPassword");
  6073. messageHandler.openTwoButtonDialog(null,
  6074. '<h2>' + settings1 + '</h2>' +
  6075. '<input type="checkbox" id="initMuted">' +
  6076. settings2 + '<br/>' +
  6077. '<input type="checkbox" id="requireNicknames">' +
  6078. settings3 +
  6079. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6080. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6081. null,
  6082. null,
  6083. false,
  6084. "dialog.Save",
  6085. function () {
  6086. document.getElementById('lockKey').focus();
  6087. },
  6088. function (e, v) {
  6089. if (v) {
  6090. if ($('#initMuted').is(":checked")) {
  6091. // it is checked
  6092. }
  6093. if ($('#requireNicknames').is(":checked")) {
  6094. // it is checked
  6095. }
  6096. /*
  6097. var lockKey = document.getElementById('lockKey');
  6098. if (lockKey.value) {
  6099. setSharedKey(lockKey.value);
  6100. lockRoom(true);
  6101. }
  6102. */
  6103. }
  6104. }
  6105. );
  6106. };
  6107. /**
  6108. * Toggles the application in and out of full screen mode
  6109. * (a.k.a. presentation mode in Chrome).
  6110. */
  6111. my.toggleFullScreen = function () {
  6112. var fsElement = document.documentElement;
  6113. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6114. //Enter Full Screen
  6115. if (fsElement.mozRequestFullScreen) {
  6116. fsElement.mozRequestFullScreen();
  6117. }
  6118. else {
  6119. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6120. }
  6121. } else {
  6122. //Exit Full Screen
  6123. if (document.mozCancelFullScreen) {
  6124. document.mozCancelFullScreen();
  6125. } else {
  6126. document.webkitCancelFullScreen();
  6127. }
  6128. }
  6129. };
  6130. /**
  6131. * Unlocks the lock button state.
  6132. */
  6133. my.unlockLockButton = function () {
  6134. if ($("#lockIcon").hasClass("icon-security-locked"))
  6135. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6136. };
  6137. /**
  6138. * Updates the lock button state to locked.
  6139. */
  6140. my.lockLockButton = function () {
  6141. if ($("#lockIcon").hasClass("icon-security"))
  6142. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6143. };
  6144. /**
  6145. * Shows or hides authentication button
  6146. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6147. */
  6148. my.showAuthenticateButton = function (show) {
  6149. if (show) {
  6150. $('#authentication').css({display: "inline"});
  6151. }
  6152. else {
  6153. $('#authentication').css({display: "none"});
  6154. }
  6155. };
  6156. // Shows or hides the 'recording' button.
  6157. my.showRecordingButton = function (show) {
  6158. if (!config.enableRecording) {
  6159. return;
  6160. }
  6161. if (show) {
  6162. $('#recording').css({display: "inline"});
  6163. }
  6164. else {
  6165. $('#recording').css({display: "none"});
  6166. }
  6167. };
  6168. // Sets the state of the recording button
  6169. my.setRecordingButtonState = function (recordingState) {
  6170. var selector = $('#recordButton');
  6171. if (recordingState === 'on') {
  6172. selector.removeClass("icon-recEnable");
  6173. selector.addClass("icon-recEnable active");
  6174. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6175. var recordOnKey = "recording.on";
  6176. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6177. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6178. setTimeout(function(){
  6179. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6180. $('#videoConnectionMessage').css({display: "none"});
  6181. }, 1500);
  6182. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6183. null, null, {timeOut: 0, closeButton: null, tapToDismiss: false});
  6184. } else if (recordingState === 'off') {
  6185. selector.removeClass("icon-recEnable active");
  6186. selector.addClass("icon-recEnable");
  6187. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6188. $('#videoConnectionMessage').css({display: "none"});
  6189. if (recordingToaster)
  6190. messageHandler.remove(recordingToaster);
  6191. } else if (recordingState === 'pending') {
  6192. selector.removeClass("icon-recEnable active");
  6193. selector.addClass("icon-recEnable");
  6194. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6195. var recordPendingKey = "recording.pending";
  6196. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6197. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6198. $('#videoConnectionMessage').css({display: "block"});
  6199. }
  6200. };
  6201. // checks whether recording is enabled and whether we have params to start automatically recording
  6202. my.checkAutoRecord = function () {
  6203. if (config.enableRecording && config.autoRecord) {
  6204. toggleRecording(config.autoRecordToken);
  6205. }
  6206. }
  6207. // Shows or hides SIP calls button
  6208. my.showSipCallButton = function (show) {
  6209. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6210. $('#sipCallButton').css({display: "inline-block"});
  6211. } else {
  6212. $('#sipCallButton').css({display: "none"});
  6213. }
  6214. };
  6215. // Shows or hides the dialpad button
  6216. my.showDialPadButton = function (show) {
  6217. if (show) {
  6218. $('#dialPadButton').css({display: "inline-block"});
  6219. } else {
  6220. $('#dialPadButton').css({display: "none"});
  6221. }
  6222. };
  6223. /**
  6224. * Displays user authenticated identity name(login).
  6225. * @param authIdentity identity name to be displayed.
  6226. */
  6227. my.setAuthenticatedIdentity = function (authIdentity) {
  6228. if (authIdentity) {
  6229. var selector = $('#toolbar_auth_identity');
  6230. selector.css({display: "list-item"});
  6231. selector.text(authIdentity);
  6232. } else {
  6233. $('#toolbar_auth_identity').css({display: "none"});
  6234. }
  6235. };
  6236. /**
  6237. * Shows/hides login button.
  6238. * @param show <tt>true</tt> to show
  6239. */
  6240. my.showLoginButton = function (show) {
  6241. if (show) {
  6242. $('#toolbar_button_login').css({display: "list-item"});
  6243. } else {
  6244. $('#toolbar_button_login').css({display: "none"});
  6245. }
  6246. };
  6247. /**
  6248. * Shows/hides logout button.
  6249. * @param show <tt>true</tt> to show
  6250. */
  6251. my.showLogoutButton = function (show) {
  6252. if (show) {
  6253. $('#toolbar_button_logout').css({display: "list-item"});
  6254. } else {
  6255. $('#toolbar_button_logout').css({display: "none"});
  6256. }
  6257. };
  6258. /**
  6259. * Sets the state of the button. The button has blue glow if desktop
  6260. * streaming is active.
  6261. * @param active the state of the desktop streaming.
  6262. */
  6263. my.changeDesktopSharingButtonState = function (active) {
  6264. var button = $("#desktopsharing > a");
  6265. if (active) {
  6266. button.addClass("glow");
  6267. } else {
  6268. button.removeClass("glow");
  6269. }
  6270. };
  6271. return my;
  6272. }(Toolbar || {}));
  6273. module.exports = Toolbar;
  6274. },{"../../../service/authentication/AuthenticationEvents":105,"../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){
  6275. /* global APP, config, $, interfaceConfig, Moderator,
  6276. DesktopStreaming.showDesktopSharingButton */
  6277. var toolbarTimeoutObject,
  6278. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6279. function showDesktopSharingButton() {
  6280. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6281. $('#desktopsharing').css({display: "inline"});
  6282. } else {
  6283. $('#desktopsharing').css({display: "none"});
  6284. }
  6285. }
  6286. /**
  6287. * Hides the toolbar.
  6288. */
  6289. function hideToolbar() {
  6290. if(config.alwaysVisibleToolbar)
  6291. return;
  6292. var header = $("#header"),
  6293. bottomToolbar = $("#bottomToolbar");
  6294. var isToolbarHover = false;
  6295. header.find('*').each(function () {
  6296. var id = $(this).attr('id');
  6297. if ($("#" + id + ":hover").length > 0) {
  6298. isToolbarHover = true;
  6299. }
  6300. });
  6301. if ($("#bottomToolbar:hover").length > 0) {
  6302. isToolbarHover = true;
  6303. }
  6304. clearTimeout(toolbarTimeoutObject);
  6305. toolbarTimeoutObject = null;
  6306. if (!isToolbarHover) {
  6307. header.hide("slide", { direction: "up", duration: 300});
  6308. $('#subject').animate({top: "-=40"}, 300);
  6309. if ($("#remoteVideos").hasClass("hidden")) {
  6310. bottomToolbar.hide(
  6311. "slide", {direction: "right", duration: 300});
  6312. }
  6313. }
  6314. else {
  6315. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6316. }
  6317. }
  6318. var ToolbarToggler = {
  6319. /**
  6320. * Shows the main toolbar.
  6321. */
  6322. showToolbar: function () {
  6323. if (interfaceConfig.filmStripOnly)
  6324. return;
  6325. var header = $("#header"),
  6326. bottomToolbar = $("#bottomToolbar");
  6327. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6328. header.show("slide", { direction: "up", duration: 300});
  6329. $('#subject').animate({top: "+=40"}, 300);
  6330. if (!bottomToolbar.is(":visible")) {
  6331. bottomToolbar.show(
  6332. "slide", {direction: "right", duration: 300});
  6333. }
  6334. if (toolbarTimeoutObject) {
  6335. clearTimeout(toolbarTimeoutObject);
  6336. toolbarTimeoutObject = null;
  6337. }
  6338. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6339. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6340. }
  6341. if (APP.xmpp.isModerator())
  6342. {
  6343. // TODO: Enable settings functionality.
  6344. // Need to uncomment the settings button in index.html.
  6345. // $('#settingsButton').css({visibility:"visible"});
  6346. }
  6347. // Show/hide desktop sharing button
  6348. showDesktopSharingButton();
  6349. },
  6350. /**
  6351. * Docks/undocks the toolbar.
  6352. *
  6353. * @param isDock indicates what operation to perform
  6354. */
  6355. dockToolbar: function (isDock) {
  6356. if (interfaceConfig.filmStripOnly)
  6357. return;
  6358. if (isDock) {
  6359. // First make sure the toolbar is shown.
  6360. if (!$('#header').is(':visible')) {
  6361. this.showToolbar();
  6362. }
  6363. // Then clear the time out, to dock the toolbar.
  6364. if (toolbarTimeoutObject) {
  6365. clearTimeout(toolbarTimeoutObject);
  6366. toolbarTimeoutObject = null;
  6367. }
  6368. }
  6369. else {
  6370. if (!$('#header').is(':visible')) {
  6371. this.showToolbar();
  6372. }
  6373. else {
  6374. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6375. }
  6376. }
  6377. },
  6378. showDesktopSharingButton: showDesktopSharingButton
  6379. };
  6380. module.exports = ToolbarToggler;
  6381. },{}],30:[function(require,module,exports){
  6382. /* global $ */
  6383. var JitsiPopover = (function () {
  6384. /**
  6385. * Constructs new JitsiPopover and attaches it to the element
  6386. * @param element jquery selector
  6387. * @param options the options for the popover.
  6388. * @constructor
  6389. */
  6390. function JitsiPopover(element, options)
  6391. {
  6392. this.options = {
  6393. skin: "white",
  6394. content: ""
  6395. };
  6396. if(options)
  6397. {
  6398. if(options.skin)
  6399. this.options.skin = options.skin;
  6400. if(options.content)
  6401. this.options.content = options.content;
  6402. }
  6403. this.elementIsHovered = false;
  6404. this.popoverIsHovered = false;
  6405. this.popoverShown = false;
  6406. element.data("jitsi_popover", this);
  6407. this.element = element;
  6408. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6409. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6410. '<div class="jitsiPopupmenuPadding"></div></div>';
  6411. var self = this;
  6412. this.element.on("mouseenter", function () {
  6413. self.elementIsHovered = true;
  6414. self.show();
  6415. }).on("mouseleave", function () {
  6416. self.elementIsHovered = false;
  6417. setTimeout(function () {
  6418. self.hide();
  6419. }, 10);
  6420. });
  6421. }
  6422. /**
  6423. * Shows the popover
  6424. */
  6425. JitsiPopover.prototype.show = function () {
  6426. if(!JitsiPopover.enabled)
  6427. return;
  6428. this.createPopover();
  6429. this.popoverShown = true;
  6430. };
  6431. /**
  6432. * Hides the popover
  6433. */
  6434. JitsiPopover.prototype.hide = function () {
  6435. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6436. this.popoverShown) {
  6437. this.forceHide();
  6438. }
  6439. };
  6440. /**
  6441. * Hides the popover.
  6442. */
  6443. JitsiPopover.prototype.forceHide = function () {
  6444. $(".jitsipopover").remove();
  6445. this.popoverShown = false;
  6446. };
  6447. /**
  6448. * Creates the popover html.
  6449. */
  6450. JitsiPopover.prototype.createPopover = function () {
  6451. $("body").append(this.template);
  6452. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6453. var self = this;
  6454. $(".jitsipopover").on("mouseenter", function () {
  6455. self.popoverIsHovered = true;
  6456. }).on("mouseleave", function () {
  6457. self.popoverIsHovered = false;
  6458. self.hide();
  6459. });
  6460. this.refreshPosition();
  6461. };
  6462. /**
  6463. * Refreshes the position of the popover.
  6464. */
  6465. JitsiPopover.prototype.refreshPosition = function () {
  6466. $(".jitsipopover").position({
  6467. my: "bottom",
  6468. at: "top",
  6469. collision: "fit",
  6470. of: this.element,
  6471. using: function (position, elements) {
  6472. var calcLeft = elements.target.left - elements.element.left +
  6473. elements.target.width/2;
  6474. $(".jitsipopover").css(
  6475. {top: position.top, left: position.left, display: "table"});
  6476. $(".jitsipopover > .arrow").css({left: calcLeft});
  6477. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6478. {left: calcLeft - 50});
  6479. }
  6480. });
  6481. };
  6482. /**
  6483. * Updates the content of popover.
  6484. * @param content new content
  6485. */
  6486. JitsiPopover.prototype.updateContent = function (content) {
  6487. this.options.content = content;
  6488. if(!this.popoverShown)
  6489. return;
  6490. $(".jitsipopover").remove();
  6491. this.createPopover();
  6492. };
  6493. JitsiPopover.enabled = true;
  6494. return JitsiPopover;
  6495. })();
  6496. module.exports = JitsiPopover;
  6497. },{}],31:[function(require,module,exports){
  6498. /* global $, APP, jQuery, toastr */
  6499. /**
  6500. * Flag for enable/disable of the notifications.
  6501. * @type {boolean}
  6502. */
  6503. var notificationsEnabled = true;
  6504. var messageHandler = (function(my) {
  6505. /**
  6506. * Shows a message to the user.
  6507. *
  6508. * @param titleKey the title of the message
  6509. * @param messageKey the text of the message
  6510. */
  6511. my.openMessageDialog = function(titleKey, messageKey) {
  6512. var title = null;
  6513. if(titleKey) {
  6514. title = APP.translation.generateTranslationHTML(titleKey);
  6515. }
  6516. var message = APP.translation.generateTranslationHTML(messageKey);
  6517. $.prompt(message,
  6518. {title: title, persistent: false}
  6519. );
  6520. };
  6521. /**
  6522. * Shows a message to the user with two buttons: first is given as a
  6523. * 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 leftButton the fist button's text
  6530. * @param submitFunction function to be called on submit
  6531. * @param loadedFunction function to be called after the prompt is fully
  6532. * loaded
  6533. * @param closeFunction function to be called after the prompt is closed
  6534. * @param focus optional focus selector or button index to be focused after
  6535. * the dialog is opened
  6536. * @param defaultButton index of default button which will be activated when
  6537. * the user press 'enter'. Indexed from 0.
  6538. */
  6539. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6540. persistent, leftButtonKey, submitFunction, loadedFunction,
  6541. closeFunction, focus, defaultButton) {
  6542. var buttons = [];
  6543. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6544. buttons.push({ title: leftButton, value: true});
  6545. var cancelButton
  6546. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6547. buttons.push({title: cancelButton, value: false});
  6548. var message = msgString, title = titleString;
  6549. if (titleKey) {
  6550. title = APP.translation.generateTranslationHTML(titleKey);
  6551. }
  6552. if (msgKey) {
  6553. message = APP.translation.generateTranslationHTML(msgKey);
  6554. }
  6555. $.prompt(message, {
  6556. title: title,
  6557. persistent: false,
  6558. buttons: buttons,
  6559. defaultButton: defaultButton,
  6560. focus: focus,
  6561. loaded: loadedFunction,
  6562. submit: submitFunction,
  6563. close: closeFunction
  6564. });
  6565. };
  6566. /**
  6567. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6568. *
  6569. * @param titleString the title of the message
  6570. * @param msgString the text of the message
  6571. * @param persistent boolean value which determines whether the message is
  6572. * persistent or not
  6573. * @param buttons object with the buttons. The keys must be the name of the
  6574. * button and value is the value that will be passed to
  6575. * submitFunction
  6576. * @param submitFunction function to be called on submit
  6577. * @param loadedFunction function to be called after the prompt is fully
  6578. * loaded
  6579. */
  6580. my.openDialog = function (titleString, msgString, persistent, buttons,
  6581. submitFunction, loadedFunction) {
  6582. var args = {
  6583. title: titleString,
  6584. persistent: persistent,
  6585. buttons: buttons,
  6586. defaultButton: 1,
  6587. loaded: loadedFunction,
  6588. submit: submitFunction
  6589. };
  6590. if (persistent) {
  6591. args.closeText = '';
  6592. }
  6593. return new Impromptu(msgString, args);
  6594. };
  6595. /**
  6596. * Closes currently opened dialog.
  6597. */
  6598. my.closeDialog = function () {
  6599. $.prompt.close();
  6600. };
  6601. /**
  6602. * Shows a dialog with different states to the user.
  6603. *
  6604. * @param statesObject object containing all the states of the dialog.
  6605. */
  6606. my.openDialogWithStates = function (statesObject, options) {
  6607. return new Impromptu(statesObject, options);
  6608. };
  6609. /**
  6610. * Opens new popup window for given <tt>url</tt> centered over current
  6611. * window.
  6612. *
  6613. * @param url the URL to be displayed in the popup window
  6614. * @param w the width of the popup window
  6615. * @param h the height of the popup window
  6616. * @param onPopupClosed optional callback function called when popup window
  6617. * has been closed.
  6618. *
  6619. * @returns {object} popup window object if opened successfully or undefined
  6620. * in case we failed to open it(popup blocked)
  6621. */
  6622. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6623. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6624. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6625. var popup = window.open(
  6626. url, '_blank',
  6627. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6628. if (popup && onPopupClosed) {
  6629. var pollTimer = window.setInterval(function () {
  6630. if (popup.closed !== false) {
  6631. window.clearInterval(pollTimer);
  6632. onPopupClosed();
  6633. }
  6634. }, 200);
  6635. }
  6636. return popup;
  6637. };
  6638. /**
  6639. * Shows a dialog prompting the user to send an error report.
  6640. *
  6641. * @param titleKey the title of the message
  6642. * @param msgKey the text of the message
  6643. * @param error the error that is being reported
  6644. */
  6645. my.openReportDialog = function(titleKey, msgKey, error) {
  6646. my.openMessageDialog(titleKey, msgKey);
  6647. console.log(error);
  6648. //FIXME send the error to the server
  6649. };
  6650. /**
  6651. * Shows an error dialog to the user.
  6652. * @param titleKey the title of the message.
  6653. * @param msgKey the text of the message.
  6654. */
  6655. my.showError = function(titleKey, msgKey) {
  6656. if (!titleKey) {
  6657. titleKey = "dialog.oops";
  6658. }
  6659. if (!msgKey) {
  6660. msgKey = "dialog.defaultError";
  6661. }
  6662. messageHandler.openMessageDialog(titleKey, msgKey);
  6663. };
  6664. /**
  6665. * Displayes notification.
  6666. * @param displayName display name of the participant that is associated with the notification.
  6667. * @param displayNameKey the key from the language file for the display name.
  6668. * @param cls css class for the notification
  6669. * @param messageKey the key from the language file for the text of the message.
  6670. * @param messageArguments object with the arguments for the message.
  6671. * @param options object with language options.
  6672. */
  6673. my.notify = function(displayName, displayNameKey,
  6674. cls, messageKey, messageArguments, options) {
  6675. if(!notificationsEnabled)
  6676. return;
  6677. var displayNameSpan = '<span class="nickname" ';
  6678. if (displayName) {
  6679. displayNameSpan += ">" + displayName;
  6680. } else {
  6681. displayNameSpan += "data-i18n='" + displayNameKey +
  6682. "'>" + APP.translation.translateString(displayNameKey);
  6683. }
  6684. displayNameSpan += "</span>";
  6685. return toastr.info(
  6686. displayNameSpan + '<br>' +
  6687. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6688. (messageArguments?
  6689. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6690. : "") + ">" +
  6691. APP.translation.translateString(messageKey,
  6692. messageArguments) +
  6693. '</span>', null, options);
  6694. };
  6695. /**
  6696. * Removes the toaster.
  6697. * @param toasterElement
  6698. */
  6699. my.remove = function(toasterElement) {
  6700. toasterElement.remove();
  6701. };
  6702. /**
  6703. * Disables notifications.
  6704. */
  6705. my.disableNotifications = function () {
  6706. notificationsEnabled = false;
  6707. };
  6708. /**
  6709. * Enables notifications.
  6710. */
  6711. my.enableNotifications = function () {
  6712. notificationsEnabled = true;
  6713. };
  6714. return my;
  6715. }(messageHandler || {}));
  6716. module.exports = messageHandler;
  6717. },{}],32:[function(require,module,exports){
  6718. var UIEvents = require("../../../service/UI/UIEvents");
  6719. var nickname = null;
  6720. var eventEmitter = null;
  6721. var NicknameHandler = {
  6722. init: function (emitter) {
  6723. eventEmitter = emitter;
  6724. var storedDisplayName = window.localStorage.displayname;
  6725. if (storedDisplayName) {
  6726. nickname = storedDisplayName;
  6727. }
  6728. },
  6729. setNickname: function (newNickname) {
  6730. if (!newNickname || nickname === newNickname)
  6731. return;
  6732. nickname = newNickname;
  6733. window.localStorage.displayname = nickname;
  6734. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6735. },
  6736. getNickname: function () {
  6737. return nickname;
  6738. },
  6739. addListener: function (type, listener) {
  6740. eventEmitter.on(type, listener);
  6741. }
  6742. };
  6743. module.exports = NicknameHandler;
  6744. },{"../../../service/UI/UIEvents":104}],33:[function(require,module,exports){
  6745. /* global $ */
  6746. /**
  6747. * Created by hristo on 12/22/14.
  6748. */
  6749. module.exports = {
  6750. /**
  6751. * Returns the available video width.
  6752. */
  6753. getAvailableVideoWidth: function (isVisible) {
  6754. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6755. if(typeof isVisible === "undefined" || isVisible === null)
  6756. isVisible = PanelToggler.isVisible();
  6757. var rightPanelWidth
  6758. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6759. return window.innerWidth - rightPanelWidth;
  6760. },
  6761. /**
  6762. * Changes the style class of the element given by id.
  6763. */
  6764. buttonClick: function(id, classname) {
  6765. $(id).toggleClass(classname); // add the class to the clicked element
  6766. },
  6767. /**
  6768. * Returns the text width for the given element.
  6769. *
  6770. * @param el the element
  6771. */
  6772. getTextWidth: function (el) {
  6773. return (el.clientWidth + 1);
  6774. },
  6775. /**
  6776. * Returns the text height for the given element.
  6777. *
  6778. * @param el the element
  6779. */
  6780. getTextHeight: function (el) {
  6781. return (el.clientHeight + 1);
  6782. },
  6783. /**
  6784. * Plays the sound given by id.
  6785. *
  6786. * @param id the identifier of the audio element.
  6787. */
  6788. playSoundNotification: function (id) {
  6789. document.getElementById(id).play();
  6790. },
  6791. /**
  6792. * Escapes the given text.
  6793. */
  6794. escapeHtml: function (unsafeText) {
  6795. return $('<div/>').text(unsafeText).html();
  6796. },
  6797. imageToGrayScale: function (canvas) {
  6798. var context = canvas.getContext('2d');
  6799. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6800. var pixels = imgData.data;
  6801. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6802. var grayscale
  6803. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  6804. pixels[i ] = grayscale; // red
  6805. pixels[i+1] = grayscale; // green
  6806. pixels[i+2] = grayscale; // blue
  6807. // pixels[i+3] is alpha
  6808. }
  6809. // redraw the image in black & white
  6810. context.putImageData(imgData, 0, 0);
  6811. },
  6812. setTooltip: function (element, key, position) {
  6813. element.setAttribute("data-i18n", "[data-content]" + key);
  6814. element.setAttribute("data-toggle", "popover");
  6815. element.setAttribute("data-placement", position);
  6816. element.setAttribute("data-html", true);
  6817. element.setAttribute("data-container", "body");
  6818. }
  6819. };
  6820. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6821. /* global APP, $ */
  6822. var JitsiPopover = require("../util/JitsiPopover");
  6823. /**
  6824. * Constructs new connection indicator.
  6825. * @param videoContainer the video container associated with the indicator.
  6826. * @constructor
  6827. */
  6828. function ConnectionIndicator(videoContainer, jid) {
  6829. this.videoContainer = videoContainer;
  6830. this.bandwidth = null;
  6831. this.packetLoss = null;
  6832. this.bitrate = null;
  6833. this.showMoreValue = false;
  6834. this.resolution = null;
  6835. this.transport = [];
  6836. this.popover = null;
  6837. this.jid = jid;
  6838. this.create();
  6839. }
  6840. /**
  6841. * Values for the connection quality
  6842. * @type {{98: string,
  6843. * 81: string,
  6844. * 64: string,
  6845. * 47: string,
  6846. * 30: string,
  6847. * 0: string}}
  6848. */
  6849. ConnectionIndicator.connectionQualityValues = {
  6850. 98: "18px", //full
  6851. 81: "15px",//4 bars
  6852. 64: "11px",//3 bars
  6853. 47: "7px",//2 bars
  6854. 30: "3px",//1 bar
  6855. 0: "0px"//empty
  6856. };
  6857. ConnectionIndicator.getIP = function(value) {
  6858. return value.substring(0, value.lastIndexOf(":"));
  6859. };
  6860. ConnectionIndicator.getPort = function(value) {
  6861. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6862. };
  6863. ConnectionIndicator.getStringFromArray = function (array) {
  6864. var res = "";
  6865. for(var i = 0; i < array.length; i++) {
  6866. res += (i === 0? "" : ", ") + array[i];
  6867. }
  6868. return res;
  6869. };
  6870. /**
  6871. * Generates the html content.
  6872. * @returns {string} the html content.
  6873. */
  6874. ConnectionIndicator.prototype.generateText = function () {
  6875. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6876. var translate = APP.translation.translateString;
  6877. if(this.bitrate === null) {
  6878. downloadBitrate = "N/A";
  6879. uploadBitrate = "N/A";
  6880. }
  6881. else {
  6882. downloadBitrate =
  6883. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6884. uploadBitrate =
  6885. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6886. }
  6887. if(this.packetLoss === null) {
  6888. packetLoss = "N/A";
  6889. } else {
  6890. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6891. (this.packetLoss.download !== null ?
  6892. this.packetLoss.download : "N/A") +
  6893. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6894. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  6895. "%";
  6896. }
  6897. var resolutionValue = null;
  6898. if(this.resolution && this.jid != null) {
  6899. var keys = Object.keys(this.resolution);
  6900. for(var ssrc in this.resolution) {
  6901. resolutionValue = this.resolution[ssrc];
  6902. }
  6903. }
  6904. if(this.jid === null) {
  6905. resolution = "";
  6906. if(this.resolution === null || !Object.keys(this.resolution) ||
  6907. Object.keys(this.resolution).length === 0) {
  6908. resolution = "N/A";
  6909. } else {
  6910. for (i in this.resolution) {
  6911. resolutionValue = this.resolution[i];
  6912. if (resolutionValue) {
  6913. if (resolutionValue.height &&
  6914. resolutionValue.width) {
  6915. resolution += (resolution === "" ? "" : ", ") +
  6916. resolutionValue.width + "x" +
  6917. resolutionValue.height;
  6918. }
  6919. }
  6920. }
  6921. }
  6922. } else if(!resolutionValue ||
  6923. !resolutionValue.height ||
  6924. !resolutionValue.width) {
  6925. resolution = "N/A";
  6926. } else {
  6927. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6928. }
  6929. var result = "<table style='width:100%'>" +
  6930. "<tr>" +
  6931. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6932. translate("connectionindicator.bitrate") + "</span></td>" +
  6933. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6934. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6935. uploadBitrate + "</td>" +
  6936. "</tr><tr>" +
  6937. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6938. translate("connectionindicator.packetloss") + "</span></td>" +
  6939. "<td>" + packetLoss + "</td>" +
  6940. "</tr><tr>" +
  6941. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6942. translate("connectionindicator.resolution") + "</span></td>" +
  6943. "<td>" + resolution + "</td></tr></table>";
  6944. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6945. result += "<div class=\"jitsipopover_showmore\" " +
  6946. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6947. // FIXME: we do not know local jid when this text is generated
  6948. //this.jid + "')\" data-i18n='connectionindicator." +
  6949. "local')\" data-i18n='connectionindicator." +
  6950. (this.showMoreValue ? "less" : "more") + "'>" +
  6951. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6952. "</div><br />";
  6953. }
  6954. if (this.showMoreValue) {
  6955. var downloadBandwidth, uploadBandwidth, transport;
  6956. if (this.bandwidth === null) {
  6957. downloadBandwidth = "N/A";
  6958. uploadBandwidth = "N/A";
  6959. } else {
  6960. downloadBandwidth = this.bandwidth.download?
  6961. this.bandwidth.download + " Kbps" :
  6962. "N/A";
  6963. uploadBandwidth = this.bandwidth.upload?
  6964. this.bandwidth.upload + " Kbps" :
  6965. "N/A";
  6966. }
  6967. if (!this.transport || this.transport.length === 0) {
  6968. transport = "<tr>" +
  6969. "<td><span class='jitsipopover_blue' " +
  6970. "data-i18n='connectionindicator.address'>" +
  6971. translate("connectionindicator.address") + "</span></td>" +
  6972. "<td> N/A</td></tr>";
  6973. } else {
  6974. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  6975. for(i = 0; i < this.transport.length; i++) {
  6976. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  6977. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  6978. var localIP =
  6979. ConnectionIndicator.getIP(this.transport[i].localip);
  6980. var localPort =
  6981. ConnectionIndicator.getPort(this.transport[i].localip);
  6982. if(data.remoteIP.indexOf(ip) == -1) {
  6983. data.remoteIP.push(ip);
  6984. }
  6985. if(data.remotePort.indexOf(port) == -1) {
  6986. data.remotePort.push(port);
  6987. }
  6988. if(data.localIP.indexOf(localIP) == -1) {
  6989. data.localIP.push(localIP);
  6990. }
  6991. if(data.localPort.indexOf(localPort) == -1) {
  6992. data.localPort.push(localPort);
  6993. }
  6994. }
  6995. var local_address_key = "connectionindicator.localaddress";
  6996. var remote_address_key = "connectionindicator.remoteaddress";
  6997. var localTransport =
  6998. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6999. local_address_key +"' data-i18n-options='" +
  7000. JSON.stringify({count: data.localIP.length}) + "'>" +
  7001. translate(local_address_key, {count: data.localIP.length}) +
  7002. "</span></td><td> " +
  7003. ConnectionIndicator.getStringFromArray(data.localIP) +
  7004. "</td></tr>";
  7005. transport =
  7006. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7007. remote_address_key + "' data-i18n-options='" +
  7008. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7009. translate(remote_address_key,
  7010. {count: data.remoteIP.length}) +
  7011. "</span></td><td> " +
  7012. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7013. "</td></tr>";
  7014. var key_remote = "connectionindicator.remoteport",
  7015. key_local = "connectionindicator.localport";
  7016. transport += "<tr>" +
  7017. "<td>" +
  7018. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7019. "' data-i18n-options='" +
  7020. JSON.stringify({count: this.transport.length}) + "'>" +
  7021. translate(key_remote, {count: this.transport.length}) +
  7022. "</span></td><td>";
  7023. localTransport += "<tr>" +
  7024. "<td>" +
  7025. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7026. "' data-i18n-options='" +
  7027. JSON.stringify({count: this.transport.length}) + "'>" +
  7028. translate(key_local, {count: this.transport.length}) +
  7029. "</span></td><td>";
  7030. transport +=
  7031. ConnectionIndicator.getStringFromArray(data.remotePort);
  7032. localTransport +=
  7033. ConnectionIndicator.getStringFromArray(data.localPort);
  7034. transport += "</td></tr>";
  7035. transport += localTransport + "</td></tr>";
  7036. transport +="<tr>" +
  7037. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7038. translate("connectionindicator.transport") + "</span></td>" +
  7039. "<td>" + this.transport[0].type + "</td></tr>";
  7040. }
  7041. result += "<table style='width:100%'>" +
  7042. "<tr>" +
  7043. "<td>" +
  7044. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7045. translate("connectionindicator.bandwidth") + "</span>" +
  7046. "</td><td>" +
  7047. "<span class='jitsipopover_green'>&darr;</span>" +
  7048. downloadBandwidth +
  7049. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7050. uploadBandwidth + "</td></tr>";
  7051. result += transport + "</table>";
  7052. }
  7053. return result;
  7054. };
  7055. /**
  7056. * Shows or hide the additional information.
  7057. */
  7058. ConnectionIndicator.prototype.showMore = function () {
  7059. this.showMoreValue = !this.showMoreValue;
  7060. this.updatePopoverData();
  7061. };
  7062. function createIcon(classes) {
  7063. var icon = document.createElement("span");
  7064. for(var i in classes) {
  7065. icon.classList.add(classes[i]);
  7066. }
  7067. icon.appendChild(
  7068. document.createElement("i")).classList.add("icon-connection");
  7069. return icon;
  7070. }
  7071. /**
  7072. * Creates the indicator
  7073. */
  7074. ConnectionIndicator.prototype.create = function () {
  7075. this.connectionIndicatorContainer = document.createElement("div");
  7076. this.connectionIndicatorContainer.className = "connectionindicator";
  7077. this.connectionIndicatorContainer.style.display = "none";
  7078. this.videoContainer.container.appendChild(
  7079. this.connectionIndicatorContainer);
  7080. this.popover = new JitsiPopover(
  7081. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7082. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7083. APP.translation.translateString("connectionindicator.na") + "</div>",
  7084. skin: "black"});
  7085. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7086. createIcon(["connection", "connection_empty"]));
  7087. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7088. createIcon(["connection", "connection_full"]));
  7089. };
  7090. /**
  7091. * Removes the indicator
  7092. */
  7093. ConnectionIndicator.prototype.remove = function() {
  7094. if (this.connectionIndicatorContainer.parentNode) {
  7095. this.connectionIndicatorContainer.parentNode.removeChild(
  7096. this.connectionIndicatorContainer);
  7097. }
  7098. this.popover.forceHide();
  7099. };
  7100. /**
  7101. * Updates the data of the indicator
  7102. * @param percent the percent of connection quality
  7103. * @param object the statistics data.
  7104. */
  7105. ConnectionIndicator.prototype.updateConnectionQuality =
  7106. function (percent, object) {
  7107. if (percent === null) {
  7108. this.connectionIndicatorContainer.style.display = "none";
  7109. this.popover.forceHide();
  7110. return;
  7111. } else {
  7112. if(this.connectionIndicatorContainer.style.display == "none") {
  7113. this.connectionIndicatorContainer.style.display = "block";
  7114. this.videoContainer.updateIconPositions();
  7115. }
  7116. }
  7117. this.bandwidth = object.bandwidth;
  7118. this.bitrate = object.bitrate;
  7119. this.packetLoss = object.packetLoss;
  7120. this.transport = object.transport;
  7121. if (object.resolution) {
  7122. this.resolution = object.resolution;
  7123. }
  7124. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7125. if (percent >= quality) {
  7126. this.fullIcon.style.width =
  7127. ConnectionIndicator.connectionQualityValues[quality];
  7128. }
  7129. }
  7130. this.updatePopoverData();
  7131. };
  7132. /**
  7133. * Updates the resolution
  7134. * @param resolution the new resolution
  7135. */
  7136. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7137. this.resolution = resolution;
  7138. this.updatePopoverData();
  7139. };
  7140. /**
  7141. * Updates the content of the popover
  7142. */
  7143. ConnectionIndicator.prototype.updatePopoverData = function () {
  7144. this.popover.updateContent(
  7145. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7146. APP.translation.translateElement($(".connection_info"));
  7147. };
  7148. /**
  7149. * Hides the popover
  7150. */
  7151. ConnectionIndicator.prototype.hide = function () {
  7152. this.popover.forceHide();
  7153. };
  7154. /**
  7155. * Hides the indicator
  7156. */
  7157. ConnectionIndicator.prototype.hideIndicator = function () {
  7158. this.connectionIndicatorContainer.style.display = "none";
  7159. if(this.popover)
  7160. this.popover.forceHide();
  7161. };
  7162. module.exports = ConnectionIndicator;
  7163. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7164. /* global $, APP, Strophe, interfaceConfig */
  7165. var Avatar = require("../avatar/Avatar");
  7166. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7167. var UIUtil = require("../util/UIUtil");
  7168. var UIEvents = require("../../../service/UI/UIEvents");
  7169. var xmpp = require("../../xmpp/xmpp");
  7170. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7171. // FIXME: With Temasys we have to re-select everytime
  7172. //var video = $('#largeVideo');
  7173. var currentVideoWidth = null;
  7174. var currentVideoHeight = null;
  7175. // By default we use camera
  7176. var getVideoSize = getCameraVideoSize;
  7177. var getVideoPosition = getCameraVideoPosition;
  7178. /**
  7179. * The small video instance that is displayed in the large video
  7180. * @type {SmallVideo}
  7181. */
  7182. var currentSmallVideo = null;
  7183. /**
  7184. * Indicates whether the large video is enabled.
  7185. * @type {boolean}
  7186. */
  7187. var isEnabled = true;
  7188. /**
  7189. * Current large video state.
  7190. * Possible values - video, prezi or etherpad.
  7191. * @type {string}
  7192. */
  7193. var state = "video";
  7194. /**
  7195. * Returns the html element associated with the passed state of large video
  7196. * @param state the state.
  7197. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7198. */
  7199. function getContainerByState(state)
  7200. {
  7201. var selector = null;
  7202. switch (state)
  7203. {
  7204. case "video":
  7205. selector = "#largeVideo";
  7206. break;
  7207. case "etherpad":
  7208. selector = "#etherpad>iframe";
  7209. break;
  7210. case "prezi":
  7211. selector = "#presentation>iframe";
  7212. break;
  7213. }
  7214. return (selector !== null)? $(selector) : null;
  7215. }
  7216. /**
  7217. * Sets the size and position of the given video element.
  7218. *
  7219. * @param video the video element to position
  7220. * @param width the desired video width
  7221. * @param height the desired video height
  7222. * @param horizontalIndent the left and right indent
  7223. * @param verticalIndent the top and bottom indent
  7224. */
  7225. function positionVideo(video,
  7226. width,
  7227. height,
  7228. horizontalIndent,
  7229. verticalIndent,
  7230. animate) {
  7231. if (animate) {
  7232. video.animate({
  7233. width: width,
  7234. height: height,
  7235. top: verticalIndent,
  7236. bottom: verticalIndent,
  7237. left: horizontalIndent,
  7238. right: horizontalIndent
  7239. },
  7240. {
  7241. queue: false,
  7242. duration: 500
  7243. });
  7244. } else {
  7245. video.width(width);
  7246. video.height(height);
  7247. video.css({ top: verticalIndent + 'px',
  7248. bottom: verticalIndent + 'px',
  7249. left: horizontalIndent + 'px',
  7250. right: horizontalIndent + 'px'});
  7251. }
  7252. }
  7253. /**
  7254. * Returns an array of the video dimensions, so that it keeps it's aspect
  7255. * ratio and fits available area with it's larger dimension. This method
  7256. * ensures that whole video will be visible and can leave empty areas.
  7257. *
  7258. * @return an array with 2 elements, the video width and the video height
  7259. */
  7260. function getDesktopVideoSize(videoWidth,
  7261. videoHeight,
  7262. videoSpaceWidth,
  7263. videoSpaceHeight) {
  7264. if (!videoWidth)
  7265. videoWidth = currentVideoWidth;
  7266. if (!videoHeight)
  7267. videoHeight = currentVideoHeight;
  7268. var aspectRatio = videoWidth / videoHeight;
  7269. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7270. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7271. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7272. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7273. {
  7274. availableHeight = videoSpaceHeight;
  7275. availableWidth = availableHeight * aspectRatio;
  7276. }
  7277. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7278. {
  7279. availableWidth = videoSpaceWidth;
  7280. availableHeight = availableWidth / aspectRatio;
  7281. }
  7282. return [availableWidth, availableHeight];
  7283. }
  7284. /**
  7285. * Returns an array of the video horizontal and vertical indents,
  7286. * so that if fits its parent.
  7287. *
  7288. * @return an array with 2 elements, the horizontal indent and the vertical
  7289. * indent
  7290. */
  7291. function getCameraVideoPosition(videoWidth,
  7292. videoHeight,
  7293. videoSpaceWidth,
  7294. videoSpaceHeight) {
  7295. // Parent height isn't completely calculated when we position the video in
  7296. // full screen mode and this is why we use the screen height in this case.
  7297. // Need to think it further at some point and implement it properly.
  7298. var isFullScreen = document.fullScreen ||
  7299. document.mozFullScreen ||
  7300. document.webkitIsFullScreen;
  7301. if (isFullScreen)
  7302. videoSpaceHeight = window.innerHeight;
  7303. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7304. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7305. return [horizontalIndent, verticalIndent];
  7306. }
  7307. /**
  7308. * Returns an array of the video horizontal and vertical indents.
  7309. * Centers horizontally and top aligns vertically.
  7310. *
  7311. * @return an array with 2 elements, the horizontal indent and the vertical
  7312. * indent
  7313. */
  7314. function getDesktopVideoPosition(videoWidth,
  7315. videoHeight,
  7316. videoSpaceWidth,
  7317. videoSpaceHeight) {
  7318. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7319. var verticalIndent = 0;// Top aligned
  7320. return [horizontalIndent, verticalIndent];
  7321. }
  7322. /**
  7323. * Returns an array of the video dimensions, so that it covers the screen.
  7324. * It leaves no empty areas, but some parts of the video might not be visible.
  7325. *
  7326. * @return an array with 2 elements, the video width and the video height
  7327. */
  7328. function getCameraVideoSize(videoWidth,
  7329. videoHeight,
  7330. videoSpaceWidth,
  7331. videoSpaceHeight) {
  7332. if (!videoWidth)
  7333. videoWidth = currentVideoWidth;
  7334. if (!videoHeight)
  7335. videoHeight = currentVideoHeight;
  7336. var aspectRatio = videoWidth / videoHeight;
  7337. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7338. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7339. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7340. availableHeight = videoSpaceHeight;
  7341. availableWidth = availableHeight * aspectRatio;
  7342. }
  7343. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7344. availableWidth = videoSpaceWidth;
  7345. availableHeight = availableWidth / aspectRatio;
  7346. }
  7347. return [availableWidth, availableHeight];
  7348. }
  7349. /**
  7350. * Updates the src of the active speaker avatar
  7351. * @param jid of the current active speaker
  7352. */
  7353. function updateActiveSpeakerAvatarSrc() {
  7354. var avatar = $("#activeSpeakerAvatar")[0];
  7355. var jid = currentSmallVideo.peerJid;
  7356. var url = Avatar.getActiveSpeakerUrl(jid);
  7357. if (avatar.src === url)
  7358. return;
  7359. if (jid) {
  7360. avatar.src = url;
  7361. currentSmallVideo.showAvatar();
  7362. }
  7363. }
  7364. /**
  7365. * Change the video source of the large video.
  7366. * @param isVisible
  7367. */
  7368. function changeVideo(isVisible) {
  7369. if (!currentSmallVideo) {
  7370. console.error("Unable to change large video - no 'currentSmallVideo'");
  7371. return;
  7372. }
  7373. updateActiveSpeakerAvatarSrc();
  7374. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7375. var videoTransform = document.getElementById('largeVideo')
  7376. .style.webkitTransform;
  7377. var flipX = currentSmallVideo.flipX;
  7378. if (flipX && videoTransform !== 'scaleX(-1)') {
  7379. document.getElementById('largeVideo').style.webkitTransform =
  7380. "scaleX(-1)";
  7381. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7382. document.getElementById('largeVideo').style.webkitTransform =
  7383. "none";
  7384. }
  7385. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7386. // Change the way we'll be measuring and positioning large video
  7387. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7388. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7389. getCameraVideoPosition;
  7390. // Only if the large video is currently visible.
  7391. if (isVisible) {
  7392. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7393. $('#largeVideo').fadeIn(300);
  7394. }
  7395. }
  7396. /**
  7397. * Creates the html elements for the large video.
  7398. */
  7399. function createLargeVideoHTML()
  7400. {
  7401. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7402. html += '<div id="presentation"></div>' +
  7403. '<div id="etherpad"></div>' +
  7404. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7405. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7406. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7407. '<span data-i18n="poweredby"></span> jitsi.org' +
  7408. '</a>'+
  7409. '<div id="activeSpeaker">' +
  7410. '<img id="activeSpeakerAvatar" src=""/>' +
  7411. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7412. '</div>' +
  7413. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7414. '<span id="videoConnectionMessage"></span>';
  7415. html += '</div>';
  7416. $(html).prependTo("#videospace");
  7417. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7418. var leftWatermarkDiv
  7419. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7420. leftWatermarkDiv.css({display: 'block'});
  7421. leftWatermarkDiv.parent().get(0).href
  7422. = interfaceConfig.JITSI_WATERMARK_LINK;
  7423. }
  7424. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7425. var rightWatermarkDiv
  7426. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7427. rightWatermarkDiv.css({display: 'block'});
  7428. rightWatermarkDiv.parent().get(0).href
  7429. = interfaceConfig.BRAND_WATERMARK_LINK;
  7430. rightWatermarkDiv.get(0).style.backgroundImage
  7431. = "url(images/rightwatermark.png)";
  7432. }
  7433. if (interfaceConfig.SHOW_POWERED_BY) {
  7434. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7435. }
  7436. if (!RTCBrowserType.isIExplorer()) {
  7437. $('#largeVideo').volume = 0;
  7438. }
  7439. }
  7440. var LargeVideo = {
  7441. init: function (VideoLayout, emitter) {
  7442. if(!isEnabled)
  7443. return;
  7444. createLargeVideoHTML();
  7445. this.VideoLayout = VideoLayout;
  7446. this.eventEmitter = emitter;
  7447. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7448. var self = this;
  7449. // Listen for large video size updates
  7450. var largeVideo = $('#largeVideo')[0];
  7451. var onplaying = function (arg1, arg2, arg3) {
  7452. // re-select
  7453. if (RTCBrowserType.isTemasysPluginUsed())
  7454. largeVideo = $('#largeVideo')[0];
  7455. currentVideoWidth = largeVideo.videoWidth;
  7456. currentVideoHeight = largeVideo.videoHeight;
  7457. self.position(currentVideoWidth, currentVideoHeight);
  7458. };
  7459. largeVideo.onplaying = onplaying;
  7460. },
  7461. /**
  7462. * Indicates if the large video is currently visible.
  7463. *
  7464. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7465. */
  7466. isLargeVideoVisible: function() {
  7467. return $('#largeVideo').is(':visible');
  7468. },
  7469. /**
  7470. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7471. */
  7472. isCurrentlyOnLarge: function (resourceJid) {
  7473. return currentSmallVideo && resourceJid &&
  7474. currentSmallVideo.getResourceJid() === resourceJid;
  7475. },
  7476. /**
  7477. * Updates the large video with the given new video source.
  7478. */
  7479. updateLargeVideo: function (resourceJid, forceUpdate) {
  7480. if(!isEnabled)
  7481. return;
  7482. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7483. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7484. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7485. $('#activeSpeaker').css('visibility', 'hidden');
  7486. var oldSmallVideo = null;
  7487. if (currentSmallVideo) {
  7488. oldSmallVideo = currentSmallVideo;
  7489. }
  7490. currentSmallVideo = newSmallVideo;
  7491. var oldJid = null;
  7492. if (oldSmallVideo)
  7493. oldJid = oldSmallVideo.peerJid;
  7494. if (oldJid !== resourceJid) {
  7495. // we want the notification to trigger even if userJid is undefined,
  7496. // or null.
  7497. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7498. }
  7499. if (RTCBrowserType.isSafari()) {
  7500. // FIXME In Safari fadeOut works only for the first time
  7501. changeVideo(this.isLargeVideoVisible());
  7502. } else {
  7503. $('#largeVideo').fadeOut(300,
  7504. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7505. }
  7506. } else {
  7507. if (currentSmallVideo) {
  7508. currentSmallVideo.showAvatar();
  7509. }
  7510. }
  7511. },
  7512. /**
  7513. * Shows/hides the large video.
  7514. */
  7515. setLargeVideoVisible: function(isVisible) {
  7516. if(!isEnabled)
  7517. return;
  7518. if (isVisible) {
  7519. $('#largeVideo').css({visibility: 'visible'});
  7520. $('.watermark').css({visibility: 'visible'});
  7521. if(currentSmallVideo)
  7522. currentSmallVideo.enableDominantSpeaker(true);
  7523. }
  7524. else {
  7525. $('#largeVideo').css({visibility: 'hidden'});
  7526. $('#activeSpeaker').css('visibility', 'hidden');
  7527. $('.watermark').css({visibility: 'hidden'});
  7528. if(currentSmallVideo)
  7529. currentSmallVideo.enableDominantSpeaker(false);
  7530. }
  7531. },
  7532. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7533. if (!isEnabled)
  7534. return;
  7535. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7536. {
  7537. var isDesktop = newVideoType === 'screen';
  7538. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7539. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7540. : getCameraVideoPosition;
  7541. this.position(null, null);
  7542. }
  7543. },
  7544. /**
  7545. * Positions the large video.
  7546. *
  7547. * @param videoWidth the stream video width
  7548. * @param videoHeight the stream video height
  7549. */
  7550. position: function (videoWidth, videoHeight,
  7551. videoSpaceWidth, videoSpaceHeight, animate) {
  7552. if(!isEnabled)
  7553. return;
  7554. if(!videoSpaceWidth)
  7555. videoSpaceWidth = $('#videospace').width();
  7556. if(!videoSpaceHeight)
  7557. videoSpaceHeight = window.innerHeight;
  7558. var videoSize = getVideoSize(videoWidth,
  7559. videoHeight,
  7560. videoSpaceWidth,
  7561. videoSpaceHeight);
  7562. var largeVideoWidth = videoSize[0];
  7563. var largeVideoHeight = videoSize[1];
  7564. var videoPosition = getVideoPosition(largeVideoWidth,
  7565. largeVideoHeight,
  7566. videoSpaceWidth,
  7567. videoSpaceHeight);
  7568. var horizontalIndent = videoPosition[0];
  7569. var verticalIndent = videoPosition[1];
  7570. positionVideo($('#largeVideo'),
  7571. largeVideoWidth,
  7572. largeVideoHeight,
  7573. horizontalIndent, verticalIndent, animate);
  7574. },
  7575. /**
  7576. * Resizes the large html elements.
  7577. * @param animate boolean property that indicates whether the resize should be animated or not.
  7578. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  7579. * If that parameter is null the method will check the chat pannel visibility.
  7580. * @param completeFunction a function to be called when the video space is resized
  7581. * @returns {*[]} array with the current width and height values of the largeVideo html element.
  7582. */
  7583. resize: function (animate, isVisible, completeFunction) {
  7584. if(!isEnabled)
  7585. return;
  7586. var availableHeight = window.innerHeight;
  7587. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7588. if (availableWidth < 0 || availableHeight < 0) return;
  7589. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7590. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7591. $('#activeSpeaker').css('top', top);
  7592. this.VideoLayout.resizeVideoSpace(animate, isVisible, completeFunction);
  7593. if(animate) {
  7594. $('#largeVideoContainer').animate({
  7595. width: availableWidth,
  7596. height: availableHeight
  7597. },
  7598. {
  7599. queue: false,
  7600. duration: 500
  7601. });
  7602. } else {
  7603. $('#largeVideoContainer').width(availableWidth);
  7604. $('#largeVideoContainer').height(availableHeight);
  7605. }
  7606. return [availableWidth, availableHeight];
  7607. },
  7608. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7609. if(!isEnabled)
  7610. return;
  7611. var size = this.resize(true, isVisible, completeFunction);
  7612. this.position(null, null, size[0], size[1], true);
  7613. },
  7614. getResourceJid: function () {
  7615. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7616. },
  7617. updateAvatar: function (resourceJid) {
  7618. if(!isEnabled)
  7619. return;
  7620. if (resourceJid === this.getResourceJid()) {
  7621. updateActiveSpeakerAvatarSrc();
  7622. }
  7623. },
  7624. showAvatar: function (resourceJid, show) {
  7625. if(!isEnabled)
  7626. return;
  7627. if(this.getResourceJid() === resourceJid && state === "video") {
  7628. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7629. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7630. return true;
  7631. }
  7632. return false;
  7633. },
  7634. /**
  7635. * Disables the large video
  7636. */
  7637. disable: function () {
  7638. isEnabled = false;
  7639. },
  7640. /**
  7641. * Enables the large video
  7642. */
  7643. enable: function () {
  7644. isEnabled = true;
  7645. },
  7646. /**
  7647. * Returns true if the video is enabled.
  7648. */
  7649. isEnabled: function () {
  7650. return isEnabled;
  7651. },
  7652. /**
  7653. * Creates the iframe used by the etherpad
  7654. * @param src the value for src attribute
  7655. * @param onloadHandler handler executed when the iframe loads it content
  7656. * @returns {HTMLElement} the iframe
  7657. */
  7658. createEtherpadIframe: function (src, onloadHandler) {
  7659. if(!isEnabled)
  7660. return;
  7661. var etherpadIFrame = document.createElement('iframe');
  7662. etherpadIFrame.src = src;
  7663. etherpadIFrame.frameBorder = 0;
  7664. etherpadIFrame.scrolling = "no";
  7665. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7666. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7667. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7668. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7669. etherpadIFrame.onload = onloadHandler;
  7670. return etherpadIFrame;
  7671. },
  7672. /**
  7673. * Changes the state of the large video.
  7674. * Possible values - video, prezi, etherpad.
  7675. * @param newState - the new state
  7676. */
  7677. setState: function (newState) {
  7678. if(state === newState)
  7679. return;
  7680. var currentContainer = getContainerByState(state);
  7681. if(!currentContainer)
  7682. return;
  7683. var self = this;
  7684. var oldState = state;
  7685. switch (newState)
  7686. {
  7687. case "etherpad":
  7688. $('#activeSpeaker').css('visibility', 'hidden');
  7689. currentContainer.fadeOut(300, function () {
  7690. if (oldState === "prezi") {
  7691. currentContainer.css({opacity: '0'});
  7692. $('#reloadPresentation').css({display: 'none'});
  7693. }
  7694. else {
  7695. self.setLargeVideoVisible(false);
  7696. }
  7697. });
  7698. $('#etherpad>iframe').fadeIn(300, function () {
  7699. document.body.style.background = '#eeeeee';
  7700. $('#etherpad>iframe').css({visibility: 'visible'});
  7701. $('#etherpad').css({zIndex: 2});
  7702. });
  7703. break;
  7704. case "prezi":
  7705. var prezi = $('#presentation>iframe');
  7706. currentContainer.fadeOut(300, function() {
  7707. document.body.style.background = 'black';
  7708. });
  7709. prezi.fadeIn(300, function() {
  7710. prezi.css({opacity:'1'});
  7711. ToolbarToggler.dockToolbar(true);//fix that
  7712. self.setLargeVideoVisible(false);
  7713. $('#etherpad>iframe').css({visibility: 'hidden'});
  7714. $('#etherpad').css({zIndex: 0});
  7715. });
  7716. $('#activeSpeaker').css('visibility', 'hidden');
  7717. break;
  7718. case "video":
  7719. currentContainer.fadeOut(300, function () {
  7720. $('#presentation>iframe').css({opacity:'0'});
  7721. $('#reloadPresentation').css({display:'none'});
  7722. $('#etherpad>iframe').css({visibility: 'hidden'});
  7723. $('#etherpad').css({zIndex: 0});
  7724. document.body.style.background = 'black';
  7725. ToolbarToggler.dockToolbar(false);//fix that
  7726. });
  7727. $('#largeVideo').fadeIn(300, function () {
  7728. self.setLargeVideoVisible(true);
  7729. });
  7730. break;
  7731. }
  7732. state = newState;
  7733. },
  7734. /**
  7735. * Returns the current state of the large video.
  7736. * @returns {string} the current state - video, prezi or etherpad.
  7737. */
  7738. getState: function () {
  7739. return state;
  7740. },
  7741. /**
  7742. * Sets hover handlers for the large video container div.
  7743. *
  7744. * @param inHandler
  7745. * @param outHandler
  7746. */
  7747. setHover: function(inHandler, outHandler)
  7748. {
  7749. $('#largeVideoContainer').hover(inHandler, outHandler);
  7750. },
  7751. /**
  7752. * Enables/disables the filter indicating a video problem to the user.
  7753. *
  7754. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  7755. */
  7756. enableVideoProblemFilter: function (enable) {
  7757. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  7758. }
  7759. };
  7760. module.exports = LargeVideo;
  7761. },{"../../../service/UI/UIEvents":104,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":68,"../avatar/Avatar":16,"../toolbars/ToolbarToggler":29,"../util/UIUtil":33}],36:[function(require,module,exports){
  7762. /* global $, interfaceConfig, APP */
  7763. var SmallVideo = require("./SmallVideo");
  7764. var ConnectionIndicator = require("./ConnectionIndicator");
  7765. var NicknameHandler = require("../util/NicknameHandler");
  7766. var UIUtil = require("../util/UIUtil");
  7767. var LargeVideo = require("./LargeVideo");
  7768. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7769. function LocalVideo(VideoLayout) {
  7770. this.videoSpanId = "localVideoContainer";
  7771. this.container = $("#localVideoContainer").get(0);
  7772. this.VideoLayout = VideoLayout;
  7773. this.flipX = true;
  7774. this.isLocal = true;
  7775. this.peerJid = null;
  7776. }
  7777. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7778. LocalVideo.prototype.constructor = LocalVideo;
  7779. /**
  7780. * Creates the edit display name button.
  7781. *
  7782. * @returns {object} the edit button
  7783. */
  7784. function createEditDisplayNameButton() {
  7785. var editButton = document.createElement('a');
  7786. editButton.className = 'displayname';
  7787. UIUtil.setTooltip(editButton,
  7788. "videothumbnail.editnickname",
  7789. "top");
  7790. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7791. return editButton;
  7792. }
  7793. /**
  7794. * Sets the display name for the given video span id.
  7795. */
  7796. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7797. if (!this.container) {
  7798. console.warn(
  7799. "Unable to set displayName - " + this.videoSpanId +
  7800. " does not exist");
  7801. return;
  7802. }
  7803. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7804. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7805. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7806. var meHTML;
  7807. // If we already have a display name for this video.
  7808. if (nameSpan.length > 0) {
  7809. if (nameSpan.text() !== displayName) {
  7810. if (displayName && displayName.length > 0) {
  7811. meHTML = APP.translation.generateTranslationHTML("me");
  7812. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7813. } else {
  7814. $('#localDisplayName').html(defaultLocalDisplayName);
  7815. }
  7816. }
  7817. } else {
  7818. var editButton = createEditDisplayNameButton();
  7819. nameSpan = document.createElement('span');
  7820. nameSpan.className = 'displayname';
  7821. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7822. if (displayName && displayName.length > 0) {
  7823. meHTML = APP.translation.generateTranslationHTML("me");
  7824. nameSpan.innerHTML = displayName + meHTML;
  7825. }
  7826. else {
  7827. nameSpan.innerHTML = defaultLocalDisplayName;
  7828. }
  7829. nameSpan.id = 'localDisplayName';
  7830. this.container.appendChild(editButton);
  7831. //translates popover of edit button
  7832. APP.translation.translateElement($("a.displayname"));
  7833. var editableText = document.createElement('input');
  7834. editableText.className = 'displayname';
  7835. editableText.type = 'text';
  7836. editableText.id = 'editDisplayName';
  7837. if (displayName && displayName.length) {
  7838. editableText.value = displayName;
  7839. }
  7840. var defaultNickname = APP.translation.translateString(
  7841. "defaultNickname", {name: "Jane Pink"});
  7842. editableText.setAttribute('style', 'display:none;');
  7843. editableText.setAttribute('data-18n',
  7844. '[placeholder]defaultNickname');
  7845. editableText.setAttribute("data-i18n-options",
  7846. JSON.stringify({name: "Jane Pink"}));
  7847. editableText.setAttribute("placeholder", defaultNickname);
  7848. this.container.appendChild(editableText);
  7849. var self = this;
  7850. $('#localVideoContainer .displayname')
  7851. .bind("click", function (e) {
  7852. var editDisplayName = $('#editDisplayName');
  7853. e.preventDefault();
  7854. e.stopPropagation();
  7855. $('#localDisplayName').hide();
  7856. editDisplayName.show();
  7857. editDisplayName.focus();
  7858. editDisplayName.select();
  7859. editDisplayName.one("focusout", function (e) {
  7860. self.VideoLayout.inputDisplayNameHandler(this.value);
  7861. });
  7862. editDisplayName.on('keydown', function (e) {
  7863. if (e.keyCode === 13) {
  7864. e.preventDefault();
  7865. self.VideoLayout.inputDisplayNameHandler(this.value);
  7866. }
  7867. });
  7868. });
  7869. }
  7870. };
  7871. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7872. NicknameHandler.setNickname(name);
  7873. var localDisplayName = $('#localDisplayName');
  7874. if (!localDisplayName.is(":visible")) {
  7875. if (NicknameHandler.getNickname()) {
  7876. var meHTML = APP.translation.generateTranslationHTML("me");
  7877. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  7878. meHTML + ")");
  7879. } else {
  7880. var defaultHTML = APP.translation.generateTranslationHTML(
  7881. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7882. localDisplayName .html(defaultHTML);
  7883. }
  7884. localDisplayName.show();
  7885. }
  7886. $('#editDisplayName').hide();
  7887. };
  7888. LocalVideo.prototype.createConnectionIndicator = function() {
  7889. if(this.connectionIndicator)
  7890. return;
  7891. this.connectionIndicator = new ConnectionIndicator(this, null);
  7892. };
  7893. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7894. var self = this;
  7895. function localVideoClick(event) {
  7896. // FIXME: with Temasys plugin event arg is not an event, but
  7897. // the clicked object itself, so we have to skip this call
  7898. if (event.stopPropagation) {
  7899. event.stopPropagation();
  7900. }
  7901. self.VideoLayout.handleVideoThumbClicked(
  7902. false,
  7903. APP.xmpp.myResource());
  7904. }
  7905. var localVideoContainerSelector = $('#localVideoContainer');
  7906. localVideoContainerSelector.off('click');
  7907. localVideoContainerSelector.on('click', localVideoClick);
  7908. // Add hover handler
  7909. localVideoContainerSelector.hover(
  7910. function() {
  7911. self.showDisplayName(true);
  7912. },
  7913. function() {
  7914. if (!LargeVideo.isLargeVideoVisible() ||
  7915. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  7916. self.showDisplayName(false);
  7917. }
  7918. }
  7919. );
  7920. if(isMuted) {
  7921. APP.UI.setVideoMute(true);
  7922. return;
  7923. }
  7924. this.flipX = stream.videoType != "screen";
  7925. var localVideo = document.createElement('video');
  7926. localVideo.id = 'localVideo_' +
  7927. APP.RTC.getStreamID(stream.getOriginalStream());
  7928. if (!RTCBrowserType.isIExplorer()) {
  7929. localVideo.autoplay = true;
  7930. localVideo.volume = 0; // is it required if audio is separated ?
  7931. }
  7932. localVideo.oncontextmenu = function () { return false; };
  7933. var localVideoContainer = document.getElementById('localVideoWrapper');
  7934. localVideoContainer.appendChild(localVideo);
  7935. var localVideoSelector = $('#' + localVideo.id);
  7936. // Add click handler to both video and video wrapper elements in case
  7937. // there's no video.
  7938. // onclick has to be used with Temasys plugin
  7939. localVideo.onclick = localVideoClick;
  7940. if (this.flipX) {
  7941. localVideoSelector.addClass("flipVideoX");
  7942. }
  7943. // Attach WebRTC stream
  7944. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7945. // Add stream ended handler
  7946. stream.getOriginalStream().onended = function () {
  7947. // We have to re-select after attach when Temasys plugin is used,
  7948. // because <video> element is replaced with <object>
  7949. localVideo = $('#' + localVideo.id)[0];
  7950. localVideoContainer.removeChild(localVideo);
  7951. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7952. };
  7953. };
  7954. LocalVideo.prototype.joined = function (jid) {
  7955. this.peerJid = jid;
  7956. };
  7957. LocalVideo.prototype.getResourceJid = function () {
  7958. var myResource = APP.xmpp.myResource();
  7959. if (!myResource) {
  7960. console.error("Requested local resource before we're in the MUC");
  7961. }
  7962. return myResource;
  7963. };
  7964. module.exports = LocalVideo;
  7965. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7966. /* global $, APP, require, Strophe, interfaceConfig */
  7967. var ConnectionIndicator = require("./ConnectionIndicator");
  7968. var SmallVideo = require("./SmallVideo");
  7969. var AudioLevels = require("../audio_levels/AudioLevels");
  7970. var LargeVideo = require("./LargeVideo");
  7971. var Avatar = require("../avatar/Avatar");
  7972. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7973. function RemoteVideo(peerJid, VideoLayout) {
  7974. this.peerJid = peerJid;
  7975. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7976. this.videoSpanId = 'participant_' + this.resourceJid;
  7977. this.VideoLayout = VideoLayout;
  7978. this.addRemoteVideoContainer();
  7979. this.connectionIndicator = new ConnectionIndicator(
  7980. this, this.peerJid);
  7981. this.setDisplayName();
  7982. var nickfield = document.createElement('span');
  7983. nickfield.className = "nick";
  7984. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7985. this.container.appendChild(nickfield);
  7986. this.flipX = false;
  7987. this.isLocal = false;
  7988. }
  7989. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7990. RemoteVideo.prototype.constructor = RemoteVideo;
  7991. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7992. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7993. if (APP.xmpp.isModerator())
  7994. this.addRemoteVideoMenu();
  7995. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7996. return this.container;
  7997. };
  7998. /**
  7999. * Adds the remote video menu element for the given <tt>jid</tt> in the
  8000. * given <tt>parentElement</tt>.
  8001. *
  8002. * @param jid the jid indicating the video for which we're adding a menu.
  8003. * @param parentElement the parent element where this menu will be added
  8004. */
  8005. if (!interfaceConfig.filmStripOnly) {
  8006. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  8007. var spanElement = document.createElement('span');
  8008. spanElement.className = 'remotevideomenu';
  8009. this.container.appendChild(spanElement);
  8010. var menuElement = document.createElement('i');
  8011. menuElement.className = 'fa fa-angle-down';
  8012. menuElement.title = 'Remote user controls';
  8013. spanElement.appendChild(menuElement);
  8014. var popupmenuElement = document.createElement('ul');
  8015. popupmenuElement.className = 'popupmenu';
  8016. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  8017. spanElement.appendChild(popupmenuElement);
  8018. var muteMenuItem = document.createElement('li');
  8019. var muteLinkItem = document.createElement('a');
  8020. var mutedIndicator = "<i style='float:left;' " +
  8021. "class='icon-mic-disabled'></i>";
  8022. if (!this.isMuted) {
  8023. muteLinkItem.innerHTML = mutedIndicator +
  8024. " <div style='width: 90px;margin-left: 20px;' " +
  8025. "data-i18n='videothumbnail.domute'></div>";
  8026. muteLinkItem.className = 'mutelink';
  8027. }
  8028. else {
  8029. muteLinkItem.innerHTML = mutedIndicator +
  8030. " <div style='width: 90px;margin-left: 20px;' " +
  8031. "data-i18n='videothumbnail.muted'></div>";
  8032. muteLinkItem.className = 'mutelink disabled';
  8033. }
  8034. var self = this;
  8035. muteLinkItem.onclick = function(){
  8036. if ($(this).attr('disabled') != undefined) {
  8037. event.preventDefault();
  8038. }
  8039. var isMute = self.isMuted == true;
  8040. APP.xmpp.setMute(self.peerJid, !isMute);
  8041. popupmenuElement.setAttribute('style', 'display:none;');
  8042. if (isMute) {
  8043. this.innerHTML = mutedIndicator +
  8044. " <div style='width: 90px;margin-left: 20px;' " +
  8045. "data-i18n='videothumbnail.muted'></div>";
  8046. this.className = 'mutelink disabled';
  8047. }
  8048. else {
  8049. this.innerHTML = mutedIndicator +
  8050. " <div style='width: 90px;margin-left: 20px;' " +
  8051. "data-i18n='videothumbnail.domute'></div>";
  8052. this.className = 'mutelink';
  8053. }
  8054. };
  8055. muteMenuItem.appendChild(muteLinkItem);
  8056. popupmenuElement.appendChild(muteMenuItem);
  8057. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8058. var ejectMenuItem = document.createElement('li');
  8059. var ejectLinkItem = document.createElement('a');
  8060. var ejectText = "<div style='width: 90px;margin-left: 20px;' " +
  8061. "data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8062. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8063. ejectLinkItem.onclick = function(){
  8064. APP.xmpp.eject(self.peerJid);
  8065. popupmenuElement.setAttribute('style', 'display:none;');
  8066. };
  8067. ejectMenuItem.appendChild(ejectLinkItem);
  8068. popupmenuElement.appendChild(ejectMenuItem);
  8069. var paddingSpan = document.createElement('span');
  8070. paddingSpan.className = 'popupmenuPadding';
  8071. popupmenuElement.appendChild(paddingSpan);
  8072. APP.translation.translateElement(
  8073. $("#" + popupmenuElement.id + " > li > a > div"));
  8074. };
  8075. } else {
  8076. RemoteVideo.prototype.addRemoteVideoMenu = function() {}
  8077. }
  8078. /**
  8079. * Removes the remote stream element corresponding to the given stream and
  8080. * parent container.
  8081. *
  8082. * @param stream the stream
  8083. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8084. */
  8085. RemoteVideo.prototype.removeRemoteStreamElement =
  8086. function (stream, isVideo, id) {
  8087. if (!this.container)
  8088. return false;
  8089. var select = null;
  8090. if (isVideo) {
  8091. select = $('#' + id);
  8092. }
  8093. else
  8094. select = $('#' + this.videoSpanId + '>audio');
  8095. select.remove();
  8096. console.info((isVideo ? "Video" : "Audio") +
  8097. " removed " + this.getResourceJid(), select);
  8098. if (isVideo)
  8099. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8100. };
  8101. /**
  8102. * Removes RemoteVideo from the page.
  8103. */
  8104. RemoteVideo.prototype.remove = function () {
  8105. console.log("Remove thumbnail", this.peerJid);
  8106. this.removeConnectionIndicator();
  8107. // Remove whole container
  8108. if (this.container.parentNode)
  8109. this.container.parentNode.removeChild(this.container);
  8110. };
  8111. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8112. var isVideo = stream.getVideoTracks().length > 0;
  8113. if (!isVideo || stream.id === 'mixedmslabel') {
  8114. return;
  8115. }
  8116. var self = this;
  8117. var resourceJid = this.getResourceJid();
  8118. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8119. // when video playback starts
  8120. var onPlayingHandler = function () {
  8121. // FIXME: why do i have to do this for FF?
  8122. if (RTCBrowserType.isFirefox()) {
  8123. APP.RTC.attachMediaStream(sel, stream);
  8124. }
  8125. if (RTCBrowserType.isTemasysPluginUsed()) {
  8126. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8127. }
  8128. self.VideoLayout.videoactive(sel, resourceJid);
  8129. sel[0].onplaying = null;
  8130. if (RTCBrowserType.isTemasysPluginUsed()) {
  8131. // 'currentTime' is used to check if the video has started
  8132. // and the value is not set by the plugin, so we do it
  8133. sel[0].currentTime = 1;
  8134. }
  8135. };
  8136. sel[0].onplaying = onPlayingHandler;
  8137. };
  8138. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8139. if (!this.container)
  8140. return;
  8141. var self = this;
  8142. var isVideo = stream.getVideoTracks().length > 0;
  8143. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8144. var newElementId = streamElement.id;
  8145. this.container.appendChild(streamElement);
  8146. var sel = $('#' + newElementId);
  8147. sel.hide();
  8148. // If the container is currently visible we attach the stream.
  8149. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8150. this.waitForPlayback(sel, stream);
  8151. APP.RTC.attachMediaStream(sel, stream);
  8152. }
  8153. stream.onended = function () {
  8154. console.log('stream ended', this);
  8155. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8156. };
  8157. // Name of video element name is different for IE/Safari
  8158. var videoElem = APP.RTC.getVideoElementName();
  8159. // Add click handler.
  8160. var onClickHandler = function (event) {
  8161. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8162. // On IE we need to populate this handler on video <object>
  8163. // and it does not give event instance as an argument,
  8164. // so we check here for methods.
  8165. if (event.stopPropagation && event.preventDefault) {
  8166. event.stopPropagation();
  8167. event.preventDefault();
  8168. }
  8169. return false;
  8170. };
  8171. this.container.onclick = onClickHandler;
  8172. // reselect
  8173. if (RTCBrowserType.isTemasysPluginUsed())
  8174. sel = $('#' + newElementId);
  8175. sel[0].onclick = onClickHandler;
  8176. //FIXME
  8177. // Add hover handler
  8178. $(this.container).hover(
  8179. function() {
  8180. self.showDisplayName(true);
  8181. },
  8182. function() {
  8183. // If the video has been "pinned" by the user we want to
  8184. // keep the display name on place.
  8185. if (!LargeVideo.isLargeVideoVisible() ||
  8186. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8187. self.showDisplayName(false);
  8188. }
  8189. );
  8190. },
  8191. /**
  8192. * Show/hide peer container for the given resourceJid.
  8193. */
  8194. RemoteVideo.prototype.showPeerContainer = function (state) {
  8195. if (!this.container)
  8196. return;
  8197. var isHide = state === 'hide';
  8198. var resizeThumbnails = false;
  8199. if (!isHide) {
  8200. if (!$(this.container).is(':visible')) {
  8201. resizeThumbnails = true;
  8202. $(this.container).show();
  8203. }
  8204. this.showAvatar(state !== 'show');
  8205. }
  8206. else if ($(this.container).is(':visible') && isHide)
  8207. {
  8208. resizeThumbnails = true;
  8209. $(this.container).hide();
  8210. if(this.connectionIndicator)
  8211. this.connectionIndicator.hide();
  8212. }
  8213. if (resizeThumbnails) {
  8214. this.VideoLayout.resizeThumbnails();
  8215. }
  8216. // We want to be able to pin a participant from the contact list, even
  8217. // if he's not in the lastN set!
  8218. // ContactList.setClickable(resourceJid, !isHide);
  8219. };
  8220. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8221. if (this.connectionIndicator)
  8222. this.connectionIndicator.remove();
  8223. };
  8224. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8225. if (this.connectionIndicator)
  8226. this.connectionIndicator.hide();
  8227. };
  8228. /**
  8229. * Updates the remote video menu.
  8230. *
  8231. * @param jid the jid indicating the video for which we're adding a menu.
  8232. * @param isMuted indicates the current mute state
  8233. */
  8234. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8235. var muteMenuItem
  8236. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8237. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8238. if (muteMenuItem.length) {
  8239. var muteLink = muteMenuItem.get(0);
  8240. if (isMuted === 'true') {
  8241. muteLink.innerHTML = mutedIndicator + ' Muted';
  8242. muteLink.className = 'mutelink disabled';
  8243. }
  8244. else {
  8245. muteLink.innerHTML = mutedIndicator + ' Mute';
  8246. muteLink.className = 'mutelink';
  8247. }
  8248. }
  8249. };
  8250. /**
  8251. * Sets the display name for the given video span id.
  8252. */
  8253. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8254. if (!this.container) {
  8255. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8256. " does not exist");
  8257. return;
  8258. }
  8259. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8260. // If we already have a display name for this video.
  8261. if (nameSpan.length > 0) {
  8262. if (displayName && displayName.length > 0) {
  8263. $('#' + this.videoSpanId + '_name').html(displayName);
  8264. }
  8265. else if (key && key.length > 0) {
  8266. var nameHtml = APP.translation.generateTranslationHTML(key);
  8267. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8268. }
  8269. else
  8270. $('#' + this.videoSpanId + '_name').text(
  8271. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8272. } else {
  8273. nameSpan = document.createElement('span');
  8274. nameSpan.className = 'displayname';
  8275. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8276. if (displayName && displayName.length > 0) {
  8277. nameSpan.innerText = displayName;
  8278. }
  8279. else
  8280. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8281. nameSpan.id = this.videoSpanId + '_name';
  8282. }
  8283. };
  8284. /**
  8285. * Removes remote video menu element from video element identified by
  8286. * given <tt>videoElementId</tt>.
  8287. *
  8288. * @param videoElementId the id of local or remote video element.
  8289. */
  8290. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8291. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8292. if (menuSpan.length) {
  8293. menuSpan.remove();
  8294. }
  8295. };
  8296. RemoteVideo.prototype.getResourceJid = function () {
  8297. if (!this.resourceJid) {
  8298. console.error("Undefined resource jid");
  8299. }
  8300. return this.resourceJid;
  8301. };
  8302. RemoteVideo.createContainer = function (spanId) {
  8303. var container = document.createElement('span');
  8304. container.id = spanId;
  8305. container.className = 'videocontainer';
  8306. var remotes = document.getElementById('remoteVideos');
  8307. return remotes.appendChild(container);
  8308. };
  8309. module.exports = RemoteVideo;
  8310. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8311. /* global $, APP, require */
  8312. var Avatar = require("../avatar/Avatar");
  8313. var UIUtil = require("../util/UIUtil");
  8314. var LargeVideo = require("./LargeVideo");
  8315. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8316. function SmallVideo() {
  8317. this.isMuted = false;
  8318. this.hasAvatar = false;
  8319. }
  8320. function setVisibility(selector, show) {
  8321. if (selector && selector.length > 0) {
  8322. selector.css("visibility", show ? "visible" : "hidden");
  8323. }
  8324. }
  8325. SmallVideo.prototype.showDisplayName = function(isShow) {
  8326. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8327. if (isShow) {
  8328. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8329. nameSpan.setAttribute("style", "display:inline-block;");
  8330. }
  8331. else {
  8332. if (nameSpan)
  8333. nameSpan.setAttribute("style", "display:none;");
  8334. }
  8335. };
  8336. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8337. if(!this.container)
  8338. return;
  8339. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8340. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8341. noMic.remove();
  8342. noVideo.remove();
  8343. if (!devices.audio) {
  8344. this.container.appendChild(
  8345. document.createElement("div")).setAttribute("class", "noMic");
  8346. }
  8347. if (!devices.video) {
  8348. this.container.appendChild(
  8349. document.createElement("div")).setAttribute("class", "noVideo");
  8350. }
  8351. if (!devices.audio && !devices.video) {
  8352. noMic.css("background-position", "75%");
  8353. noVideo.css("background-position", "25%");
  8354. noVideo.css("background-color", "transparent");
  8355. }
  8356. };
  8357. /**
  8358. * Sets the type of the video displayed by this instance.
  8359. * @param videoType 'camera' or 'screen'
  8360. */
  8361. SmallVideo.prototype.setVideoType = function (videoType) {
  8362. this.videoType = videoType;
  8363. };
  8364. /**
  8365. * Returns the type of the video displayed by this instance.
  8366. * @returns {String} 'camera', 'screen' or undefined.
  8367. */
  8368. SmallVideo.prototype.getVideoType = function () {
  8369. return this.videoType;
  8370. };
  8371. /**
  8372. * Shows the presence status message for the given video.
  8373. */
  8374. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8375. if (!this.container) {
  8376. // No container
  8377. return;
  8378. }
  8379. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8380. if (!statusSpan.length) {
  8381. //Add status span
  8382. statusSpan = document.createElement('span');
  8383. statusSpan.className = 'status';
  8384. statusSpan.id = this.videoSpanId + '_status';
  8385. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8386. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8387. }
  8388. // Display status
  8389. if (statusMsg && statusMsg.length) {
  8390. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8391. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8392. }
  8393. else {
  8394. // Hide
  8395. statusSpan.get(0).setAttribute("style", "display:none;");
  8396. }
  8397. };
  8398. /**
  8399. * Creates an audio or video stream element.
  8400. */
  8401. SmallVideo.createStreamElement = function (sid, stream) {
  8402. var isVideo = stream.getVideoTracks().length > 0;
  8403. var element = isVideo ? document.createElement('video')
  8404. : document.createElement('audio');
  8405. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8406. APP.RTC.getStreamID(stream);
  8407. element.id = id;
  8408. if (!RTCBrowserType.isIExplorer()) {
  8409. element.autoplay = true;
  8410. }
  8411. element.oncontextmenu = function () { return false; };
  8412. return element;
  8413. };
  8414. /**
  8415. * Updates the data for the indicator
  8416. * @param id the id of the indicator
  8417. * @param percent the percent for connection quality
  8418. * @param object the data
  8419. */
  8420. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8421. if(this.connectionIndicator)
  8422. this.connectionIndicator.updateConnectionQuality(percent, object);
  8423. };
  8424. SmallVideo.prototype.hideIndicator = function () {
  8425. if(this.connectionIndicator)
  8426. this.connectionIndicator.hideIndicator();
  8427. };
  8428. /**
  8429. * Shows audio muted indicator over small videos.
  8430. * @param {string} isMuted
  8431. */
  8432. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8433. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8434. if (!isMuted) {
  8435. if (audioMutedSpan.length > 0) {
  8436. audioMutedSpan.popover('hide');
  8437. audioMutedSpan.remove();
  8438. }
  8439. }
  8440. else {
  8441. if(audioMutedSpan.length == 0 ) {
  8442. audioMutedSpan = document.createElement('span');
  8443. audioMutedSpan.className = 'audioMuted';
  8444. UIUtil.setTooltip(audioMutedSpan,
  8445. "videothumbnail.mute",
  8446. "top");
  8447. this.container.appendChild(audioMutedSpan);
  8448. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8449. var mutedIndicator = document.createElement('i');
  8450. mutedIndicator.className = 'icon-mic-disabled';
  8451. audioMutedSpan.appendChild(mutedIndicator);
  8452. }
  8453. this.updateIconPositions();
  8454. }
  8455. this.isMuted = isMuted;
  8456. };
  8457. /**
  8458. * Shows video muted indicator over small videos.
  8459. */
  8460. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8461. this.showAvatar(isMuted);
  8462. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8463. if (isMuted === false) {
  8464. if (videoMutedSpan.length > 0) {
  8465. videoMutedSpan.remove();
  8466. }
  8467. }
  8468. else {
  8469. if(videoMutedSpan.length == 0) {
  8470. videoMutedSpan = document.createElement('span');
  8471. videoMutedSpan.className = 'videoMuted';
  8472. this.container.appendChild(videoMutedSpan);
  8473. var mutedIndicator = document.createElement('i');
  8474. mutedIndicator.className = 'icon-camera-disabled';
  8475. UIUtil.setTooltip(mutedIndicator,
  8476. "videothumbnail.videomute",
  8477. "top");
  8478. videoMutedSpan.appendChild(mutedIndicator);
  8479. //translate texts for muted indicator
  8480. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8481. }
  8482. this.updateIconPositions();
  8483. }
  8484. };
  8485. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8486. var resourceJid = this.getResourceJid();
  8487. var displayName = resourceJid;
  8488. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8489. if (nameSpan.length > 0)
  8490. displayName = nameSpan.html();
  8491. console.log("UI enable dominant speaker",
  8492. displayName,
  8493. resourceJid,
  8494. isEnable);
  8495. if (!this.container) {
  8496. return;
  8497. }
  8498. if (isEnable) {
  8499. this.showDisplayName(LargeVideo.getState() === "video");
  8500. if (!this.container.classList.contains("dominantspeaker"))
  8501. this.container.classList.add("dominantspeaker");
  8502. }
  8503. else {
  8504. this.showDisplayName(false);
  8505. if (this.container.classList.contains("dominantspeaker"))
  8506. this.container.classList.remove("dominantspeaker");
  8507. }
  8508. this.showAvatar();
  8509. };
  8510. SmallVideo.prototype.updateIconPositions = function () {
  8511. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8512. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8513. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8514. if(connectionIndicator.length > 0 &&
  8515. connectionIndicator[0].style.display != "none") {
  8516. audioMutedSpan.css({right: "23px"});
  8517. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8518. } else {
  8519. audioMutedSpan.css({right: "0px"});
  8520. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8521. }
  8522. };
  8523. /**
  8524. * Creates the element indicating the moderator(owner) of the conference.
  8525. *
  8526. * @param parentElement the parent element where the owner indicator will
  8527. * be added
  8528. */
  8529. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8530. // Show moderator indicator
  8531. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8532. if (!indicatorSpan || indicatorSpan.length === 0) {
  8533. indicatorSpan = document.createElement('span');
  8534. indicatorSpan.className = 'focusindicator';
  8535. this.container.appendChild(indicatorSpan);
  8536. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8537. }
  8538. if (indicatorSpan.children().length !== 0)
  8539. return;
  8540. var moderatorIndicator = document.createElement('i');
  8541. moderatorIndicator.className = 'fa fa-star';
  8542. indicatorSpan[0].appendChild(moderatorIndicator);
  8543. UIUtil.setTooltip(indicatorSpan[0],
  8544. "videothumbnail.moderator",
  8545. "top");
  8546. //translates text in focus indicators
  8547. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8548. };
  8549. SmallVideo.prototype.getSrc = function () {
  8550. var videoElement = APP.RTC.getVideoElementName();
  8551. return APP.RTC.getVideoSrc(
  8552. $('#' + this.videoSpanId).find(videoElement).get(0));
  8553. };
  8554. SmallVideo.prototype.focus = function(isFocused) {
  8555. if(!isFocused) {
  8556. this.container.classList.remove("videoContainerFocused");
  8557. } else {
  8558. this.container.classList.add("videoContainerFocused");
  8559. }
  8560. };
  8561. SmallVideo.prototype.hasVideo = function () {
  8562. return $("#" + this.videoSpanId).find(
  8563. APP.RTC.getVideoElementName()).length !== 0;
  8564. };
  8565. /**
  8566. * Hides or shows the user's avatar
  8567. * @param show whether we should show the avatar or not
  8568. * video because there is no dominant speaker and no focused speaker
  8569. */
  8570. SmallVideo.prototype.showAvatar = function (show) {
  8571. if (!this.hasAvatar) {
  8572. if (this.peerJid) {
  8573. // Init avatar
  8574. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8575. } else {
  8576. console.error("Unable to init avatar - no peerjid", this);
  8577. return;
  8578. }
  8579. }
  8580. var resourceJid = this.getResourceJid();
  8581. var videoElem = APP.RTC.getVideoElementName();
  8582. var video = $('#' + this.videoSpanId).find(videoElem);
  8583. var avatar = $('#avatar_' + resourceJid);
  8584. if (show === undefined || show === null) {
  8585. if (!this.isLocal &&
  8586. !this.VideoLayout.isInLastN(resourceJid)) {
  8587. show = true;
  8588. } else {
  8589. // We want to show the avatar when the video is muted or not exists
  8590. // that is when 'true' or 'null' is returned
  8591. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8592. }
  8593. }
  8594. if (LargeVideo.showAvatar(resourceJid, show)) {
  8595. setVisibility(avatar, false);
  8596. setVisibility(video, false);
  8597. } else {
  8598. if (video && video.length > 0) {
  8599. setVisibility(video, !show);
  8600. }
  8601. setVisibility(avatar, show);
  8602. }
  8603. };
  8604. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8605. var thumbnail = $('#' + this.videoSpanId);
  8606. var resourceJid = this.getResourceJid();
  8607. var avatar = $('#avatar_' + resourceJid);
  8608. this.hasAvatar = true;
  8609. // set the avatar in the thumbnail
  8610. if (avatar && avatar.length > 0) {
  8611. avatar[0].src = thumbUrl;
  8612. } else {
  8613. if (thumbnail && thumbnail.length > 0) {
  8614. avatar = document.createElement('img');
  8615. avatar.id = 'avatar_' + resourceJid;
  8616. avatar.className = 'userAvatar';
  8617. avatar.src = thumbUrl;
  8618. thumbnail.append(avatar);
  8619. }
  8620. }
  8621. };
  8622. module.exports = SmallVideo;
  8623. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8624. /* global config, APP, $, Strophe, require, interfaceConfig */
  8625. var AudioLevels = require("../audio_levels/AudioLevels");
  8626. var ContactList = require("../side_pannels/contactlist/ContactList");
  8627. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8628. var UIEvents = require("../../../service/UI/UIEvents");
  8629. var UIUtil = require("../util/UIUtil");
  8630. var RTC = require("../../RTC/RTC");
  8631. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8632. var RemoteVideo = require("./RemoteVideo");
  8633. var LargeVideo = require("./LargeVideo");
  8634. var LocalVideo = require("./LocalVideo");
  8635. var remoteVideos = {};
  8636. var remoteVideoTypes = {};
  8637. var localVideoThumbnail = null;
  8638. var currentDominantSpeaker = null;
  8639. var lastNCount = config.channelLastN;
  8640. var localLastNCount = config.channelLastN;
  8641. var localLastNSet = [];
  8642. var lastNEndpointsCache = [];
  8643. var lastNPickupJid = null;
  8644. var eventEmitter = null;
  8645. /**
  8646. * Currently focused video jid
  8647. * @type {String}
  8648. */
  8649. var focusedVideoResourceJid = null;
  8650. var VideoLayout = (function (my) {
  8651. my.init = function (emitter) {
  8652. eventEmitter = emitter;
  8653. localVideoThumbnail = new LocalVideo(VideoLayout);
  8654. if (interfaceConfig.filmStripOnly) {
  8655. LargeVideo.disable();
  8656. } else {
  8657. LargeVideo.init(VideoLayout, emitter);
  8658. }
  8659. VideoLayout.resizeLargeVideoContainer();
  8660. };
  8661. my.isInLastN = function(resource) {
  8662. return lastNCount < 0 || // lastN is disabled
  8663. // lastNEndpoints cache not built yet
  8664. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8665. (lastNEndpointsCache &&
  8666. lastNEndpointsCache.indexOf(resource) !== -1);
  8667. };
  8668. my.changeLocalStream = function (stream, isMuted) {
  8669. VideoLayout.changeLocalVideo(stream, isMuted);
  8670. };
  8671. my.changeLocalAudio = function(stream, isMuted) {
  8672. if (isMuted)
  8673. APP.UI.setAudioMuted(true, true);
  8674. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8675. var localAudio = document.getElementById('localAudio');
  8676. // Writing volume not allowed in IE
  8677. if (!RTCBrowserType.isIExplorer()) {
  8678. localAudio.autoplay = true;
  8679. localAudio.volume = 0;
  8680. }
  8681. };
  8682. my.changeLocalVideo = function(stream, isMuted) {
  8683. // Set default display name.
  8684. localVideoThumbnail.setDisplayName();
  8685. localVideoThumbnail.createConnectionIndicator();
  8686. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  8687. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8688. localVideoThumbnail.changeVideo(stream, isMuted);
  8689. /* force update if we're currently being displayed */
  8690. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8691. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8692. }
  8693. };
  8694. my.mucJoined = function () {
  8695. var myResourceJid = APP.xmpp.myResource();
  8696. localVideoThumbnail.joined(APP.xmpp.myJid());
  8697. if (!LargeVideo.getResourceJid())
  8698. LargeVideo.updateLargeVideo(myResourceJid, true);
  8699. };
  8700. /**
  8701. * Adds or removes icons for not available camera and microphone.
  8702. * @param resourceJid the jid of user
  8703. * @param devices available devices
  8704. */
  8705. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8706. if(!devices)
  8707. return;
  8708. if(!resourceJid) {
  8709. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8710. } else {
  8711. if(remoteVideos[resourceJid])
  8712. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8713. }
  8714. };
  8715. /**
  8716. * Checks if removed video is currently displayed and tries to display
  8717. * another one instead.
  8718. * @param removedVideoSrc src stream identifier of the video.
  8719. */
  8720. my.updateRemovedVideo = function(resourceJid) {
  8721. if (resourceJid === LargeVideo.getResourceJid()) {
  8722. var newResourceJid;
  8723. // We'll show user's avatar if he is the dominant speaker or if
  8724. // his video thumbnail is pinned
  8725. if (remoteVideos[resourceJid] &&
  8726. resourceJid === focusedVideoResourceJid ||
  8727. resourceJid === currentDominantSpeaker) {
  8728. newResourceJid = resourceJid;
  8729. } else {
  8730. // Otherwise select last visible video
  8731. newResourceJid = this.electLastVisibleVideo();
  8732. }
  8733. LargeVideo.updateLargeVideo(newResourceJid);
  8734. }
  8735. };
  8736. my.electLastVisibleVideo = function() {
  8737. // pick the last visible video in the row
  8738. // if nobody else is left, this picks the local video
  8739. var jid;
  8740. var videoElem = RTC.getVideoElementName();
  8741. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8742. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8743. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8744. } else {
  8745. console.info("Last visible video no longer exists");
  8746. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8747. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8748. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8749. } else {
  8750. // Try local video
  8751. console.info("Fallback to local video...");
  8752. jid = APP.xmpp.myResource();
  8753. }
  8754. }
  8755. console.info("electLastVisibleVideo: " + jid);
  8756. return jid;
  8757. };
  8758. my.onRemoteStreamAdded = function (stream) {
  8759. if (stream.peerjid) {
  8760. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8761. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8762. remoteVideos[resourceJid].addRemoteStreamElement(
  8763. stream.sid,
  8764. stream.getOriginalStream(),
  8765. stream.ssrc);
  8766. }
  8767. };
  8768. my.getLargeVideoJid = function () {
  8769. return LargeVideo.getResourceJid();
  8770. };
  8771. /**
  8772. * Called when large video update is finished
  8773. * @param currentSmallVideo small video currently displayed on large video
  8774. */
  8775. my.largeVideoUpdated = function (currentSmallVideo) {
  8776. // Makes sure that dominant speaker UI
  8777. // is enabled only on current small video
  8778. localVideoThumbnail.enableDominantSpeaker(
  8779. localVideoThumbnail === currentSmallVideo);
  8780. Object.keys(remoteVideos).forEach(
  8781. function (resourceJid) {
  8782. var remoteVideo = remoteVideos[resourceJid];
  8783. if (remoteVideo) {
  8784. remoteVideo.enableDominantSpeaker(
  8785. remoteVideo === currentSmallVideo);
  8786. }
  8787. }
  8788. );
  8789. };
  8790. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8791. resourceJid) {
  8792. if(focusedVideoResourceJid) {
  8793. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8794. if (oldSmallVideo && !interfaceConfig.filmStripOnly)
  8795. oldSmallVideo.focus(false);
  8796. }
  8797. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8798. // Unlock current focused.
  8799. if (focusedVideoResourceJid === resourceJid)
  8800. {
  8801. focusedVideoResourceJid = null;
  8802. // Enable the currently set dominant speaker.
  8803. if (currentDominantSpeaker) {
  8804. if(smallVideo && smallVideo.hasVideo()) {
  8805. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8806. }
  8807. }
  8808. if (!noPinnedEndpointChangedEvent) {
  8809. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8810. }
  8811. return;
  8812. }
  8813. // Lock new video
  8814. focusedVideoResourceJid = resourceJid;
  8815. // Update focused/pinned interface.
  8816. if (resourceJid) {
  8817. if (smallVideo && !interfaceConfig.filmStripOnly)
  8818. smallVideo.focus(true);
  8819. if (!noPinnedEndpointChangedEvent) {
  8820. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8821. }
  8822. }
  8823. LargeVideo.setState("video");
  8824. LargeVideo.updateLargeVideo(resourceJid);
  8825. // Writing volume not allowed in IE
  8826. if (!RTCBrowserType.isIExplorer()) {
  8827. $('audio').each(function (idx, el) {
  8828. el.volume = 0;
  8829. el.volume = 1;
  8830. });
  8831. }
  8832. };
  8833. /**
  8834. * Checks if container for participant identified by given peerJid exists
  8835. * in the document and creates it eventually.
  8836. *
  8837. * @param peerJid peer Jid to check.
  8838. *
  8839. * @return Returns <tt>true</tt> if the peer container exists,
  8840. * <tt>false</tt> - otherwise
  8841. */
  8842. my.ensurePeerContainerExists = function(peerJid) {
  8843. ContactList.ensureAddContact(peerJid);
  8844. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8845. if (!remoteVideos[resourceJid]) {
  8846. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  8847. remoteVideos[resourceJid] = remoteVideo;
  8848. var videoType = remoteVideoTypes[resourceJid];
  8849. if (videoType) {
  8850. remoteVideo.setVideoType(videoType);
  8851. }
  8852. // In case this is not currently in the last n we don't show it.
  8853. if (localLastNCount &&
  8854. localLastNCount > 0 &&
  8855. $('#remoteVideos>span').length >= localLastNCount + 2) {
  8856. remoteVideo.showPeerContainer('hide');
  8857. }
  8858. else
  8859. VideoLayout.resizeThumbnails();
  8860. }
  8861. };
  8862. my.inputDisplayNameHandler = function (name) {
  8863. localVideoThumbnail.inputDisplayNameHandler(name);
  8864. };
  8865. my.videoactive = function (videoelem, resourceJid) {
  8866. console.info(resourceJid + " video is now active");
  8867. videoelem.show();
  8868. VideoLayout.resizeThumbnails();
  8869. // Update the large video to the last added video only if there's no
  8870. // current dominant, focused speaker or prezi playing or update it to
  8871. // the current dominant speaker.
  8872. if ((!focusedVideoResourceJid &&
  8873. !currentDominantSpeaker &&
  8874. !require("../prezi/Prezi").isPresentationVisible()) ||
  8875. focusedVideoResourceJid === resourceJid ||
  8876. (resourceJid &&
  8877. currentDominantSpeaker === resourceJid)) {
  8878. LargeVideo.updateLargeVideo(resourceJid, true);
  8879. }
  8880. };
  8881. /**
  8882. * Shows the presence status message for the given video.
  8883. */
  8884. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8885. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8886. };
  8887. /**
  8888. * Shows a visual indicator for the moderator of the conference.
  8889. */
  8890. my.showModeratorIndicator = function () {
  8891. var isModerator = APP.xmpp.isModerator();
  8892. if (isModerator) {
  8893. localVideoThumbnail.createModeratorIndicatorElement();
  8894. }
  8895. var members = APP.xmpp.getMembers();
  8896. Object.keys(members).forEach(function (jid) {
  8897. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8898. // Skip server side focus
  8899. return;
  8900. }
  8901. var resourceJid = Strophe.getResourceFromJid(jid);
  8902. var member = members[jid];
  8903. if (member.role === 'moderator') {
  8904. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8905. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8906. } else if (isModerator) {
  8907. // We are moderator, but user is not - add menu
  8908. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8909. remoteVideos[resourceJid].addRemoteVideoMenu();
  8910. }
  8911. }
  8912. });
  8913. };
  8914. /*
  8915. * Shows or hides the audio muted indicator over the local thumbnail video.
  8916. * @param {boolean} isMuted
  8917. */
  8918. my.showLocalAudioIndicator = function(isMuted) {
  8919. localVideoThumbnail.showAudioIndicator(isMuted);
  8920. };
  8921. /**
  8922. * Resizes the large video container.
  8923. */
  8924. my.resizeLargeVideoContainer = function () {
  8925. if(LargeVideo.isEnabled()) {
  8926. LargeVideo.resize();
  8927. } else {
  8928. VideoLayout.resizeVideoSpace();
  8929. }
  8930. VideoLayout.resizeThumbnails();
  8931. LargeVideo.position();
  8932. };
  8933. /**
  8934. * Resizes thumbnails.
  8935. */
  8936. my.resizeThumbnails = function(animate) {
  8937. var videoSpaceWidth = $('#remoteVideos').width();
  8938. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8939. var width = thumbnailSize[0];
  8940. var height = thumbnailSize[1];
  8941. $('.userAvatar').css('left', (width - height) / 2);
  8942. if(animate) {
  8943. $('#remoteVideos').animate({
  8944. height: height + 2 // adds 2 px because of small video 1px border
  8945. },
  8946. {
  8947. queue: false,
  8948. duration: 500
  8949. });
  8950. $('#remoteVideos>span').animate({
  8951. height: height,
  8952. width: width
  8953. },
  8954. {
  8955. queue: false,
  8956. duration: 500,
  8957. complete: function () {
  8958. $(document).trigger(
  8959. "remotevideo.resized",
  8960. [width,
  8961. height]);
  8962. }
  8963. });
  8964. } else {
  8965. // size videos so that while keeping AR and max height, we have a
  8966. // nice fit
  8967. $('#remoteVideos').height(height + 2);// adds 2 px because of small video 1px border
  8968. $('#remoteVideos>span').width(width);
  8969. $('#remoteVideos>span').height(height);
  8970. $(document).trigger("remotevideo.resized", [width, height]);
  8971. }
  8972. };
  8973. /**
  8974. * Calculates the thumbnail size.
  8975. *
  8976. * @param videoSpaceWidth the width of the video space
  8977. */
  8978. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8979. // Calculate the available height, which is the inner window height minus
  8980. // 39px for the header minus 2px for the delimiter lines on the top and
  8981. // bottom of the large video, minus the 36px space inside the remoteVideos
  8982. // container used for highlighting shadow.
  8983. var availableHeight = 100;
  8984. var numvids = $('#remoteVideos>span:visible').length;
  8985. if (localLastNCount && localLastNCount > 0) {
  8986. numvids = Math.min(localLastNCount + 1, numvids);
  8987. }
  8988. // Remove the 3px borders arround videos and border around the remote
  8989. // videos area and the 4 pixels between the local video and the others
  8990. //TODO: Find out where the 4 pixels come from and remove them
  8991. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8992. var availableWidth = availableWinWidth / numvids;
  8993. var aspectRatio = 16.0 / 9.0;
  8994. var maxHeight = Math.min(160, availableHeight);
  8995. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio, window.innerHeight - 18);
  8996. if (availableHeight < availableWidth / aspectRatio) {
  8997. availableWidth = Math.floor(availableHeight * aspectRatio);
  8998. }
  8999. return [availableWidth, availableHeight];
  9000. };
  9001. /**
  9002. * Returns the corresponding resource jid to the given peer container
  9003. * DOM element.
  9004. *
  9005. * @return the corresponding resource jid to the given peer container
  9006. * DOM element
  9007. */
  9008. my.getPeerContainerResourceJid = function (containerElement) {
  9009. var i = containerElement.id.indexOf('participant_');
  9010. if (i >= 0)
  9011. return containerElement.id.substring(i + 12);
  9012. };
  9013. my.getPeerVideoSel = function (peerResourceJid) {
  9014. return $('#participant_' + peerResourceJid +
  9015. '>' + APP.RTC.getVideoElementName());
  9016. };
  9017. /**
  9018. * On contact list item clicked.
  9019. */
  9020. $(ContactList).bind('contactclicked', function(event, jid) {
  9021. if (!jid) {
  9022. return;
  9023. }
  9024. if (jid === APP.xmpp.myJid()) {
  9025. $("#localVideoContainer").click();
  9026. return;
  9027. }
  9028. var resource = Strophe.getResourceFromJid(jid);
  9029. var videoSel = VideoLayout.getPeerVideoSel(resource);
  9030. if (videoSel.length > 0) {
  9031. var videoThumb = videoSel[0];
  9032. // It is not always the case that a videoThumb exists (if there is
  9033. // no actual video).
  9034. if (RTC.getVideoSrc(videoThumb)) {
  9035. // We have a video src, great! Let's update the large video
  9036. // now.
  9037. VideoLayout.handleVideoThumbClicked(
  9038. false,
  9039. Strophe.getResourceFromJid(jid));
  9040. } else {
  9041. // If we don't have a video src for jid, there's absolutely
  9042. // no point in calling handleVideoThumbClicked; Quite
  9043. // simply, it won't work because it needs an src to attach
  9044. // to the large video.
  9045. //
  9046. // Instead, we trigger the pinned endpoint changed event to
  9047. // let the bridge adjust its lastN set for myjid and store
  9048. // the pinned user in the lastNPickupJid variable to be
  9049. // picked up later by the lastN changed event handler.
  9050. lastNPickupJid = jid;
  9051. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9052. Strophe.getResourceFromJid(jid));
  9053. }
  9054. }
  9055. });
  9056. /**
  9057. * On audio muted event.
  9058. */
  9059. my.onAudioMute = function (jid, isMuted) {
  9060. var resourceJid = Strophe.getResourceFromJid(jid);
  9061. if (resourceJid === APP.xmpp.myResource()) {
  9062. localVideoThumbnail.showAudioIndicator(isMuted);
  9063. } else {
  9064. VideoLayout.ensurePeerContainerExists(jid);
  9065. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9066. if (APP.xmpp.isModerator()) {
  9067. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9068. }
  9069. }
  9070. };
  9071. /**
  9072. * On video muted event.
  9073. */
  9074. my.onVideoMute = function (jid, value) {
  9075. if (jid !== APP.xmpp.myJid() &&
  9076. !APP.RTC.muteRemoteVideoStream(jid, value))
  9077. return;
  9078. if (jid === APP.xmpp.myJid()) {
  9079. localVideoThumbnail.showVideoIndicator(value);
  9080. } else {
  9081. var resource = Strophe.getResourceFromJid(jid);
  9082. VideoLayout.ensurePeerContainerExists(jid);
  9083. remoteVideos[resource].showVideoIndicator(value);
  9084. var el = VideoLayout.getPeerVideoSel(resource);
  9085. if (!value)
  9086. el.show();
  9087. else
  9088. el.hide();
  9089. }
  9090. };
  9091. /**
  9092. * Display name changed.
  9093. */
  9094. my.onDisplayNameChanged =
  9095. function (jid, displayName, status) {
  9096. if (jid === 'localVideoContainer' ||
  9097. jid === APP.xmpp.myJid()) {
  9098. localVideoThumbnail.setDisplayName(displayName);
  9099. } else {
  9100. VideoLayout.ensurePeerContainerExists(jid);
  9101. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9102. displayName,
  9103. status);
  9104. }
  9105. };
  9106. /**
  9107. * On dominant speaker changed event.
  9108. */
  9109. my.onDominantSpeakerChanged = function (resourceJid) {
  9110. // We ignore local user events.
  9111. if (resourceJid === APP.xmpp.myResource())
  9112. return;
  9113. var members = APP.xmpp.getMembers();
  9114. // Update the current dominant speaker.
  9115. if (resourceJid !== currentDominantSpeaker) {
  9116. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9117. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9118. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9119. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9120. remoteVideos[resourceJid].setDisplayName(null);
  9121. }
  9122. if(resourceJid && (!members || !members[newJID] ||
  9123. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9124. remoteVideos[resourceJid].setDisplayName(null,
  9125. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9126. }
  9127. currentDominantSpeaker = resourceJid;
  9128. } else {
  9129. return;
  9130. }
  9131. // Obtain container for new dominant speaker.
  9132. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9133. // Local video will not have container found, but that's ok
  9134. // since we don't want to switch to local video.
  9135. if (!focusedVideoResourceJid && videoSel.length) {
  9136. // Update the large video if the video source is already available,
  9137. // otherwise wait for the "videoactive.jingle" event.
  9138. if (videoSel[0].currentTime > 0) {
  9139. LargeVideo.updateLargeVideo(resourceJid);
  9140. }
  9141. }
  9142. };
  9143. /**
  9144. * On last N change event.
  9145. *
  9146. * @param lastNEndpoints the list of last N endpoints
  9147. * @param endpointsEnteringLastN the list currently entering last N
  9148. * endpoints
  9149. */
  9150. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9151. endpointsEnteringLastN,
  9152. stream) {
  9153. if (lastNCount !== lastNEndpoints.length)
  9154. lastNCount = lastNEndpoints.length;
  9155. lastNEndpointsCache = lastNEndpoints;
  9156. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9157. //
  9158. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9159. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9160. // so E sees them. C is only in E's local LastN set.
  9161. //
  9162. // If F starts talking and LastN = 3, then E should see thumbnails for
  9163. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9164. // enters E's local LastN ejecting C.
  9165. // Increase the local LastN set size, if necessary.
  9166. if (lastNCount > localLastNCount) {
  9167. localLastNCount = lastNCount;
  9168. }
  9169. // Update the local LastN set preserving the order in which the
  9170. // endpoints appeared in the LastN/local LastN set.
  9171. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9172. for (var i = 0; i < localLastNSet.length; i++) {
  9173. if (nextLocalLastNSet.length >= localLastNCount) {
  9174. break;
  9175. }
  9176. var resourceJid = localLastNSet[i];
  9177. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9178. nextLocalLastNSet.push(resourceJid);
  9179. }
  9180. }
  9181. localLastNSet = nextLocalLastNSet;
  9182. var updateLargeVideo = false;
  9183. // Handle LastN/local LastN changes.
  9184. $('#remoteVideos>span').each(function( index, element ) {
  9185. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9186. var isReceived = true;
  9187. if (resourceJid &&
  9188. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9189. localLastNSet.indexOf(resourceJid) < 0) {
  9190. console.log("Remove from last N", resourceJid);
  9191. remoteVideos[resourceJid].showPeerContainer('hide');
  9192. isReceived = false;
  9193. } else if (resourceJid &&
  9194. $('#participant_' + resourceJid).is(':visible') &&
  9195. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9196. localLastNSet.indexOf(resourceJid) >= 0) {
  9197. remoteVideos[resourceJid].showPeerContainer('avatar');
  9198. isReceived = false;
  9199. }
  9200. if (!isReceived) {
  9201. // resourceJid has dropped out of the server side lastN set, so
  9202. // it is no longer being received. If resourceJid was being
  9203. // displayed in the large video we have to switch to another
  9204. // user.
  9205. if (!updateLargeVideo &&
  9206. resourceJid === LargeVideo.getResourceJid()) {
  9207. updateLargeVideo = true;
  9208. }
  9209. }
  9210. });
  9211. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9212. endpointsEnteringLastN = lastNEndpoints;
  9213. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9214. endpointsEnteringLastN.forEach(function (resourceJid) {
  9215. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9216. remoteVideos[resourceJid].showPeerContainer('show');
  9217. if (!isVisible) {
  9218. console.log("Add to last N", resourceJid);
  9219. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9220. var mediaStream =
  9221. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9222. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9223. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9224. if (lastNPickupJid == mediaStream.peerjid) {
  9225. // Clean up the lastN pickup jid.
  9226. lastNPickupJid = null;
  9227. // Don't fire the events again, they've already
  9228. // been fired in the contact list click handler.
  9229. VideoLayout.handleVideoThumbClicked(
  9230. false,
  9231. Strophe.getResourceFromJid(mediaStream.peerjid));
  9232. updateLargeVideo = false;
  9233. }
  9234. remoteVideos[resourceJid].
  9235. waitForPlayback(sel, mediaStream.stream);
  9236. }
  9237. });
  9238. }
  9239. // The endpoint that was being shown in the large video has dropped out
  9240. // of the lastN set and there was no lastN pickup jid. We need to update
  9241. // the large video now.
  9242. if (updateLargeVideo) {
  9243. var resource;
  9244. var myResource
  9245. = APP.xmpp.myResource();
  9246. // Find out which endpoint to show in the large video.
  9247. for (i = 0; i < lastNEndpoints.length; i++) {
  9248. resource = lastNEndpoints[i];
  9249. if (!resource || resource === myResource)
  9250. continue;
  9251. // videoSrcToSsrc needs to be update for this call to succeed.
  9252. LargeVideo.updateLargeVideo(resource);
  9253. break;
  9254. }
  9255. }
  9256. };
  9257. /**
  9258. * Updates local stats
  9259. * @param percent
  9260. * @param object
  9261. */
  9262. my.updateLocalConnectionStats = function (percent, object) {
  9263. var resolution = null;
  9264. if (object.resolution !== null) {
  9265. resolution = object.resolution;
  9266. object.resolution = resolution[APP.xmpp.myJid()];
  9267. delete resolution[APP.xmpp.myJid()];
  9268. }
  9269. localVideoThumbnail.updateStatsIndicator(percent, object);
  9270. for (var jid in resolution) {
  9271. if (resolution[jid] === null)
  9272. continue;
  9273. var resourceJid = Strophe.getResourceFromJid(jid);
  9274. if (remoteVideos[resourceJid] &&
  9275. remoteVideos[resourceJid].connectionIndicator) {
  9276. remoteVideos[resourceJid].connectionIndicator.
  9277. updateResolution(resolution[jid]);
  9278. }
  9279. }
  9280. };
  9281. /**
  9282. * Updates remote stats.
  9283. * @param jid the jid associated with the stats
  9284. * @param percent the connection quality percent
  9285. * @param object the stats data
  9286. */
  9287. my.updateConnectionStats = function (jid, percent, object) {
  9288. var resourceJid = Strophe.getResourceFromJid(jid);
  9289. if (remoteVideos[resourceJid])
  9290. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9291. };
  9292. /**
  9293. * Hides the connection indicator
  9294. * @param jid
  9295. */
  9296. my.hideConnectionIndicator = function (jid) {
  9297. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9298. };
  9299. /**
  9300. * Hides all the indicators
  9301. */
  9302. my.onStatsStop = function () {
  9303. for(var video in remoteVideos) {
  9304. remoteVideos[video].hideIndicator();
  9305. }
  9306. localVideoThumbnail.hideIndicator();
  9307. };
  9308. my.participantLeft = function (jid) {
  9309. // Unlock large video
  9310. var resourceJid = Strophe.getResourceFromJid(jid);
  9311. if (focusedVideoResourceJid === resourceJid) {
  9312. console.info("Focused video owner has left the conference");
  9313. focusedVideoResourceJid = null;
  9314. }
  9315. if (currentDominantSpeaker === resourceJid)
  9316. {
  9317. console.info("Dominant speaker has left the conference");
  9318. currentDominantSpeaker = null;
  9319. }
  9320. var remoteVideo = remoteVideos[resourceJid];
  9321. if (remoteVideo) {
  9322. // Remove remote video
  9323. console.info("Removing remote video: " + resourceJid);
  9324. remoteVideo.remove();
  9325. delete remoteVideos[resourceJid];
  9326. } else {
  9327. console.warn("No remote video for " + resourceJid);
  9328. }
  9329. VideoLayout.resizeThumbnails();
  9330. };
  9331. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9332. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9333. return;
  9334. }
  9335. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9336. remoteVideoTypes[resourceJid] = newVideoType;
  9337. var smallVideo;
  9338. if (resourceJid === APP.xmpp.myResource()) {
  9339. if (!localVideoThumbnail) {
  9340. console.warn("Local video not ready yet");
  9341. return;
  9342. }
  9343. smallVideo = localVideoThumbnail;
  9344. } else if (remoteVideos[resourceJid]) {
  9345. smallVideo = remoteVideos[resourceJid];
  9346. } else {
  9347. return;
  9348. }
  9349. smallVideo.setVideoType(newVideoType);
  9350. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9351. };
  9352. my.showMore = function (jid) {
  9353. if (jid === 'local') {
  9354. localVideoThumbnail.connectionIndicator.showMore();
  9355. } else {
  9356. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9357. if (remoteVideo) {
  9358. remoteVideo.connectionIndicator.showMore();
  9359. } else {
  9360. console.info("Error - no remote video for jid: " + jid);
  9361. }
  9362. }
  9363. };
  9364. my.addPreziContainer = function (id) {
  9365. var container = RemoteVideo.createContainer(id);
  9366. VideoLayout.resizeThumbnails();
  9367. return container;
  9368. };
  9369. my.setLargeVideoVisible = function (isVisible) {
  9370. LargeVideo.setLargeVideoVisible(isVisible);
  9371. if(!isVisible && focusedVideoResourceJid) {
  9372. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9373. if(smallVideo) {
  9374. smallVideo.focus(false);
  9375. smallVideo.showAvatar();
  9376. }
  9377. focusedVideoResourceJid = null;
  9378. }
  9379. };
  9380. /**
  9381. * Resizes the video area
  9382. * @param callback a function to be called when the video space is
  9383. * resized.
  9384. */
  9385. my.resizeVideoArea = function(isVisible, callback) {
  9386. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9387. VideoLayout.resizeThumbnails(true);
  9388. };
  9389. /**
  9390. * Resizes the #videospace html element
  9391. * @param animate boolean property that indicates whether the resize should be animated or not.
  9392. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  9393. * If that parameter is null the method will check the chat pannel visibility.
  9394. * @param completeFunction a function to be called when the video space is resized
  9395. */
  9396. my.resizeVideoSpace = function (animate, isChatVisible, completeFunction) {
  9397. var availableHeight = window.innerHeight;
  9398. var availableWidth = UIUtil.getAvailableVideoWidth(isChatVisible);
  9399. if (availableWidth < 0 || availableHeight < 0) return;
  9400. if(animate) {
  9401. $('#videospace').animate({
  9402. right: window.innerWidth - availableWidth,
  9403. width: availableWidth,
  9404. height: availableHeight
  9405. },
  9406. {
  9407. queue: false,
  9408. duration: 500,
  9409. complete: completeFunction
  9410. });
  9411. } else {
  9412. $('#videospace').width(availableWidth);
  9413. $('#videospace').height(availableHeight);
  9414. }
  9415. };
  9416. my.getSmallVideo = function (resourceJid) {
  9417. if(resourceJid == APP.xmpp.myResource()) {
  9418. return localVideoThumbnail;
  9419. } else {
  9420. if(!remoteVideos[resourceJid])
  9421. return null;
  9422. return remoteVideos[resourceJid];
  9423. }
  9424. };
  9425. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9426. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9427. if(smallVideo)
  9428. smallVideo.avatarChanged(thumbUrl);
  9429. else
  9430. console.warn(
  9431. "Missed avatar update - no small video yet for " + resourceJid);
  9432. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9433. };
  9434. my.createEtherpadIframe = function(src, onloadHandler)
  9435. {
  9436. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9437. };
  9438. my.setLargeVideoState = function (state) {
  9439. LargeVideo.setState(state);
  9440. };
  9441. my.getLargeVideoState = function () {
  9442. return LargeVideo.getState();
  9443. };
  9444. my.setLargeVideoHover = function (inHandler, outHandler) {
  9445. LargeVideo.setHover(inHandler, outHandler);
  9446. };
  9447. /**
  9448. * Indicates that the video has been interrupted.
  9449. */
  9450. my.onVideoInterrupted = function () {
  9451. LargeVideo.enableVideoProblemFilter(true);
  9452. var reconnectingKey = "connection.RECONNECTING";
  9453. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9454. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9455. $('#videoConnectionMessage').css({display: "block"});
  9456. };
  9457. /**
  9458. * Indicates that the video has been restored.
  9459. */
  9460. my.onVideoRestored = function () {
  9461. LargeVideo.enableVideoProblemFilter(false);
  9462. $('#videoConnectionMessage').css({display: "none"});
  9463. };
  9464. return my;
  9465. }(VideoLayout || {}));
  9466. module.exports = VideoLayout;
  9467. },{"../../../service/RTC/MediaStreamTypes":100,"../../../service/UI/UIEvents":104,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"../util/UIUtil":33,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  9468. //var nouns = [
  9469. //];
  9470. var pluralNouns = [
  9471. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9472. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9473. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9474. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9475. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9476. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9477. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9478. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9479. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9480. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9481. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9482. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9483. ];
  9484. //var places = [
  9485. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9486. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9487. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9488. // "Bridge"
  9489. //];
  9490. var verbs = [
  9491. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9492. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9493. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9494. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9495. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9496. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9497. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9498. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9499. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9500. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9501. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9502. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9503. ];
  9504. var adverbs = [
  9505. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9506. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9507. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9508. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9509. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9510. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9511. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9512. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9513. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9514. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9515. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9516. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9517. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9518. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9519. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9520. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9521. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9522. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9523. ];
  9524. var adjectives = [
  9525. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9526. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9527. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9528. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9529. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9530. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9531. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9532. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9533. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9534. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9535. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9536. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9537. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9538. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9539. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9540. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9541. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9542. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9543. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9544. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9545. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9546. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9547. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9548. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9549. "Zealous"
  9550. ];
  9551. //var pronouns = [
  9552. //];
  9553. //var conjunctions = [
  9554. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9555. //];
  9556. /*
  9557. * Maps a string (category name) to the array of words from that category.
  9558. */
  9559. var CATEGORIES =
  9560. {
  9561. //"_NOUN_": nouns,
  9562. "_PLURALNOUN_": pluralNouns,
  9563. //"_PLACE_": places,
  9564. "_VERB_": verbs,
  9565. "_ADVERB_": adverbs,
  9566. "_ADJECTIVE_": adjectives
  9567. //"_PRONOUN_": pronouns,
  9568. //"_CONJUNCTION_": conjunctions,
  9569. };
  9570. var PATTERNS = [
  9571. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9572. // BeautifulFungiOrSpaghetti
  9573. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9574. // AmazinglyScaryToy
  9575. //"_ADVERB__ADJECTIVE__NOUN_",
  9576. // NeitherTrashNorRifle
  9577. //"Neither_NOUN_Nor_NOUN_",
  9578. //"Either_NOUN_Or_NOUN_",
  9579. // EitherCopulateOrInvestigate
  9580. //"Either_VERB_Or_VERB_",
  9581. //"Neither_VERB_Nor_VERB_",
  9582. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9583. //"The_ADVERB__ADJECTIVE__NOUN_",
  9584. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9585. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9586. // WolvesComputeBadly
  9587. //"_PLURALNOUN__VERB__ADVERB_",
  9588. // UniteFacilitateAndMerge
  9589. //"_VERB__VERB_And_VERB_",
  9590. //NastyWitchesAtThePub
  9591. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9592. ];
  9593. /*
  9594. * Returns a random element from the array 'arr'
  9595. */
  9596. function randomElement(arr) {
  9597. return arr[Math.floor(Math.random() * arr.length)];
  9598. }
  9599. /*
  9600. * Returns true if the string 's' contains one of the
  9601. * template strings.
  9602. */
  9603. function hasTemplate(s) {
  9604. for (var template in CATEGORIES){
  9605. if (s.indexOf(template) >= 0){
  9606. return true;
  9607. }
  9608. }
  9609. }
  9610. /**
  9611. * Generates new room name.
  9612. */
  9613. var RoomNameGenerator = {
  9614. generateRoomWithoutSeparator: function() {
  9615. // Note that if more than one pattern is available, the choice of
  9616. // 'name' won't have a uniform distribution amongst all patterns (names
  9617. // from patterns with fewer options will have higher probability of
  9618. // being chosen that names from patterns with more options).
  9619. var name = randomElement(PATTERNS);
  9620. var word;
  9621. while (hasTemplate(name)) {
  9622. for (var template in CATEGORIES) {
  9623. word = randomElement(CATEGORIES[template]);
  9624. name = name.replace(template, word);
  9625. }
  9626. }
  9627. return name;
  9628. }
  9629. };
  9630. module.exports = RoomNameGenerator;
  9631. },{}],41:[function(require,module,exports){
  9632. /* global $, interfaceConfig */
  9633. var animateTimeout, updateTimeout;
  9634. var RoomNameGenerator = require("./RoomnameGenerator");
  9635. function enter_room() {
  9636. var val = $("#enter_room_field").val();
  9637. if(!val) {
  9638. val = $("#enter_room_field").attr("room_name");
  9639. }
  9640. if (val) {
  9641. window.location.pathname = "/" + val;
  9642. }
  9643. }
  9644. function animate(word) {
  9645. var currentVal = $("#enter_room_field").attr("placeholder");
  9646. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9647. animateTimeout = setTimeout(function() {
  9648. animate(word.substring(1, word.length))
  9649. }, 70);
  9650. }
  9651. function update_roomname() {
  9652. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9653. $("#enter_room_field").attr("room_name", word);
  9654. $("#enter_room_field").attr("placeholder", "");
  9655. clearTimeout(animateTimeout);
  9656. animate(word);
  9657. updateTimeout = setTimeout(update_roomname, 10000);
  9658. }
  9659. function setupWelcomePage() {
  9660. $("#videoconference_page").hide();
  9661. $("#domain_name").text(
  9662. window.location.protocol + "//" + window.location.host + "/");
  9663. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9664. var leftWatermarkDiv =
  9665. $("#welcome_page_header div[class='watermark leftwatermark']");
  9666. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9667. leftWatermarkDiv.css({display: 'block'});
  9668. leftWatermarkDiv.parent().get(0).href =
  9669. interfaceConfig.JITSI_WATERMARK_LINK;
  9670. }
  9671. }
  9672. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9673. var rightWatermarkDiv =
  9674. $("#welcome_page_header div[class='watermark rightwatermark']");
  9675. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9676. rightWatermarkDiv.css({display: 'block'});
  9677. rightWatermarkDiv.parent().get(0).href =
  9678. interfaceConfig.BRAND_WATERMARK_LINK;
  9679. rightWatermarkDiv.get(0).style.backgroundImage =
  9680. "url(images/rightwatermark.png)";
  9681. }
  9682. }
  9683. if (interfaceConfig.SHOW_POWERED_BY) {
  9684. $("#welcome_page_header>a[class='poweredby']")
  9685. .css({display: 'block'});
  9686. }
  9687. $("#enter_room_button").click(function() {
  9688. enter_room();
  9689. });
  9690. $("#enter_room_field").keydown(function (event) {
  9691. if (event.keyCode === 13 /* enter */) {
  9692. enter_room();
  9693. }
  9694. });
  9695. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9696. var updateTimeout;
  9697. var animateTimeout;
  9698. var selector = $("#reload_roomname");
  9699. selector.click(function () {
  9700. clearTimeout(updateTimeout);
  9701. clearTimeout(animateTimeout);
  9702. update_roomname();
  9703. });
  9704. selector.show();
  9705. update_roomname();
  9706. }
  9707. $("#disable_welcome").click(function () {
  9708. window.localStorage.welcomePageDisabled =
  9709. $("#disable_welcome").is(":checked");
  9710. });
  9711. }
  9712. module.exports = setupWelcomePage;
  9713. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9714. /* global $, $iq, config, interfaceConfig */
  9715. var params = {};
  9716. function getConfigParamsFromUrl() {
  9717. if(!location.hash)
  9718. return {};
  9719. var hash = location.hash.substr(1);
  9720. var result = {};
  9721. hash.split("&").forEach(function(part) {
  9722. var item = part.split("=");
  9723. result[item[0]] = JSON.parse(
  9724. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9725. });
  9726. return result;
  9727. }
  9728. params = getConfigParamsFromUrl();
  9729. var URLProcessor = {
  9730. setConfigParametersFromUrl: function () {
  9731. for(var key in params) {
  9732. if(typeof key !== "string")
  9733. continue;
  9734. var confObj = null, confKey;
  9735. if (key.indexOf("config.") === 0) {
  9736. confObj = config;
  9737. confKey = key.substr("config.".length);
  9738. } else if (key.indexOf("interfaceConfig.") === 0) {
  9739. confObj = interfaceConfig;
  9740. confKey = key.substr("interfaceConfig.".length);
  9741. }
  9742. if (!confObj)
  9743. continue;
  9744. var value = params[key];
  9745. if (confObj[confKey] && typeof confObj[confKey] !== typeof value)
  9746. {
  9747. console.warn("The type of " + key +
  9748. " is wrong. That parameter won't be updated in config.js.");
  9749. continue;
  9750. }
  9751. confObj[confKey] = value;
  9752. }
  9753. }
  9754. };
  9755. module.exports = URLProcessor;
  9756. },{}],43:[function(require,module,exports){
  9757. /* global APP, require */
  9758. var EventEmitter = require("events");
  9759. var eventEmitter = new EventEmitter();
  9760. var CQEvents = require("../../service/connectionquality/CQEvents");
  9761. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9762. /**
  9763. * local stats
  9764. * @type {{}}
  9765. */
  9766. var stats = {};
  9767. /**
  9768. * remote stats
  9769. * @type {{}}
  9770. */
  9771. var remoteStats = {};
  9772. /**
  9773. * Interval for sending statistics to other participants
  9774. * @type {null}
  9775. */
  9776. var sendIntervalId = null;
  9777. /**
  9778. * Start statistics sending.
  9779. */
  9780. function startSendingStats() {
  9781. sendStats();
  9782. sendIntervalId = setInterval(sendStats, 10000);
  9783. }
  9784. /**
  9785. * Sends statistics to other participants
  9786. */
  9787. function sendStats() {
  9788. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9789. }
  9790. /**
  9791. * Converts statistics to format for sending through XMPP
  9792. * @param stats the statistics
  9793. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9794. */
  9795. function convertToMUCStats(stats) {
  9796. return {
  9797. "bitrate_download": stats.bitrate.download,
  9798. "bitrate_upload": stats.bitrate.upload,
  9799. "packetLoss_total": stats.packetLoss.total,
  9800. "packetLoss_download": stats.packetLoss.download,
  9801. "packetLoss_upload": stats.packetLoss.upload
  9802. };
  9803. }
  9804. /**
  9805. * Converts statistics to format used by VideoLayout
  9806. * @param stats
  9807. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9808. */
  9809. function parseMUCStats(stats) {
  9810. return {
  9811. bitrate: {
  9812. download: stats.bitrate_download,
  9813. upload: stats.bitrate_upload
  9814. },
  9815. packetLoss: {
  9816. total: stats.packetLoss_total,
  9817. download: stats.packetLoss_download,
  9818. upload: stats.packetLoss_upload
  9819. }
  9820. };
  9821. }
  9822. var ConnectionQuality = {
  9823. init: function () {
  9824. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9825. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9826. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9827. },
  9828. /**
  9829. * Updates the local statistics
  9830. * @param data new statistics
  9831. */
  9832. updateLocalStats: function (data) {
  9833. stats = data;
  9834. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9835. if (sendIntervalId == null) {
  9836. startSendingStats();
  9837. }
  9838. },
  9839. /**
  9840. * Updates remote statistics
  9841. * @param jid the jid associated with the statistics
  9842. * @param data the statistics
  9843. */
  9844. updateRemoteStats: function (jid, data) {
  9845. if (data == null || data.packetLoss_total == null) {
  9846. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9847. return;
  9848. }
  9849. remoteStats[jid] = parseMUCStats(data);
  9850. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9851. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9852. },
  9853. /**
  9854. * Stops statistics sending.
  9855. */
  9856. stopSendingStats: function () {
  9857. clearInterval(sendIntervalId);
  9858. sendIntervalId = null;
  9859. //notify UI about stopping statistics gathering
  9860. eventEmitter.emit(CQEvents.STOP);
  9861. },
  9862. /**
  9863. * Returns the local statistics.
  9864. */
  9865. getStats: function () {
  9866. return stats;
  9867. },
  9868. addListener: function (type, listener) {
  9869. eventEmitter.on(type, listener);
  9870. }
  9871. };
  9872. module.exports = ConnectionQuality;
  9873. },{"../../service/connectionquality/CQEvents":106,"../../service/xmpp/XMPPEvents":110,"events":111}],44:[function(require,module,exports){
  9874. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9875. getUserMediaWithConstraints */
  9876. /**
  9877. * Indicates that desktop stream is currently in use(for toggle purpose).
  9878. * @type {boolean}
  9879. */
  9880. var isUsingScreenStream = false;
  9881. /**
  9882. * Indicates that switch stream operation is in progress and prevent from
  9883. * triggering new events.
  9884. * @type {boolean}
  9885. */
  9886. var switchInProgress = false;
  9887. /**
  9888. * Method used to get screen sharing stream.
  9889. *
  9890. * @type {function (stream_callback, failure_callback}
  9891. */
  9892. var obtainDesktopStream = null;
  9893. /**
  9894. * Indicates whether desktop sharing extension is installed.
  9895. * @type {boolean}
  9896. */
  9897. var extInstalled = false;
  9898. /**
  9899. * Indicates whether update of desktop sharing extension is required.
  9900. * @type {boolean}
  9901. */
  9902. var extUpdateRequired = false;
  9903. var AdapterJS = require("../RTC/adapter.screenshare");
  9904. var EventEmitter = require("events");
  9905. var eventEmitter = new EventEmitter();
  9906. var DesktopSharingEventTypes
  9907. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9908. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9909. var RTCEvents = require("../../service/RTC/RTCEvents");
  9910. /**
  9911. * Method obtains desktop stream from WebRTC 'screen' source.
  9912. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9913. */
  9914. function obtainWebRTCScreen(streamCallback, failCallback) {
  9915. APP.RTC.getUserMediaWithConstraints(
  9916. ['screen'],
  9917. streamCallback,
  9918. failCallback
  9919. );
  9920. }
  9921. /**
  9922. * Constructs inline install URL for Chrome desktop streaming extension.
  9923. * The 'chromeExtensionId' must be defined in config.js.
  9924. * @returns {string}
  9925. */
  9926. function getWebStoreInstallUrl()
  9927. {
  9928. return "https://chrome.google.com/webstore/detail/" +
  9929. config.chromeExtensionId;
  9930. }
  9931. /**
  9932. * Checks whether extension update is required.
  9933. * @param minVersion minimal required version
  9934. * @param extVersion current extension version
  9935. * @returns {boolean}
  9936. */
  9937. function isUpdateRequired(minVersion, extVersion)
  9938. {
  9939. try
  9940. {
  9941. var s1 = minVersion.split('.');
  9942. var s2 = extVersion.split('.');
  9943. var len = Math.max(s1.length, s2.length);
  9944. for (var i = 0; i < len; i++)
  9945. {
  9946. var n1 = 0,
  9947. n2 = 0;
  9948. if (i < s1.length)
  9949. n1 = parseInt(s1[i]);
  9950. if (i < s2.length)
  9951. n2 = parseInt(s2[i]);
  9952. if (isNaN(n1) || isNaN(n2))
  9953. {
  9954. return true;
  9955. }
  9956. else if (n1 !== n2)
  9957. {
  9958. return n1 > n2;
  9959. }
  9960. }
  9961. // will happen if boths version has identical numbers in
  9962. // their components (even if one of them is longer, has more components)
  9963. return false;
  9964. }
  9965. catch (e)
  9966. {
  9967. console.error("Failed to parse extension version", e);
  9968. APP.UI.messageHandler.showError("dialog.error",
  9969. "dialog.detectext");
  9970. return true;
  9971. }
  9972. }
  9973. function checkChromeExtInstalled(callback) {
  9974. if (!chrome.runtime) {
  9975. // No API, so no extension for sure
  9976. callback(false, false);
  9977. return;
  9978. }
  9979. chrome.runtime.sendMessage(
  9980. config.chromeExtensionId,
  9981. { getVersion: true },
  9982. function (response) {
  9983. if (!response || !response.version) {
  9984. // Communication failure - assume that no endpoint exists
  9985. console.warn(
  9986. "Extension not installed?: ", chrome.runtime.lastError);
  9987. callback(false, false);
  9988. return;
  9989. }
  9990. // Check installed extension version
  9991. var extVersion = response.version;
  9992. console.log('Extension version is: ' + extVersion);
  9993. var updateRequired
  9994. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  9995. callback(!updateRequired, updateRequired);
  9996. }
  9997. );
  9998. }
  9999. function doGetStreamFromExtension(streamCallback, failCallback) {
  10000. // Sends 'getStream' msg to the extension.
  10001. // Extension id must be defined in the config.
  10002. chrome.runtime.sendMessage(
  10003. config.chromeExtensionId,
  10004. { getStream: true, sources: config.desktopSharingSources },
  10005. function (response) {
  10006. if (!response) {
  10007. failCallback(chrome.runtime.lastError);
  10008. return;
  10009. }
  10010. console.log("Response from extension: " + response);
  10011. if (response.streamId) {
  10012. APP.RTC.getUserMediaWithConstraints(
  10013. ['desktop'],
  10014. function (stream) {
  10015. streamCallback(stream);
  10016. },
  10017. failCallback,
  10018. null, null, null,
  10019. response.streamId);
  10020. } else {
  10021. failCallback("Extension failed to get the stream");
  10022. }
  10023. }
  10024. );
  10025. }
  10026. /**
  10027. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10028. * stream for returned stream token.
  10029. */
  10030. function obtainScreenFromExtension(streamCallback, failCallback) {
  10031. if (extInstalled) {
  10032. doGetStreamFromExtension(streamCallback, failCallback);
  10033. } else {
  10034. if (extUpdateRequired) {
  10035. alert(
  10036. 'Jitsi Desktop Streamer requires update. ' +
  10037. 'Changes will take effect after next Chrome restart.');
  10038. }
  10039. chrome.webstore.install(
  10040. getWebStoreInstallUrl(),
  10041. function (arg) {
  10042. console.log("Extension installed successfully", arg);
  10043. extInstalled = true;
  10044. // We need to give a moment for the endpoint to become available
  10045. window.setTimeout(function () {
  10046. doGetStreamFromExtension(streamCallback, failCallback);
  10047. }, 500);
  10048. },
  10049. function (arg) {
  10050. console.log("Failed to install the extension", arg);
  10051. failCallback(arg);
  10052. APP.UI.messageHandler.showError("dialog.error",
  10053. "dialog.failtoinstall");
  10054. }
  10055. );
  10056. }
  10057. }
  10058. /**
  10059. * Call this method to toggle desktop sharing feature.
  10060. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10061. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10062. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10063. * enabled), pass any other string or nothing in order to disable this
  10064. * feature completely.
  10065. */
  10066. function setDesktopSharing(method) {
  10067. obtainDesktopStream = null;
  10068. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10069. // care about 'method' parameter
  10070. if (RTCBrowserType.isTemasysPluginUsed()) {
  10071. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10072. console.info("Screensharing not supported by this plugin version");
  10073. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10074. console.info(
  10075. "Screensharing not available with Temasys plugin on this site");
  10076. } else {
  10077. obtainDesktopStream = obtainWebRTCScreen;
  10078. console.info("Using Temasys plugin for desktop sharing");
  10079. }
  10080. } else if (RTCBrowserType.isChrome()) {
  10081. if (method == "ext") {
  10082. if (RTCBrowserType.getChromeVersion() >= 34) {
  10083. obtainDesktopStream = obtainScreenFromExtension;
  10084. console.info("Using Chrome extension for desktop sharing");
  10085. initChromeExtension();
  10086. } else {
  10087. console.info("Chrome extension not supported until ver 34");
  10088. }
  10089. } else if (method == "webrtc") {
  10090. obtainDesktopStream = obtainWebRTCScreen;
  10091. console.info("Using Chrome WebRTC for desktop sharing");
  10092. }
  10093. }
  10094. if (!obtainDesktopStream) {
  10095. console.info("Desktop sharing disabled");
  10096. }
  10097. }
  10098. /**
  10099. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10100. * config.js to support inline installs. Host site must be selected as main
  10101. * website of published extension.
  10102. */
  10103. function initInlineInstalls()
  10104. {
  10105. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10106. }
  10107. function initChromeExtension() {
  10108. // Initialize Chrome extension inline installs
  10109. initInlineInstalls();
  10110. // Check if extension is installed
  10111. checkChromeExtInstalled(function (installed, updateRequired) {
  10112. extInstalled = installed;
  10113. extUpdateRequired = updateRequired;
  10114. console.info(
  10115. "Chrome extension installed: " + extInstalled +
  10116. " updateRequired: " + extUpdateRequired);
  10117. });
  10118. }
  10119. function getVideoStreamFailed(error) {
  10120. console.error("Failed to obtain the stream to switch to", error);
  10121. switchInProgress = false;
  10122. isUsingScreenStream = false;
  10123. newStreamCreated(null);
  10124. }
  10125. function getDesktopStreamFailed(error) {
  10126. console.error("Failed to obtain the stream to switch to", error);
  10127. switchInProgress = false;
  10128. }
  10129. function streamSwitchDone() {
  10130. switchInProgress = false;
  10131. eventEmitter.emit(
  10132. DesktopSharingEventTypes.SWITCHING_DONE,
  10133. isUsingScreenStream);
  10134. }
  10135. function newStreamCreated(stream)
  10136. {
  10137. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10138. stream, isUsingScreenStream, streamSwitchDone);
  10139. }
  10140. function onEndedHandler(stream) {
  10141. if (!switchInProgress && isUsingScreenStream) {
  10142. APP.desktopsharing.toggleScreenSharing();
  10143. }
  10144. //FIXME: to be verified
  10145. if (stream.removeEventListener) {
  10146. stream.removeEventListener('ended', onEndedHandler);
  10147. } else {
  10148. stream.detachEvent('ended', onEndedHandler);
  10149. }
  10150. }
  10151. // Called when RTC finishes initialization
  10152. function onWebRtcReady() {
  10153. setDesktopSharing(config.desktopSharing);
  10154. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10155. }
  10156. module.exports = {
  10157. isUsingScreenStream: function () {
  10158. return isUsingScreenStream;
  10159. },
  10160. /**
  10161. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10162. * and enabled.
  10163. */
  10164. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10165. init: function () {
  10166. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10167. },
  10168. addListener: function (listener, type)
  10169. {
  10170. eventEmitter.on(type, listener);
  10171. },
  10172. removeListener: function (listener, type) {
  10173. eventEmitter.removeListener(type, listener);
  10174. },
  10175. /*
  10176. * Toggles screen sharing.
  10177. */
  10178. toggleScreenSharing: function () {
  10179. if (switchInProgress || !obtainDesktopStream) {
  10180. console.warn("Switch in progress or no method defined");
  10181. return;
  10182. }
  10183. switchInProgress = true;
  10184. if (!isUsingScreenStream)
  10185. {
  10186. // Switch to desktop stream
  10187. obtainDesktopStream(
  10188. function (stream) {
  10189. // We now use screen stream
  10190. isUsingScreenStream = true;
  10191. // Hook 'ended' event to restore camera
  10192. // when screen stream stops
  10193. //FIXME: to be verified
  10194. if (stream.addEventListener) {
  10195. stream.addEventListener('ended', function () {
  10196. onEndedHandler(stream);
  10197. });
  10198. } else {
  10199. stream.attachEvent('ended', function () {
  10200. onEndedHandler(stream);
  10201. });
  10202. }
  10203. newStreamCreated(stream);
  10204. },
  10205. getDesktopStreamFailed);
  10206. } else {
  10207. // Disable screen stream
  10208. APP.RTC.getUserMediaWithConstraints(
  10209. ['video'],
  10210. function (stream) {
  10211. // We are now using camera stream
  10212. isUsingScreenStream = false;
  10213. newStreamCreated(stream);
  10214. },
  10215. getVideoStreamFailed, config.resolution || '360'
  10216. );
  10217. }
  10218. }
  10219. };
  10220. },{"../../service/RTC/RTCEvents":101,"../../service/desktopsharing/DesktopSharingEventTypes":107,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":111}],45:[function(require,module,exports){
  10221. /* global APP, $ */
  10222. //maps keycode to character, id of popover for given function and function
  10223. var shortcuts = {};
  10224. function initShortcutHandlers() {
  10225. shortcuts = {
  10226. 67: {
  10227. character: "C",
  10228. id: "toggleChatPopover",
  10229. function: APP.UI.toggleChat
  10230. },
  10231. 70: {
  10232. character: "F",
  10233. id: "filmstripPopover",
  10234. function: APP.UI.toggleFilmStrip
  10235. },
  10236. 77: {
  10237. character: "M",
  10238. id: "mutePopover",
  10239. function: APP.UI.toggleAudio
  10240. },
  10241. 84: {
  10242. character: "T",
  10243. function: function() {
  10244. if(!APP.RTC.localAudio.isMuted()) {
  10245. APP.UI.toggleAudio();
  10246. }
  10247. }
  10248. },
  10249. 86: {
  10250. character: "V",
  10251. id: "toggleVideoPopover",
  10252. function: APP.UI.toggleVideo
  10253. }
  10254. };
  10255. }
  10256. var KeyboardShortcut = {
  10257. init: function () {
  10258. initShortcutHandlers();
  10259. window.onkeyup = function(e) {
  10260. var keycode = e.which;
  10261. if(!($(":focus").is("input[type=text]") ||
  10262. $(":focus").is("input[type=password]") ||
  10263. $(":focus").is("textarea"))) {
  10264. if (typeof shortcuts[keycode] === "object") {
  10265. shortcuts[keycode].function();
  10266. }
  10267. else if (keycode >= "0".charCodeAt(0) &&
  10268. keycode <= "9".charCodeAt(0)) {
  10269. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10270. }
  10271. //esc while the smileys are visible hides them
  10272. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10273. APP.UI.toggleSmileys();
  10274. }
  10275. };
  10276. window.onkeydown = function(e) {
  10277. if(!($(":focus").is("input[type=text]") ||
  10278. $(":focus").is("input[type=password]") ||
  10279. $(":focus").is("textarea"))) {
  10280. if(e.which === "T".charCodeAt(0)) {
  10281. if(APP.RTC.localAudio.isMuted()) {
  10282. APP.UI.toggleAudio();
  10283. }
  10284. }
  10285. }
  10286. };
  10287. var self = this;
  10288. $('body').popover({ selector: '[data-toggle=popover]',
  10289. trigger: 'click hover',
  10290. content: function() {
  10291. return this.getAttribute("content") +
  10292. self.getShortcut(this.getAttribute("shortcut"));
  10293. }
  10294. });
  10295. },
  10296. /**
  10297. *
  10298. * @param id indicates the popover associated with the shortcut
  10299. * @returns {string} the keyboard shortcut used for the id given
  10300. */
  10301. getShortcut: function (id) {
  10302. for (var keycode in shortcuts) {
  10303. if (shortcuts.hasOwnProperty(keycode)) {
  10304. if (shortcuts[keycode].id === id) {
  10305. return " (" + shortcuts[keycode].character + ")";
  10306. }
  10307. }
  10308. }
  10309. return "";
  10310. }
  10311. };
  10312. module.exports = KeyboardShortcut;
  10313. },{}],46:[function(require,module,exports){
  10314. /* global APP, require, $ */
  10315. /**
  10316. * This module is meant to (eventually) contain and manage all information
  10317. * about members/participants of the conference, so that other modules don't
  10318. * have to do it on their own, and so that other modules can access members'
  10319. * information from a single place.
  10320. *
  10321. * Currently this module only manages information about the support of jingle
  10322. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10323. * be added as needed.
  10324. */
  10325. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10326. var Events = require("../../service/members/Events");
  10327. var EventEmitter = require("events");
  10328. var eventEmitter = new EventEmitter();
  10329. /**
  10330. * The actual container.
  10331. */
  10332. var members = {};
  10333. /**
  10334. * There is at least one member that supports DTMF (i.e. is jigasi).
  10335. */
  10336. var atLeastOneDtmf = false;
  10337. function registerListeners() {
  10338. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10339. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10340. }
  10341. /**
  10342. * Handles a new member joining the MUC.
  10343. */
  10344. function onMucMemberJoined(jid, id, displayName) {
  10345. var member = {
  10346. displayName: displayName
  10347. };
  10348. APP.xmpp.getConnection().disco.info(
  10349. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10350. members[jid] = member;
  10351. }
  10352. /**
  10353. * Handles a member leaving the MUC.
  10354. */
  10355. function onMucMemberLeft(jid) {
  10356. delete members[jid];
  10357. updateAtLeastOneDtmf();
  10358. }
  10359. /**
  10360. * Handles the reception of a disco#info packet from a particular JID.
  10361. * @param jid the JID sending the packet.
  10362. * @param iq the packet.
  10363. */
  10364. function onDiscoInfoReceived(jid, iq) {
  10365. if (!members[jid])
  10366. return;
  10367. var supportsDtmf
  10368. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10369. updateDtmf(jid, supportsDtmf);
  10370. }
  10371. /**
  10372. * Updates the 'supportsDtmf' field for a member.
  10373. * @param jid the jid of the member.
  10374. * @param newValue the new value for the 'supportsDtmf' field.
  10375. */
  10376. function updateDtmf(jid, newValue) {
  10377. var oldValue = members[jid].supportsDtmf;
  10378. members[jid].supportsDtmf = newValue;
  10379. if (newValue != oldValue) {
  10380. updateAtLeastOneDtmf();
  10381. }
  10382. }
  10383. /**
  10384. * Checks each member's 'supportsDtmf' field and updates
  10385. * 'atLastOneSupportsDtmf'.
  10386. */
  10387. function updateAtLeastOneDtmf() {
  10388. var newAtLeastOneDtmf = false;
  10389. for (var key in members) {
  10390. if (typeof members[key].supportsDtmf !== 'undefined'
  10391. && members[key].supportsDtmf) {
  10392. newAtLeastOneDtmf= true;
  10393. break;
  10394. }
  10395. }
  10396. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10397. atLeastOneDtmf = newAtLeastOneDtmf;
  10398. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10399. }
  10400. }
  10401. /**
  10402. * Exported interface.
  10403. */
  10404. var Members = {
  10405. start: function() {
  10406. registerListeners();
  10407. },
  10408. addListener: function(type, listener) {
  10409. eventEmitter.on(type, listener);
  10410. },
  10411. removeListener: function (type, listener) {
  10412. eventEmitter.removeListener(type, listener);
  10413. },
  10414. size: function () {
  10415. return Object.keys(members).length;
  10416. },
  10417. getMembers: function () {
  10418. return members;
  10419. }
  10420. };
  10421. module.exports = Members;
  10422. },{"../../service/members/Events":108,"../../service/xmpp/XMPPEvents":110,"events":111}],47:[function(require,module,exports){
  10423. var email = '';
  10424. var displayName = '';
  10425. var userId;
  10426. var language = null;
  10427. function supportsLocalStorage() {
  10428. try {
  10429. return 'localStorage' in window && window.localStorage !== null;
  10430. } catch (e) {
  10431. console.log("localstorage is not supported");
  10432. return false;
  10433. }
  10434. }
  10435. function generateUniqueId() {
  10436. function _p8() {
  10437. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10438. }
  10439. return _p8() + _p8() + _p8() + _p8();
  10440. }
  10441. if (supportsLocalStorage()) {
  10442. if (!window.localStorage.jitsiMeetId) {
  10443. window.localStorage.jitsiMeetId = generateUniqueId();
  10444. console.log("generated id", window.localStorage.jitsiMeetId);
  10445. }
  10446. userId = window.localStorage.jitsiMeetId || '';
  10447. email = window.localStorage.email || '';
  10448. displayName = window.localStorage.displayname || '';
  10449. language = window.localStorage.language;
  10450. } else {
  10451. console.log("local storage is not supported");
  10452. userId = generateUniqueId();
  10453. }
  10454. var Settings = {
  10455. setDisplayName: function (newDisplayName) {
  10456. displayName = newDisplayName;
  10457. window.localStorage.displayname = displayName;
  10458. return displayName;
  10459. },
  10460. setEmail: function (newEmail) {
  10461. email = newEmail;
  10462. window.localStorage.email = newEmail;
  10463. return email;
  10464. },
  10465. getSettings: function () {
  10466. return {
  10467. email: email,
  10468. displayName: displayName,
  10469. uid: userId,
  10470. language: language
  10471. };
  10472. },
  10473. setLanguage: function (lang) {
  10474. language = lang;
  10475. window.localStorage.language = lang;
  10476. }
  10477. };
  10478. module.exports = Settings;
  10479. },{}],48:[function(require,module,exports){
  10480. /* global config, $, APP, Strophe, callstats */
  10481. var callStats = null;
  10482. function initCallback (err, msg) {
  10483. console.log("Initializing Status: err="+err+" msg="+msg);
  10484. }
  10485. var CallStats = {
  10486. init: function (jingleSession) {
  10487. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10488. return;
  10489. callStats = new callstats($,io,jsSHA);
  10490. this.session = jingleSession;
  10491. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10492. this.userID = APP.xmpp.myResource();
  10493. var location = window.location;
  10494. this.confID = location.protocol + "//" +
  10495. location.hostname + location.pathname;
  10496. //userID is generated or given by the origin server
  10497. callStats.initialize(config.callStatsID,
  10498. config.callStatsSecret,
  10499. this.userID,
  10500. initCallback);
  10501. var usage = callStats.fabricUsage.multiplex;
  10502. callStats.addNewFabric(this.peerconnection,
  10503. Strophe.getResourceFromJid(jingleSession.peerjid),
  10504. usage,
  10505. this.confID,
  10506. this.pcCallback.bind(this));
  10507. },
  10508. pcCallback: function (err, msg) {
  10509. if (!callStats)
  10510. return;
  10511. console.log("Monitoring status: "+ err + " msg: " + msg);
  10512. callStats.sendFabricEvent(this.peerconnection,
  10513. callStats.fabricEvent.fabricSetup, this.confID);
  10514. },
  10515. sendMuteEvent: function (mute, type) {
  10516. if (!callStats)
  10517. return;
  10518. var event = null;
  10519. if (type === "video") {
  10520. event = (mute? callStats.fabricEvent.videoPause :
  10521. callStats.fabricEvent.videoResume);
  10522. }
  10523. else {
  10524. event = (mute? callStats.fabricEvent.audioMute :
  10525. callStats.fabricEvent.audioUnmute);
  10526. }
  10527. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10528. },
  10529. sendTerminateEvent: function () {
  10530. if(!callStats) {
  10531. return;
  10532. }
  10533. callStats.sendFabricEvent(this.peerconnection,
  10534. callStats.fabricEvent.fabricTerminated, this.confID);
  10535. },
  10536. sendSetupFailedEvent: function () {
  10537. if(!callStats) {
  10538. return;
  10539. }
  10540. callStats.sendFabricEvent(this.peerconnection,
  10541. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10542. }
  10543. };
  10544. module.exports = CallStats;
  10545. },{}],49:[function(require,module,exports){
  10546. /* global config */
  10547. /**
  10548. * Provides statistics for the local stream.
  10549. */
  10550. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10551. /**
  10552. * Size of the webaudio analyzer buffer.
  10553. * @type {number}
  10554. */
  10555. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10556. /**
  10557. * Value of the webaudio analyzer smoothing time parameter.
  10558. * @type {number}
  10559. */
  10560. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10561. /**
  10562. * Converts time domain data array to audio level.
  10563. * @param samples the time domain data array.
  10564. * @returns {number} the audio level
  10565. */
  10566. function timeDomainDataToAudioLevel(samples) {
  10567. var maxVolume = 0;
  10568. var length = samples.length;
  10569. for (var i = 0; i < length; i++) {
  10570. if (maxVolume < samples[i])
  10571. maxVolume = samples[i];
  10572. }
  10573. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10574. }
  10575. /**
  10576. * Animates audio level change
  10577. * @param newLevel the new audio level
  10578. * @param lastLevel the last audio level
  10579. * @returns {Number} the audio level to be set
  10580. */
  10581. function animateLevel(newLevel, lastLevel) {
  10582. var value = 0;
  10583. var diff = lastLevel - newLevel;
  10584. if(diff > 0.2) {
  10585. value = lastLevel - 0.2;
  10586. }
  10587. else if(diff < -0.4) {
  10588. value = lastLevel + 0.4;
  10589. }
  10590. else {
  10591. value = newLevel;
  10592. }
  10593. return parseFloat(value.toFixed(3));
  10594. }
  10595. /**
  10596. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10597. *
  10598. * @param stream the local stream
  10599. * @param interval stats refresh interval given in ms.
  10600. * @constructor
  10601. */
  10602. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10603. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10604. this.stream = stream;
  10605. this.intervalId = null;
  10606. this.intervalMilis = interval;
  10607. this.eventEmitter = eventEmitter;
  10608. this.audioLevel = 0;
  10609. this.statisticsService = statisticsService;
  10610. }
  10611. /**
  10612. * Starts the collecting the statistics.
  10613. */
  10614. LocalStatsCollector.prototype.start = function () {
  10615. if (config.disableAudioLevels || !window.AudioContext ||
  10616. RTCBrowserType.isTemasysPluginUsed())
  10617. return;
  10618. var context = new AudioContext();
  10619. var analyser = context.createAnalyser();
  10620. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10621. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10622. var source = context.createMediaStreamSource(this.stream);
  10623. source.connect(analyser);
  10624. var self = this;
  10625. this.intervalId = setInterval(
  10626. function () {
  10627. var array = new Uint8Array(analyser.frequencyBinCount);
  10628. analyser.getByteTimeDomainData(array);
  10629. var audioLevel = timeDomainDataToAudioLevel(array);
  10630. if (audioLevel != self.audioLevel) {
  10631. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10632. self.eventEmitter.emit(
  10633. "statistics.audioLevel",
  10634. self.statisticsService.LOCAL_JID,
  10635. self.audioLevel);
  10636. }
  10637. },
  10638. this.intervalMilis
  10639. );
  10640. };
  10641. /**
  10642. * Stops collecting the statistics.
  10643. */
  10644. LocalStatsCollector.prototype.stop = function () {
  10645. if (this.intervalId) {
  10646. clearInterval(this.intervalId);
  10647. this.intervalId = null;
  10648. }
  10649. };
  10650. module.exports = LocalStatsCollector;
  10651. },{"../RTC/RTCBrowserType":8}],50:[function(require,module,exports){
  10652. /* global require, ssrc2jid */
  10653. /* jshint -W117 */
  10654. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10655. /* Whether we support the browser we are running into for logging statistics */
  10656. var browserSupported = RTCBrowserType.isChrome() ||
  10657. RTCBrowserType.isOpera();
  10658. /**
  10659. * Calculates packet lost percent using the number of lost packets and the
  10660. * number of all packet.
  10661. * @param lostPackets the number of lost packets
  10662. * @param totalPackets the number of all packets.
  10663. * @returns {number} packet loss percent
  10664. */
  10665. function calculatePacketLoss(lostPackets, totalPackets) {
  10666. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10667. return 0;
  10668. return Math.round((lostPackets/totalPackets)*100);
  10669. }
  10670. function getStatValue(item, name) {
  10671. var browserType = RTCBrowserType.getBrowserType();
  10672. if (!keyMap[browserType][name])
  10673. throw "The property isn't supported!";
  10674. var key = keyMap[browserType][name];
  10675. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10676. item.stat(key) : item[key];
  10677. }
  10678. /**
  10679. * Peer statistics data holder.
  10680. * @constructor
  10681. */
  10682. function PeerStats()
  10683. {
  10684. this.ssrc2Loss = {};
  10685. this.ssrc2AudioLevel = {};
  10686. this.ssrc2bitrate = {};
  10687. this.ssrc2resolution = {};
  10688. }
  10689. /**
  10690. * The bandwidth
  10691. * @type {{}}
  10692. */
  10693. PeerStats.bandwidth = {};
  10694. /**
  10695. * The bit rate
  10696. * @type {{}}
  10697. */
  10698. PeerStats.bitrate = {};
  10699. /**
  10700. * The packet loss rate
  10701. * @type {{}}
  10702. */
  10703. PeerStats.packetLoss = null;
  10704. /**
  10705. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10706. * represented by this instance.
  10707. * @param ssrc audio or video RTP stream SSRC.
  10708. * @param lossRate new packet loss rate value to be set.
  10709. */
  10710. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10711. {
  10712. this.ssrc2Loss[ssrc] = lossRate;
  10713. };
  10714. /**
  10715. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10716. * represented by this instance.
  10717. * @param ssrc audio or video RTP stream SSRC.
  10718. * @param resolution new resolution value to be set.
  10719. */
  10720. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10721. {
  10722. if(resolution === null && this.ssrc2resolution[ssrc])
  10723. {
  10724. delete this.ssrc2resolution[ssrc];
  10725. }
  10726. else if(resolution !== null)
  10727. this.ssrc2resolution[ssrc] = resolution;
  10728. };
  10729. /**
  10730. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10731. * represented by this instance.
  10732. * @param ssrc audio or video RTP stream SSRC.
  10733. * @param bitrate new bitrate value to be set.
  10734. */
  10735. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10736. {
  10737. if(this.ssrc2bitrate[ssrc])
  10738. {
  10739. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10740. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10741. }
  10742. else {
  10743. this.ssrc2bitrate[ssrc] = bitrate;
  10744. }
  10745. };
  10746. /**
  10747. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10748. * the stream which belongs to the peer represented by this instance.
  10749. * @param ssrc RTP stream SSRC for which current audio level value will be
  10750. * updated.
  10751. * @param audioLevel the new audio level value to be set. Value is truncated to
  10752. * fit the range from 0 to 1.
  10753. */
  10754. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10755. {
  10756. // Range limit 0 - 1
  10757. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10758. };
  10759. function formatAudioLevel(audioLevel) {
  10760. return Math.min(Math.max(audioLevel, 0), 1);
  10761. }
  10762. /**
  10763. * Array with the transport information.
  10764. * @type {Array}
  10765. */
  10766. PeerStats.transport = [];
  10767. /**
  10768. * <tt>StatsCollector</tt> registers for stats updates of given
  10769. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10770. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10771. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10772. * instance as an event source.
  10773. *
  10774. * @param peerconnection webRTC peer connection object.
  10775. * @param interval stats refresh interval given in ms.
  10776. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10777. * called on stats update.
  10778. * @constructor
  10779. */
  10780. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10781. {
  10782. this.peerconnection = peerconnection;
  10783. this.baselineAudioLevelsReport = null;
  10784. this.currentAudioLevelsReport = null;
  10785. this.currentStatsReport = null;
  10786. this.baselineStatsReport = null;
  10787. this.audioLevelsIntervalId = null;
  10788. this.eventEmitter = eventEmitter;
  10789. /**
  10790. * Gather PeerConnection stats once every this many milliseconds.
  10791. */
  10792. this.GATHER_INTERVAL = 15000;
  10793. /**
  10794. * Log stats via the focus once every this many milliseconds.
  10795. */
  10796. this.LOG_INTERVAL = 60000;
  10797. /**
  10798. * Gather stats and store them in this.statsToBeLogged.
  10799. */
  10800. this.gatherStatsIntervalId = null;
  10801. /**
  10802. * Send the stats already saved in this.statsToBeLogged to be logged via
  10803. * the focus.
  10804. */
  10805. this.logStatsIntervalId = null;
  10806. /**
  10807. * Stores the statistics which will be send to the focus to be logged.
  10808. */
  10809. this.statsToBeLogged =
  10810. {
  10811. timestamps: [],
  10812. stats: {}
  10813. };
  10814. // Updates stats interval
  10815. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10816. this.statsIntervalId = null;
  10817. this.statsIntervalMilis = statsInterval;
  10818. // Map of jids to PeerStats
  10819. this.jid2stats = {};
  10820. }
  10821. module.exports = StatsCollector;
  10822. /**
  10823. * Stops stats updates.
  10824. */
  10825. StatsCollector.prototype.stop = function () {
  10826. if (this.audioLevelsIntervalId) {
  10827. clearInterval(this.audioLevelsIntervalId);
  10828. this.audioLevelsIntervalId = null;
  10829. }
  10830. if (this.statsIntervalId)
  10831. {
  10832. clearInterval(this.statsIntervalId);
  10833. this.statsIntervalId = null;
  10834. }
  10835. if(this.logStatsIntervalId)
  10836. {
  10837. clearInterval(this.logStatsIntervalId);
  10838. this.logStatsIntervalId = null;
  10839. }
  10840. if(this.gatherStatsIntervalId)
  10841. {
  10842. clearInterval(this.gatherStatsIntervalId);
  10843. this.gatherStatsIntervalId = null;
  10844. }
  10845. };
  10846. /**
  10847. * Callback passed to <tt>getStats</tt> method.
  10848. * @param error an error that occurred on <tt>getStats</tt> call.
  10849. */
  10850. StatsCollector.prototype.errorCallback = function (error)
  10851. {
  10852. console.error("Get stats error", error);
  10853. this.stop();
  10854. };
  10855. /**
  10856. * Starts stats updates.
  10857. */
  10858. StatsCollector.prototype.start = function ()
  10859. {
  10860. var self = this;
  10861. if (!config.disableAudioLevels) {
  10862. this.audioLevelsIntervalId = setInterval(
  10863. function () {
  10864. // Interval updates
  10865. self.peerconnection.getStats(
  10866. function (report) {
  10867. var results = null;
  10868. if (!report || !report.result ||
  10869. typeof report.result != 'function') {
  10870. results = report;
  10871. }
  10872. else {
  10873. results = report.result();
  10874. }
  10875. //console.error("Got interval report", results);
  10876. self.currentAudioLevelsReport = results;
  10877. self.processAudioLevelReport();
  10878. self.baselineAudioLevelsReport =
  10879. self.currentAudioLevelsReport;
  10880. },
  10881. self.errorCallback
  10882. );
  10883. },
  10884. self.audioLevelsIntervalMilis
  10885. );
  10886. }
  10887. if (!config.disableStats && browserSupported) {
  10888. this.statsIntervalId = setInterval(
  10889. function () {
  10890. // Interval updates
  10891. self.peerconnection.getStats(
  10892. function (report) {
  10893. var results = null;
  10894. if (!report || !report.result ||
  10895. typeof report.result != 'function') {
  10896. //firefox
  10897. results = report;
  10898. }
  10899. else {
  10900. //chrome
  10901. results = report.result();
  10902. }
  10903. //console.error("Got interval report", results);
  10904. self.currentStatsReport = results;
  10905. try {
  10906. self.processStatsReport();
  10907. }
  10908. catch (e) {
  10909. console.error("Unsupported key:" + e, e);
  10910. }
  10911. self.baselineStatsReport = self.currentStatsReport;
  10912. },
  10913. self.errorCallback
  10914. );
  10915. },
  10916. self.statsIntervalMilis
  10917. );
  10918. }
  10919. if (config.logStats && browserSupported) {
  10920. this.gatherStatsIntervalId = setInterval(
  10921. function () {
  10922. self.peerconnection.getStats(
  10923. function (report) {
  10924. self.addStatsToBeLogged(report.result());
  10925. },
  10926. function () {
  10927. }
  10928. );
  10929. },
  10930. this.GATHER_INTERVAL
  10931. );
  10932. this.logStatsIntervalId = setInterval(
  10933. function() { self.logStats(); },
  10934. this.LOG_INTERVAL);
  10935. }
  10936. };
  10937. /**
  10938. * Checks whether a certain record should be included in the logged statistics.
  10939. */
  10940. function acceptStat(reportId, reportType, statName) {
  10941. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10942. return false;
  10943. if (reportType == "ssrc") {
  10944. if (statName == "googTrackId" ||
  10945. statName == "transportId" ||
  10946. statName == "ssrc")
  10947. return false;
  10948. }
  10949. return true;
  10950. }
  10951. /**
  10952. * Checks whether a certain record should be included in the logged statistics.
  10953. */
  10954. function acceptReport(id, type) {
  10955. if (id.substring(0, 15) == "googCertificate" ||
  10956. id.substring(0, 9) == "googTrack" ||
  10957. id.substring(0, 20) == "googLibjingleSession")
  10958. return false;
  10959. if (type == "googComponent")
  10960. return false;
  10961. return true;
  10962. }
  10963. /**
  10964. * Converts the stats to the format used for logging, and saves the data in
  10965. * this.statsToBeLogged.
  10966. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10967. */
  10968. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10969. var self = this;
  10970. var num_records = this.statsToBeLogged.timestamps.length;
  10971. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10972. reports.map(function (report) {
  10973. if (!acceptReport(report.id, report.type))
  10974. return;
  10975. var stat = self.statsToBeLogged.stats[report.id];
  10976. if (!stat) {
  10977. stat = self.statsToBeLogged.stats[report.id] = {};
  10978. }
  10979. stat.type = report.type;
  10980. report.names().map(function (name) {
  10981. if (!acceptStat(report.id, report.type, name))
  10982. return;
  10983. var values = stat[name];
  10984. if (!values) {
  10985. values = stat[name] = [];
  10986. }
  10987. while (values.length < num_records) {
  10988. values.push(null);
  10989. }
  10990. values.push(report.stat(name));
  10991. });
  10992. });
  10993. };
  10994. StatsCollector.prototype.logStats = function () {
  10995. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10996. return;
  10997. // Reset the stats
  10998. this.statsToBeLogged.stats = {};
  10999. this.statsToBeLogged.timestamps = [];
  11000. };
  11001. var keyMap = {};
  11002. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11003. "ssrc": "ssrc",
  11004. "packetsReceived": "packetsReceived",
  11005. "packetsLost": "packetsLost",
  11006. "packetsSent": "packetsSent",
  11007. "bytesReceived": "bytesReceived",
  11008. "bytesSent": "bytesSent"
  11009. };
  11010. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11011. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11012. "sendBandwidth": "googAvailableSendBandwidth",
  11013. "remoteAddress": "googRemoteAddress",
  11014. "transportType": "googTransportType",
  11015. "localAddress": "googLocalAddress",
  11016. "activeConnection": "googActiveConnection",
  11017. "ssrc": "ssrc",
  11018. "packetsReceived": "packetsReceived",
  11019. "packetsSent": "packetsSent",
  11020. "packetsLost": "packetsLost",
  11021. "bytesReceived": "bytesReceived",
  11022. "bytesSent": "bytesSent",
  11023. "googFrameHeightReceived": "googFrameHeightReceived",
  11024. "googFrameWidthReceived": "googFrameWidthReceived",
  11025. "googFrameHeightSent": "googFrameHeightSent",
  11026. "googFrameWidthSent": "googFrameWidthSent",
  11027. "audioInputLevel": "audioInputLevel",
  11028. "audioOutputLevel": "audioOutputLevel"
  11029. };
  11030. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11031. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11032. /**
  11033. * Stats processing logic.
  11034. */
  11035. StatsCollector.prototype.processStatsReport = function () {
  11036. if (!this.baselineStatsReport) {
  11037. return;
  11038. }
  11039. for (var idx in this.currentStatsReport) {
  11040. var now = this.currentStatsReport[idx];
  11041. try {
  11042. if (getStatValue(now, 'receiveBandwidth') ||
  11043. getStatValue(now, 'sendBandwidth')) {
  11044. PeerStats.bandwidth = {
  11045. "download": Math.round(
  11046. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11047. "upload": Math.round(
  11048. (getStatValue(now, 'sendBandwidth')) / 1000)
  11049. };
  11050. }
  11051. }
  11052. catch(e){/*not supported*/}
  11053. if(now.type == 'googCandidatePair')
  11054. {
  11055. var ip, type, localIP, active;
  11056. try {
  11057. ip = getStatValue(now, 'remoteAddress');
  11058. type = getStatValue(now, "transportType");
  11059. localIP = getStatValue(now, "localAddress");
  11060. active = getStatValue(now, "activeConnection");
  11061. }
  11062. catch(e){/*not supported*/}
  11063. if(!ip || !type || !localIP || active != "true")
  11064. continue;
  11065. var addressSaved = false;
  11066. for(var i = 0; i < PeerStats.transport.length; i++)
  11067. {
  11068. if(PeerStats.transport[i].ip == ip &&
  11069. PeerStats.transport[i].type == type &&
  11070. PeerStats.transport[i].localip == localIP)
  11071. {
  11072. addressSaved = true;
  11073. }
  11074. }
  11075. if(addressSaved)
  11076. continue;
  11077. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11078. continue;
  11079. }
  11080. if(now.type == "candidatepair")
  11081. {
  11082. if(now.state == "succeeded")
  11083. continue;
  11084. var local = this.currentStatsReport[now.localCandidateId];
  11085. var remote = this.currentStatsReport[now.remoteCandidateId];
  11086. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11087. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11088. }
  11089. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11090. now.type != "inboundrtp") {
  11091. continue;
  11092. }
  11093. var before = this.baselineStatsReport[idx];
  11094. if (!before) {
  11095. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11096. continue;
  11097. }
  11098. var ssrc = getStatValue(now, 'ssrc');
  11099. if(!ssrc)
  11100. continue;
  11101. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11102. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11103. console.warn("No jid for ssrc: " + ssrc);
  11104. continue;
  11105. }
  11106. var jidStats = this.jid2stats[jid];
  11107. if (!jidStats) {
  11108. jidStats = new PeerStats();
  11109. this.jid2stats[jid] = jidStats;
  11110. }
  11111. var isDownloadStream = true;
  11112. var key = 'packetsReceived';
  11113. if (!getStatValue(now, key))
  11114. {
  11115. isDownloadStream = false;
  11116. key = 'packetsSent';
  11117. if (!getStatValue(now, key))
  11118. {
  11119. console.warn("No packetsReceived nor packetSent stat found");
  11120. continue;
  11121. }
  11122. }
  11123. var packetsNow = getStatValue(now, key);
  11124. if(!packetsNow || packetsNow < 0)
  11125. packetsNow = 0;
  11126. var packetsBefore = getStatValue(before, key);
  11127. if(!packetsBefore || packetsBefore < 0)
  11128. packetsBefore = 0;
  11129. var packetRate = packetsNow - packetsBefore;
  11130. if(!packetRate || packetRate < 0)
  11131. packetRate = 0;
  11132. var currentLoss = getStatValue(now, 'packetsLost');
  11133. if(!currentLoss || currentLoss < 0)
  11134. currentLoss = 0;
  11135. var previousLoss = getStatValue(before, 'packetsLost');
  11136. if(!previousLoss || previousLoss < 0)
  11137. previousLoss = 0;
  11138. var lossRate = currentLoss - previousLoss;
  11139. if(!lossRate || lossRate < 0)
  11140. lossRate = 0;
  11141. var packetsTotal = (packetRate + lossRate);
  11142. jidStats.setSsrcLoss(ssrc,
  11143. {"packetsTotal": packetsTotal,
  11144. "packetsLost": lossRate,
  11145. "isDownloadStream": isDownloadStream});
  11146. var bytesReceived = 0, bytesSent = 0;
  11147. if(getStatValue(now, "bytesReceived"))
  11148. {
  11149. bytesReceived = getStatValue(now, "bytesReceived") -
  11150. getStatValue(before, "bytesReceived");
  11151. }
  11152. if(getStatValue(now, "bytesSent"))
  11153. {
  11154. bytesSent = getStatValue(now, "bytesSent") -
  11155. getStatValue(before, "bytesSent");
  11156. }
  11157. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11158. if(bytesReceived <= 0 || time <= 0)
  11159. {
  11160. bytesReceived = 0;
  11161. }
  11162. else
  11163. {
  11164. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11165. }
  11166. if(bytesSent <= 0 || time <= 0)
  11167. {
  11168. bytesSent = 0;
  11169. }
  11170. else
  11171. {
  11172. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11173. }
  11174. jidStats.setSsrcBitrate(ssrc, {
  11175. "download": bytesReceived,
  11176. "upload": bytesSent});
  11177. var resolution = {height: null, width: null};
  11178. try {
  11179. if (getStatValue(now, "googFrameHeightReceived") &&
  11180. getStatValue(now, "googFrameWidthReceived")) {
  11181. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11182. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11183. }
  11184. else if (getStatValue(now, "googFrameHeightSent") &&
  11185. getStatValue(now, "googFrameWidthSent")) {
  11186. resolution.height = getStatValue(now, "googFrameHeightSent");
  11187. resolution.width = getStatValue(now, "googFrameWidthSent");
  11188. }
  11189. }
  11190. catch(e){/*not supported*/}
  11191. if(resolution.height && resolution.width)
  11192. {
  11193. jidStats.setSsrcResolution(ssrc, resolution);
  11194. }
  11195. else
  11196. {
  11197. jidStats.setSsrcResolution(ssrc, null);
  11198. }
  11199. }
  11200. var self = this;
  11201. // Jid stats
  11202. var totalPackets = {download: 0, upload: 0};
  11203. var lostPackets = {download: 0, upload: 0};
  11204. var bitrateDownload = 0;
  11205. var bitrateUpload = 0;
  11206. var resolutions = {};
  11207. Object.keys(this.jid2stats).forEach(
  11208. function (jid)
  11209. {
  11210. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11211. function (ssrc)
  11212. {
  11213. var type = "upload";
  11214. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11215. type = "download";
  11216. totalPackets[type] +=
  11217. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11218. lostPackets[type] +=
  11219. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11220. }
  11221. );
  11222. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11223. function (ssrc) {
  11224. bitrateDownload +=
  11225. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11226. bitrateUpload +=
  11227. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11228. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11229. }
  11230. );
  11231. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11232. }
  11233. );
  11234. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11235. PeerStats.packetLoss = {
  11236. total:
  11237. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11238. totalPackets.download + totalPackets.upload),
  11239. download:
  11240. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11241. upload:
  11242. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11243. };
  11244. this.eventEmitter.emit("statistics.connectionstats",
  11245. {
  11246. "bitrate": PeerStats.bitrate,
  11247. "packetLoss": PeerStats.packetLoss,
  11248. "bandwidth": PeerStats.bandwidth,
  11249. "resolution": resolutions,
  11250. "transport": PeerStats.transport
  11251. });
  11252. PeerStats.transport = [];
  11253. };
  11254. /**
  11255. * Stats processing logic.
  11256. */
  11257. StatsCollector.prototype.processAudioLevelReport = function () {
  11258. if (!this.baselineAudioLevelsReport) {
  11259. return;
  11260. }
  11261. for (var idx in this.currentAudioLevelsReport) {
  11262. var now = this.currentAudioLevelsReport[idx];
  11263. if (now.type != 'ssrc') {
  11264. continue;
  11265. }
  11266. var before = this.baselineAudioLevelsReport[idx];
  11267. if (!before) {
  11268. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11269. continue;
  11270. }
  11271. var ssrc = getStatValue(now, 'ssrc');
  11272. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11273. if (!jid) {
  11274. if((Date.now() - now.timestamp) < 3000)
  11275. console.warn("No jid for ssrc: " + ssrc);
  11276. continue;
  11277. }
  11278. var jidStats = this.jid2stats[jid];
  11279. if (!jidStats) {
  11280. jidStats = new PeerStats();
  11281. this.jid2stats[jid] = jidStats;
  11282. }
  11283. // Audio level
  11284. var audioLevel = null;
  11285. try {
  11286. audioLevel = getStatValue(now, 'audioInputLevel');
  11287. if (!audioLevel)
  11288. audioLevel = getStatValue(now, 'audioOutputLevel');
  11289. }
  11290. catch(e) {/*not supported*/
  11291. console.warn("Audio Levels are not available in the statistics.");
  11292. clearInterval(this.audioLevelsIntervalId);
  11293. return;
  11294. }
  11295. if (audioLevel) {
  11296. // TODO: can't find specs about what this value really is,
  11297. // but it seems to vary between 0 and around 32k.
  11298. audioLevel = audioLevel / 32767;
  11299. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11300. if(jid != APP.xmpp.myJid())
  11301. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11302. }
  11303. }
  11304. };
  11305. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11306. /* global require, APP */
  11307. /**
  11308. * Created by hristo on 8/4/14.
  11309. */
  11310. var LocalStats = require("./LocalStatsCollector.js");
  11311. var RTPStats = require("./RTPStatsCollector.js");
  11312. var EventEmitter = require("events");
  11313. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11314. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11315. var CallStats = require("./CallStats");
  11316. var RTCEvents = require("../../service/RTC/RTCEvents");
  11317. var eventEmitter = new EventEmitter();
  11318. var localStats = null;
  11319. var rtpStats = null;
  11320. function stopLocal() {
  11321. if (localStats) {
  11322. localStats.stop();
  11323. localStats = null;
  11324. }
  11325. }
  11326. function stopRemote() {
  11327. if (rtpStats) {
  11328. rtpStats.stop();
  11329. eventEmitter.emit("statistics.stop");
  11330. rtpStats = null;
  11331. }
  11332. }
  11333. function startRemoteStats (peerconnection) {
  11334. if (rtpStats) {
  11335. rtpStats.stop();
  11336. }
  11337. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11338. rtpStats.start();
  11339. }
  11340. function onStreamCreated(stream) {
  11341. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11342. return;
  11343. }
  11344. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11345. eventEmitter);
  11346. localStats.start();
  11347. }
  11348. function onDisposeConference(onUnload) {
  11349. CallStats.sendTerminateEvent();
  11350. stopRemote();
  11351. if(onUnload) {
  11352. stopLocal();
  11353. eventEmitter.removeAllListeners();
  11354. }
  11355. }
  11356. var statistics = {
  11357. /**
  11358. * Indicates that this audio level is for local jid.
  11359. * @type {string}
  11360. */
  11361. LOCAL_JID: 'local',
  11362. addAudioLevelListener: function(listener)
  11363. {
  11364. eventEmitter.on("statistics.audioLevel", listener);
  11365. },
  11366. removeAudioLevelListener: function(listener)
  11367. {
  11368. eventEmitter.removeListener("statistics.audioLevel", listener);
  11369. },
  11370. addConnectionStatsListener: function(listener)
  11371. {
  11372. eventEmitter.on("statistics.connectionstats", listener);
  11373. },
  11374. removeConnectionStatsListener: function(listener)
  11375. {
  11376. eventEmitter.removeListener("statistics.connectionstats", listener);
  11377. },
  11378. addRemoteStatsStopListener: function(listener)
  11379. {
  11380. eventEmitter.on("statistics.stop", listener);
  11381. },
  11382. removeRemoteStatsStopListener: function(listener)
  11383. {
  11384. eventEmitter.removeListener("statistics.stop", listener);
  11385. },
  11386. stop: function () {
  11387. stopLocal();
  11388. stopRemote();
  11389. if(eventEmitter)
  11390. {
  11391. eventEmitter.removeAllListeners();
  11392. }
  11393. },
  11394. stopRemoteStatistics: function()
  11395. {
  11396. stopRemote();
  11397. },
  11398. start: function () {
  11399. APP.RTC.addStreamListener(onStreamCreated,
  11400. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11401. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11402. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11403. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11404. startRemoteStats(event.peerconnection);
  11405. // CallStats.init(event);
  11406. });
  11407. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11408. CallStats.init(session);
  11409. });
  11410. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11411. CallStats.sendMuteEvent(mute, "audio");
  11412. });
  11413. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11414. CallStats.sendSetupFailedEvent();
  11415. });
  11416. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11417. CallStats.sendMuteEvent(mute, "video");
  11418. });
  11419. }
  11420. };
  11421. module.exports = statistics;
  11422. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes.js":103,"../../service/xmpp/XMPPEvents":110,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":111}],52:[function(require,module,exports){
  11423. /* global $, require, config, interfaceConfig */
  11424. var i18n = require("i18next-client");
  11425. var languages = require("../../service/translation/languages");
  11426. var Settings = require("../settings/Settings");
  11427. var DEFAULT_LANG = languages.EN;
  11428. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11429. return value.replace("__app__", interfaceConfig.APP_NAME);
  11430. });
  11431. var defaultOptions = {
  11432. detectLngQS: "lang",
  11433. useCookie: false,
  11434. fallbackLng: DEFAULT_LANG,
  11435. load: "unspecific",
  11436. resGetPath: 'lang/__ns__-__lng__.json',
  11437. ns: {
  11438. namespaces: ['main', 'languages'],
  11439. defaultNs: 'main'
  11440. },
  11441. lngWhitelist : languages.getLanguages(),
  11442. fallbackOnNull: true,
  11443. fallbackOnEmpty: true,
  11444. useDataAttrOptions: true,
  11445. app: interfaceConfig.APP_NAME,
  11446. getAsync: false,
  11447. defaultValueFromContent: false,
  11448. customLoad: function(lng, ns, options, done) {
  11449. var resPath = "lang/__ns__-__lng__.json";
  11450. if(lng === languages.EN)
  11451. resPath = "lang/__ns__.json";
  11452. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11453. i18n.functions.ajax({
  11454. url: url,
  11455. success: function(data, status, xhr) {
  11456. i18n.functions.log('loaded: ' + url);
  11457. done(null, data);
  11458. },
  11459. error : function(xhr, status, error) {
  11460. if ((status && status == 200) ||
  11461. (xhr && xhr.status && xhr.status == 200)) {
  11462. // file loaded but invalid json, stop waste time !
  11463. i18n.functions.error('There is a typo in: ' + url);
  11464. } else if ((status && status == 404) ||
  11465. (xhr && xhr.status && xhr.status == 404)) {
  11466. i18n.functions.log('Does not exist: ' + url);
  11467. } else {
  11468. var theStatus = status ? status :
  11469. ((xhr && xhr.status) ? xhr.status : null);
  11470. i18n.functions.log(theStatus + ' when loading ' + url);
  11471. }
  11472. done(error, {});
  11473. },
  11474. dataType: "json",
  11475. async : options.getAsync
  11476. });
  11477. }
  11478. // options for caching
  11479. // useLocalStorage: true,
  11480. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11481. };
  11482. function initCompleted(t) {
  11483. $("[data-i18n]").i18n();
  11484. }
  11485. function checkForParameter() {
  11486. var query = window.location.search.substring(1);
  11487. var vars = query.split("&");
  11488. for (var i=0;i<vars.length;i++) {
  11489. var pair = vars[i].split("=");
  11490. if(pair[0] == "lang")
  11491. {
  11492. return pair[1];
  11493. }
  11494. }
  11495. return null;
  11496. }
  11497. module.exports = {
  11498. init: function (lang) {
  11499. var options = defaultOptions;
  11500. if(!lang)
  11501. {
  11502. lang = checkForParameter();
  11503. if(!lang)
  11504. {
  11505. var settings = Settings.getSettings();
  11506. if(settings)
  11507. lang = settings.language;
  11508. if(!lang && config.defaultLanguage)
  11509. {
  11510. lang = config.defaultLanguage;
  11511. }
  11512. }
  11513. }
  11514. if(lang) {
  11515. options.lng = lang;
  11516. }
  11517. i18n.init(options, initCompleted);
  11518. },
  11519. translateString: function (key, options) {
  11520. return i18n.t(key, options);
  11521. },
  11522. setLanguage: function (lang) {
  11523. if(!lang)
  11524. lang = DEFAULT_LANG;
  11525. i18n.setLng(lang, defaultOptions, initCompleted);
  11526. },
  11527. getCurrentLanguage: function () {
  11528. return i18n.lng();
  11529. },
  11530. translateElement: function (selector) {
  11531. selector.i18n();
  11532. },
  11533. generateTranslationHTML: function (key, options) {
  11534. var str = "<span data-i18n=\"" + key + "\"";
  11535. if(options)
  11536. {
  11537. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11538. }
  11539. str += ">";
  11540. str += this.translateString(key, options);
  11541. str += "</span>";
  11542. return str;
  11543. }
  11544. };
  11545. },{"../../service/translation/languages":109,"../settings/Settings":47,"i18next-client":70}],53:[function(require,module,exports){
  11546. /*
  11547. * JingleSession provides an API to manage a single Jingle session. We will
  11548. * have different implementations depending on the underlying interface used
  11549. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  11550. */
  11551. function JingleSession(me, sid, connection, service, eventEmitter) {
  11552. /**
  11553. * Our JID.
  11554. */
  11555. this.me = me;
  11556. /**
  11557. * The Jingle session identifier.
  11558. */
  11559. this.sid = sid;
  11560. /**
  11561. * The XMPP connection.
  11562. */
  11563. this.connection = connection;
  11564. /**
  11565. * The XMPP service.
  11566. */
  11567. this.service = service;
  11568. /**
  11569. * The event emitter.
  11570. */
  11571. this.eventEmitter = eventEmitter;
  11572. /**
  11573. * Whether to use dripping or not. Dripping is sending trickle candidates
  11574. * not one-by-one.
  11575. * Note: currently we do not support 'false'.
  11576. */
  11577. this.usedrip = true;
  11578. /**
  11579. * When dripping is used, stores ICE candidates which are to be sent.
  11580. */
  11581. this.drip_container = [];
  11582. // Media constraints. Is this WebRTC only?
  11583. this.media_constraints = null;
  11584. // ICE servers config (RTCConfiguration?).
  11585. this.ice_config = {};
  11586. }
  11587. /**
  11588. * Prepares this object to initiate a session.
  11589. * @param peerjid the JID of the remote peer.
  11590. * @param isInitiator whether we will be the Jingle initiator.
  11591. * @param media_constraints
  11592. * @param ice_config
  11593. */
  11594. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  11595. media_constraints, ice_config) {
  11596. this.media_constraints = media_constraints;
  11597. this.ice_config = ice_config;
  11598. if (this.state !== null) {
  11599. console.error('attempt to initiate on session ' + this.sid +
  11600. 'in state ' + this.state);
  11601. return;
  11602. }
  11603. this.state = 'pending';
  11604. this.initiator = isInitiator ? this.me : peerjid;
  11605. this.responder = !isInitiator ? this.me : peerjid;
  11606. this.peerjid = peerjid;
  11607. this.doInitialize();
  11608. };
  11609. /**
  11610. * Finishes initialization.
  11611. */
  11612. JingleSession.prototype.doInitialize = function() {};
  11613. /**
  11614. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  11615. * Note: currently only used on transport-info
  11616. */
  11617. JingleSession.prototype.addIceCandidates = function(contents) {};
  11618. /**
  11619. * Handles an 'add-source' event.
  11620. *
  11621. * @param contents an array of Jingle 'content' elements.
  11622. */
  11623. JingleSession.prototype.addSources = function(contents) {};
  11624. /**
  11625. * Handles a 'remove-source' event.
  11626. *
  11627. * @param contents an array of Jingle 'content' elements.
  11628. */
  11629. JingleSession.prototype.removeSources = function(contents) {};
  11630. /**
  11631. * Terminates this Jingle session (stops sending media and closes the streams?)
  11632. */
  11633. JingleSession.prototype.terminate = function() {};
  11634. /**
  11635. * Sends a Jingle session-terminate message to the peer and terminates the
  11636. * session.
  11637. * @param reason
  11638. * @param text
  11639. */
  11640. JingleSession.prototype.sendTerminate = function(reason, text) {};
  11641. /**
  11642. * Handles an offer from the remote peer (prepares to accept a session).
  11643. * @param jingle the 'jingle' XML element.
  11644. */
  11645. JingleSession.prototype.setOffer = function(jingle) {};
  11646. /**
  11647. * Handles an answer from the remote peer (prepares to accept a session).
  11648. * @param jingle the 'jingle' XML element.
  11649. */
  11650. JingleSession.prototype.setAnswer = function(jingle) {};
  11651. module.exports = JingleSession;
  11652. },{}],54:[function(require,module,exports){
  11653. /* jshint -W117 */
  11654. var JingleSession = require("./JingleSession");
  11655. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11656. var SDPDiffer = require("./SDPDiffer");
  11657. var SDPUtil = require("./SDPUtil");
  11658. var SDP = require("./SDP");
  11659. var async = require("async");
  11660. var transform = require("sdp-transform");
  11661. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11662. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11663. var SSRCReplacement = require("./LocalSSRCReplacement");
  11664. // Jingle stuff
  11665. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  11666. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  11667. this.initiator = null;
  11668. this.responder = null;
  11669. this.peerjid = null;
  11670. this.state = null;
  11671. this.localSDP = null;
  11672. this.remoteSDP = null;
  11673. this.relayedStreams = [];
  11674. this.pc_constraints = null;
  11675. this.usetrickle = true;
  11676. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11677. this.hadstuncandidate = false;
  11678. this.hadturncandidate = false;
  11679. this.lasticecandidate = false;
  11680. this.statsinterval = null;
  11681. this.reason = null;
  11682. this.addssrc = [];
  11683. this.removessrc = [];
  11684. this.pendingop = null;
  11685. this.switchstreams = false;
  11686. this.wait = true;
  11687. this.localStreamsSSRC = null;
  11688. this.ssrcOwners = {};
  11689. this.ssrcVideoTypes = {};
  11690. this.eventEmitter = eventEmitter;
  11691. /**
  11692. * The indicator which determines whether the (local) video has been muted
  11693. * in response to a user command in contrast to an automatic decision made
  11694. * by the application logic.
  11695. */
  11696. this.videoMuteByUser = false;
  11697. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11698. // We start with the queue paused. We resume it when the signaling state is
  11699. // stable and the ice connection state is connected.
  11700. this.modifySourcesQueue.pause();
  11701. }
  11702. JingleSessionPC.prototype = JingleSession.prototype;
  11703. JingleSessionPC.prototype.constructor = JingleSessionPC;
  11704. JingleSessionPC.prototype.setOffer = function(offer) {
  11705. this.setRemoteDescription(offer, 'offer');
  11706. };
  11707. JingleSessionPC.prototype.setAnswer = function(answer) {
  11708. this.setRemoteDescription(answer, 'answer');
  11709. };
  11710. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  11711. var signalingState = this.peerconnection.signalingState;
  11712. var iceConnectionState = this.peerconnection.iceConnectionState;
  11713. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11714. this.modifySourcesQueue.resume();
  11715. } else {
  11716. this.modifySourcesQueue.pause();
  11717. }
  11718. };
  11719. JingleSessionPC.prototype.doInitialize = function () {
  11720. var self = this;
  11721. this.hadstuncandidate = false;
  11722. this.hadturncandidate = false;
  11723. this.lasticecandidate = false;
  11724. this.isreconnect = false;
  11725. this.peerconnection = new TraceablePeerConnection(
  11726. this.connection.jingle.ice_config,
  11727. this.connection.jingle.pc_constraints,
  11728. this);
  11729. this.peerconnection.onicecandidate = function (event) {
  11730. self.sendIceCandidate(event.candidate);
  11731. };
  11732. this.peerconnection.onaddstream = function (event) {
  11733. if (event.stream.id !== 'default') {
  11734. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11735. self.remoteStreamAdded(event);
  11736. } else {
  11737. // This is a recvonly stream. Clients that implement Unified Plan,
  11738. // such as Firefox use recvonly "streams/channels/tracks" for
  11739. // receiving remote stream/tracks, as opposed to Plan B where there
  11740. // are only 3 channels: audio, video and data.
  11741. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11742. }
  11743. };
  11744. this.peerconnection.onremovestream = function (event) {
  11745. // Remove the stream from remoteStreams
  11746. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11747. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11748. };
  11749. this.peerconnection.onsignalingstatechange = function (event) {
  11750. if (!(self && self.peerconnection)) return;
  11751. self.updateModifySourcesQueue();
  11752. };
  11753. /**
  11754. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  11755. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  11756. * RTCPeerConnection.iceConnectionState changes.
  11757. *
  11758. * @param event the event containing information about the change
  11759. */
  11760. this.peerconnection.oniceconnectionstatechange = function (event) {
  11761. if (!(self && self.peerconnection)) return;
  11762. self.updateModifySourcesQueue();
  11763. switch (self.peerconnection.iceConnectionState) {
  11764. case 'connected':
  11765. // Informs interested parties that the connection has been restored.
  11766. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  11767. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  11768. self.isreconnect = false;
  11769. break;
  11770. case 'disconnected':
  11771. self.isreconnect = true;
  11772. // Informs interested parties that the connection has been interrupted.
  11773. if (self.peerconnection.signalingState === 'stable')
  11774. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  11775. break;
  11776. case 'failed':
  11777. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11778. break;
  11779. }
  11780. onIceConnectionStateChange(self.sid, self);
  11781. };
  11782. this.peerconnection.onnegotiationneeded = function (event) {
  11783. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11784. };
  11785. // add any local and relayed stream
  11786. APP.RTC.localStreams.forEach(function(stream) {
  11787. self.peerconnection.addStream(stream.getOriginalStream());
  11788. });
  11789. this.relayedStreams.forEach(function(stream) {
  11790. self.peerconnection.addStream(stream);
  11791. });
  11792. };
  11793. function onIceConnectionStateChange(sid, session) {
  11794. switch (session.peerconnection.iceConnectionState) {
  11795. case 'checking':
  11796. session.timeChecking = (new Date()).getTime();
  11797. session.firstconnect = true;
  11798. break;
  11799. case 'completed': // on caller side
  11800. case 'connected':
  11801. if (session.firstconnect) {
  11802. session.firstconnect = false;
  11803. var metadata = {};
  11804. metadata.setupTime
  11805. = (new Date()).getTime() - session.timeChecking;
  11806. session.peerconnection.getStats(function (res) {
  11807. if(res && res.result) {
  11808. res.result().forEach(function (report) {
  11809. if (report.type == 'googCandidatePair' &&
  11810. report.stat('googActiveConnection') == 'true') {
  11811. metadata.localCandidateType
  11812. = report.stat('googLocalCandidateType');
  11813. metadata.remoteCandidateType
  11814. = report.stat('googRemoteCandidateType');
  11815. // log pair as well so we can get nice pie
  11816. // charts
  11817. metadata.candidatePair
  11818. = report.stat('googLocalCandidateType') +
  11819. ';' +
  11820. report.stat('googRemoteCandidateType');
  11821. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11822. {
  11823. metadata.ipv6 = true;
  11824. }
  11825. }
  11826. });
  11827. }
  11828. });
  11829. }
  11830. break;
  11831. }
  11832. }
  11833. JingleSessionPC.prototype.accept = function () {
  11834. this.state = 'active';
  11835. var pranswer = this.peerconnection.localDescription;
  11836. if (!pranswer || pranswer.type != 'pranswer') {
  11837. return;
  11838. }
  11839. console.log('going from pranswer to answer');
  11840. if (this.usetrickle) {
  11841. // remove candidates already sent from session-accept
  11842. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11843. for (var i = 0; i < lines.length; i++) {
  11844. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11845. }
  11846. }
  11847. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11848. // FIXME: change any inactive to sendrecv or whatever they were originally
  11849. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11850. }
  11851. var prsdp = new SDP(pranswer.sdp);
  11852. var accept = $iq({to: this.peerjid,
  11853. type: 'set'})
  11854. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11855. action: 'session-accept',
  11856. initiator: this.initiator,
  11857. responder: this.responder,
  11858. sid: this.sid });
  11859. // FIXME why do we generate session-accept in 3 different places ?
  11860. prsdp.toJingle(
  11861. accept,
  11862. this.initiator == this.me ? 'initiator' : 'responder',
  11863. this.localStreamsSSRC);
  11864. var sdp = this.peerconnection.localDescription.sdp;
  11865. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11866. // FIXME: change any inactive to sendrecv or whatever they were originally
  11867. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11868. }
  11869. var self = this;
  11870. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11871. function () {
  11872. //console.log('setLocalDescription success');
  11873. self.setLocalDescription();
  11874. SSRCReplacement.processSessionInit(accept);
  11875. self.connection.sendIQ(accept,
  11876. function () {
  11877. var ack = {};
  11878. ack.source = 'answer';
  11879. $(document).trigger('ack.jingle', [self.sid, ack]);
  11880. },
  11881. function (stanza) {
  11882. var error = ($(stanza).find('error').length) ? {
  11883. code: $(stanza).find('error').attr('code'),
  11884. reason: $(stanza).find('error :first')[0].tagName
  11885. }:{};
  11886. error.source = 'answer';
  11887. JingleSessionPC.onJingleError(self.sid, error);
  11888. },
  11889. 10000);
  11890. },
  11891. function (e) {
  11892. console.error('setLocalDescription failed', e);
  11893. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11894. }
  11895. );
  11896. };
  11897. JingleSessionPC.prototype.terminate = function (reason) {
  11898. this.state = 'ended';
  11899. this.reason = reason;
  11900. this.peerconnection.close();
  11901. if (this.statsinterval !== null) {
  11902. window.clearInterval(this.statsinterval);
  11903. this.statsinterval = null;
  11904. }
  11905. };
  11906. JingleSessionPC.prototype.active = function () {
  11907. return this.state == 'active';
  11908. };
  11909. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  11910. var self = this;
  11911. if (candidate && !this.lasticecandidate) {
  11912. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11913. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11914. if (!(ice && jcand)) {
  11915. console.error('failed to get ice && jcand');
  11916. return;
  11917. }
  11918. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11919. if (jcand.type === 'srflx') {
  11920. this.hadstuncandidate = true;
  11921. } else if (jcand.type === 'relay') {
  11922. this.hadturncandidate = true;
  11923. }
  11924. if (this.usetrickle) {
  11925. if (this.usedrip) {
  11926. if (this.drip_container.length === 0) {
  11927. // start 20ms callout
  11928. window.setTimeout(function () {
  11929. if (self.drip_container.length === 0) return;
  11930. self.sendIceCandidates(self.drip_container);
  11931. self.drip_container = [];
  11932. }, 20);
  11933. }
  11934. this.drip_container.push(candidate);
  11935. return;
  11936. } else {
  11937. self.sendIceCandidate([candidate]);
  11938. }
  11939. }
  11940. } else {
  11941. //console.log('sendIceCandidate: last candidate.');
  11942. if (!this.usetrickle) {
  11943. //console.log('should send full offer now...');
  11944. //FIXME why do we generate session-accept in 3 different places ?
  11945. var init = $iq({to: this.peerjid,
  11946. type: 'set'})
  11947. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11948. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11949. initiator: this.initiator,
  11950. sid: this.sid});
  11951. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11952. var sendJingle = function (ssrc) {
  11953. if(!ssrc)
  11954. ssrc = {};
  11955. self.localSDP.toJingle(
  11956. init,
  11957. self.initiator == self.me ? 'initiator' : 'responder',
  11958. ssrc);
  11959. SSRCReplacement.processSessionInit(init);
  11960. self.connection.sendIQ(init,
  11961. function () {
  11962. //console.log('session initiate ack');
  11963. var ack = {};
  11964. ack.source = 'offer';
  11965. $(document).trigger('ack.jingle', [self.sid, ack]);
  11966. },
  11967. function (stanza) {
  11968. self.state = 'error';
  11969. self.peerconnection.close();
  11970. var error = ($(stanza).find('error').length) ? {
  11971. code: $(stanza).find('error').attr('code'),
  11972. reason: $(stanza).find('error :first')[0].tagName,
  11973. }:{};
  11974. error.source = 'offer';
  11975. JingleSessionPC.onJingleError(self.sid, error);
  11976. },
  11977. 10000);
  11978. };
  11979. sendJingle();
  11980. }
  11981. this.lasticecandidate = true;
  11982. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11983. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11984. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11985. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11986. }
  11987. }
  11988. };
  11989. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  11990. console.log('sendIceCandidates', candidates);
  11991. var cand = $iq({to: this.peerjid, type: 'set'})
  11992. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11993. action: 'transport-info',
  11994. initiator: this.initiator,
  11995. sid: this.sid});
  11996. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11997. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11998. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11999. if (cands.length > 0) {
  12000. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  12001. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12002. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  12003. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  12004. }).c('transport', ice);
  12005. for (var i = 0; i < cands.length; i++) {
  12006. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  12007. }
  12008. // add fingerprint
  12009. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  12010. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  12011. tmp.required = true;
  12012. cand.c(
  12013. 'fingerprint',
  12014. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  12015. .t(tmp.fingerprint);
  12016. delete tmp.fingerprint;
  12017. cand.attrs(tmp);
  12018. cand.up();
  12019. }
  12020. cand.up(); // transport
  12021. cand.up(); // content
  12022. }
  12023. }
  12024. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  12025. //console.log('was this the last candidate', this.lasticecandidate);
  12026. this.connection.sendIQ(cand,
  12027. function () {
  12028. var ack = {};
  12029. ack.source = 'transportinfo';
  12030. $(document).trigger('ack.jingle', [this.sid, ack]);
  12031. },
  12032. function (stanza) {
  12033. var error = ($(stanza).find('error').length) ? {
  12034. code: $(stanza).find('error').attr('code'),
  12035. reason: $(stanza).find('error :first')[0].tagName,
  12036. }:{};
  12037. error.source = 'transportinfo';
  12038. JingleSessionPC.onJingleError(this.sid, error);
  12039. },
  12040. 10000);
  12041. };
  12042. JingleSessionPC.prototype.sendOffer = function () {
  12043. //console.log('sendOffer...');
  12044. var self = this;
  12045. this.peerconnection.createOffer(function (sdp) {
  12046. self.createdOffer(sdp);
  12047. },
  12048. function (e) {
  12049. console.error('createOffer failed', e);
  12050. },
  12051. this.media_constraints
  12052. );
  12053. };
  12054. // FIXME createdOffer is never used in jitsi-meet
  12055. JingleSessionPC.prototype.createdOffer = function (sdp) {
  12056. //console.log('createdOffer', sdp);
  12057. var self = this;
  12058. this.localSDP = new SDP(sdp.sdp);
  12059. //this.localSDP.mangle();
  12060. var sendJingle = function () {
  12061. var init = $iq({to: this.peerjid,
  12062. type: 'set'})
  12063. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12064. action: 'session-initiate',
  12065. initiator: this.initiator,
  12066. sid: this.sid});
  12067. self.localSDP.toJingle(
  12068. init,
  12069. this.initiator == this.me ? 'initiator' : 'responder',
  12070. this.localStreamsSSRC);
  12071. SSRCReplacement.processSessionInit(init);
  12072. self.connection.sendIQ(init,
  12073. function () {
  12074. var ack = {};
  12075. ack.source = 'offer';
  12076. $(document).trigger('ack.jingle', [self.sid, ack]);
  12077. },
  12078. function (stanza) {
  12079. self.state = 'error';
  12080. self.peerconnection.close();
  12081. var error = ($(stanza).find('error').length) ? {
  12082. code: $(stanza).find('error').attr('code'),
  12083. reason: $(stanza).find('error :first')[0].tagName,
  12084. }:{};
  12085. error.source = 'offer';
  12086. JingleSessionPC.onJingleError(self.sid, error);
  12087. },
  12088. 10000);
  12089. }
  12090. sdp.sdp = this.localSDP.raw;
  12091. this.peerconnection.setLocalDescription(sdp,
  12092. function () {
  12093. if(self.usetrickle)
  12094. {
  12095. sendJingle();
  12096. }
  12097. self.setLocalDescription();
  12098. //console.log('setLocalDescription success');
  12099. },
  12100. function (e) {
  12101. console.error('setLocalDescription failed', e);
  12102. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12103. }
  12104. );
  12105. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12106. for (var i = 0; i < cands.length; i++) {
  12107. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12108. if (cand.type == 'srflx') {
  12109. this.hadstuncandidate = true;
  12110. } else if (cand.type == 'relay') {
  12111. this.hadturncandidate = true;
  12112. }
  12113. }
  12114. };
  12115. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  12116. var self = this;
  12117. $(contents).each(function (idx, content) {
  12118. var name = $(content).attr('name');
  12119. var mediaType = this.getAttribute('name');
  12120. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12121. ssrcs.each(function () {
  12122. var ssrc = this.getAttribute('ssrc');
  12123. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12124. function () {
  12125. var owner = this.getAttribute('owner');
  12126. self.ssrcOwners[ssrc] = owner;
  12127. }
  12128. );
  12129. });
  12130. });
  12131. };
  12132. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  12133. return this.ssrcOwners[ssrc];
  12134. };
  12135. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  12136. //console.log('setting remote description... ', desctype);
  12137. this.remoteSDP = new SDP('');
  12138. this.remoteSDP.fromJingle(elem);
  12139. this.readSsrcInfo($(elem).find(">content"));
  12140. if (this.peerconnection.remoteDescription !== null) {
  12141. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12142. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12143. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12144. for (var i = 0; i < pranswer.media.length; i++) {
  12145. // make sure we have ice ufrag and pwd
  12146. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12147. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12148. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12149. } else {
  12150. console.warn('no ice ufrag?');
  12151. }
  12152. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12153. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12154. } else {
  12155. console.warn('no ice pwd?');
  12156. }
  12157. }
  12158. // copy over candidates
  12159. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12160. for (var j = 0; j < lines.length; j++) {
  12161. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12162. }
  12163. }
  12164. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12165. }
  12166. }
  12167. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12168. this.peerconnection.setRemoteDescription(remotedesc,
  12169. function () {
  12170. //console.log('setRemoteDescription success');
  12171. },
  12172. function (e) {
  12173. console.error('setRemoteDescription error', e);
  12174. JingleSessionPC.onJingleFatalError(self, e);
  12175. }
  12176. );
  12177. };
  12178. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  12179. var self = this;
  12180. if (this.peerconnection.signalingState == 'closed') {
  12181. return;
  12182. }
  12183. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12184. console.log('trickle ice candidate arriving before session accept...');
  12185. // create a PRANSWER for setRemoteDescription
  12186. if (!this.remoteSDP) {
  12187. var cobbled = 'v=0\r\n' +
  12188. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12189. 's=-\r\n' +
  12190. 't=0 0\r\n';
  12191. // first, take some things from the local description
  12192. for (var i = 0; i < this.localSDP.media.length; i++) {
  12193. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12194. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12195. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12196. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12197. }
  12198. cobbled += 'a=inactive\r\n';
  12199. }
  12200. this.remoteSDP = new SDP(cobbled);
  12201. }
  12202. // then add things like ice and dtls from remote candidate
  12203. elem.each(function () {
  12204. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12205. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12206. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12207. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12208. var tmp = $(this).find('transport');
  12209. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12210. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12211. tmp = $(this).find('transport>fingerprint');
  12212. if (tmp.length) {
  12213. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12214. } else {
  12215. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12216. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12217. }
  12218. break;
  12219. }
  12220. }
  12221. }
  12222. });
  12223. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12224. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12225. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12226. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12227. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12228. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12229. }).length == this.remoteSDP.media.length;
  12230. if (iscomplete) {
  12231. console.log('setting pranswer');
  12232. try {
  12233. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12234. function() {
  12235. },
  12236. function(e) {
  12237. console.log('setRemoteDescription pranswer failed', e.toString());
  12238. });
  12239. } catch (e) {
  12240. console.error('setting pranswer failed', e);
  12241. }
  12242. } else {
  12243. //console.log('not yet setting pranswer');
  12244. }
  12245. }
  12246. // operate on each content element
  12247. elem.each(function () {
  12248. // would love to deactivate this, but firefox still requires it
  12249. var idx = -1;
  12250. var i;
  12251. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12252. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12253. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12254. idx = i;
  12255. break;
  12256. }
  12257. }
  12258. if (idx == -1) { // fall back to localdescription
  12259. for (i = 0; i < self.localSDP.media.length; i++) {
  12260. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12261. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12262. idx = i;
  12263. break;
  12264. }
  12265. }
  12266. }
  12267. var name = $(this).attr('name');
  12268. // TODO: check ice-pwd and ice-ufrag?
  12269. $(this).find('transport>candidate').each(function () {
  12270. var line, candidate;
  12271. line = SDPUtil.candidateFromJingle(this);
  12272. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12273. sdpMid: name,
  12274. candidate: line});
  12275. try {
  12276. self.peerconnection.addIceCandidate(candidate);
  12277. } catch (e) {
  12278. console.error('addIceCandidate failed', e.toString(), line);
  12279. }
  12280. });
  12281. });
  12282. };
  12283. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  12284. //console.log('createAnswer', provisional);
  12285. var self = this;
  12286. this.peerconnection.createAnswer(
  12287. function (sdp) {
  12288. self.createdAnswer(sdp, provisional);
  12289. },
  12290. function (e) {
  12291. console.error('createAnswer failed', e);
  12292. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12293. },
  12294. this.media_constraints
  12295. );
  12296. };
  12297. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  12298. //console.log('createAnswer callback');
  12299. var self = this;
  12300. this.localSDP = new SDP(sdp.sdp);
  12301. //this.localSDP.mangle();
  12302. this.usepranswer = provisional === true;
  12303. if (this.usetrickle) {
  12304. if (this.usepranswer) {
  12305. sdp.type = 'pranswer';
  12306. for (var i = 0; i < this.localSDP.media.length; i++) {
  12307. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12308. }
  12309. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12310. }
  12311. }
  12312. var self = this;
  12313. var sendJingle = function (ssrcs) {
  12314. // FIXME why do we generate session-accept in 3 different places ?
  12315. var accept = $iq({to: self.peerjid,
  12316. type: 'set'})
  12317. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12318. action: 'session-accept',
  12319. initiator: self.initiator,
  12320. responder: self.responder,
  12321. sid: self.sid });
  12322. self.localSDP.toJingle(
  12323. accept,
  12324. self.initiator == self.me ? 'initiator' : 'responder',
  12325. ssrcs);
  12326. SSRCReplacement.processSessionInit(accept);
  12327. self.connection.sendIQ(accept,
  12328. function () {
  12329. var ack = {};
  12330. ack.source = 'answer';
  12331. $(document).trigger('ack.jingle', [self.sid, ack]);
  12332. },
  12333. function (stanza) {
  12334. var error = ($(stanza).find('error').length) ? {
  12335. code: $(stanza).find('error').attr('code'),
  12336. reason: $(stanza).find('error :first')[0].tagName,
  12337. }:{};
  12338. error.source = 'answer';
  12339. JingleSessionPC.onJingleError(self.sid, error);
  12340. },
  12341. 10000);
  12342. }
  12343. sdp.sdp = this.localSDP.raw;
  12344. this.peerconnection.setLocalDescription(sdp,
  12345. function () {
  12346. //console.log('setLocalDescription success');
  12347. if (self.usetrickle && !self.usepranswer) {
  12348. sendJingle();
  12349. }
  12350. self.setLocalDescription();
  12351. },
  12352. function (e) {
  12353. console.error('setLocalDescription failed', e);
  12354. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12355. }
  12356. );
  12357. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12358. for (var j = 0; j < cands.length; j++) {
  12359. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12360. if (cand.type == 'srflx') {
  12361. this.hadstuncandidate = true;
  12362. } else if (cand.type == 'relay') {
  12363. this.hadturncandidate = true;
  12364. }
  12365. }
  12366. };
  12367. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  12368. var self = this,
  12369. term = $iq({to: this.peerjid,
  12370. type: 'set'})
  12371. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12372. action: 'session-terminate',
  12373. initiator: this.initiator,
  12374. sid: this.sid})
  12375. .c('reason')
  12376. .c(reason || 'success');
  12377. if (text) {
  12378. term.up().c('text').t(text);
  12379. }
  12380. this.connection.sendIQ(term,
  12381. function () {
  12382. self.peerconnection.close();
  12383. self.peerconnection = null;
  12384. self.terminate();
  12385. var ack = {};
  12386. ack.source = 'terminate';
  12387. $(document).trigger('ack.jingle', [self.sid, ack]);
  12388. },
  12389. function (stanza) {
  12390. var error = ($(stanza).find('error').length) ? {
  12391. code: $(stanza).find('error').attr('code'),
  12392. reason: $(stanza).find('error :first')[0].tagName,
  12393. }:{};
  12394. $(document).trigger('ack.jingle', [self.sid, error]);
  12395. },
  12396. 10000);
  12397. if (this.statsinterval !== null) {
  12398. window.clearInterval(this.statsinterval);
  12399. this.statsinterval = null;
  12400. }
  12401. };
  12402. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  12403. var self = this;
  12404. // FIXME: dirty waiting
  12405. if (!this.peerconnection.localDescription)
  12406. {
  12407. console.warn("addSource - localDescription not ready yet")
  12408. setTimeout(function()
  12409. {
  12410. self.addSource(elem, fromJid);
  12411. },
  12412. 200
  12413. );
  12414. return;
  12415. }
  12416. console.log('addssrc', new Date().getTime());
  12417. console.log('ice', this.peerconnection.iceConnectionState);
  12418. this.readSsrcInfo(elem);
  12419. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12420. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12421. $(elem).each(function (idx, content) {
  12422. var name = $(content).attr('name');
  12423. var lines = '';
  12424. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12425. var semantics = this.getAttribute('semantics');
  12426. var ssrcs = $(this).find('>source').map(function () {
  12427. return this.getAttribute('ssrc');
  12428. }).get();
  12429. if (ssrcs.length != 0) {
  12430. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12431. }
  12432. });
  12433. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12434. tmp.each(function () {
  12435. var ssrc = $(this).attr('ssrc');
  12436. if(mySdp.containsSSRC(ssrc)){
  12437. /**
  12438. * This happens when multiple participants change their streams at the same time and
  12439. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12440. * addssrc are scheduled for update IQ. See
  12441. */
  12442. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12443. return;
  12444. }
  12445. if (sdp.containsSSRC(ssrc)) {
  12446. console.warn("Source-add request for existing SSRC: " + ssrc);
  12447. return;
  12448. }
  12449. $(this).find('>parameter').each(function () {
  12450. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12451. if ($(this).attr('value') && $(this).attr('value').length)
  12452. lines += ':' + $(this).attr('value');
  12453. lines += '\r\n';
  12454. });
  12455. });
  12456. sdp.media.forEach(function(media, idx) {
  12457. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12458. return;
  12459. sdp.media[idx] += lines;
  12460. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12461. self.addssrc[idx] += lines;
  12462. });
  12463. sdp.raw = sdp.session + sdp.media.join('');
  12464. });
  12465. this.modifySourcesQueue.push(function() {
  12466. // When a source is added and if this is FF, a new channel is allocated
  12467. // for receiving the added source. We need to diffuse the SSRC of this
  12468. // new recvonly channel to the rest of the peers.
  12469. console.log('modify sources done');
  12470. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12471. console.log("SDPs", mySdp, newSdp);
  12472. self.notifyMySSRCUpdate(mySdp, newSdp);
  12473. });
  12474. };
  12475. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  12476. var self = this;
  12477. // FIXME: dirty waiting
  12478. if (!this.peerconnection.localDescription)
  12479. {
  12480. console.warn("removeSource - localDescription not ready yet")
  12481. setTimeout(function()
  12482. {
  12483. self.removeSource(elem, fromJid);
  12484. },
  12485. 200
  12486. );
  12487. return;
  12488. }
  12489. console.log('removessrc', new Date().getTime());
  12490. console.log('ice', this.peerconnection.iceConnectionState);
  12491. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12492. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12493. $(elem).each(function (idx, content) {
  12494. var name = $(content).attr('name');
  12495. var lines = '';
  12496. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12497. var semantics = this.getAttribute('semantics');
  12498. var ssrcs = $(this).find('>source').map(function () {
  12499. return this.getAttribute('ssrc');
  12500. }).get();
  12501. if (ssrcs.length != 0) {
  12502. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12503. }
  12504. });
  12505. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12506. tmp.each(function () {
  12507. var ssrc = $(this).attr('ssrc');
  12508. // This should never happen, but can be useful for bug detection
  12509. if(mySdp.containsSSRC(ssrc)){
  12510. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12511. return;
  12512. }
  12513. $(this).find('>parameter').each(function () {
  12514. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12515. if ($(this).attr('value') && $(this).attr('value').length)
  12516. lines += ':' + $(this).attr('value');
  12517. lines += '\r\n';
  12518. });
  12519. });
  12520. sdp.media.forEach(function(media, idx) {
  12521. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12522. return;
  12523. sdp.media[idx] += lines;
  12524. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12525. self.removessrc[idx] += lines;
  12526. });
  12527. sdp.raw = sdp.session + sdp.media.join('');
  12528. });
  12529. this.modifySourcesQueue.push(function() {
  12530. // When a source is removed and if this is FF, the recvonly channel that
  12531. // receives the remote stream is deactivated . We need to diffuse the
  12532. // recvonly SSRC removal to the rest of the peers.
  12533. console.log('modify sources done');
  12534. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12535. console.log("SDPs", mySdp, newSdp);
  12536. self.notifyMySSRCUpdate(mySdp, newSdp);
  12537. });
  12538. };
  12539. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  12540. var self = this;
  12541. if (this.peerconnection.signalingState == 'closed') return;
  12542. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12543. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12544. this.setLocalDescription();
  12545. if(successCallback){
  12546. successCallback();
  12547. }
  12548. queueCallback();
  12549. return;
  12550. }
  12551. // Reset switch streams flag
  12552. this.switchstreams = false;
  12553. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12554. // add sources
  12555. this.addssrc.forEach(function(lines, idx) {
  12556. sdp.media[idx] += lines;
  12557. });
  12558. this.addssrc = [];
  12559. // remove sources
  12560. this.removessrc.forEach(function(lines, idx) {
  12561. lines = lines.split('\r\n');
  12562. lines.pop(); // remove empty last element;
  12563. lines.forEach(function(line) {
  12564. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12565. });
  12566. });
  12567. this.removessrc = [];
  12568. sdp.raw = sdp.session + sdp.media.join('');
  12569. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12570. function() {
  12571. if(self.signalingState == 'closed') {
  12572. console.error("createAnswer attempt on closed state");
  12573. queueCallback("createAnswer attempt on closed state");
  12574. return;
  12575. }
  12576. self.peerconnection.createAnswer(
  12577. function(modifiedAnswer) {
  12578. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12579. if (self.pendingop !== null) {
  12580. var sdp = new SDP(modifiedAnswer.sdp);
  12581. if (sdp.media.length > 1) {
  12582. switch(self.pendingop) {
  12583. case 'mute':
  12584. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12585. break;
  12586. case 'unmute':
  12587. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12588. break;
  12589. }
  12590. sdp.raw = sdp.session + sdp.media.join('');
  12591. modifiedAnswer.sdp = sdp.raw;
  12592. }
  12593. self.pendingop = null;
  12594. }
  12595. // FIXME: pushing down an answer while ice connection state
  12596. // is still checking is bad...
  12597. //console.log(self.peerconnection.iceConnectionState);
  12598. // trying to work around another chrome bug
  12599. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12600. self.peerconnection.setLocalDescription(modifiedAnswer,
  12601. function() {
  12602. //console.log('modified setLocalDescription ok');
  12603. self.setLocalDescription();
  12604. if(successCallback){
  12605. successCallback();
  12606. }
  12607. queueCallback();
  12608. },
  12609. function(error) {
  12610. console.error('modified setLocalDescription failed', error);
  12611. queueCallback(error);
  12612. }
  12613. );
  12614. },
  12615. function(error) {
  12616. console.error('modified answer failed', error);
  12617. queueCallback(error);
  12618. }
  12619. );
  12620. },
  12621. function(error) {
  12622. console.error('modify failed', error);
  12623. queueCallback(error);
  12624. }
  12625. );
  12626. };
  12627. /**
  12628. * Switches video streams.
  12629. * @param new_stream new stream that will be used as video of this session.
  12630. * @param oldStream old video stream of this session.
  12631. * @param success_callback callback executed after successful stream switch.
  12632. */
  12633. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12634. var self = this;
  12635. // Remember SDP to figure out added/removed SSRCs
  12636. var oldSdp = null;
  12637. if(self.peerconnection) {
  12638. if(self.peerconnection.localDescription) {
  12639. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12640. }
  12641. self.peerconnection.removeStream(oldStream, true);
  12642. if(new_stream)
  12643. self.peerconnection.addStream(new_stream);
  12644. }
  12645. // Conference is not active
  12646. if(!oldSdp || !self.peerconnection) {
  12647. success_callback();
  12648. return;
  12649. }
  12650. self.switchstreams = true;
  12651. self.modifySourcesQueue.push(function() {
  12652. console.log('modify sources done');
  12653. success_callback();
  12654. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12655. console.log("SDPs", oldSdp, newSdp);
  12656. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12657. });
  12658. };
  12659. /**
  12660. * Figures out added/removed ssrcs and send update IQs.
  12661. * @param old_sdp SDP object for old description.
  12662. * @param new_sdp SDP object for new description.
  12663. */
  12664. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12665. if (!(this.peerconnection.signalingState == 'stable' &&
  12666. this.peerconnection.iceConnectionState == 'connected')){
  12667. console.log("Too early to send updates");
  12668. return;
  12669. }
  12670. // send source-remove IQ.
  12671. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12672. var remove = $iq({to: this.peerjid, type: 'set'})
  12673. .c('jingle', {
  12674. xmlns: 'urn:xmpp:jingle:1',
  12675. action: 'source-remove',
  12676. initiator: this.initiator,
  12677. sid: this.sid
  12678. }
  12679. );
  12680. var removed = sdpDiffer.toJingle(remove);
  12681. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  12682. // it in the current form
  12683. if (removed)
  12684. remove = SSRCReplacement.processSourceRemove(remove);
  12685. if (removed && remove) {
  12686. console.info("Sending source-remove", remove);
  12687. this.connection.sendIQ(remove,
  12688. function (res) {
  12689. console.info('got remove result', res);
  12690. },
  12691. function (err) {
  12692. console.error('got remove error', err);
  12693. }
  12694. );
  12695. } else {
  12696. console.log('removal not necessary');
  12697. }
  12698. // send source-add IQ.
  12699. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12700. var add = $iq({to: this.peerjid, type: 'set'})
  12701. .c('jingle', {
  12702. xmlns: 'urn:xmpp:jingle:1',
  12703. action: 'source-add',
  12704. initiator: this.initiator,
  12705. sid: this.sid
  12706. }
  12707. );
  12708. var added = sdpDiffer.toJingle(add);
  12709. // Let 'source-add' IQ through the hack and see if we're allowed to send
  12710. // it in the current form
  12711. if (added)
  12712. add = SSRCReplacement.processSourceAdd(add);
  12713. if (added && add) {
  12714. console.info("Sending source-add", add);
  12715. this.connection.sendIQ(add,
  12716. function (res) {
  12717. console.info('got add result', res);
  12718. },
  12719. function (err) {
  12720. console.error('got add error', err);
  12721. }
  12722. );
  12723. } else {
  12724. console.log('addition not necessary');
  12725. }
  12726. };
  12727. /**
  12728. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12729. *
  12730. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12731. * tracks; otherwise, <tt>false</tt>
  12732. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12733. * tracks have been enabled/disabled. The function may, optionally, return
  12734. * another function which is to be invoked after the whole mute/unmute operation
  12735. * has completed successfully.
  12736. * @param options an object which specifies optional arguments such as the
  12737. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12738. * specifies whether the method was initiated in response to a user command (in
  12739. * contrast to an automatic decision made by the application logic)
  12740. */
  12741. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  12742. var byUser;
  12743. if (options) {
  12744. byUser = options.byUser;
  12745. if (typeof byUser === 'undefined') {
  12746. byUser = true;
  12747. }
  12748. } else {
  12749. byUser = true;
  12750. }
  12751. // The user's command to mute the (local) video takes precedence over any
  12752. // automatic decision made by the application logic.
  12753. if (byUser) {
  12754. this.videoMuteByUser = mute;
  12755. } else if (this.videoMuteByUser) {
  12756. return;
  12757. }
  12758. this.hardMuteVideo(mute);
  12759. var self = this;
  12760. var oldSdp = null;
  12761. if(self.peerconnection) {
  12762. if(self.peerconnection.localDescription) {
  12763. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12764. }
  12765. }
  12766. this.modifySourcesQueue.push(function() {
  12767. console.log('modify sources done');
  12768. callback(mute);
  12769. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12770. console.log("SDPs", oldSdp, newSdp);
  12771. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12772. });
  12773. };
  12774. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  12775. this.pendingop = muted ? 'mute' : 'unmute';
  12776. };
  12777. JingleSessionPC.prototype.sendMute = function (muted, content) {
  12778. var info = $iq({to: this.peerjid,
  12779. type: 'set'})
  12780. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12781. action: 'session-info',
  12782. initiator: this.initiator,
  12783. sid: this.sid });
  12784. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12785. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12786. if (content) {
  12787. info.attrs({'name': content});
  12788. }
  12789. this.connection.send(info);
  12790. };
  12791. JingleSessionPC.prototype.sendRinging = function () {
  12792. var info = $iq({to: this.peerjid,
  12793. type: 'set'})
  12794. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12795. action: 'session-info',
  12796. initiator: this.initiator,
  12797. sid: this.sid });
  12798. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12799. this.connection.send(info);
  12800. };
  12801. JingleSessionPC.prototype.getStats = function (interval) {
  12802. var self = this;
  12803. var recv = {audio: 0, video: 0};
  12804. var lost = {audio: 0, video: 0};
  12805. var lastrecv = {audio: 0, video: 0};
  12806. var lastlost = {audio: 0, video: 0};
  12807. var loss = {audio: 0, video: 0};
  12808. var delta = {audio: 0, video: 0};
  12809. this.statsinterval = window.setInterval(function () {
  12810. if (self && self.peerconnection && self.peerconnection.getStats) {
  12811. self.peerconnection.getStats(function (stats) {
  12812. var results = stats.result();
  12813. // TODO: there are so much statistics you can get from this..
  12814. for (var i = 0; i < results.length; ++i) {
  12815. if (results[i].type == 'ssrc') {
  12816. var packetsrecv = results[i].stat('packetsReceived');
  12817. var packetslost = results[i].stat('packetsLost');
  12818. if (packetsrecv && packetslost) {
  12819. packetsrecv = parseInt(packetsrecv, 10);
  12820. packetslost = parseInt(packetslost, 10);
  12821. if (results[i].stat('googFrameRateReceived')) {
  12822. lastlost.video = lost.video;
  12823. lastrecv.video = recv.video;
  12824. recv.video = packetsrecv;
  12825. lost.video = packetslost;
  12826. } else {
  12827. lastlost.audio = lost.audio;
  12828. lastrecv.audio = recv.audio;
  12829. recv.audio = packetsrecv;
  12830. lost.audio = packetslost;
  12831. }
  12832. }
  12833. }
  12834. }
  12835. delta.audio = recv.audio - lastrecv.audio;
  12836. delta.video = recv.video - lastrecv.video;
  12837. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12838. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12839. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12840. });
  12841. }
  12842. }, interval || 3000);
  12843. return this.statsinterval;
  12844. };
  12845. JingleSessionPC.onJingleError = function (session, error)
  12846. {
  12847. console.error("Jingle error", error);
  12848. }
  12849. JingleSessionPC.onJingleFatalError = function (session, error)
  12850. {
  12851. this.service.sessionTerminated = true;
  12852. this.connection.emuc.doLeave();
  12853. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12854. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12855. }
  12856. JingleSessionPC.prototype.setLocalDescription = function () {
  12857. var self = this;
  12858. var newssrcs = [];
  12859. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12860. session.media.forEach(function (media) {
  12861. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12862. // TODO(gp) maybe exclude FID streams?
  12863. media.ssrcs.forEach(function (ssrc) {
  12864. if (ssrc.attribute !== 'cname') {
  12865. return;
  12866. }
  12867. newssrcs.push({
  12868. 'ssrc': ssrc.id,
  12869. 'type': media.type
  12870. });
  12871. });
  12872. }
  12873. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12874. {
  12875. newssrcs.push({
  12876. 'ssrc': self.localStreamsSSRC[media.type],
  12877. 'type': media.type
  12878. });
  12879. }
  12880. });
  12881. console.log('new ssrcs', newssrcs);
  12882. // Bind us as local SSRCs owner
  12883. if (newssrcs.length > 0) {
  12884. for (var i = 1; i <= newssrcs.length; i ++) {
  12885. var ssrc = newssrcs[i-1].ssrc;
  12886. var myJid = self.connection.emuc.myroomjid;
  12887. self.ssrcOwners[ssrc] = myJid;
  12888. }
  12889. }
  12890. }
  12891. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12892. function sendKeyframe(pc) {
  12893. console.log('sendkeyframe', pc.iceConnectionState);
  12894. if (pc.iceConnectionState !== 'connected') return; // safe...
  12895. var self = this;
  12896. pc.setRemoteDescription(
  12897. pc.remoteDescription,
  12898. function () {
  12899. pc.createAnswer(
  12900. function (modifiedAnswer) {
  12901. pc.setLocalDescription(
  12902. modifiedAnswer,
  12903. function () {
  12904. // noop
  12905. },
  12906. function (error) {
  12907. console.log('triggerKeyframe setLocalDescription failed', error);
  12908. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  12909. }
  12910. );
  12911. },
  12912. function (error) {
  12913. console.log('triggerKeyframe createAnswer failed', error);
  12914. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  12915. }
  12916. );
  12917. },
  12918. function (error) {
  12919. console.log('triggerKeyframe setRemoteDescription failed', error);
  12920. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  12921. }
  12922. );
  12923. }
  12924. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  12925. var self = this;
  12926. var thessrc;
  12927. var streamId = APP.RTC.getStreamID(data.stream);
  12928. // look up an associated JID for a stream id
  12929. if (!streamId) {
  12930. console.error("No stream ID for", data.stream);
  12931. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12932. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12933. var ssrclines
  12934. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12935. ssrclines = ssrclines.filter(function (line) {
  12936. // NOTE(gp) previously we filtered on the mslabel, but that property
  12937. // is not always present.
  12938. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12939. if (RTCBrowserType.isTemasysPluginUsed()) {
  12940. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12941. } else {
  12942. return ((line.indexOf('msid:' + streamId) !== -1));
  12943. }
  12944. });
  12945. if (ssrclines.length) {
  12946. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12947. if (!self.ssrcOwners[thessrc]) {
  12948. console.error("No SSRC owner known for: " + thessrc);
  12949. return;
  12950. }
  12951. data.peerjid = self.ssrcOwners[thessrc];
  12952. console.log('associated jid', self.ssrcOwners[thessrc]);
  12953. } else {
  12954. console.error("No SSRC lines for ", streamId);
  12955. }
  12956. }
  12957. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12958. var isVideo = data.stream.getVideoTracks().length > 0;
  12959. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12960. if (isVideo &&
  12961. data.peerjid && this.peerjid === data.peerjid &&
  12962. data.stream.getVideoTracks().length === 0 &&
  12963. APP.RTC.localVideo.getTracks().length > 0) {
  12964. window.setTimeout(function () {
  12965. sendKeyframe(self.peerconnection);
  12966. }, 3000);
  12967. }
  12968. }
  12969. module.exports = JingleSessionPC;
  12970. },{"../../service/xmpp/XMPPEvents":110,"../RTC/RTCBrowserType":8,"./JingleSession":53,"./LocalSSRCReplacement":55,"./SDP":56,"./SDPDiffer":57,"./SDPUtil":58,"./TraceablePeerConnection":59,"async":69,"sdp-transform":97}],55:[function(require,module,exports){
  12971. /* global $ */
  12972. /*
  12973. Here we do modifications of local video SSRCs. There are 2 situations we have
  12974. to handle:
  12975. 1. We generate SSRC for local recvonly video stream. This is the case when we
  12976. have no local camera and it is not generated automatically, but SSRC=1 is
  12977. used implicitly. If that happens RTCP packets will be dropped by the JVB
  12978. and we won't be able to request video key frames correctly.
  12979. 2. A hack to re-use SSRC of the first video stream for any new stream created
  12980. in future. It turned out that Chrome may keep on using the SSRC of removed
  12981. video stream in RTCP even though a new one has been created. So we just
  12982. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  12983. notifications are blocked once first video SSRC is advertised to the focus.
  12984. What this hack does:
  12985. 1. Stores the SSRC of the first video stream created by
  12986. a) scanning Jingle session-accept/session-invite for existing video SSRC
  12987. b) watching for 'source-add' for new video stream if it has not been
  12988. created in step a)
  12989. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  12990. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  12991. returned to the other parts of the application.
  12992. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  12993. blocks those notifications. This makes Jicofo and all participants think
  12994. that it exists all the time even if the video stream has been removed or
  12995. replaced locally. Thanks to that there is no additional signaling activity
  12996. on video mute or when switching to the desktop stream.
  12997. */
  12998. var SDP = require('./SDP');
  12999. var RTCBrowserType = require('../RTC/RTCBrowserType');
  13000. /**
  13001. * The hack is enabled on all browsers except FF by default
  13002. * FIXME finish the hack once removeStream method is implemented in FF
  13003. * @type {boolean}
  13004. */
  13005. var isEnabled = !RTCBrowserType.isFirefox();
  13006. /**
  13007. * Stored SSRC of local video stream.
  13008. */
  13009. var localVideoSSRC;
  13010. /**
  13011. * SSRC used for recvonly video stream when we have no local camera.
  13012. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  13013. * instead of 1.
  13014. */
  13015. var localRecvOnlySSRC;
  13016. /**
  13017. * cname for <tt>localRecvOnlySSRC</tt>
  13018. */
  13019. var localRecvOnlyCName;
  13020. /**
  13021. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  13022. * from given Jingle IQ.
  13023. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  13024. * @param actionName display name of the action which will be printed in log
  13025. * messages.
  13026. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  13027. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  13028. * other SSRCs left to be signaled after removing it.
  13029. */
  13030. var filterOutSource = function (modifyIq, actionName) {
  13031. var modifyIqTree = $(modifyIq.tree());
  13032. if (!localVideoSSRC)
  13033. return modifyIqTree[0];
  13034. var videoSSRC = modifyIqTree.find(
  13035. '>jingle>content[name="video"]' +
  13036. '>description>source[ssrc="' + localVideoSSRC + '"]');
  13037. if (!videoSSRC.length) {
  13038. return modifyIqTree[0];
  13039. }
  13040. console.info(
  13041. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  13042. videoSSRC.remove();
  13043. // Check if any sources still left to be added/removed
  13044. if (modifyIqTree.find('>jingle>content>description>source').length) {
  13045. return modifyIqTree[0];
  13046. } else {
  13047. return null;
  13048. }
  13049. };
  13050. /**
  13051. * Scans given Jingle IQ for video SSRC and stores it.
  13052. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  13053. */
  13054. var storeLocalVideoSSRC = function (jingleIq) {
  13055. var videoSSRCs =
  13056. $(jingleIq.tree())
  13057. .find('>jingle>content[name="video"]>description>source');
  13058. videoSSRCs.each(function (idx, ssrcElem) {
  13059. if (localVideoSSRC)
  13060. return;
  13061. // We consider SSRC real only if it has msid attribute
  13062. // recvonly streams in FF do not have it as well as local SSRCs
  13063. // we generate for recvonly streams in Chrome
  13064. var ssrSel = $(ssrcElem);
  13065. var msid = ssrSel.find('>parameter[name="msid"]');
  13066. if (msid.length) {
  13067. var ssrcVal = ssrSel.attr('ssrc');
  13068. if (ssrcVal) {
  13069. localVideoSSRC = ssrcVal;
  13070. console.info('Stored local video SSRC' +
  13071. ' for future re-use: ' + localVideoSSRC);
  13072. }
  13073. }
  13074. });
  13075. };
  13076. /**
  13077. * Generates new SSRC for local video recvonly stream.
  13078. * FIXME what about eventual SSRC collision ?
  13079. */
  13080. function generateRecvonlySSRC() {
  13081. //
  13082. localRecvOnlySSRC =
  13083. Math.random().toString(10).substring(2, 11);
  13084. localRecvOnlyCName =
  13085. Math.random().toString(36).substring(2);
  13086. console.info(
  13087. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  13088. ", cname: " + localRecvOnlyCName);
  13089. }
  13090. var LocalSSRCReplacement = {
  13091. /**
  13092. * Method must be called before 'session-initiate' or 'session-invite' is
  13093. * sent. Scans the IQ for local video SSRC and stores it if detected.
  13094. *
  13095. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  13096. * which will be scanned for local video SSRC.
  13097. */
  13098. processSessionInit: function (sessionInit) {
  13099. if (!isEnabled)
  13100. return;
  13101. if (localVideoSSRC) {
  13102. console.error("Local SSRC stored already: " + localVideoSSRC);
  13103. return;
  13104. }
  13105. storeLocalVideoSSRC(sessionInit);
  13106. },
  13107. /**
  13108. * If we have local video SSRC stored searched given
  13109. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  13110. * with the stored one.
  13111. * @param localDescription local description object that will have local
  13112. * video SSRC replaced with the stored one
  13113. * @returns modified <tt>localDescription</tt> object.
  13114. */
  13115. mungeLocalVideoSSRC: function (localDescription) {
  13116. if (!isEnabled)
  13117. return localDescription;
  13118. // IF we have local video SSRC stored make sure it is replaced
  13119. // with old SSRC
  13120. if (localVideoSSRC) {
  13121. var newSdp = new SDP(localDescription.sdp);
  13122. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  13123. !newSdp.containsSSRC(localVideoSSRC)) {
  13124. // Get new video SSRC
  13125. var map = newSdp.getMediaSsrcMap();
  13126. var videoPart = map[1];
  13127. var videoSSRCs = videoPart.ssrcs;
  13128. var newSSRC = Object.keys(videoSSRCs)[0];
  13129. console.info(
  13130. "Replacing new video SSRC: " + newSSRC +
  13131. " with " + localVideoSSRC);
  13132. localDescription.sdp =
  13133. newSdp.raw.replace(
  13134. new RegExp('a=ssrc:' + newSSRC, 'g'),
  13135. 'a=ssrc:' + localVideoSSRC);
  13136. }
  13137. } else {
  13138. // Make sure we have any SSRC for recvonly video stream
  13139. var sdp = new SDP(localDescription.sdp);
  13140. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  13141. sdp.media[1].indexOf('a=recvonly') !== -1) {
  13142. if (!localRecvOnlySSRC) {
  13143. generateRecvonlySSRC();
  13144. }
  13145. console.info('No SSRC in video recvonly stream' +
  13146. ' - adding SSRC: ' + localRecvOnlySSRC);
  13147. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  13148. ' cname:' + localRecvOnlyCName + '\r\n';
  13149. localDescription.sdp = sdp.session + sdp.media.join('');
  13150. }
  13151. }
  13152. return localDescription;
  13153. },
  13154. /**
  13155. * Method must be called before 'source-add' notification is sent. In case
  13156. * we have local video SSRC advertised already it will be removed from the
  13157. * notification. If no other SSRCs are described by given IQ null will be
  13158. * returned which means that there is no point in sending the notification.
  13159. * @param sourceAdd 'source-add' Jingle IQ to be processed
  13160. * @returns modified 'source-add' IQ which can be sent to the focus or
  13161. * <tt>null</tt> if no notification shall be sent. It is no longer
  13162. * a Strophe IQ Builder instance, but DOM element tree.
  13163. */
  13164. processSourceAdd: function (sourceAdd) {
  13165. if (!isEnabled)
  13166. return sourceAdd;
  13167. if (!localVideoSSRC) {
  13168. // Store local SSRC if available
  13169. storeLocalVideoSSRC(sourceAdd);
  13170. return sourceAdd;
  13171. } else {
  13172. return filterOutSource(sourceAdd, 'source-add');
  13173. }
  13174. },
  13175. /**
  13176. * Method must be called before 'source-remove' notification is sent.
  13177. * Removes local video SSRC from the notification. If there are no other
  13178. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  13179. * means that there is no point in sending the notification.
  13180. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  13181. * @returns modified 'source-remove' IQ which can be sent to the focus or
  13182. * <tt>null</tt> if no notification shall be sent. It is no longer
  13183. * a Strophe IQ Builder instance, but DOM element tree.
  13184. */
  13185. processSourceRemove: function (sourceRemove) {
  13186. if (!isEnabled)
  13187. return sourceRemove;
  13188. return filterOutSource(sourceRemove, 'source-remove');
  13189. },
  13190. /**
  13191. * Turns the hack on or off
  13192. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  13193. * to disable it
  13194. */
  13195. setEnabled: function (enabled) {
  13196. isEnabled = enabled;
  13197. }
  13198. };
  13199. module.exports = LocalSSRCReplacement;
  13200. },{"../RTC/RTCBrowserType":8,"./SDP":56}],56:[function(require,module,exports){
  13201. /* jshint -W117 */
  13202. var SDPUtil = require("./SDPUtil");
  13203. // SDP STUFF
  13204. function SDP(sdp) {
  13205. this.media = sdp.split('\r\nm=');
  13206. for (var i = 1; i < this.media.length; i++) {
  13207. this.media[i] = 'm=' + this.media[i];
  13208. if (i != this.media.length - 1) {
  13209. this.media[i] += '\r\n';
  13210. }
  13211. }
  13212. this.session = this.media.shift() + '\r\n';
  13213. this.raw = this.session + this.media.join('');
  13214. }
  13215. /**
  13216. * Returns map of MediaChannel mapped per channel idx.
  13217. */
  13218. SDP.prototype.getMediaSsrcMap = function() {
  13219. var self = this;
  13220. var media_ssrcs = {};
  13221. var tmp;
  13222. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13223. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13224. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13225. var media = {
  13226. mediaindex: mediaindex,
  13227. mid: mid,
  13228. ssrcs: {},
  13229. ssrcGroups: []
  13230. };
  13231. media_ssrcs[mediaindex] = media;
  13232. tmp.forEach(function (line) {
  13233. var linessrc = line.substring(7).split(' ')[0];
  13234. // allocate new ChannelSsrc
  13235. if(!media.ssrcs[linessrc]) {
  13236. media.ssrcs[linessrc] = {
  13237. ssrc: linessrc,
  13238. lines: []
  13239. };
  13240. }
  13241. media.ssrcs[linessrc].lines.push(line);
  13242. });
  13243. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13244. tmp.forEach(function(line){
  13245. var semantics = line.substr(0, idx).substr(13);
  13246. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13247. if (ssrcs.length != 0) {
  13248. media.ssrcGroups.push({
  13249. semantics: semantics,
  13250. ssrcs: ssrcs
  13251. });
  13252. }
  13253. });
  13254. }
  13255. return media_ssrcs;
  13256. };
  13257. /**
  13258. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13259. * @param ssrc the ssrc to check.
  13260. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13261. */
  13262. SDP.prototype.containsSSRC = function(ssrc) {
  13263. var medias = this.getMediaSsrcMap();
  13264. var contains = false;
  13265. Object.keys(medias).forEach(function(mediaindex){
  13266. var media = medias[mediaindex];
  13267. //console.log("Check", channel, ssrc);
  13268. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13269. contains = true;
  13270. }
  13271. });
  13272. return contains;
  13273. };
  13274. // remove iSAC and CN from SDP
  13275. SDP.prototype.mangle = function () {
  13276. var i, j, mline, lines, rtpmap, newdesc;
  13277. for (i = 0; i < this.media.length; i++) {
  13278. lines = this.media[i].split('\r\n');
  13279. lines.pop(); // remove empty last element
  13280. mline = SDPUtil.parse_mline(lines.shift());
  13281. if (mline.media != 'audio')
  13282. continue;
  13283. newdesc = '';
  13284. mline.fmt.length = 0;
  13285. for (j = 0; j < lines.length; j++) {
  13286. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13287. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13288. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13289. continue;
  13290. mline.fmt.push(rtpmap.id);
  13291. newdesc += lines[j] + '\r\n';
  13292. } else {
  13293. newdesc += lines[j] + '\r\n';
  13294. }
  13295. }
  13296. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13297. this.media[i] += newdesc;
  13298. }
  13299. this.raw = this.session + this.media.join('');
  13300. };
  13301. // remove lines matching prefix from session section
  13302. SDP.prototype.removeSessionLines = function(prefix) {
  13303. var self = this;
  13304. var lines = SDPUtil.find_lines(this.session, prefix);
  13305. lines.forEach(function(line) {
  13306. self.session = self.session.replace(line + '\r\n', '');
  13307. });
  13308. this.raw = this.session + this.media.join('');
  13309. return lines;
  13310. }
  13311. // remove lines matching prefix from a media section specified by mediaindex
  13312. // TODO: non-numeric mediaindex could match mid
  13313. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13314. var self = this;
  13315. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13316. lines.forEach(function(line) {
  13317. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13318. });
  13319. this.raw = this.session + this.media.join('');
  13320. return lines;
  13321. }
  13322. // add content's to a jingle element
  13323. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13324. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13325. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13326. var self = this;
  13327. // new bundle plan
  13328. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13329. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13330. for (i = 0; i < lines.length; i++) {
  13331. tmp = lines[i].split(' ');
  13332. var semantics = tmp.shift().substr(8);
  13333. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13334. for (j = 0; j < tmp.length; j++) {
  13335. elem.c('content', {name: tmp[j]}).up();
  13336. }
  13337. elem.up();
  13338. }
  13339. }
  13340. for (i = 0; i < this.media.length; i++) {
  13341. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13342. if (!(mline.media === 'audio' ||
  13343. mline.media === 'video' ||
  13344. mline.media === 'application'))
  13345. {
  13346. continue;
  13347. }
  13348. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13349. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13350. } else {
  13351. if(ssrcs && ssrcs[mline.media])
  13352. {
  13353. ssrc = ssrcs[mline.media];
  13354. }
  13355. else
  13356. ssrc = false;
  13357. }
  13358. elem.c('content', {creator: thecreator, name: mline.media});
  13359. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13360. // prefer identifier from a=mid if present
  13361. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13362. elem.attrs({ name: mid });
  13363. }
  13364. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13365. {
  13366. elem.c('description',
  13367. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13368. media: mline.media });
  13369. if (ssrc) {
  13370. elem.attrs({ssrc: ssrc});
  13371. }
  13372. for (j = 0; j < mline.fmt.length; j++) {
  13373. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13374. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13375. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13376. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13377. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13378. for (k = 0; k < tmp.length; k++) {
  13379. elem.c('parameter', tmp[k]).up();
  13380. }
  13381. }
  13382. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13383. elem.up();
  13384. }
  13385. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13386. elem.c('encryption', {required: 1});
  13387. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13388. crypto.forEach(function(line) {
  13389. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13390. });
  13391. elem.up(); // end of encryption
  13392. }
  13393. if (ssrc) {
  13394. // new style mapping
  13395. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13396. // FIXME: group by ssrc and support multiple different ssrcs
  13397. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13398. if(ssrclines.length > 0) {
  13399. ssrclines.forEach(function (line) {
  13400. idx = line.indexOf(' ');
  13401. var linessrc = line.substr(0, idx).substr(7);
  13402. if (linessrc != ssrc) {
  13403. elem.up();
  13404. ssrc = linessrc;
  13405. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13406. }
  13407. var kv = line.substr(idx + 1);
  13408. elem.c('parameter');
  13409. if (kv.indexOf(':') == -1) {
  13410. elem.attrs({ name: kv });
  13411. } else {
  13412. var k = kv.split(':', 2)[0];
  13413. elem.attrs({ name: k });
  13414. var v = kv.split(':', 2)[1];
  13415. v = SDPUtil.filter_special_chars(v);
  13416. elem.attrs({ value: v });
  13417. }
  13418. elem.up();
  13419. });
  13420. }
  13421. else
  13422. {
  13423. elem.up();
  13424. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13425. elem.c('parameter');
  13426. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13427. elem.up();
  13428. var msid = null;
  13429. if(mline.media == "audio")
  13430. {
  13431. msid = APP.RTC.localAudio.getId();
  13432. }
  13433. else
  13434. {
  13435. msid = APP.RTC.localVideo.getId();
  13436. }
  13437. if(msid != null)
  13438. {
  13439. msid = SDPUtil.filter_special_chars(msid);
  13440. elem.c('parameter');
  13441. elem.attrs({name: "msid", value:msid});
  13442. elem.up();
  13443. elem.c('parameter');
  13444. elem.attrs({name: "mslabel", value:msid});
  13445. elem.up();
  13446. elem.c('parameter');
  13447. elem.attrs({name: "label", value:msid});
  13448. elem.up();
  13449. }
  13450. }
  13451. elem.up();
  13452. // XEP-0339 handle ssrc-group attributes
  13453. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13454. ssrc_group_lines.forEach(function(line) {
  13455. idx = line.indexOf(' ');
  13456. var semantics = line.substr(0, idx).substr(13);
  13457. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13458. if (ssrcs.length != 0) {
  13459. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13460. ssrcs.forEach(function(ssrc) {
  13461. elem.c('source', { ssrc: ssrc })
  13462. .up();
  13463. });
  13464. elem.up();
  13465. }
  13466. });
  13467. }
  13468. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13469. elem.c('rtcp-mux').up();
  13470. }
  13471. // XEP-0293 -- map a=rtcp-fb:*
  13472. this.RtcpFbToJingle(i, elem, '*');
  13473. // XEP-0294
  13474. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13475. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13476. for (j = 0; j < lines.length; j++) {
  13477. tmp = SDPUtil.parse_extmap(lines[j]);
  13478. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13479. uri: tmp.uri,
  13480. id: tmp.value });
  13481. if (tmp.hasOwnProperty('direction')) {
  13482. switch (tmp.direction) {
  13483. case 'sendonly':
  13484. elem.attrs({senders: 'responder'});
  13485. break;
  13486. case 'recvonly':
  13487. elem.attrs({senders: 'initiator'});
  13488. break;
  13489. case 'sendrecv':
  13490. elem.attrs({senders: 'both'});
  13491. break;
  13492. case 'inactive':
  13493. elem.attrs({senders: 'none'});
  13494. break;
  13495. }
  13496. }
  13497. // TODO: handle params
  13498. elem.up();
  13499. }
  13500. }
  13501. elem.up(); // end of description
  13502. }
  13503. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13504. this.TransportToJingle(i, elem);
  13505. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13506. elem.attrs({senders: 'both'});
  13507. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13508. elem.attrs({senders: 'initiator'});
  13509. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13510. elem.attrs({senders: 'responder'});
  13511. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13512. elem.attrs({senders: 'none'});
  13513. }
  13514. if (mline.port == '0') {
  13515. // estos hack to reject an m-line
  13516. elem.attrs({senders: 'rejected'});
  13517. }
  13518. elem.up(); // end of content
  13519. }
  13520. elem.up();
  13521. return elem;
  13522. };
  13523. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13524. var i = mediaindex;
  13525. var tmp;
  13526. var self = this;
  13527. elem.c('transport');
  13528. // XEP-0343 DTLS/SCTP
  13529. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13530. {
  13531. var sctpmap = SDPUtil.find_line(
  13532. this.media[i], 'a=sctpmap:', self.session);
  13533. if (sctpmap)
  13534. {
  13535. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13536. elem.c('sctpmap',
  13537. {
  13538. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13539. number: sctpAttrs[0], /* SCTP port */
  13540. protocol: sctpAttrs[1], /* protocol */
  13541. });
  13542. // Optional stream count attribute
  13543. if (sctpAttrs.length > 2)
  13544. elem.attrs({ streams: sctpAttrs[2]});
  13545. elem.up();
  13546. }
  13547. }
  13548. // XEP-0320
  13549. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13550. fingerprints.forEach(function(line) {
  13551. tmp = SDPUtil.parse_fingerprint(line);
  13552. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13553. elem.c('fingerprint').t(tmp.fingerprint);
  13554. delete tmp.fingerprint;
  13555. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13556. if (line) {
  13557. tmp.setup = line.substr(8);
  13558. }
  13559. elem.attrs(tmp);
  13560. elem.up(); // end of fingerprint
  13561. });
  13562. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13563. if (tmp) {
  13564. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13565. elem.attrs(tmp);
  13566. // XEP-0176
  13567. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13568. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13569. lines.forEach(function (line) {
  13570. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13571. });
  13572. }
  13573. }
  13574. elem.up(); // end of transport
  13575. }
  13576. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13577. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13578. lines.forEach(function (line) {
  13579. var tmp = SDPUtil.parse_rtcpfb(line);
  13580. if (tmp.type == 'trr-int') {
  13581. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13582. elem.up();
  13583. } else {
  13584. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13585. if (tmp.params.length > 0) {
  13586. elem.attrs({'subtype': tmp.params[0]});
  13587. }
  13588. elem.up();
  13589. }
  13590. });
  13591. };
  13592. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13593. var media = '';
  13594. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13595. if (tmp.length) {
  13596. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13597. if (tmp.attr('value')) {
  13598. media += tmp.attr('value');
  13599. } else {
  13600. media += '0';
  13601. }
  13602. media += '\r\n';
  13603. }
  13604. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13605. tmp.each(function () {
  13606. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13607. if ($(this).attr('subtype')) {
  13608. media += ' ' + $(this).attr('subtype');
  13609. }
  13610. media += '\r\n';
  13611. });
  13612. return media;
  13613. };
  13614. // construct an SDP from a jingle stanza
  13615. SDP.prototype.fromJingle = function (jingle) {
  13616. var self = this;
  13617. this.raw = 'v=0\r\n' +
  13618. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13619. 's=-\r\n' +
  13620. 't=0 0\r\n';
  13621. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13622. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13623. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13624. var contents = $(group).find('>content').map(function (idx, content) {
  13625. return content.getAttribute('name');
  13626. }).get();
  13627. if (contents.length > 0) {
  13628. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13629. }
  13630. });
  13631. }
  13632. this.session = this.raw;
  13633. jingle.find('>content').each(function () {
  13634. var m = self.jingle2media($(this));
  13635. self.media.push(m);
  13636. });
  13637. // reconstruct msid-semantic -- apparently not necessary
  13638. /*
  13639. var msid = SDPUtil.parse_ssrc(this.raw);
  13640. if (msid.hasOwnProperty('mslabel')) {
  13641. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13642. }
  13643. */
  13644. this.raw = this.session + this.media.join('');
  13645. };
  13646. // translate a jingle content element into an an SDP media part
  13647. SDP.prototype.jingle2media = function (content) {
  13648. var media = '',
  13649. desc = content.find('description'),
  13650. ssrc = desc.attr('ssrc'),
  13651. self = this,
  13652. tmp;
  13653. var sctp = content.find(
  13654. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13655. tmp = { media: desc.attr('media') };
  13656. tmp.port = '1';
  13657. if (content.attr('senders') == 'rejected') {
  13658. // estos hack to reject an m-line.
  13659. tmp.port = '0';
  13660. }
  13661. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13662. if (sctp.length)
  13663. tmp.proto = 'DTLS/SCTP';
  13664. else
  13665. tmp.proto = 'RTP/SAVPF';
  13666. } else {
  13667. tmp.proto = 'RTP/AVPF';
  13668. }
  13669. if (!sctp.length)
  13670. {
  13671. tmp.fmt = desc.find('payload-type').map(
  13672. function () { return this.getAttribute('id'); }).get();
  13673. media += SDPUtil.build_mline(tmp) + '\r\n';
  13674. }
  13675. else
  13676. {
  13677. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13678. media += 'a=sctpmap:' + sctp.attr('number') +
  13679. ' ' + sctp.attr('protocol');
  13680. var streamCount = sctp.attr('streams');
  13681. if (streamCount)
  13682. media += ' ' + streamCount + '\r\n';
  13683. else
  13684. media += '\r\n';
  13685. }
  13686. media += 'c=IN IP4 0.0.0.0\r\n';
  13687. if (!sctp.length)
  13688. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13689. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13690. if (tmp.length) {
  13691. if (tmp.attr('ufrag')) {
  13692. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13693. }
  13694. if (tmp.attr('pwd')) {
  13695. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13696. }
  13697. tmp.find('>fingerprint').each(function () {
  13698. // FIXME: check namespace at some point
  13699. media += 'a=fingerprint:' + this.getAttribute('hash');
  13700. media += ' ' + $(this).text();
  13701. media += '\r\n';
  13702. if (this.getAttribute('setup')) {
  13703. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13704. }
  13705. });
  13706. }
  13707. switch (content.attr('senders')) {
  13708. case 'initiator':
  13709. media += 'a=sendonly\r\n';
  13710. break;
  13711. case 'responder':
  13712. media += 'a=recvonly\r\n';
  13713. break;
  13714. case 'none':
  13715. media += 'a=inactive\r\n';
  13716. break;
  13717. case 'both':
  13718. media += 'a=sendrecv\r\n';
  13719. break;
  13720. }
  13721. media += 'a=mid:' + content.attr('name') + '\r\n';
  13722. // <description><rtcp-mux/></description>
  13723. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13724. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13725. if (desc.find('rtcp-mux').length) {
  13726. media += 'a=rtcp-mux\r\n';
  13727. }
  13728. if (desc.find('encryption').length) {
  13729. desc.find('encryption>crypto').each(function () {
  13730. media += 'a=crypto:' + this.getAttribute('tag');
  13731. media += ' ' + this.getAttribute('crypto-suite');
  13732. media += ' ' + this.getAttribute('key-params');
  13733. if (this.getAttribute('session-params')) {
  13734. media += ' ' + this.getAttribute('session-params');
  13735. }
  13736. media += '\r\n';
  13737. });
  13738. }
  13739. desc.find('payload-type').each(function () {
  13740. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13741. if ($(this).find('>parameter').length) {
  13742. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13743. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13744. media += '\r\n';
  13745. }
  13746. // xep-0293
  13747. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13748. });
  13749. // xep-0293
  13750. media += self.RtcpFbFromJingle(desc, '*');
  13751. // xep-0294
  13752. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13753. tmp.each(function () {
  13754. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13755. });
  13756. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13757. media += SDPUtil.candidateFromJingle(this);
  13758. });
  13759. // XEP-0339 handle ssrc-group attributes
  13760. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13761. var semantics = this.getAttribute('semantics');
  13762. var ssrcs = $(this).find('>source').map(function() {
  13763. return this.getAttribute('ssrc');
  13764. }).get();
  13765. if (ssrcs.length != 0) {
  13766. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13767. }
  13768. });
  13769. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13770. tmp.each(function () {
  13771. var ssrc = this.getAttribute('ssrc');
  13772. $(this).find('>parameter').each(function () {
  13773. var name = this.getAttribute('name');
  13774. var value = this.getAttribute('value');
  13775. value = SDPUtil.filter_special_chars(value);
  13776. media += 'a=ssrc:' + ssrc + ' ' + name;
  13777. if (value && value.length)
  13778. media += ':' + value;
  13779. media += '\r\n';
  13780. });
  13781. });
  13782. return media;
  13783. };
  13784. module.exports = SDP;
  13785. },{"./SDPUtil":58}],57:[function(require,module,exports){
  13786. var SDPUtil = require("./SDPUtil");
  13787. function SDPDiffer(mySDP, otherSDP) {
  13788. this.mySDP = mySDP;
  13789. this.otherSDP = otherSDP;
  13790. }
  13791. /**
  13792. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13793. * @param otherSdp the other SDP to check ssrc with.
  13794. */
  13795. SDPDiffer.prototype.getNewMedia = function() {
  13796. // this could be useful in Array.prototype.
  13797. function arrayEquals(array) {
  13798. // if the other array is a falsy value, return
  13799. if (!array)
  13800. return false;
  13801. // compare lengths - can save a lot of time
  13802. if (this.length != array.length)
  13803. return false;
  13804. for (var i = 0, l=this.length; i < l; i++) {
  13805. // Check if we have nested arrays
  13806. if (this[i] instanceof Array && array[i] instanceof Array) {
  13807. // recurse into the nested arrays
  13808. if (!this[i].equals(array[i]))
  13809. return false;
  13810. }
  13811. else if (this[i] != array[i]) {
  13812. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13813. return false;
  13814. }
  13815. }
  13816. return true;
  13817. }
  13818. var myMedias = this.mySDP.getMediaSsrcMap();
  13819. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13820. var newMedia = {};
  13821. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13822. var myMedia = myMedias[othersMediaIdx];
  13823. var othersMedia = othersMedias[othersMediaIdx];
  13824. if(!myMedia && othersMedia) {
  13825. // Add whole channel
  13826. newMedia[othersMediaIdx] = othersMedia;
  13827. return;
  13828. }
  13829. // Look for new ssrcs accross the channel
  13830. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13831. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13832. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13833. if(!newMedia[othersMediaIdx]){
  13834. newMedia[othersMediaIdx] = {
  13835. mediaindex: othersMedia.mediaindex,
  13836. mid: othersMedia.mid,
  13837. ssrcs: {},
  13838. ssrcGroups: []
  13839. };
  13840. }
  13841. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13842. }
  13843. });
  13844. // Look for new ssrc groups across the channels
  13845. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13846. // try to match the other ssrc-group with an ssrc-group of ours
  13847. var matched = false;
  13848. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13849. var mySsrcGroup = myMedia.ssrcGroups[i];
  13850. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13851. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13852. matched = true;
  13853. break;
  13854. }
  13855. }
  13856. if (!matched) {
  13857. // Allocate channel if we've found an ssrc-group that doesn't
  13858. // exist in our channel
  13859. if(!newMedia[othersMediaIdx]){
  13860. newMedia[othersMediaIdx] = {
  13861. mediaindex: othersMedia.mediaindex,
  13862. mid: othersMedia.mid,
  13863. ssrcs: {},
  13864. ssrcGroups: []
  13865. };
  13866. }
  13867. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13868. }
  13869. });
  13870. });
  13871. return newMedia;
  13872. };
  13873. /**
  13874. * Sends SSRC update IQ.
  13875. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13876. * @param sid session identifier that will be put into the IQ.
  13877. * @param initiator initiator identifier.
  13878. * @param toJid destination Jid
  13879. * @param isAdd indicates if this is remove or add operation.
  13880. */
  13881. SDPDiffer.prototype.toJingle = function(modify) {
  13882. var sdpMediaSsrcs = this.getNewMedia();
  13883. var self = this;
  13884. // FIXME: only announce video ssrcs since we mix audio and dont need
  13885. // the audio ssrcs therefore
  13886. var modified = false;
  13887. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13888. modified = true;
  13889. var media = sdpMediaSsrcs[mediaindex];
  13890. modify.c('content', {name: media.mid});
  13891. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13892. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13893. // generate sources from lines
  13894. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13895. var mediaSsrc = media.ssrcs[ssrcNum];
  13896. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13897. modify.attrs({ssrc: mediaSsrc.ssrc});
  13898. // iterate over ssrc lines
  13899. mediaSsrc.lines.forEach(function (line) {
  13900. var idx = line.indexOf(' ');
  13901. var kv = line.substr(idx + 1);
  13902. modify.c('parameter');
  13903. if (kv.indexOf(':') == -1) {
  13904. modify.attrs({ name: kv });
  13905. } else {
  13906. var nv = kv.split(':', 2);
  13907. var name = nv[0];
  13908. var value = SDPUtil.filter_special_chars(nv[1]);
  13909. modify.attrs({ name: name });
  13910. modify.attrs({ value: value });
  13911. }
  13912. modify.up(); // end of parameter
  13913. });
  13914. modify.up(); // end of source
  13915. });
  13916. // generate source groups from lines
  13917. media.ssrcGroups.forEach(function(ssrcGroup) {
  13918. if (ssrcGroup.ssrcs.length != 0) {
  13919. modify.c('ssrc-group', {
  13920. semantics: ssrcGroup.semantics,
  13921. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13922. });
  13923. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13924. modify.c('source', { ssrc: ssrc })
  13925. .up(); // end of source
  13926. });
  13927. modify.up(); // end of ssrc-group
  13928. }
  13929. });
  13930. modify.up(); // end of description
  13931. modify.up(); // end of content
  13932. });
  13933. return modified;
  13934. };
  13935. module.exports = SDPDiffer;
  13936. },{"./SDPUtil":58}],58:[function(require,module,exports){
  13937. SDPUtil = {
  13938. filter_special_chars: function (text) {
  13939. return text.replace(/[\\\/\{,\}\+]/g, "");
  13940. },
  13941. iceparams: function (mediadesc, sessiondesc) {
  13942. var data = null;
  13943. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13944. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13945. data = {
  13946. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13947. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13948. };
  13949. }
  13950. return data;
  13951. },
  13952. parse_iceufrag: function (line) {
  13953. return line.substring(12);
  13954. },
  13955. build_iceufrag: function (frag) {
  13956. return 'a=ice-ufrag:' + frag;
  13957. },
  13958. parse_icepwd: function (line) {
  13959. return line.substring(10);
  13960. },
  13961. build_icepwd: function (pwd) {
  13962. return 'a=ice-pwd:' + pwd;
  13963. },
  13964. parse_mid: function (line) {
  13965. return line.substring(6);
  13966. },
  13967. parse_mline: function (line) {
  13968. var parts = line.substring(2).split(' '),
  13969. data = {};
  13970. data.media = parts.shift();
  13971. data.port = parts.shift();
  13972. data.proto = parts.shift();
  13973. if (parts[parts.length - 1] === '') { // trailing whitespace
  13974. parts.pop();
  13975. }
  13976. data.fmt = parts;
  13977. return data;
  13978. },
  13979. build_mline: function (mline) {
  13980. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13981. },
  13982. parse_rtpmap: function (line) {
  13983. var parts = line.substring(9).split(' '),
  13984. data = {};
  13985. data.id = parts.shift();
  13986. parts = parts[0].split('/');
  13987. data.name = parts.shift();
  13988. data.clockrate = parts.shift();
  13989. data.channels = parts.length ? parts.shift() : '1';
  13990. return data;
  13991. },
  13992. /**
  13993. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13994. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13995. * @returns [SCTP port number, protocol, streams]
  13996. */
  13997. parse_sctpmap: function (line)
  13998. {
  13999. var parts = line.substring(10).split(' ');
  14000. var sctpPort = parts[0];
  14001. var protocol = parts[1];
  14002. // Stream count is optional
  14003. var streamCount = parts.length > 2 ? parts[2] : null;
  14004. return [sctpPort, protocol, streamCount];// SCTP port
  14005. },
  14006. build_rtpmap: function (el) {
  14007. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  14008. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  14009. line += '/' + el.getAttribute('channels');
  14010. }
  14011. return line;
  14012. },
  14013. parse_crypto: function (line) {
  14014. var parts = line.substring(9).split(' '),
  14015. data = {};
  14016. data.tag = parts.shift();
  14017. data['crypto-suite'] = parts.shift();
  14018. data['key-params'] = parts.shift();
  14019. if (parts.length) {
  14020. data['session-params'] = parts.join(' ');
  14021. }
  14022. return data;
  14023. },
  14024. parse_fingerprint: function (line) { // RFC 4572
  14025. var parts = line.substring(14).split(' '),
  14026. data = {};
  14027. data.hash = parts.shift();
  14028. data.fingerprint = parts.shift();
  14029. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  14030. return data;
  14031. },
  14032. parse_fmtp: function (line) {
  14033. var parts = line.split(' '),
  14034. i, key, value,
  14035. data = [];
  14036. parts.shift();
  14037. parts = parts.join(' ').split(';');
  14038. for (i = 0; i < parts.length; i++) {
  14039. key = parts[i].split('=')[0];
  14040. while (key.length && key[0] == ' ') {
  14041. key = key.substring(1);
  14042. }
  14043. value = parts[i].split('=')[1];
  14044. if (key && value) {
  14045. data.push({name: key, value: value});
  14046. } else if (key) {
  14047. // rfc 4733 (DTMF) style stuff
  14048. data.push({name: '', value: key});
  14049. }
  14050. }
  14051. return data;
  14052. },
  14053. parse_icecandidate: function (line) {
  14054. var candidate = {},
  14055. elems = line.split(' ');
  14056. candidate.foundation = elems[0].substring(12);
  14057. candidate.component = elems[1];
  14058. candidate.protocol = elems[2].toLowerCase();
  14059. candidate.priority = elems[3];
  14060. candidate.ip = elems[4];
  14061. candidate.port = elems[5];
  14062. // elems[6] => "typ"
  14063. candidate.type = elems[7];
  14064. candidate.generation = 0; // default value, may be overwritten below
  14065. for (var i = 8; i < elems.length; i += 2) {
  14066. switch (elems[i]) {
  14067. case 'raddr':
  14068. candidate['rel-addr'] = elems[i + 1];
  14069. break;
  14070. case 'rport':
  14071. candidate['rel-port'] = elems[i + 1];
  14072. break;
  14073. case 'generation':
  14074. candidate.generation = elems[i + 1];
  14075. break;
  14076. case 'tcptype':
  14077. candidate.tcptype = elems[i + 1];
  14078. break;
  14079. default: // TODO
  14080. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14081. }
  14082. }
  14083. candidate.network = '1';
  14084. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14085. return candidate;
  14086. },
  14087. build_icecandidate: function (cand) {
  14088. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  14089. line += ' ';
  14090. switch (cand.type) {
  14091. case 'srflx':
  14092. case 'prflx':
  14093. case 'relay':
  14094. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  14095. line += 'raddr';
  14096. line += ' ';
  14097. line += cand['rel-addr'];
  14098. line += ' ';
  14099. line += 'rport';
  14100. line += ' ';
  14101. line += cand['rel-port'];
  14102. line += ' ';
  14103. }
  14104. break;
  14105. }
  14106. if (cand.hasOwnAttribute('tcptype')) {
  14107. line += 'tcptype';
  14108. line += ' ';
  14109. line += cand.tcptype;
  14110. line += ' ';
  14111. }
  14112. line += 'generation';
  14113. line += ' ';
  14114. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  14115. return line;
  14116. },
  14117. parse_ssrc: function (desc) {
  14118. // proprietary mapping of a=ssrc lines
  14119. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  14120. // and parse according to that
  14121. var lines = desc.split('\r\n'),
  14122. data = {};
  14123. for (var i = 0; i < lines.length; i++) {
  14124. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  14125. var idx = lines[i].indexOf(' ');
  14126. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  14127. }
  14128. }
  14129. return data;
  14130. },
  14131. parse_rtcpfb: function (line) {
  14132. var parts = line.substr(10).split(' ');
  14133. var data = {};
  14134. data.pt = parts.shift();
  14135. data.type = parts.shift();
  14136. data.params = parts;
  14137. return data;
  14138. },
  14139. parse_extmap: function (line) {
  14140. var parts = line.substr(9).split(' ');
  14141. var data = {};
  14142. data.value = parts.shift();
  14143. if (data.value.indexOf('/') != -1) {
  14144. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  14145. data.value = data.value.substr(0, data.value.indexOf('/'));
  14146. } else {
  14147. data.direction = 'both';
  14148. }
  14149. data.uri = parts.shift();
  14150. data.params = parts;
  14151. return data;
  14152. },
  14153. find_line: function (haystack, needle, sessionpart) {
  14154. var lines = haystack.split('\r\n');
  14155. for (var i = 0; i < lines.length; i++) {
  14156. if (lines[i].substring(0, needle.length) == needle) {
  14157. return lines[i];
  14158. }
  14159. }
  14160. if (!sessionpart) {
  14161. return false;
  14162. }
  14163. // search session part
  14164. lines = sessionpart.split('\r\n');
  14165. for (var j = 0; j < lines.length; j++) {
  14166. if (lines[j].substring(0, needle.length) == needle) {
  14167. return lines[j];
  14168. }
  14169. }
  14170. return false;
  14171. },
  14172. find_lines: function (haystack, needle, sessionpart) {
  14173. var lines = haystack.split('\r\n'),
  14174. needles = [];
  14175. for (var i = 0; i < lines.length; i++) {
  14176. if (lines[i].substring(0, needle.length) == needle)
  14177. needles.push(lines[i]);
  14178. }
  14179. if (needles.length || !sessionpart) {
  14180. return needles;
  14181. }
  14182. // search session part
  14183. lines = sessionpart.split('\r\n');
  14184. for (var j = 0; j < lines.length; j++) {
  14185. if (lines[j].substring(0, needle.length) == needle) {
  14186. needles.push(lines[j]);
  14187. }
  14188. }
  14189. return needles;
  14190. },
  14191. candidateToJingle: function (line) {
  14192. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14193. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14194. if (line.indexOf('candidate:') === 0) {
  14195. line = 'a=' + line;
  14196. } else if (line.substring(0, 12) != 'a=candidate:') {
  14197. console.log('parseCandidate called with a line that is not a candidate line');
  14198. console.log(line);
  14199. return null;
  14200. }
  14201. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14202. line = line.substring(0, line.length - 2);
  14203. var candidate = {},
  14204. elems = line.split(' '),
  14205. i;
  14206. if (elems[6] != 'typ') {
  14207. console.log('did not find typ in the right place');
  14208. console.log(line);
  14209. return null;
  14210. }
  14211. candidate.foundation = elems[0].substring(12);
  14212. candidate.component = elems[1];
  14213. candidate.protocol = elems[2].toLowerCase();
  14214. candidate.priority = elems[3];
  14215. candidate.ip = elems[4];
  14216. candidate.port = elems[5];
  14217. // elems[6] => "typ"
  14218. candidate.type = elems[7];
  14219. candidate.generation = '0'; // default, may be overwritten below
  14220. for (i = 8; i < elems.length; i += 2) {
  14221. switch (elems[i]) {
  14222. case 'raddr':
  14223. candidate['rel-addr'] = elems[i + 1];
  14224. break;
  14225. case 'rport':
  14226. candidate['rel-port'] = elems[i + 1];
  14227. break;
  14228. case 'generation':
  14229. candidate.generation = elems[i + 1];
  14230. break;
  14231. case 'tcptype':
  14232. candidate.tcptype = elems[i + 1];
  14233. break;
  14234. default: // TODO
  14235. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14236. }
  14237. }
  14238. candidate.network = '1';
  14239. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14240. return candidate;
  14241. },
  14242. candidateFromJingle: function (cand) {
  14243. var line = 'a=candidate:';
  14244. line += cand.getAttribute('foundation');
  14245. line += ' ';
  14246. line += cand.getAttribute('component');
  14247. line += ' ';
  14248. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14249. line += ' ';
  14250. line += cand.getAttribute('priority');
  14251. line += ' ';
  14252. line += cand.getAttribute('ip');
  14253. line += ' ';
  14254. line += cand.getAttribute('port');
  14255. line += ' ';
  14256. line += 'typ';
  14257. line += ' ' + cand.getAttribute('type');
  14258. line += ' ';
  14259. switch (cand.getAttribute('type')) {
  14260. case 'srflx':
  14261. case 'prflx':
  14262. case 'relay':
  14263. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14264. line += 'raddr';
  14265. line += ' ';
  14266. line += cand.getAttribute('rel-addr');
  14267. line += ' ';
  14268. line += 'rport';
  14269. line += ' ';
  14270. line += cand.getAttribute('rel-port');
  14271. line += ' ';
  14272. }
  14273. break;
  14274. }
  14275. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14276. line += 'tcptype';
  14277. line += ' ';
  14278. line += cand.getAttribute('tcptype');
  14279. line += ' ';
  14280. }
  14281. line += 'generation';
  14282. line += ' ';
  14283. line += cand.getAttribute('generation') || '0';
  14284. return line + '\r\n';
  14285. }
  14286. };
  14287. module.exports = SDPUtil;
  14288. },{}],59:[function(require,module,exports){
  14289. var RTC = require('../RTC/RTC');
  14290. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14291. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14292. var SSRCReplacement = require("./LocalSSRCReplacement");
  14293. function TraceablePeerConnection(ice_config, constraints, session) {
  14294. var self = this;
  14295. var RTCPeerConnectionType = null;
  14296. if (RTCBrowserType.isFirefox()) {
  14297. RTCPeerConnectionType = mozRTCPeerConnection;
  14298. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14299. RTCPeerConnectionType = RTCPeerConnection;
  14300. } else {
  14301. RTCPeerConnectionType = webkitRTCPeerConnection;
  14302. }
  14303. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  14304. this.updateLog = [];
  14305. this.stats = {};
  14306. this.statsinterval = null;
  14307. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14308. var Interop = require('sdp-interop').Interop;
  14309. this.interop = new Interop();
  14310. var Simulcast = require('sdp-simulcast');
  14311. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14312. // override as desired
  14313. this.trace = function (what, info) {
  14314. /*console.warn('WTRACE', what, info);
  14315. if (info && RTCBrowserType.isIExplorer()) {
  14316. if (info.length > 1024) {
  14317. console.warn('WTRACE', what, info.substr(1024));
  14318. }
  14319. if (info.length > 2048) {
  14320. console.warn('WTRACE', what, info.substr(2048));
  14321. }
  14322. }*/
  14323. self.updateLog.push({
  14324. time: new Date(),
  14325. type: what,
  14326. value: info || ""
  14327. });
  14328. };
  14329. this.onicecandidate = null;
  14330. this.peerconnection.onicecandidate = function (event) {
  14331. // FIXME: this causes stack overflow with Temasys Plugin
  14332. if (!RTCBrowserType.isTemasysPluginUsed())
  14333. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14334. if (self.onicecandidate !== null) {
  14335. self.onicecandidate(event);
  14336. }
  14337. };
  14338. this.onaddstream = null;
  14339. this.peerconnection.onaddstream = function (event) {
  14340. self.trace('onaddstream', event.stream.id);
  14341. if (self.onaddstream !== null) {
  14342. self.onaddstream(event);
  14343. }
  14344. };
  14345. this.onremovestream = null;
  14346. this.peerconnection.onremovestream = function (event) {
  14347. self.trace('onremovestream', event.stream.id);
  14348. if (self.onremovestream !== null) {
  14349. self.onremovestream(event);
  14350. }
  14351. };
  14352. this.onsignalingstatechange = null;
  14353. this.peerconnection.onsignalingstatechange = function (event) {
  14354. self.trace('onsignalingstatechange', self.signalingState);
  14355. if (self.onsignalingstatechange !== null) {
  14356. self.onsignalingstatechange(event);
  14357. }
  14358. };
  14359. this.oniceconnectionstatechange = null;
  14360. this.peerconnection.oniceconnectionstatechange = function (event) {
  14361. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14362. if (self.oniceconnectionstatechange !== null) {
  14363. self.oniceconnectionstatechange(event);
  14364. }
  14365. };
  14366. this.onnegotiationneeded = null;
  14367. this.peerconnection.onnegotiationneeded = function (event) {
  14368. self.trace('onnegotiationneeded');
  14369. if (self.onnegotiationneeded !== null) {
  14370. self.onnegotiationneeded(event);
  14371. }
  14372. };
  14373. self.ondatachannel = null;
  14374. this.peerconnection.ondatachannel = function (event) {
  14375. self.trace('ondatachannel', event);
  14376. if (self.ondatachannel !== null) {
  14377. self.ondatachannel(event);
  14378. }
  14379. };
  14380. // XXX: do all non-firefox browsers which we support also support this?
  14381. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14382. this.statsinterval = window.setInterval(function() {
  14383. self.peerconnection.getStats(function(stats) {
  14384. var results = stats.result();
  14385. var now = new Date();
  14386. for (var i = 0; i < results.length; ++i) {
  14387. results[i].names().forEach(function (name) {
  14388. var id = results[i].id + '-' + name;
  14389. if (!self.stats[id]) {
  14390. self.stats[id] = {
  14391. startTime: now,
  14392. endTime: now,
  14393. values: [],
  14394. times: []
  14395. };
  14396. }
  14397. self.stats[id].values.push(results[i].stat(name));
  14398. self.stats[id].times.push(now.getTime());
  14399. if (self.stats[id].values.length > self.maxstats) {
  14400. self.stats[id].values.shift();
  14401. self.stats[id].times.shift();
  14402. }
  14403. self.stats[id].endTime = now;
  14404. });
  14405. }
  14406. });
  14407. }, 1000);
  14408. }
  14409. }
  14410. /**
  14411. * Returns a string representation of a SessionDescription object.
  14412. */
  14413. var dumpSDP = function(description) {
  14414. if (typeof description === 'undefined' || description == null) {
  14415. return '';
  14416. }
  14417. return 'type: ' + description.type + '\r\n' + description.sdp;
  14418. };
  14419. /**
  14420. * Takes a SessionDescription object and returns a "normalized" version.
  14421. * Currently it only takes care of ordering the a=ssrc lines.
  14422. */
  14423. var normalizePlanB = function(desc) {
  14424. if (typeof desc !== 'object' || desc === null ||
  14425. typeof desc.sdp !== 'string') {
  14426. console.warn('An empty description was passed as an argument.');
  14427. return desc;
  14428. }
  14429. var transform = require('sdp-transform');
  14430. var session = transform.parse(desc.sdp);
  14431. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14432. Array.isArray(session.media)) {
  14433. session.media.forEach(function (mLine) {
  14434. // Chrome appears to be picky about the order in which a=ssrc lines
  14435. // are listed in an m-line when rtx is enabled (and thus there are
  14436. // a=ssrc-group lines with FID semantics). Specifically if we have
  14437. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14438. // the "a=ssrc:S1" lines, SRD fails.
  14439. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14440. // first.
  14441. var firstSsrcs = [];
  14442. var newSsrcLines = [];
  14443. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14444. mLine.ssrcGroups.forEach(function (group) {
  14445. if (typeof group.semantics !== 'undefined' &&
  14446. group.semantics === 'FID') {
  14447. if (typeof group.ssrcs !== 'undefined') {
  14448. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14449. }
  14450. }
  14451. });
  14452. }
  14453. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14454. for (var i = 0; i<mLine.ssrcs.length; i++){
  14455. if (typeof mLine.ssrcs[i] === 'object'
  14456. && typeof mLine.ssrcs[i].id !== 'undefined'
  14457. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14458. newSsrcLines.push(mLine.ssrcs[i]);
  14459. delete mLine.ssrcs[i];
  14460. }
  14461. }
  14462. for (var i = 0; i<mLine.ssrcs.length; i++){
  14463. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14464. newSsrcLines.push(mLine.ssrcs[i]);
  14465. }
  14466. }
  14467. mLine.ssrcs = newSsrcLines;
  14468. }
  14469. });
  14470. }
  14471. var resStr = transform.write(session);
  14472. return new RTCSessionDescription({
  14473. type: desc.type,
  14474. sdp: resStr
  14475. });
  14476. };
  14477. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14478. TraceablePeerConnection.prototype.__defineGetter__(
  14479. 'signalingState',
  14480. function() { return this.peerconnection.signalingState; });
  14481. TraceablePeerConnection.prototype.__defineGetter__(
  14482. 'iceConnectionState',
  14483. function() { return this.peerconnection.iceConnectionState; });
  14484. TraceablePeerConnection.prototype.__defineGetter__(
  14485. 'localDescription',
  14486. function() {
  14487. var desc = this.peerconnection.localDescription;
  14488. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  14489. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14490. // if we're running on FF, transform to Plan B first.
  14491. if (RTCBrowserType.usesUnifiedPlan()) {
  14492. desc = this.interop.toPlanB(desc);
  14493. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14494. }
  14495. return desc;
  14496. });
  14497. TraceablePeerConnection.prototype.__defineGetter__(
  14498. 'remoteDescription',
  14499. function() {
  14500. var desc = this.peerconnection.remoteDescription;
  14501. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14502. // if we're running on FF, transform to Plan B first.
  14503. if (RTCBrowserType.usesUnifiedPlan()) {
  14504. desc = this.interop.toPlanB(desc);
  14505. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14506. }
  14507. return desc;
  14508. });
  14509. }
  14510. TraceablePeerConnection.prototype.addStream = function (stream) {
  14511. this.trace('addStream', stream.id);
  14512. try
  14513. {
  14514. this.peerconnection.addStream(stream);
  14515. }
  14516. catch (e)
  14517. {
  14518. console.error(e);
  14519. }
  14520. };
  14521. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14522. this.trace('removeStream', stream.id);
  14523. if(stopStreams) {
  14524. stream.getAudioTracks().forEach(function (track) {
  14525. // stop() not supported with IE
  14526. if (track.stop) {
  14527. track.stop();
  14528. }
  14529. });
  14530. stream.getVideoTracks().forEach(function (track) {
  14531. // stop() not supported with IE
  14532. if (track.stop) {
  14533. track.stop();
  14534. }
  14535. });
  14536. if (stream.stop) {
  14537. stream.stop();
  14538. }
  14539. }
  14540. try {
  14541. // FF doesn't support this yet.
  14542. if (this.peerconnection.removeStream)
  14543. this.peerconnection.removeStream(stream);
  14544. } catch (e) {
  14545. console.error(e);
  14546. }
  14547. };
  14548. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14549. this.trace('createDataChannel', label, opts);
  14550. return this.peerconnection.createDataChannel(label, opts);
  14551. };
  14552. TraceablePeerConnection.prototype.setLocalDescription
  14553. = function (description, successCallback, failureCallback) {
  14554. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14555. // if we're running on FF, transform to Plan A first.
  14556. if (RTCBrowserType.usesUnifiedPlan()) {
  14557. description = this.interop.toUnifiedPlan(description);
  14558. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14559. }
  14560. var self = this;
  14561. this.peerconnection.setLocalDescription(description,
  14562. function () {
  14563. self.trace('setLocalDescriptionOnSuccess');
  14564. successCallback();
  14565. },
  14566. function (err) {
  14567. self.trace('setLocalDescriptionOnFailure', err);
  14568. failureCallback(err);
  14569. }
  14570. );
  14571. /*
  14572. if (this.statsinterval === null && this.maxstats > 0) {
  14573. // start gathering stats
  14574. }
  14575. */
  14576. };
  14577. TraceablePeerConnection.prototype.setRemoteDescription
  14578. = function (description, successCallback, failureCallback) {
  14579. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14580. // TODO the focus should squeze or explode the remote simulcast
  14581. description = this.simulcast.mungeRemoteDescription(description);
  14582. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14583. // if we're running on FF, transform to Plan A first.
  14584. if (RTCBrowserType.usesUnifiedPlan()) {
  14585. description = this.interop.toUnifiedPlan(description);
  14586. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14587. }
  14588. if (RTCBrowserType.usesPlanB()) {
  14589. description = normalizePlanB(description);
  14590. }
  14591. var self = this;
  14592. this.peerconnection.setRemoteDescription(description,
  14593. function () {
  14594. self.trace('setRemoteDescriptionOnSuccess');
  14595. successCallback();
  14596. },
  14597. function (err) {
  14598. self.trace('setRemoteDescriptionOnFailure', err);
  14599. failureCallback(err);
  14600. }
  14601. );
  14602. /*
  14603. if (this.statsinterval === null && this.maxstats > 0) {
  14604. // start gathering stats
  14605. }
  14606. */
  14607. };
  14608. TraceablePeerConnection.prototype.close = function () {
  14609. this.trace('stop');
  14610. if (this.statsinterval !== null) {
  14611. window.clearInterval(this.statsinterval);
  14612. this.statsinterval = null;
  14613. }
  14614. this.peerconnection.close();
  14615. };
  14616. TraceablePeerConnection.prototype.createOffer
  14617. = function (successCallback, failureCallback, constraints) {
  14618. var self = this;
  14619. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14620. this.peerconnection.createOffer(
  14621. function (offer) {
  14622. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14623. // NOTE this is not tested because in meet the focus generates the
  14624. // offer.
  14625. // if we're running on FF, transform to Plan B first.
  14626. if (RTCBrowserType.usesUnifiedPlan()) {
  14627. offer = self.interop.toPlanB(offer);
  14628. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14629. }
  14630. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  14631. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14632. offer = self.simulcast.mungeLocalDescription(offer);
  14633. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14634. }
  14635. successCallback(offer);
  14636. },
  14637. function(err) {
  14638. self.trace('createOfferOnFailure', err);
  14639. failureCallback(err);
  14640. },
  14641. constraints
  14642. );
  14643. };
  14644. TraceablePeerConnection.prototype.createAnswer
  14645. = function (successCallback, failureCallback, constraints) {
  14646. var self = this;
  14647. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14648. this.peerconnection.createAnswer(
  14649. function (answer) {
  14650. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14651. // if we're running on FF, transform to Plan A first.
  14652. if (RTCBrowserType.usesUnifiedPlan()) {
  14653. answer = self.interop.toPlanB(answer);
  14654. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14655. }
  14656. // munge local video SSRC
  14657. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  14658. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14659. answer = self.simulcast.mungeLocalDescription(answer);
  14660. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14661. }
  14662. successCallback(answer);
  14663. },
  14664. function(err) {
  14665. self.trace('createAnswerOnFailure', err);
  14666. failureCallback(err);
  14667. },
  14668. constraints
  14669. );
  14670. };
  14671. TraceablePeerConnection.prototype.addIceCandidate
  14672. = function (candidate, successCallback, failureCallback) {
  14673. //var self = this;
  14674. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14675. this.peerconnection.addIceCandidate(candidate);
  14676. /* maybe later
  14677. this.peerconnection.addIceCandidate(candidate,
  14678. function () {
  14679. self.trace('addIceCandidateOnSuccess');
  14680. successCallback();
  14681. },
  14682. function (err) {
  14683. self.trace('addIceCandidateOnFailure', err);
  14684. failureCallback(err);
  14685. }
  14686. );
  14687. */
  14688. };
  14689. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14690. // TODO: Is this the correct way to handle Opera, Temasys?
  14691. if (RTCBrowserType.isFirefox()) {
  14692. // ignore for now...
  14693. if(!errback)
  14694. errback = function () {};
  14695. this.peerconnection.getStats(null, callback, errback);
  14696. } else {
  14697. this.peerconnection.getStats(callback);
  14698. }
  14699. };
  14700. module.exports = TraceablePeerConnection;
  14701. },{"../../service/xmpp/XMPPEvents":110,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"./LocalSSRCReplacement":55,"sdp-interop":91,"sdp-simulcast":94,"sdp-transform":97}],60:[function(require,module,exports){
  14702. /* global $, $iq, APP, config, messageHandler,
  14703. roomName, sessionTerminated, Strophe, Util */
  14704. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14705. var Settings = require("../settings/Settings");
  14706. var AuthenticationEvents
  14707. = require("../../service/authentication/AuthenticationEvents");
  14708. /**
  14709. * Contains logic responsible for enabling/disabling functionality available
  14710. * only to moderator users.
  14711. */
  14712. var connection = null;
  14713. var focusUserJid;
  14714. function createExpBackoffTimer(step) {
  14715. var count = 1;
  14716. return function (reset) {
  14717. // Reset call
  14718. if (reset) {
  14719. count = 1;
  14720. return;
  14721. }
  14722. // Calculate next timeout
  14723. var timeout = Math.pow(2, count - 1);
  14724. count += 1;
  14725. return timeout * step;
  14726. };
  14727. }
  14728. var getNextTimeout = createExpBackoffTimer(1000);
  14729. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14730. // External authentication stuff
  14731. var externalAuthEnabled = false;
  14732. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14733. // it will be enabled automatically if focus detects the component through
  14734. // service discovery.
  14735. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14736. var eventEmitter = null;
  14737. var Moderator = {
  14738. isModerator: function () {
  14739. return connection && connection.emuc.isModerator();
  14740. },
  14741. isPeerModerator: function (peerJid) {
  14742. return connection &&
  14743. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14744. },
  14745. isExternalAuthEnabled: function () {
  14746. return externalAuthEnabled;
  14747. },
  14748. isSipGatewayEnabled: function () {
  14749. return sipGatewayEnabled;
  14750. },
  14751. setConnection: function (con) {
  14752. connection = con;
  14753. },
  14754. init: function (xmpp, emitter) {
  14755. this.xmppService = xmpp;
  14756. eventEmitter = emitter;
  14757. // Message listener that talks to POPUP window
  14758. function listener(event) {
  14759. if (event.data && event.data.sessionId) {
  14760. if (event.origin !== window.location.origin) {
  14761. console.warn("Ignoring sessionId from different origin: " +
  14762. event.origin);
  14763. return;
  14764. }
  14765. localStorage.setItem('sessionId', event.data.sessionId);
  14766. // After popup is closed we will authenticate
  14767. }
  14768. }
  14769. // Register
  14770. if (window.addEventListener) {
  14771. window.addEventListener("message", listener, false);
  14772. } else {
  14773. window.attachEvent("onmessage", listener);
  14774. }
  14775. },
  14776. onMucMemberLeft: function (jid) {
  14777. console.info("Someone left is it focus ? " + jid);
  14778. var resource = Strophe.getResourceFromJid(jid);
  14779. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14780. console.info(
  14781. "Focus has left the room - leaving conference");
  14782. //hangUp();
  14783. // We'd rather reload to have everything re-initialized
  14784. // FIXME: show some message before reload
  14785. location.reload();
  14786. }
  14787. },
  14788. setFocusUserJid: function (focusJid) {
  14789. if (!focusUserJid) {
  14790. focusUserJid = focusJid;
  14791. console.info("Focus jid set to: " + focusUserJid);
  14792. }
  14793. },
  14794. getFocusUserJid: function () {
  14795. return focusUserJid;
  14796. },
  14797. getFocusComponent: function () {
  14798. // Get focus component address
  14799. var focusComponent = config.hosts.focus;
  14800. // If not specified use default: 'focus.domain'
  14801. if (!focusComponent) {
  14802. focusComponent = 'focus.' + config.hosts.domain;
  14803. }
  14804. return focusComponent;
  14805. },
  14806. createConferenceIq: function (roomName) {
  14807. // Generate create conference IQ
  14808. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14809. // Session Id used for authentication
  14810. var sessionId = localStorage.getItem('sessionId');
  14811. var machineUID = Settings.getSettings().uid;
  14812. console.info(
  14813. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14814. elem.c('conference', {
  14815. xmlns: 'http://jitsi.org/protocol/focus',
  14816. room: roomName,
  14817. 'machine-uid': machineUID
  14818. });
  14819. if (sessionId) {
  14820. elem.attrs({ 'session-id': sessionId});
  14821. }
  14822. if (config.hosts.bridge !== undefined) {
  14823. elem.c(
  14824. 'property',
  14825. { name: 'bridge', value: config.hosts.bridge})
  14826. .up();
  14827. }
  14828. // Tell the focus we have Jigasi configured
  14829. if (config.hosts.call_control !== undefined) {
  14830. elem.c(
  14831. 'property',
  14832. { name: 'call_control', value: config.hosts.call_control})
  14833. .up();
  14834. }
  14835. if (config.channelLastN !== undefined) {
  14836. elem.c(
  14837. 'property',
  14838. { name: 'channelLastN', value: config.channelLastN})
  14839. .up();
  14840. }
  14841. if (config.adaptiveLastN !== undefined) {
  14842. elem.c(
  14843. 'property',
  14844. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14845. .up();
  14846. }
  14847. if (config.adaptiveSimulcast !== undefined) {
  14848. elem.c(
  14849. 'property',
  14850. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14851. .up();
  14852. }
  14853. if (config.openSctp !== undefined) {
  14854. elem.c(
  14855. 'property',
  14856. { name: 'openSctp', value: config.openSctp})
  14857. .up();
  14858. }
  14859. if(config.startAudioMuted !== undefined)
  14860. {
  14861. elem.c(
  14862. 'property',
  14863. { name: 'startAudioMuted', value: config.startAudioMuted})
  14864. .up();
  14865. }
  14866. if(config.startVideoMuted !== undefined)
  14867. {
  14868. elem.c(
  14869. 'property',
  14870. { name: 'startVideoMuted', value: config.startVideoMuted})
  14871. .up();
  14872. }
  14873. elem.c(
  14874. 'property',
  14875. { name: 'simulcastMode', value: 'rewriting'})
  14876. .up();
  14877. elem.up();
  14878. return elem;
  14879. },
  14880. parseSessionId: function (resultIq) {
  14881. var sessionId = $(resultIq).find('conference').attr('session-id');
  14882. if (sessionId) {
  14883. console.info('Received sessionId: ' + sessionId);
  14884. localStorage.setItem('sessionId', sessionId);
  14885. }
  14886. },
  14887. parseConfigOptions: function (resultIq) {
  14888. Moderator.setFocusUserJid(
  14889. $(resultIq).find('conference').attr('focusjid'));
  14890. var authenticationEnabled
  14891. = $(resultIq).find(
  14892. '>conference>property' +
  14893. '[name=\'authentication\'][value=\'true\']').length > 0;
  14894. console.info("Authentication enabled: " + authenticationEnabled);
  14895. externalAuthEnabled = $(resultIq).find(
  14896. '>conference>property' +
  14897. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14898. console.info('External authentication enabled: ' + externalAuthEnabled);
  14899. if (!externalAuthEnabled) {
  14900. // We expect to receive sessionId in 'internal' authentication mode
  14901. Moderator.parseSessionId(resultIq);
  14902. }
  14903. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14904. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14905. authenticationEnabled, authIdentity);
  14906. // Check if focus has auto-detected Jigasi component(this will be also
  14907. // included if we have passed our host from the config)
  14908. if ($(resultIq).find(
  14909. '>conference>property' +
  14910. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14911. sipGatewayEnabled = true;
  14912. }
  14913. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14914. },
  14915. // FIXME: we need to show the fact that we're waiting for the focus
  14916. // to the user(or that focus is not available)
  14917. allocateConferenceFocus: function (roomName, callback) {
  14918. // Try to use focus user JID from the config
  14919. Moderator.setFocusUserJid(config.focusUserJid);
  14920. // Send create conference IQ
  14921. var iq = Moderator.createConferenceIq(roomName);
  14922. var self = this;
  14923. connection.sendIQ(
  14924. iq,
  14925. function (result) {
  14926. // Setup config options
  14927. Moderator.parseConfigOptions(result);
  14928. if ('true' === $(result).find('conference').attr('ready')) {
  14929. // Reset both timers
  14930. getNextTimeout(true);
  14931. getNextErrorTimeout(true);
  14932. // Exec callback
  14933. callback();
  14934. } else {
  14935. var waitMs = getNextTimeout();
  14936. console.info("Waiting for the focus... " + waitMs);
  14937. // Reset error timeout
  14938. getNextErrorTimeout(true);
  14939. window.setTimeout(
  14940. function () {
  14941. Moderator.allocateConferenceFocus(
  14942. roomName, callback);
  14943. }, waitMs);
  14944. }
  14945. },
  14946. function (error) {
  14947. // Invalid session ? remove and try again
  14948. // without session ID to get a new one
  14949. var invalidSession
  14950. = $(error).find('>error>session-invalid').length;
  14951. if (invalidSession) {
  14952. console.info("Session expired! - removing");
  14953. localStorage.removeItem("sessionId");
  14954. }
  14955. if ($(error).find('>error>graceful-shutdown').length) {
  14956. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14957. return;
  14958. }
  14959. // Check for error returned by the reservation system
  14960. var reservationErr = $(error).find('>error>reservation-error');
  14961. if (reservationErr.length) {
  14962. // Trigger error event
  14963. var errorCode = reservationErr.attr('error-code');
  14964. var errorMsg;
  14965. if ($(error).find('>error>text')) {
  14966. errorMsg = $(error).find('>error>text').text();
  14967. }
  14968. eventEmitter.emit(
  14969. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14970. return;
  14971. }
  14972. // Not authorized to create new room
  14973. if ($(error).find('>error>not-authorized').length) {
  14974. console.warn("Unauthorized to start the conference", error);
  14975. var toDomain
  14976. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14977. if (toDomain !== config.hosts.anonymousdomain) {
  14978. // FIXME: "is external" should come either from
  14979. // the focus or config.js
  14980. externalAuthEnabled = true;
  14981. }
  14982. eventEmitter.emit(
  14983. XMPPEvents.AUTHENTICATION_REQUIRED,
  14984. function () {
  14985. Moderator.allocateConferenceFocus(
  14986. roomName, callback);
  14987. });
  14988. return;
  14989. }
  14990. var waitMs = getNextErrorTimeout();
  14991. console.error("Focus error, retry after " + waitMs, error);
  14992. // Show message
  14993. var focusComponent = Moderator.getFocusComponent();
  14994. var retrySec = waitMs / 1000;
  14995. // FIXME: message is duplicated ?
  14996. // Do not show in case of session invalid
  14997. // which means just a retry
  14998. if (!invalidSession) {
  14999. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  15000. focusComponent, retrySec);
  15001. }
  15002. // Reset response timeout
  15003. getNextTimeout(true);
  15004. window.setTimeout(
  15005. function () {
  15006. Moderator.allocateConferenceFocus(roomName, callback);
  15007. }, waitMs);
  15008. }
  15009. );
  15010. },
  15011. getLoginUrl: function (roomName, urlCallback) {
  15012. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15013. iq.c('login-url', {
  15014. xmlns: 'http://jitsi.org/protocol/focus',
  15015. room: roomName,
  15016. 'machine-uid': Settings.getSettings().uid
  15017. });
  15018. connection.sendIQ(
  15019. iq,
  15020. function (result) {
  15021. var url = $(result).find('login-url').attr('url');
  15022. url = url = decodeURIComponent(url);
  15023. if (url) {
  15024. console.info("Got auth url: " + url);
  15025. urlCallback(url);
  15026. } else {
  15027. console.error(
  15028. "Failed to get auth url from the focus", result);
  15029. }
  15030. },
  15031. function (error) {
  15032. console.error("Get auth url error", error);
  15033. }
  15034. );
  15035. },
  15036. getPopupLoginUrl: function (roomName, urlCallback) {
  15037. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15038. iq.c('login-url', {
  15039. xmlns: 'http://jitsi.org/protocol/focus',
  15040. room: roomName,
  15041. 'machine-uid': Settings.getSettings().uid,
  15042. popup: true
  15043. });
  15044. connection.sendIQ(
  15045. iq,
  15046. function (result) {
  15047. var url = $(result).find('login-url').attr('url');
  15048. url = url = decodeURIComponent(url);
  15049. if (url) {
  15050. console.info("Got POPUP auth url: " + url);
  15051. urlCallback(url);
  15052. } else {
  15053. console.error(
  15054. "Failed to get POPUP auth url from the focus", result);
  15055. }
  15056. },
  15057. function (error) {
  15058. console.error('Get POPUP auth url error', error);
  15059. }
  15060. );
  15061. },
  15062. logout: function (callback) {
  15063. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15064. var sessionId = localStorage.getItem('sessionId');
  15065. if (!sessionId) {
  15066. callback();
  15067. return;
  15068. }
  15069. iq.c('logout', {
  15070. xmlns: 'http://jitsi.org/protocol/focus',
  15071. 'session-id': sessionId
  15072. });
  15073. connection.sendIQ(
  15074. iq,
  15075. function (result) {
  15076. var logoutUrl = $(result).find('logout').attr('logout-url');
  15077. if (logoutUrl) {
  15078. logoutUrl = decodeURIComponent(logoutUrl);
  15079. }
  15080. console.info("Log out OK, url: " + logoutUrl, result);
  15081. localStorage.removeItem('sessionId');
  15082. callback(logoutUrl);
  15083. },
  15084. function (error) {
  15085. console.error("Logout error", error);
  15086. }
  15087. );
  15088. }
  15089. };
  15090. module.exports = Moderator;
  15091. },{"../../service/authentication/AuthenticationEvents":105,"../../service/xmpp/XMPPEvents":110,"../settings/Settings":47}],61:[function(require,module,exports){
  15092. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  15093. Toolbar, Util */
  15094. var Moderator = require("./moderator");
  15095. var recordingToken = null;
  15096. var recordingEnabled;
  15097. /**
  15098. * Whether to use a jirecon component for recording, or use the videobridge
  15099. * through COLIBRI.
  15100. */
  15101. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  15102. /**
  15103. * The ID of the jirecon recording session. Jirecon generates it when we
  15104. * initially start recording, and it needs to be used in subsequent requests
  15105. * to jirecon.
  15106. */
  15107. var jireconRid = null;
  15108. /**
  15109. * The callback to update the recording button. Currently used from colibri
  15110. * after receiving a pending status.
  15111. */
  15112. var recordingStateChangeCallback = null;
  15113. function setRecordingToken(token) {
  15114. recordingToken = token;
  15115. }
  15116. function setRecordingJirecon(state, token, callback, connection) {
  15117. if (state == recordingEnabled){
  15118. return;
  15119. }
  15120. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  15121. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  15122. action: (state === 'on') ? 'start' : 'stop',
  15123. mucjid: connection.emuc.roomjid});
  15124. if (state === 'off'){
  15125. iq.attrs({rid: jireconRid});
  15126. }
  15127. console.log('Start recording');
  15128. connection.sendIQ(
  15129. iq,
  15130. function (result) {
  15131. // TODO wait for an IQ with the real status, since this is
  15132. // provisional?
  15133. jireconRid = $(result).find('recording').attr('rid');
  15134. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  15135. '(jirecon)' + result);
  15136. recordingEnabled = state;
  15137. if (state === 'off'){
  15138. jireconRid = null;
  15139. }
  15140. callback(state);
  15141. },
  15142. function (error) {
  15143. console.log('Failed to start recording, error: ', error);
  15144. callback(recordingEnabled);
  15145. });
  15146. }
  15147. // Sends a COLIBRI message which enables or disables (according to 'state')
  15148. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  15149. // with the new recording state, according to the IQ.
  15150. function setRecordingColibri(state, token, callback, connection) {
  15151. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  15152. elem.c('conference', {
  15153. xmlns: 'http://jitsi.org/protocol/colibri'
  15154. });
  15155. elem.c('recording', {state: state, token: token});
  15156. connection.sendIQ(elem,
  15157. function (result) {
  15158. console.log('Set recording "', state, '". Result:', result);
  15159. var recordingElem = $(result).find('>conference>recording');
  15160. var newState = recordingElem.attr('state');
  15161. recordingEnabled = newState;
  15162. callback(newState);
  15163. if (newState === 'pending' && recordingStateChangeCallback == null) {
  15164. recordingStateChangeCallback = callback;
  15165. connection.addHandler(function(iq){
  15166. var state = $(iq).find('recording').attr('state');
  15167. if (state)
  15168. recordingStateChangeCallback(state);
  15169. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  15170. }
  15171. },
  15172. function (error) {
  15173. console.warn(error);
  15174. callback(recordingEnabled);
  15175. }
  15176. );
  15177. }
  15178. function setRecording(state, token, callback, connection) {
  15179. if (useJirecon){
  15180. setRecordingJirecon(state, token, callback, connection);
  15181. } else {
  15182. setRecordingColibri(state, token, callback, connection);
  15183. }
  15184. }
  15185. var Recording = {
  15186. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  15187. if (!Moderator.isModerator()) {
  15188. console.log(
  15189. 'non-focus, or conference not yet organized:' +
  15190. ' not enabling recording');
  15191. return;
  15192. }
  15193. var self = this;
  15194. // Jirecon does not (currently) support a token.
  15195. if (!recordingToken && !useJirecon) {
  15196. tokenEmptyCallback(function (value) {
  15197. setRecordingToken(value);
  15198. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  15199. });
  15200. return;
  15201. }
  15202. var oldState = recordingEnabled;
  15203. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  15204. setRecording(newState,
  15205. recordingToken,
  15206. function (state) {
  15207. console.log("New recording state: ", state);
  15208. if (state === oldState) {
  15209. // FIXME: new focus:
  15210. // this will not work when moderator changes
  15211. // during active session. Then it will assume that
  15212. // recording status has changed to true, but it might have
  15213. // been already true(and we only received actual status from
  15214. // the focus).
  15215. //
  15216. // SO we start with status null, so that it is initialized
  15217. // here and will fail only after second click, so if invalid
  15218. // token was used we have to press the button twice before
  15219. // current status will be fetched and token will be reset.
  15220. //
  15221. // Reliable way would be to return authentication error.
  15222. // Or status update when moderator connects.
  15223. // Or we have to stop recording session when current
  15224. // moderator leaves the room.
  15225. // Failed to change, reset the token because it might
  15226. // have been wrong
  15227. setRecordingToken(null);
  15228. }
  15229. recordingStateChangeCallback(state);
  15230. },
  15231. connection
  15232. );
  15233. }
  15234. };
  15235. module.exports = Recording;
  15236. },{"./moderator":60}],62:[function(require,module,exports){
  15237. /* jshint -W117 */
  15238. /* a simple MUC connection plugin
  15239. * can only handle a single MUC room
  15240. */
  15241. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15242. var Moderator = require("./moderator");
  15243. module.exports = function(XMPP, eventEmitter) {
  15244. Strophe.addConnectionPlugin('emuc', {
  15245. connection: null,
  15246. roomjid: null,
  15247. myroomjid: null,
  15248. members: {},
  15249. list_members: [], // so we can elect a new focus
  15250. presMap: {},
  15251. preziMap: {},
  15252. joined: false,
  15253. isOwner: false,
  15254. role: null,
  15255. focusMucJid: null,
  15256. bridgeIsDown: false,
  15257. init: function (conn) {
  15258. this.connection = conn;
  15259. },
  15260. initPresenceMap: function (myroomjid) {
  15261. this.presMap['to'] = myroomjid;
  15262. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15263. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15264. this.addAudioInfoToPresence(true);
  15265. }
  15266. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15267. this.addVideoInfoToPresence(true);
  15268. }
  15269. },
  15270. doJoin: function (jid, password) {
  15271. this.myroomjid = jid;
  15272. console.info("Joined MUC as " + this.myroomjid);
  15273. this.initPresenceMap(this.myroomjid);
  15274. if (!this.roomjid) {
  15275. this.roomjid = Strophe.getBareJidFromJid(jid);
  15276. // add handlers (just once)
  15277. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15278. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15279. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15280. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15281. }
  15282. if (password !== undefined) {
  15283. this.presMap['password'] = password;
  15284. }
  15285. this.sendPresence();
  15286. },
  15287. doLeave: function () {
  15288. console.log("do leave", this.myroomjid);
  15289. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15290. this.presMap.length = 0;
  15291. this.connection.send(pres);
  15292. },
  15293. createNonAnonymousRoom: function () {
  15294. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15295. var getForm = $iq({type: 'get', to: this.roomjid})
  15296. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15297. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15298. var self = this;
  15299. this.connection.sendIQ(getForm, function (form) {
  15300. if (!$(form).find(
  15301. '>query>x[xmlns="jabber:x:data"]' +
  15302. '>field[var="muc#roomconfig_whois"]').length) {
  15303. console.error('non-anonymous rooms not supported');
  15304. return;
  15305. }
  15306. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15307. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15308. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15309. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15310. .c('value')
  15311. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15312. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15313. .c('value').t('anyone').up().up();
  15314. self.connection.sendIQ(formSubmit);
  15315. }, function (error) {
  15316. console.error("Error getting room configuration form");
  15317. });
  15318. },
  15319. onPresence: function (pres) {
  15320. var from = pres.getAttribute('from');
  15321. // What is this for? A workaround for something?
  15322. if (pres.getAttribute('type')) {
  15323. return true;
  15324. }
  15325. // Parse etherpad tag.
  15326. var etherpad = $(pres).find('>etherpad');
  15327. if (etherpad.length) {
  15328. if (config.etherpad_base) {
  15329. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15330. }
  15331. }
  15332. // Parse prezi tag.
  15333. var presentation = $(pres).find('>prezi');
  15334. if (presentation.length) {
  15335. var url = presentation.attr('url');
  15336. var current = presentation.find('>current').text();
  15337. console.log('presentation info received from', from, url);
  15338. if (this.preziMap[from] == null) {
  15339. this.preziMap[from] = url;
  15340. $(document).trigger('presentationadded.muc', [from, url, current]);
  15341. }
  15342. else {
  15343. $(document).trigger('gotoslide.muc', [from, url, current]);
  15344. }
  15345. }
  15346. else if (this.preziMap[from] != null) {
  15347. var url = this.preziMap[from];
  15348. delete this.preziMap[from];
  15349. $(document).trigger('presentationremoved.muc', [from, url]);
  15350. }
  15351. // Parse audio info tag.
  15352. var audioMuted = $(pres).find('>audiomuted');
  15353. if (audioMuted.length) {
  15354. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  15355. from, (audioMuted.text() === "true"));
  15356. }
  15357. // Parse video info tag.
  15358. var videoMuted = $(pres).find('>videomuted');
  15359. if (videoMuted.length) {
  15360. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  15361. from, (videoMuted.text() === "true"));
  15362. }
  15363. var startMuted = $(pres).find('>startmuted');
  15364. if (startMuted.length)
  15365. {
  15366. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15367. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  15368. }
  15369. var devices = $(pres).find('>devices');
  15370. if(devices.length)
  15371. {
  15372. var audio = devices.find('>audio');
  15373. var video = devices.find('>video');
  15374. var devicesValues = {audio: false, video: false};
  15375. if(audio.length && audio.text() === "true")
  15376. {
  15377. devicesValues.audio = true;
  15378. }
  15379. if(video.length && video.text() === "true")
  15380. {
  15381. devicesValues.video = true;
  15382. }
  15383. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15384. Strophe.getResourceFromJid(from), devicesValues);
  15385. }
  15386. var videoType = $(pres).find('>videoType');
  15387. if (videoType.length)
  15388. {
  15389. if (videoType.text().length)
  15390. {
  15391. eventEmitter.emit(XMPPEvents.VIDEO_TYPE,
  15392. Strophe.getResourceFromJid(from), videoType.text());
  15393. }
  15394. }
  15395. var stats = $(pres).find('>stats');
  15396. if (stats.length) {
  15397. var statsObj = {};
  15398. Strophe.forEachChild(stats[0], "stat", function (el) {
  15399. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15400. });
  15401. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15402. }
  15403. // Parse status.
  15404. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15405. this.isOwner = true;
  15406. this.createNonAnonymousRoom();
  15407. }
  15408. // Parse roles.
  15409. var member = {};
  15410. member.show = $(pres).find('>show').text();
  15411. member.status = $(pres).find('>status').text();
  15412. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15413. member.affiliation = tmp.attr('affiliation');
  15414. member.role = tmp.attr('role');
  15415. // Focus recognition
  15416. member.jid = tmp.attr('jid');
  15417. member.isFocus = false;
  15418. if (member.jid
  15419. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15420. member.isFocus = true;
  15421. }
  15422. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15423. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  15424. if (from == this.myroomjid) {
  15425. if (member.affiliation == 'owner') this.isOwner = true;
  15426. if (this.role !== member.role) {
  15427. this.role = member.role;
  15428. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15429. from, member, pres, Moderator.isModerator());
  15430. }
  15431. if (!this.joined) {
  15432. this.joined = true;
  15433. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15434. this.list_members.push(from);
  15435. }
  15436. } else if (this.members[from] === undefined) {
  15437. // new participant
  15438. this.members[from] = member;
  15439. this.list_members.push(from);
  15440. console.log('entered', from, member);
  15441. if (member.isFocus) {
  15442. this.focusMucJid = from;
  15443. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15444. }
  15445. else {
  15446. var id = $(pres).find('>userId').text();
  15447. var email = $(pres).find('>email');
  15448. if (email.length > 0) {
  15449. id = email.text();
  15450. }
  15451. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15452. }
  15453. } else {
  15454. // Presence update for existing participant
  15455. // Watch role change:
  15456. if (this.members[from].role != member.role) {
  15457. this.members[from].role = member.role;
  15458. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15459. member.role, member.displayName);
  15460. }
  15461. }
  15462. // Always trigger presence to update bindings
  15463. this.parsePresence(from, member, pres);
  15464. // Trigger status message update
  15465. if (member.status) {
  15466. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15467. }
  15468. return true;
  15469. },
  15470. onPresenceUnavailable: function (pres) {
  15471. var from = pres.getAttribute('from');
  15472. // room destroyed ?
  15473. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15474. '>destroy').length) {
  15475. var reason;
  15476. var reasonSelect = $(pres).find(
  15477. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15478. '>destroy>reason');
  15479. if (reasonSelect.length) {
  15480. reason = reasonSelect.text();
  15481. }
  15482. XMPP.disposeConference(false);
  15483. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15484. return true;
  15485. }
  15486. // Status code 110 indicates that this notification is "self-presence".
  15487. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15488. delete this.members[from];
  15489. this.list_members.splice(this.list_members.indexOf(from), 1);
  15490. this.onParticipantLeft(from);
  15491. }
  15492. // If the status code is 110 this means we're leaving and we would like
  15493. // to remove everyone else from our view, so we trigger the event.
  15494. else if (this.list_members.length > 1) {
  15495. for (var i = 0; i < this.list_members.length; i++) {
  15496. var member = this.list_members[i];
  15497. delete this.members[i];
  15498. this.list_members.splice(i, 1);
  15499. this.onParticipantLeft(member);
  15500. }
  15501. }
  15502. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15503. $(document).trigger('kicked.muc', [from]);
  15504. if (this.myroomjid === from) {
  15505. XMPP.disposeConference(false);
  15506. eventEmitter.emit(XMPPEvents.KICKED);
  15507. }
  15508. }
  15509. return true;
  15510. },
  15511. onPresenceError: function (pres) {
  15512. var from = pres.getAttribute('from');
  15513. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15514. console.log('on password required', from);
  15515. var self = this;
  15516. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15517. self.doJoin(from, value);
  15518. });
  15519. } else if ($(pres).find(
  15520. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15521. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15522. if (toDomain === config.hosts.anonymousdomain) {
  15523. // enter the room by replying with 'not-authorized'. This would
  15524. // result in reconnection from authorized domain.
  15525. // We're either missing Jicofo/Prosody config for anonymous
  15526. // domains or something is wrong.
  15527. // XMPP.promptLogin();
  15528. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15529. } else {
  15530. console.warn('onPresError ', pres);
  15531. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15532. }
  15533. } else {
  15534. console.warn('onPresError ', pres);
  15535. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15536. }
  15537. return true;
  15538. },
  15539. sendMessage: function (body, nickname) {
  15540. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15541. msg.c('body', body).up();
  15542. if (nickname) {
  15543. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15544. }
  15545. this.connection.send(msg);
  15546. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15547. },
  15548. setSubject: function (subject) {
  15549. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15550. msg.c('subject', subject);
  15551. this.connection.send(msg);
  15552. console.log("topic changed to " + subject);
  15553. },
  15554. onMessage: function (msg) {
  15555. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15556. var from = msg.getAttribute('from');
  15557. var nick =
  15558. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15559. .text() ||
  15560. Strophe.getResourceFromJid(from);
  15561. var txt = $(msg).find('>body').text();
  15562. var type = msg.getAttribute("type");
  15563. if (type == "error") {
  15564. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15565. $(msg).find('>text').text(), txt);
  15566. return true;
  15567. }
  15568. var subject = $(msg).find('>subject');
  15569. if (subject.length) {
  15570. var subjectText = subject.text();
  15571. if (subjectText || subjectText == "") {
  15572. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15573. console.log("Subject is changed to " + subjectText);
  15574. }
  15575. }
  15576. // xep-0203 delay
  15577. var stamp = $(msg).find('>delay').attr('stamp');
  15578. if (!stamp) {
  15579. // or xep-0091 delay, UTC timestamp
  15580. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15581. if (stamp) {
  15582. // the format is CCYYMMDDThh:mm:ss
  15583. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15584. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15585. }
  15586. }
  15587. if (txt) {
  15588. console.log('chat', nick, txt);
  15589. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15590. from, nick, txt, this.myroomjid, stamp);
  15591. }
  15592. return true;
  15593. },
  15594. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15595. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15596. var ob = this;
  15597. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15598. function (res) {
  15599. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15600. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15601. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15602. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15603. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15604. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15605. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15606. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15607. ob.connection.sendIQ(formsubmit,
  15608. onSuccess,
  15609. onError);
  15610. } else {
  15611. onNotSupported();
  15612. }
  15613. }, onError);
  15614. },
  15615. kick: function (jid) {
  15616. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15617. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15618. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15619. .c('reason').t('You have been kicked.').up().up().up();
  15620. this.connection.sendIQ(
  15621. kickIQ,
  15622. function (result) {
  15623. console.log('Kick participant with jid: ', jid, result);
  15624. },
  15625. function (error) {
  15626. console.log('Kick participant error: ', error);
  15627. });
  15628. },
  15629. sendPresence: function () {
  15630. if (!this.presMap['to']) {
  15631. // Too early to send presence - not initialized
  15632. return;
  15633. }
  15634. var pres = $pres({to: this.presMap['to'] });
  15635. pres.c('x', {xmlns: this.presMap['xns']});
  15636. if (this.presMap['password']) {
  15637. pres.c('password').t(this.presMap['password']).up();
  15638. }
  15639. pres.up();
  15640. // Send XEP-0115 'c' stanza that contains our capabilities info
  15641. if (this.connection.caps) {
  15642. this.connection.caps.node = config.clientNode;
  15643. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15644. }
  15645. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15646. .t(navigator.userAgent).up();
  15647. if (this.presMap['bridgeIsDown']) {
  15648. pres.c('bridgeIsDown').up();
  15649. }
  15650. if (this.presMap['email']) {
  15651. pres.c('email').t(this.presMap['email']).up();
  15652. }
  15653. if (this.presMap['userId']) {
  15654. pres.c('userId').t(this.presMap['userId']).up();
  15655. }
  15656. if (this.presMap['displayName']) {
  15657. // XEP-0172
  15658. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15659. .t(this.presMap['displayName']).up();
  15660. }
  15661. if(this.presMap["devices"])
  15662. {
  15663. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15664. .c('video').t(this.presMap['devices'].video).up().up();
  15665. }
  15666. if (this.presMap['audions']) {
  15667. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15668. .t(this.presMap['audiomuted']).up();
  15669. }
  15670. if (this.presMap['videons']) {
  15671. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15672. .t(this.presMap['videomuted']).up();
  15673. }
  15674. if (this.presMap['videoTypeNs']) {
  15675. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  15676. .t(this.presMap['videoType']).up();
  15677. }
  15678. if (this.presMap['statsns']) {
  15679. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15680. for (var stat in this.presMap["stats"])
  15681. if (this.presMap["stats"][stat] != null)
  15682. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15683. pres.up();
  15684. }
  15685. if (this.presMap['prezins']) {
  15686. pres.c('prezi',
  15687. {xmlns: this.presMap['prezins'],
  15688. 'url': this.presMap['preziurl']})
  15689. .c('current').t(this.presMap['prezicurrent']).up().up();
  15690. }
  15691. if(this.presMap["startMuted"] !== undefined)
  15692. {
  15693. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15694. video: this.presMap["startMuted"].video,
  15695. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15696. delete this.presMap["startMuted"];
  15697. }
  15698. pres.up();
  15699. this.connection.send(pres);
  15700. },
  15701. addDisplayNameToPresence: function (displayName) {
  15702. this.presMap['displayName'] = displayName;
  15703. },
  15704. addDevicesToPresence: function (devices) {
  15705. this.presMap['devices'] = devices;
  15706. },
  15707. /**
  15708. * Adds the info about the type of our video stream.
  15709. * @param videoType 'camera' or 'screen'
  15710. */
  15711. addVideoTypeToPresence: function (videoType) {
  15712. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  15713. this.presMap['videoType'] = videoType;
  15714. },
  15715. addPreziToPresence: function (url, currentSlide) {
  15716. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15717. this.presMap['preziurl'] = url;
  15718. this.presMap['prezicurrent'] = currentSlide;
  15719. },
  15720. removePreziFromPresence: function () {
  15721. delete this.presMap['prezins'];
  15722. delete this.presMap['preziurl'];
  15723. delete this.presMap['prezicurrent'];
  15724. },
  15725. addCurrentSlideToPresence: function (currentSlide) {
  15726. this.presMap['prezicurrent'] = currentSlide;
  15727. },
  15728. getPrezi: function (roomjid) {
  15729. return this.preziMap[roomjid];
  15730. },
  15731. addAudioInfoToPresence: function (isMuted) {
  15732. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15733. this.presMap['audiomuted'] = isMuted.toString();
  15734. },
  15735. addVideoInfoToPresence: function (isMuted) {
  15736. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15737. this.presMap['videomuted'] = isMuted.toString();
  15738. },
  15739. addConnectionInfoToPresence: function (stats) {
  15740. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15741. this.presMap['stats'] = stats;
  15742. },
  15743. findJidFromResource: function (resourceJid) {
  15744. if (resourceJid &&
  15745. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15746. return this.myroomjid;
  15747. }
  15748. var peerJid = null;
  15749. Object.keys(this.members).some(function (jid) {
  15750. peerJid = jid;
  15751. return Strophe.getResourceFromJid(jid) === resourceJid;
  15752. });
  15753. return peerJid;
  15754. },
  15755. addBridgeIsDownToPresence: function () {
  15756. this.presMap['bridgeIsDown'] = true;
  15757. },
  15758. addEmailToPresence: function (email) {
  15759. this.presMap['email'] = email;
  15760. },
  15761. addUserIdToPresence: function (userId) {
  15762. this.presMap['userId'] = userId;
  15763. },
  15764. addStartMutedToPresence: function (audio, video) {
  15765. this.presMap["startMuted"] = {audio: audio, video: video};
  15766. },
  15767. isModerator: function () {
  15768. return this.role === 'moderator';
  15769. },
  15770. getMemberRole: function (peerJid) {
  15771. if (this.members[peerJid]) {
  15772. return this.members[peerJid].role;
  15773. }
  15774. return null;
  15775. },
  15776. onParticipantLeft: function (jid) {
  15777. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15778. this.connection.jingle.terminateByJid(jid);
  15779. if (this.getPrezi(jid)) {
  15780. $(document).trigger('presentationremoved.muc',
  15781. [jid, this.getPrezi(jid)]);
  15782. }
  15783. Moderator.onMucMemberLeft(jid);
  15784. },
  15785. parsePresence: function (from, member, pres) {
  15786. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  15787. this.bridgeIsDown = true;
  15788. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15789. }
  15790. if(member.isFocus)
  15791. return;
  15792. var displayName = !config.displayJids
  15793. ? member.displayName : Strophe.getResourceFromJid(from);
  15794. if (displayName && displayName.length > 0) {
  15795. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15796. }
  15797. var id = $(pres).find('>userID').text();
  15798. var email = $(pres).find('>email');
  15799. if (email.length > 0) {
  15800. id = email.text();
  15801. }
  15802. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15803. }
  15804. });
  15805. };
  15806. },{"../../service/xmpp/XMPPEvents":110,"./moderator":60}],63:[function(require,module,exports){
  15807. /* jshint -W117 */
  15808. var JingleSession = require("./JingleSessionPC");
  15809. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15810. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15811. module.exports = function(XMPP, eventEmitter) {
  15812. Strophe.addConnectionPlugin('jingle', {
  15813. connection: null,
  15814. sessions: {},
  15815. jid2session: {},
  15816. ice_config: {iceServers: []},
  15817. pc_constraints: {},
  15818. activecall: null,
  15819. media_constraints: {
  15820. mandatory: {
  15821. 'OfferToReceiveAudio': true,
  15822. 'OfferToReceiveVideo': true
  15823. }
  15824. // MozDontOfferDataChannel: true when this is firefox
  15825. },
  15826. init: function (conn) {
  15827. this.connection = conn;
  15828. if (this.connection.disco) {
  15829. // http://xmpp.org/extensions/xep-0167.html#support
  15830. // http://xmpp.org/extensions/xep-0176.html#support
  15831. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15832. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15833. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15834. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15835. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15836. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15837. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15838. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15839. || RTCBrowserType.isTemasysPluginUsed()) {
  15840. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15841. }
  15842. // this is dealt with by SDP O/A so we don't need to announce this
  15843. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15844. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15845. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15846. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15847. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15848. }
  15849. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15850. },
  15851. onJingle: function (iq) {
  15852. var sid = $(iq).find('jingle').attr('sid');
  15853. var action = $(iq).find('jingle').attr('action');
  15854. var fromJid = iq.getAttribute('from');
  15855. // send ack first
  15856. var ack = $iq({type: 'result',
  15857. to: fromJid,
  15858. id: iq.getAttribute('id')
  15859. });
  15860. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15861. var sess = this.sessions[sid];
  15862. if ('session-initiate' != action) {
  15863. if (sess === null) {
  15864. ack.type = 'error';
  15865. ack.c('error', {type: 'cancel'})
  15866. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15867. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15868. this.connection.send(ack);
  15869. return true;
  15870. }
  15871. // local jid is not checked
  15872. if (fromJid != sess.peerjid) {
  15873. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15874. ack.type = 'error';
  15875. ack.c('error', {type: 'cancel'})
  15876. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15877. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15878. this.connection.send(ack);
  15879. return true;
  15880. }
  15881. } else if (sess !== undefined) {
  15882. // existing session with same session id
  15883. // this might be out-of-order if the sess.peerjid is the same as from
  15884. ack.type = 'error';
  15885. ack.c('error', {type: 'cancel'})
  15886. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15887. console.warn('duplicate session id', sid);
  15888. this.connection.send(ack);
  15889. return true;
  15890. }
  15891. // FIXME: check for a defined action
  15892. this.connection.send(ack);
  15893. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15894. switch (action) {
  15895. case 'session-initiate':
  15896. var startMuted = $(iq).find('jingle>startmuted');
  15897. if (startMuted && startMuted.length > 0) {
  15898. var audioMuted = startMuted.attr("audio");
  15899. var videoMuted = startMuted.attr("video");
  15900. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15901. audioMuted === "true", videoMuted === "true");
  15902. }
  15903. sess = new JingleSession(
  15904. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15905. this.connection, XMPP, eventEmitter);
  15906. // configure session
  15907. sess.media_constraints = this.media_constraints;
  15908. sess.pc_constraints = this.pc_constraints;
  15909. sess.ice_config = this.ice_config;
  15910. sess.initialize(fromJid, false);
  15911. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15912. sess.setOffer($(iq).find('>jingle'));
  15913. this.sessions[sess.sid] = sess;
  15914. this.jid2session[sess.peerjid] = sess;
  15915. // the callback should either
  15916. // .sendAnswer and .accept
  15917. // or .sendTerminate -- not necessarily synchronous
  15918. // TODO: do we check activecall == null?
  15919. this.connection.jingle.activecall = sess;
  15920. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15921. // TODO: check affiliation and/or role
  15922. console.log('emuc data for', sess.peerjid,
  15923. this.connection.emuc.members[sess.peerjid]);
  15924. sess.sendAnswer();
  15925. sess.accept();
  15926. break;
  15927. case 'session-accept':
  15928. sess.setAnswer($(iq).find('>jingle'));
  15929. sess.accept();
  15930. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15931. break;
  15932. case 'session-terminate':
  15933. // If this is not the focus sending the terminate, we have
  15934. // nothing more to do here.
  15935. if (Object.keys(this.sessions).length < 1
  15936. || !(this.sessions[Object.keys(this.sessions)[0]]
  15937. instanceof JingleSession))
  15938. {
  15939. break;
  15940. }
  15941. console.log('terminating...', sess.sid);
  15942. sess.terminate();
  15943. this.terminate(sess.sid);
  15944. if ($(iq).find('>jingle>reason').length) {
  15945. $(document).trigger('callterminated.jingle', [
  15946. sess.sid,
  15947. sess.peerjid,
  15948. $(iq).find('>jingle>reason>:first')[0].tagName,
  15949. $(iq).find('>jingle>reason>text').text()
  15950. ]);
  15951. } else {
  15952. $(document).trigger('callterminated.jingle',
  15953. [sess.sid, sess.peerjid]);
  15954. }
  15955. break;
  15956. case 'transport-info':
  15957. sess.addIceCandidate($(iq).find('>jingle>content'));
  15958. break;
  15959. case 'session-info':
  15960. var affected;
  15961. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15962. $(document).trigger('ringing.jingle', [sess.sid]);
  15963. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15964. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15965. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15966. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15967. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15968. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15969. }
  15970. break;
  15971. case 'addsource': // FIXME: proprietary, un-jingleish
  15972. case 'source-add': // FIXME: proprietary
  15973. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15974. break;
  15975. case 'removesource': // FIXME: proprietary, un-jingleish
  15976. case 'source-remove': // FIXME: proprietary
  15977. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15978. break;
  15979. default:
  15980. console.warn('jingle action not implemented', action);
  15981. break;
  15982. }
  15983. return true;
  15984. },
  15985. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15986. var sess = new JingleSession(myjid || this.connection.jid,
  15987. Math.random().toString(36).substr(2, 12), // random string
  15988. this.connection, XMPP, eventEmitter);
  15989. // configure session
  15990. sess.media_constraints = this.media_constraints;
  15991. sess.pc_constraints = this.pc_constraints;
  15992. sess.ice_config = this.ice_config;
  15993. sess.initialize(peerjid, true);
  15994. this.sessions[sess.sid] = sess;
  15995. this.jid2session[sess.peerjid] = sess;
  15996. sess.sendOffer();
  15997. return sess;
  15998. },
  15999. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  16000. if (sid === null || sid === undefined) {
  16001. for (sid in this.sessions) {
  16002. if (this.sessions[sid].state != 'ended') {
  16003. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16004. this.sessions[sid].terminate();
  16005. }
  16006. delete this.jid2session[this.sessions[sid].peerjid];
  16007. delete this.sessions[sid];
  16008. }
  16009. } else if (this.sessions.hasOwnProperty(sid)) {
  16010. if (this.sessions[sid].state != 'ended') {
  16011. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16012. this.sessions[sid].terminate();
  16013. }
  16014. delete this.jid2session[this.sessions[sid].peerjid];
  16015. delete this.sessions[sid];
  16016. }
  16017. },
  16018. // Used to terminate a session when an unavailable presence is received.
  16019. terminateByJid: function (jid) {
  16020. if (this.jid2session.hasOwnProperty(jid)) {
  16021. var sess = this.jid2session[jid];
  16022. if (sess) {
  16023. sess.terminate();
  16024. console.log('peer went away silently', jid);
  16025. delete this.sessions[sess.sid];
  16026. delete this.jid2session[jid];
  16027. $(document).trigger('callterminated.jingle',
  16028. [sess.sid, jid], 'gone');
  16029. }
  16030. }
  16031. },
  16032. terminateRemoteByJid: function (jid, reason) {
  16033. if (this.jid2session.hasOwnProperty(jid)) {
  16034. var sess = this.jid2session[jid];
  16035. if (sess) {
  16036. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  16037. sess.terminate();
  16038. console.log('terminate peer with jid', sess.sid, jid);
  16039. delete this.sessions[sess.sid];
  16040. delete this.jid2session[jid];
  16041. $(document).trigger('callterminated.jingle',
  16042. [sess.sid, jid, 'kicked']);
  16043. }
  16044. }
  16045. },
  16046. getStunAndTurnCredentials: function () {
  16047. // get stun and turn configuration from server via xep-0215
  16048. // uses time-limited credentials as described in
  16049. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  16050. //
  16051. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  16052. // for a prosody module which implements this
  16053. //
  16054. // currently, this doesn't work with updateIce and therefore credentials with a long
  16055. // validity have to be fetched before creating the peerconnection
  16056. // TODO: implement refresh via updateIce as described in
  16057. // https://code.google.com/p/webrtc/issues/detail?id=1650
  16058. var self = this;
  16059. this.connection.sendIQ(
  16060. $iq({type: 'get', to: this.connection.domain})
  16061. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  16062. function (res) {
  16063. var iceservers = [];
  16064. $(res).find('>services>service').each(function (idx, el) {
  16065. el = $(el);
  16066. var dict = {};
  16067. var type = el.attr('type');
  16068. switch (type) {
  16069. case 'stun':
  16070. dict.url = 'stun:' + el.attr('host');
  16071. if (el.attr('port')) {
  16072. dict.url += ':' + el.attr('port');
  16073. }
  16074. iceservers.push(dict);
  16075. break;
  16076. case 'turn':
  16077. case 'turns':
  16078. dict.url = type + ':';
  16079. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  16080. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  16081. dict.url += el.attr('username') + '@';
  16082. } else {
  16083. dict.username = el.attr('username'); // only works in M28
  16084. }
  16085. }
  16086. dict.url += el.attr('host');
  16087. if (el.attr('port') && el.attr('port') != '3478') {
  16088. dict.url += ':' + el.attr('port');
  16089. }
  16090. if (el.attr('transport') && el.attr('transport') != 'udp') {
  16091. dict.url += '?transport=' + el.attr('transport');
  16092. }
  16093. if (el.attr('password')) {
  16094. dict.credential = el.attr('password');
  16095. }
  16096. iceservers.push(dict);
  16097. break;
  16098. }
  16099. });
  16100. self.ice_config.iceServers = iceservers;
  16101. },
  16102. function (err) {
  16103. console.warn('getting turn credentials failed', err);
  16104. console.warn('is mod_turncredentials or similar installed?');
  16105. }
  16106. );
  16107. // implement push?
  16108. },
  16109. /**
  16110. * Returns the data saved in 'updateLog' in a format to be logged.
  16111. */
  16112. getLog: function () {
  16113. var data = {};
  16114. var self = this;
  16115. Object.keys(this.sessions).forEach(function (sid) {
  16116. var session = self.sessions[sid];
  16117. if (session.peerconnection && session.peerconnection.updateLog) {
  16118. // FIXME: should probably be a .dump call
  16119. data["jingle_" + session.sid] = {
  16120. updateLog: session.peerconnection.updateLog,
  16121. stats: session.peerconnection.stats,
  16122. url: window.location.href
  16123. };
  16124. }
  16125. });
  16126. return data;
  16127. }
  16128. });
  16129. };
  16130. },{"../../service/xmpp/XMPPEvents":110,"../RTC/RTCBrowserType":8,"./JingleSessionPC":54}],64:[function(require,module,exports){
  16131. /* global Strophe */
  16132. module.exports = function () {
  16133. Strophe.addConnectionPlugin('logger', {
  16134. // logs raw stanzas and makes them available for download as JSON
  16135. connection: null,
  16136. log: [],
  16137. init: function (conn) {
  16138. this.connection = conn;
  16139. this.connection.rawInput = this.log_incoming.bind(this);
  16140. this.connection.rawOutput = this.log_outgoing.bind(this);
  16141. },
  16142. log_incoming: function (stanza) {
  16143. this.log.push([new Date().getTime(), 'incoming', stanza]);
  16144. },
  16145. log_outgoing: function (stanza) {
  16146. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  16147. }
  16148. });
  16149. };
  16150. },{}],65:[function(require,module,exports){
  16151. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  16152. setAudioMuted, Strophe */
  16153. /**
  16154. * Moderate connection plugin.
  16155. */
  16156. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16157. module.exports = function (XMPP, eventEmitter) {
  16158. Strophe.addConnectionPlugin('moderate', {
  16159. connection: null,
  16160. init: function (conn) {
  16161. this.connection = conn;
  16162. this.connection.addHandler(this.onMute.bind(this),
  16163. 'http://jitsi.org/jitmeet/audio',
  16164. 'iq',
  16165. 'set',
  16166. null,
  16167. null);
  16168. },
  16169. setMute: function (jid, mute) {
  16170. console.info("set mute", mute);
  16171. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  16172. .c('mute', {
  16173. xmlns: 'http://jitsi.org/jitmeet/audio',
  16174. jid: jid
  16175. })
  16176. .t(mute.toString())
  16177. .up();
  16178. this.connection.sendIQ(
  16179. iqToFocus,
  16180. function (result) {
  16181. console.log('set mute', result);
  16182. },
  16183. function (error) {
  16184. console.log('set mute error', error);
  16185. });
  16186. },
  16187. onMute: function (iq) {
  16188. var from = iq.getAttribute('from');
  16189. if (from !== this.connection.emuc.focusMucJid) {
  16190. console.warn("Ignored mute from non focus peer");
  16191. return false;
  16192. }
  16193. var mute = $(iq).find('mute');
  16194. if (mute.length) {
  16195. var doMuteAudio = mute.text() === "true";
  16196. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16197. XMPP.forceMuted = doMuteAudio;
  16198. }
  16199. return true;
  16200. },
  16201. eject: function (jid) {
  16202. // We're not the focus, so can't terminate
  16203. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16204. this.connection.emuc.kick(jid);
  16205. }
  16206. });
  16207. }
  16208. },{"../../service/xmpp/XMPPEvents":110}],66:[function(require,module,exports){
  16209. /* jshint -W117 */
  16210. module.exports = function() {
  16211. Strophe.addConnectionPlugin('rayo',
  16212. {
  16213. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16214. connection: null,
  16215. init: function (conn) {
  16216. this.connection = conn;
  16217. if (this.connection.disco) {
  16218. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16219. }
  16220. this.connection.addHandler(
  16221. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16222. },
  16223. onRayo: function (iq) {
  16224. console.info("Rayo IQ", iq);
  16225. },
  16226. dial: function (to, from, roomName, roomPass) {
  16227. var self = this;
  16228. var req = $iq(
  16229. {
  16230. type: 'set',
  16231. to: this.connection.emuc.focusMucJid
  16232. }
  16233. );
  16234. req.c('dial',
  16235. {
  16236. xmlns: this.RAYO_XMLNS,
  16237. to: to,
  16238. from: from
  16239. });
  16240. req.c('header',
  16241. {
  16242. name: 'JvbRoomName',
  16243. value: roomName
  16244. }).up();
  16245. if (roomPass !== null && roomPass.length) {
  16246. req.c('header',
  16247. {
  16248. name: 'JvbRoomPassword',
  16249. value: roomPass
  16250. }).up();
  16251. }
  16252. this.connection.sendIQ(
  16253. req,
  16254. function (result) {
  16255. console.info('Dial result ', result);
  16256. var resource = $(result).find('ref').attr('uri');
  16257. this.call_resource = resource.substr('xmpp:'.length);
  16258. console.info(
  16259. "Received call resource: " + this.call_resource);
  16260. },
  16261. function (error) {
  16262. console.info('Dial error ', error);
  16263. }
  16264. );
  16265. },
  16266. hang_up: function () {
  16267. if (!this.call_resource) {
  16268. console.warn("No call in progress");
  16269. return;
  16270. }
  16271. var self = this;
  16272. var req = $iq(
  16273. {
  16274. type: 'set',
  16275. to: this.call_resource
  16276. }
  16277. );
  16278. req.c('hangup',
  16279. {
  16280. xmlns: this.RAYO_XMLNS
  16281. });
  16282. this.connection.sendIQ(
  16283. req,
  16284. function (result) {
  16285. console.info('Hangup result ', result);
  16286. self.call_resource = null;
  16287. },
  16288. function (error) {
  16289. console.info('Hangup error ', error);
  16290. self.call_resource = null;
  16291. }
  16292. );
  16293. }
  16294. }
  16295. );
  16296. };
  16297. },{}],67:[function(require,module,exports){
  16298. /**
  16299. * Strophe logger implementation. Logs from level WARN and above.
  16300. */
  16301. module.exports = function () {
  16302. Strophe.log = function (level, msg) {
  16303. switch (level) {
  16304. case Strophe.LogLevel.WARN:
  16305. console.warn("Strophe: " + msg);
  16306. break;
  16307. case Strophe.LogLevel.ERROR:
  16308. case Strophe.LogLevel.FATAL:
  16309. console.error("Strophe: " + msg);
  16310. break;
  16311. }
  16312. };
  16313. Strophe.getStatusString = function (status) {
  16314. switch (status) {
  16315. case Strophe.Status.ERROR:
  16316. return "ERROR";
  16317. case Strophe.Status.CONNECTING:
  16318. return "CONNECTING";
  16319. case Strophe.Status.CONNFAIL:
  16320. return "CONNFAIL";
  16321. case Strophe.Status.AUTHENTICATING:
  16322. return "AUTHENTICATING";
  16323. case Strophe.Status.AUTHFAIL:
  16324. return "AUTHFAIL";
  16325. case Strophe.Status.CONNECTED:
  16326. return "CONNECTED";
  16327. case Strophe.Status.DISCONNECTED:
  16328. return "DISCONNECTED";
  16329. case Strophe.Status.DISCONNECTING:
  16330. return "DISCONNECTING";
  16331. case Strophe.Status.ATTACHED:
  16332. return "ATTACHED";
  16333. default:
  16334. return "unknown";
  16335. }
  16336. };
  16337. };
  16338. },{}],68:[function(require,module,exports){
  16339. /* global $, APP, config, Strophe*/
  16340. var Moderator = require("./moderator");
  16341. var EventEmitter = require("events");
  16342. var Recording = require("./recording");
  16343. var SDP = require("./SDP");
  16344. var Settings = require("../settings/Settings");
  16345. var Pako = require("pako");
  16346. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16347. var RTCEvents = require("../../service/RTC/RTCEvents");
  16348. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16349. var retry = require('retry');
  16350. var eventEmitter = new EventEmitter();
  16351. var connection = null;
  16352. var authenticatedUser = false;
  16353. function connect(jid, password) {
  16354. var faultTolerantConnect = retry.operation({
  16355. retries: 3
  16356. });
  16357. // fault tolerant connect
  16358. faultTolerantConnect.attempt(function () {
  16359. connection = XMPP.createConnection();
  16360. Moderator.setConnection(connection);
  16361. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16362. if (config.useIPv6) {
  16363. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16364. if (!connection.jingle.pc_constraints.optional)
  16365. connection.jingle.pc_constraints.optional = [];
  16366. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16367. }
  16368. // Include user info in MUC presence
  16369. var settings = Settings.getSettings();
  16370. if (settings.email) {
  16371. connection.emuc.addEmailToPresence(settings.email);
  16372. }
  16373. if (settings.uid) {
  16374. connection.emuc.addUserIdToPresence(settings.uid);
  16375. }
  16376. if (settings.displayName) {
  16377. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16378. }
  16379. // connection.connect() starts the connection process.
  16380. //
  16381. // As the connection process proceeds, the user supplied callback will
  16382. // be triggered multiple times with status updates. The callback should
  16383. // take two arguments - the status code and the error condition.
  16384. //
  16385. // The status code will be one of the values in the Strophe.Status
  16386. // constants. The error condition will be one of the conditions defined
  16387. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16388. //
  16389. // The Parameters wait, hold and route are optional and only relevant
  16390. // for BOSH connections. Please see XEP 124 for a more detailed
  16391. // explanation of the optional parameters.
  16392. //
  16393. // Connection status constants for use by the connection handler
  16394. // callback.
  16395. //
  16396. // Status.ERROR - An error has occurred (websockets specific)
  16397. // Status.CONNECTING - The connection is currently being made
  16398. // Status.CONNFAIL - The connection attempt failed
  16399. // Status.AUTHENTICATING - The connection is authenticating
  16400. // Status.AUTHFAIL - The authentication attempt failed
  16401. // Status.CONNECTED - The connection has succeeded
  16402. // Status.DISCONNECTED - The connection has been terminated
  16403. // Status.DISCONNECTING - The connection is currently being terminated
  16404. // Status.ATTACHED - The connection has been attached
  16405. var anonymousConnectionFailed = false;
  16406. var connectionFailed = false;
  16407. var lastErrorMsg;
  16408. connection.connect(jid, password, function (status, msg) {
  16409. console.log('Strophe status changed to',
  16410. Strophe.getStatusString(status), msg);
  16411. if (status === Strophe.Status.CONNECTED) {
  16412. if (config.useStunTurn) {
  16413. connection.jingle.getStunAndTurnCredentials();
  16414. }
  16415. console.info("My Jabber ID: " + connection.jid);
  16416. if (password)
  16417. authenticatedUser = true;
  16418. maybeDoJoin();
  16419. } else if (status === Strophe.Status.CONNFAIL) {
  16420. if (msg === 'x-strophe-bad-non-anon-jid') {
  16421. anonymousConnectionFailed = true;
  16422. } else {
  16423. connectionFailed = true;
  16424. }
  16425. lastErrorMsg = msg;
  16426. } else if (status === Strophe.Status.DISCONNECTED) {
  16427. if (anonymousConnectionFailed) {
  16428. // prompt user for username and password
  16429. XMPP.promptLogin();
  16430. } else {
  16431. // Strophe already has built-in HTTP/BOSH error handling and
  16432. // request retry logic. Requests are resent automatically
  16433. // until their error count reaches 5. Strophe.js disconnects
  16434. // if the error count is > 5. We are not replicating this
  16435. // here.
  16436. //
  16437. // The "problem" is that failed HTTP/BOSH requests don't
  16438. // trigger a callback with a status update, so when a
  16439. // callback with status Strophe.Status.DISCONNECTED arrives,
  16440. // we can't be sure if it's a graceful disconnect or if it's
  16441. // triggered by some HTTP/BOSH error.
  16442. //
  16443. // But that's a minor issue in Jitsi Meet as we never
  16444. // disconnect anyway, not even when the user closes the
  16445. // browser window (which is kind of wrong, but the point is
  16446. // that we should never ever get disconnected).
  16447. //
  16448. // On the other hand, failed connections due to XMPP layer
  16449. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16450. //
  16451. // Here we implement retry logic for failed connections due
  16452. // to XMPP layer errors and we display an error to the user
  16453. // if we get disconnected from the XMPP server permanently.
  16454. // If the connection failed, retry.
  16455. if (connectionFailed &&
  16456. faultTolerantConnect.retry("connection-failed")) {
  16457. return;
  16458. }
  16459. // If we failed to connect to the XMPP server, fire an event
  16460. // to let all the interested module now about it.
  16461. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16462. msg ? msg : lastErrorMsg);
  16463. }
  16464. } else if (status === Strophe.Status.AUTHFAIL) {
  16465. // wrong password or username, prompt user
  16466. XMPP.promptLogin();
  16467. }
  16468. });
  16469. });
  16470. }
  16471. function maybeDoJoin() {
  16472. if (connection && connection.connected &&
  16473. Strophe.getResourceFromJid(connection.jid) &&
  16474. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16475. // .connected is true while connecting?
  16476. doJoin();
  16477. }
  16478. }
  16479. function doJoin() {
  16480. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16481. }
  16482. function initStrophePlugins()
  16483. {
  16484. require("./strophe.emuc")(XMPP, eventEmitter);
  16485. require("./strophe.jingle")(XMPP, eventEmitter);
  16486. require("./strophe.moderate")(XMPP, eventEmitter);
  16487. require("./strophe.util")();
  16488. require("./strophe.rayo")();
  16489. require("./strophe.logger")();
  16490. }
  16491. /**
  16492. * If given <tt>localStream</tt> is video one this method will advertise it's
  16493. * video type in MUC presence.
  16494. * @param localStream new or modified <tt>LocalStream</tt>.
  16495. */
  16496. function broadcastLocalVideoType(localStream) {
  16497. if (localStream.videoType)
  16498. XMPP.addToPresence('videoType', localStream.videoType);
  16499. }
  16500. function registerListeners() {
  16501. APP.RTC.addStreamListener(
  16502. function (localStream) {
  16503. maybeDoJoin();
  16504. broadcastLocalVideoType(localStream);
  16505. },
  16506. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16507. );
  16508. APP.RTC.addStreamListener(
  16509. broadcastLocalVideoType,
  16510. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16511. );
  16512. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16513. XMPP.addToPresence("devices", devices);
  16514. });
  16515. }
  16516. var unload = (function () {
  16517. var unloaded = false;
  16518. return function () {
  16519. if (unloaded) { return; }
  16520. unloaded = true;
  16521. if (connection && connection.connected) {
  16522. // ensure signout
  16523. $.ajax({
  16524. type: 'POST',
  16525. url: config.bosh,
  16526. async: false,
  16527. cache: false,
  16528. contentType: 'application/xml',
  16529. data: "<body rid='" +
  16530. (connection.rid || connection._proto.rid) +
  16531. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16532. (connection.sid || connection._proto.sid) +
  16533. "' type='terminate'>" +
  16534. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16535. "</body>",
  16536. success: function (data) {
  16537. console.log('signed out');
  16538. console.log(data);
  16539. },
  16540. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16541. console.log('signout error',
  16542. textStatus + ' (' + errorThrown + ')');
  16543. }
  16544. });
  16545. }
  16546. XMPP.disposeConference(true);
  16547. };
  16548. })();
  16549. function setupEvents() {
  16550. // In recent versions of FF the 'beforeunload' event is not fired when the
  16551. // window or the tab is closed. It is only fired when we leave the page
  16552. // (change URL). If this participant doesn't unload properly, then it
  16553. // becomes a ghost for the rest of the participants that stay in the
  16554. // conference. Thankfully handling the 'unload' event in addition to the
  16555. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16556. // method at least once.
  16557. //
  16558. // The 'unload' method can safely be run multiple times, it will actually do
  16559. // something only the first time that it's run, so we're don't have to worry
  16560. // about browsers that fire both events.
  16561. $(window).bind('beforeunload', unload);
  16562. $(window).bind('unload', unload);
  16563. }
  16564. var XMPP = {
  16565. getConnection: function(){ return connection; },
  16566. sessionTerminated: false,
  16567. /**
  16568. * XMPP connection status
  16569. */
  16570. Status: Strophe.Status,
  16571. /**
  16572. * Remembers if we were muted by the focus.
  16573. * @type {boolean}
  16574. */
  16575. forceMuted: false,
  16576. start: function () {
  16577. setupEvents();
  16578. initStrophePlugins();
  16579. registerListeners();
  16580. Moderator.init(this, eventEmitter);
  16581. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16582. // Force authenticated domain if room is appended with '?login=true'
  16583. if (config.hosts.anonymousdomain &&
  16584. window.location.search.indexOf("login=true") !== -1) {
  16585. configDomain = config.hosts.domain;
  16586. }
  16587. var jid = configDomain || window.location.hostname;
  16588. connect(jid, null);
  16589. },
  16590. createConnection: function () {
  16591. var bosh = config.bosh || '/http-bind';
  16592. return new Strophe.Connection(bosh);
  16593. },
  16594. getStatusString: function (status) {
  16595. return Strophe.getStatusString(status);
  16596. },
  16597. promptLogin: function () {
  16598. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16599. },
  16600. joinRoom: function(roomName, useNicks, nick) {
  16601. var roomjid = roomName;
  16602. if (useNicks) {
  16603. if (nick) {
  16604. roomjid += '/' + nick;
  16605. } else {
  16606. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16607. }
  16608. } else {
  16609. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16610. if(!authenticatedUser)
  16611. tmpJid = tmpJid.substr(0, 8);
  16612. roomjid += '/' + tmpJid;
  16613. }
  16614. connection.emuc.doJoin(roomjid);
  16615. },
  16616. myJid: function () {
  16617. if(!connection)
  16618. return null;
  16619. return connection.emuc.myroomjid;
  16620. },
  16621. myResource: function () {
  16622. if(!connection || ! connection.emuc.myroomjid)
  16623. return null;
  16624. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16625. },
  16626. disposeConference: function (onUnload) {
  16627. var handler = connection.jingle.activecall;
  16628. if (handler && handler.peerconnection) {
  16629. // FIXME: probably removing streams is not required and close() should
  16630. // be enough
  16631. if (APP.RTC.localAudio) {
  16632. handler.peerconnection.removeStream(
  16633. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16634. }
  16635. if (APP.RTC.localVideo) {
  16636. handler.peerconnection.removeStream(
  16637. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16638. }
  16639. handler.peerconnection.close();
  16640. }
  16641. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16642. connection.jingle.activecall = null;
  16643. if (!onUnload) {
  16644. this.sessionTerminated = true;
  16645. connection.emuc.doLeave();
  16646. }
  16647. },
  16648. addListener: function(type, listener) {
  16649. eventEmitter.on(type, listener);
  16650. },
  16651. removeListener: function (type, listener) {
  16652. eventEmitter.removeListener(type, listener);
  16653. },
  16654. allocateConferenceFocus: function(roomName, callback) {
  16655. Moderator.allocateConferenceFocus(roomName, callback);
  16656. },
  16657. getLoginUrl: function (roomName, callback) {
  16658. Moderator.getLoginUrl(roomName, callback);
  16659. },
  16660. getPopupLoginUrl: function (roomName, callback) {
  16661. Moderator.getPopupLoginUrl(roomName, callback);
  16662. },
  16663. isModerator: function () {
  16664. return Moderator.isModerator();
  16665. },
  16666. isSipGatewayEnabled: function () {
  16667. return Moderator.isSipGatewayEnabled();
  16668. },
  16669. isExternalAuthEnabled: function () {
  16670. return Moderator.isExternalAuthEnabled();
  16671. },
  16672. isConferenceInProgress: function () {
  16673. return connection && connection.jingle.activecall &&
  16674. connection.jingle.activecall.peerconnection;
  16675. },
  16676. switchStreams: function (stream, oldStream, callback, isAudio) {
  16677. if (this.isConferenceInProgress()) {
  16678. // FIXME: will block switchInProgress on true value in case of exception
  16679. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16680. } else {
  16681. // We are done immediately
  16682. console.warn("No conference handler or conference not started yet");
  16683. callback();
  16684. }
  16685. },
  16686. sendVideoInfoPresence: function (mute) {
  16687. if(!connection)
  16688. return;
  16689. connection.emuc.addVideoInfoToPresence(mute);
  16690. connection.emuc.sendPresence();
  16691. },
  16692. setVideoMute: function (mute, callback, options) {
  16693. if(!connection)
  16694. return;
  16695. var self = this;
  16696. var localCallback = function (mute) {
  16697. self.sendVideoInfoPresence(mute);
  16698. return callback(mute);
  16699. };
  16700. if(connection.jingle.activecall)
  16701. {
  16702. connection.jingle.activecall.setVideoMute(
  16703. mute, localCallback, options);
  16704. }
  16705. else {
  16706. localCallback(mute);
  16707. }
  16708. },
  16709. setAudioMute: function (mute, callback) {
  16710. if (!(connection && APP.RTC.localAudio)) {
  16711. return false;
  16712. }
  16713. if (this.forceMuted && !mute) {
  16714. console.info("Asking focus for unmute");
  16715. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16716. // FIXME: wait for result before resetting muted status
  16717. this.forceMuted = false;
  16718. }
  16719. if (mute == APP.RTC.localAudio.isMuted()) {
  16720. // Nothing to do
  16721. return true;
  16722. }
  16723. APP.RTC.localAudio.setMute(mute);
  16724. this.sendAudioInfoPresence(mute, callback);
  16725. return true;
  16726. },
  16727. sendAudioInfoPresence: function(mute, callback) {
  16728. if(connection) {
  16729. connection.emuc.addAudioInfoToPresence(mute);
  16730. connection.emuc.sendPresence();
  16731. }
  16732. callback();
  16733. return true;
  16734. },
  16735. toggleRecording: function (tokenEmptyCallback,
  16736. recordingStateChangeCallback) {
  16737. Recording.toggleRecording(tokenEmptyCallback,
  16738. recordingStateChangeCallback, connection);
  16739. },
  16740. addToPresence: function (name, value, dontSend) {
  16741. switch (name) {
  16742. case "displayName":
  16743. connection.emuc.addDisplayNameToPresence(value);
  16744. break;
  16745. case "prezi":
  16746. connection.emuc.addPreziToPresence(value, 0);
  16747. break;
  16748. case "preziSlide":
  16749. connection.emuc.addCurrentSlideToPresence(value);
  16750. break;
  16751. case "connectionQuality":
  16752. connection.emuc.addConnectionInfoToPresence(value);
  16753. break;
  16754. case "email":
  16755. connection.emuc.addEmailToPresence(value);
  16756. break;
  16757. case "devices":
  16758. connection.emuc.addDevicesToPresence(value);
  16759. break;
  16760. case "videoType":
  16761. connection.emuc.addVideoTypeToPresence(value);
  16762. break;
  16763. case "startMuted":
  16764. if(!Moderator.isModerator())
  16765. return;
  16766. connection.emuc.addStartMutedToPresence(value[0],
  16767. value[1]);
  16768. break;
  16769. default :
  16770. console.log("Unknown tag for presence: " + name);
  16771. return;
  16772. }
  16773. if (!dontSend)
  16774. connection.emuc.sendPresence();
  16775. },
  16776. /**
  16777. * Sends 'data' as a log message to the focus. Returns true iff a message
  16778. * was sent.
  16779. * @param data
  16780. * @returns {boolean} true iff a message was sent.
  16781. */
  16782. sendLogs: function (data) {
  16783. if(!connection.emuc.focusMucJid)
  16784. return false;
  16785. var deflate = true;
  16786. var content = JSON.stringify(data);
  16787. if (deflate) {
  16788. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16789. }
  16790. content = Base64.encode(content);
  16791. // XEP-0337-ish
  16792. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16793. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16794. id: 'PeerConnectionStats'});
  16795. message.c('message').t(content).up();
  16796. if (deflate) {
  16797. message.c('tag', {name: "deflated", value: "true"}).up();
  16798. }
  16799. message.up();
  16800. connection.send(message);
  16801. return true;
  16802. },
  16803. // Gets the logs from strophe.jingle.
  16804. getJingleLog: function () {
  16805. return connection.jingle ? connection.jingle.getLog() : {};
  16806. },
  16807. // Gets the logs from strophe.
  16808. getXmppLog: function () {
  16809. return connection.logger ? connection.logger.log : null;
  16810. },
  16811. getPrezi: function () {
  16812. return connection.emuc.getPrezi(this.myJid());
  16813. },
  16814. removePreziFromPresence: function () {
  16815. connection.emuc.removePreziFromPresence();
  16816. connection.emuc.sendPresence();
  16817. },
  16818. sendChatMessage: function (message, nickname) {
  16819. connection.emuc.sendMessage(message, nickname);
  16820. },
  16821. setSubject: function (topic) {
  16822. connection.emuc.setSubject(topic);
  16823. },
  16824. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16825. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16826. },
  16827. dial: function (to, from, roomName,roomPass) {
  16828. connection.rayo.dial(to, from, roomName,roomPass);
  16829. },
  16830. setMute: function (jid, mute) {
  16831. connection.moderate.setMute(jid, mute);
  16832. },
  16833. eject: function (jid) {
  16834. connection.moderate.eject(jid);
  16835. },
  16836. logout: function (callback) {
  16837. Moderator.logout(callback);
  16838. },
  16839. findJidFromResource: function (resource) {
  16840. return connection.emuc.findJidFromResource(resource);
  16841. },
  16842. getMembers: function () {
  16843. return connection.emuc.members;
  16844. },
  16845. getJidFromSSRC: function (ssrc) {
  16846. if (!this.isConferenceInProgress())
  16847. return null;
  16848. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16849. },
  16850. // Returns true iff we have joined the MUC.
  16851. isMUCJoined: function () {
  16852. return connection.emuc.joined;
  16853. },
  16854. getSessions: function () {
  16855. return connection.jingle.sessions;
  16856. },
  16857. removeStream: function (stream) {
  16858. if (!this.isConferenceInProgress())
  16859. return;
  16860. connection.jingle.activecall.peerconnection.removeStream(stream);
  16861. }
  16862. };
  16863. module.exports = XMPP;
  16864. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes":103,"../../service/xmpp/XMPPEvents":110,"../settings/Settings":47,"./SDP":56,"./moderator":60,"./recording":61,"./strophe.emuc":62,"./strophe.jingle":63,"./strophe.logger":64,"./strophe.moderate":65,"./strophe.rayo":66,"./strophe.util":67,"events":111,"pako":71,"retry":87}],69:[function(require,module,exports){
  16865. (function (process){
  16866. /*!
  16867. * async
  16868. * https://github.com/caolan/async
  16869. *
  16870. * Copyright 2010-2014 Caolan McMahon
  16871. * Released under the MIT license
  16872. */
  16873. /*jshint onevar: false, indent:4 */
  16874. /*global setImmediate: false, setTimeout: false, console: false */
  16875. (function () {
  16876. var async = {};
  16877. // global on the server, window in the browser
  16878. var root, previous_async;
  16879. root = this;
  16880. if (root != null) {
  16881. previous_async = root.async;
  16882. }
  16883. async.noConflict = function () {
  16884. root.async = previous_async;
  16885. return async;
  16886. };
  16887. function only_once(fn) {
  16888. var called = false;
  16889. return function() {
  16890. if (called) throw new Error("Callback was already called.");
  16891. called = true;
  16892. fn.apply(root, arguments);
  16893. }
  16894. }
  16895. //// cross-browser compatiblity functions ////
  16896. var _toString = Object.prototype.toString;
  16897. var _isArray = Array.isArray || function (obj) {
  16898. return _toString.call(obj) === '[object Array]';
  16899. };
  16900. var _each = function (arr, iterator) {
  16901. if (arr.forEach) {
  16902. return arr.forEach(iterator);
  16903. }
  16904. for (var i = 0; i < arr.length; i += 1) {
  16905. iterator(arr[i], i, arr);
  16906. }
  16907. };
  16908. var _map = function (arr, iterator) {
  16909. if (arr.map) {
  16910. return arr.map(iterator);
  16911. }
  16912. var results = [];
  16913. _each(arr, function (x, i, a) {
  16914. results.push(iterator(x, i, a));
  16915. });
  16916. return results;
  16917. };
  16918. var _reduce = function (arr, iterator, memo) {
  16919. if (arr.reduce) {
  16920. return arr.reduce(iterator, memo);
  16921. }
  16922. _each(arr, function (x, i, a) {
  16923. memo = iterator(memo, x, i, a);
  16924. });
  16925. return memo;
  16926. };
  16927. var _keys = function (obj) {
  16928. if (Object.keys) {
  16929. return Object.keys(obj);
  16930. }
  16931. var keys = [];
  16932. for (var k in obj) {
  16933. if (obj.hasOwnProperty(k)) {
  16934. keys.push(k);
  16935. }
  16936. }
  16937. return keys;
  16938. };
  16939. //// exported async module functions ////
  16940. //// nextTick implementation with browser-compatible fallback ////
  16941. if (typeof process === 'undefined' || !(process.nextTick)) {
  16942. if (typeof setImmediate === 'function') {
  16943. async.nextTick = function (fn) {
  16944. // not a direct alias for IE10 compatibility
  16945. setImmediate(fn);
  16946. };
  16947. async.setImmediate = async.nextTick;
  16948. }
  16949. else {
  16950. async.nextTick = function (fn) {
  16951. setTimeout(fn, 0);
  16952. };
  16953. async.setImmediate = async.nextTick;
  16954. }
  16955. }
  16956. else {
  16957. async.nextTick = process.nextTick;
  16958. if (typeof setImmediate !== 'undefined') {
  16959. async.setImmediate = function (fn) {
  16960. // not a direct alias for IE10 compatibility
  16961. setImmediate(fn);
  16962. };
  16963. }
  16964. else {
  16965. async.setImmediate = async.nextTick;
  16966. }
  16967. }
  16968. async.each = function (arr, iterator, callback) {
  16969. callback = callback || function () {};
  16970. if (!arr.length) {
  16971. return callback();
  16972. }
  16973. var completed = 0;
  16974. _each(arr, function (x) {
  16975. iterator(x, only_once(done) );
  16976. });
  16977. function done(err) {
  16978. if (err) {
  16979. callback(err);
  16980. callback = function () {};
  16981. }
  16982. else {
  16983. completed += 1;
  16984. if (completed >= arr.length) {
  16985. callback();
  16986. }
  16987. }
  16988. }
  16989. };
  16990. async.forEach = async.each;
  16991. async.eachSeries = function (arr, iterator, callback) {
  16992. callback = callback || function () {};
  16993. if (!arr.length) {
  16994. return callback();
  16995. }
  16996. var completed = 0;
  16997. var iterate = function () {
  16998. iterator(arr[completed], function (err) {
  16999. if (err) {
  17000. callback(err);
  17001. callback = function () {};
  17002. }
  17003. else {
  17004. completed += 1;
  17005. if (completed >= arr.length) {
  17006. callback();
  17007. }
  17008. else {
  17009. iterate();
  17010. }
  17011. }
  17012. });
  17013. };
  17014. iterate();
  17015. };
  17016. async.forEachSeries = async.eachSeries;
  17017. async.eachLimit = function (arr, limit, iterator, callback) {
  17018. var fn = _eachLimit(limit);
  17019. fn.apply(null, [arr, iterator, callback]);
  17020. };
  17021. async.forEachLimit = async.eachLimit;
  17022. var _eachLimit = function (limit) {
  17023. return function (arr, iterator, callback) {
  17024. callback = callback || function () {};
  17025. if (!arr.length || limit <= 0) {
  17026. return callback();
  17027. }
  17028. var completed = 0;
  17029. var started = 0;
  17030. var running = 0;
  17031. (function replenish () {
  17032. if (completed >= arr.length) {
  17033. return callback();
  17034. }
  17035. while (running < limit && started < arr.length) {
  17036. started += 1;
  17037. running += 1;
  17038. iterator(arr[started - 1], function (err) {
  17039. if (err) {
  17040. callback(err);
  17041. callback = function () {};
  17042. }
  17043. else {
  17044. completed += 1;
  17045. running -= 1;
  17046. if (completed >= arr.length) {
  17047. callback();
  17048. }
  17049. else {
  17050. replenish();
  17051. }
  17052. }
  17053. });
  17054. }
  17055. })();
  17056. };
  17057. };
  17058. var doParallel = function (fn) {
  17059. return function () {
  17060. var args = Array.prototype.slice.call(arguments);
  17061. return fn.apply(null, [async.each].concat(args));
  17062. };
  17063. };
  17064. var doParallelLimit = function(limit, fn) {
  17065. return function () {
  17066. var args = Array.prototype.slice.call(arguments);
  17067. return fn.apply(null, [_eachLimit(limit)].concat(args));
  17068. };
  17069. };
  17070. var doSeries = function (fn) {
  17071. return function () {
  17072. var args = Array.prototype.slice.call(arguments);
  17073. return fn.apply(null, [async.eachSeries].concat(args));
  17074. };
  17075. };
  17076. var _asyncMap = function (eachfn, arr, iterator, callback) {
  17077. arr = _map(arr, function (x, i) {
  17078. return {index: i, value: x};
  17079. });
  17080. if (!callback) {
  17081. eachfn(arr, function (x, callback) {
  17082. iterator(x.value, function (err) {
  17083. callback(err);
  17084. });
  17085. });
  17086. } else {
  17087. var results = [];
  17088. eachfn(arr, function (x, callback) {
  17089. iterator(x.value, function (err, v) {
  17090. results[x.index] = v;
  17091. callback(err);
  17092. });
  17093. }, function (err) {
  17094. callback(err, results);
  17095. });
  17096. }
  17097. };
  17098. async.map = doParallel(_asyncMap);
  17099. async.mapSeries = doSeries(_asyncMap);
  17100. async.mapLimit = function (arr, limit, iterator, callback) {
  17101. return _mapLimit(limit)(arr, iterator, callback);
  17102. };
  17103. var _mapLimit = function(limit) {
  17104. return doParallelLimit(limit, _asyncMap);
  17105. };
  17106. // reduce only has a series version, as doing reduce in parallel won't
  17107. // work in many situations.
  17108. async.reduce = function (arr, memo, iterator, callback) {
  17109. async.eachSeries(arr, function (x, callback) {
  17110. iterator(memo, x, function (err, v) {
  17111. memo = v;
  17112. callback(err);
  17113. });
  17114. }, function (err) {
  17115. callback(err, memo);
  17116. });
  17117. };
  17118. // inject alias
  17119. async.inject = async.reduce;
  17120. // foldl alias
  17121. async.foldl = async.reduce;
  17122. async.reduceRight = function (arr, memo, iterator, callback) {
  17123. var reversed = _map(arr, function (x) {
  17124. return x;
  17125. }).reverse();
  17126. async.reduce(reversed, memo, iterator, callback);
  17127. };
  17128. // foldr alias
  17129. async.foldr = async.reduceRight;
  17130. var _filter = function (eachfn, arr, iterator, callback) {
  17131. var results = [];
  17132. arr = _map(arr, function (x, i) {
  17133. return {index: i, value: x};
  17134. });
  17135. eachfn(arr, function (x, callback) {
  17136. iterator(x.value, function (v) {
  17137. if (v) {
  17138. results.push(x);
  17139. }
  17140. callback();
  17141. });
  17142. }, function (err) {
  17143. callback(_map(results.sort(function (a, b) {
  17144. return a.index - b.index;
  17145. }), function (x) {
  17146. return x.value;
  17147. }));
  17148. });
  17149. };
  17150. async.filter = doParallel(_filter);
  17151. async.filterSeries = doSeries(_filter);
  17152. // select alias
  17153. async.select = async.filter;
  17154. async.selectSeries = async.filterSeries;
  17155. var _reject = function (eachfn, arr, iterator, callback) {
  17156. var results = [];
  17157. arr = _map(arr, function (x, i) {
  17158. return {index: i, value: x};
  17159. });
  17160. eachfn(arr, function (x, callback) {
  17161. iterator(x.value, function (v) {
  17162. if (!v) {
  17163. results.push(x);
  17164. }
  17165. callback();
  17166. });
  17167. }, function (err) {
  17168. callback(_map(results.sort(function (a, b) {
  17169. return a.index - b.index;
  17170. }), function (x) {
  17171. return x.value;
  17172. }));
  17173. });
  17174. };
  17175. async.reject = doParallel(_reject);
  17176. async.rejectSeries = doSeries(_reject);
  17177. var _detect = function (eachfn, arr, iterator, main_callback) {
  17178. eachfn(arr, function (x, callback) {
  17179. iterator(x, function (result) {
  17180. if (result) {
  17181. main_callback(x);
  17182. main_callback = function () {};
  17183. }
  17184. else {
  17185. callback();
  17186. }
  17187. });
  17188. }, function (err) {
  17189. main_callback();
  17190. });
  17191. };
  17192. async.detect = doParallel(_detect);
  17193. async.detectSeries = doSeries(_detect);
  17194. async.some = function (arr, iterator, main_callback) {
  17195. async.each(arr, function (x, callback) {
  17196. iterator(x, function (v) {
  17197. if (v) {
  17198. main_callback(true);
  17199. main_callback = function () {};
  17200. }
  17201. callback();
  17202. });
  17203. }, function (err) {
  17204. main_callback(false);
  17205. });
  17206. };
  17207. // any alias
  17208. async.any = async.some;
  17209. async.every = function (arr, iterator, main_callback) {
  17210. async.each(arr, function (x, callback) {
  17211. iterator(x, function (v) {
  17212. if (!v) {
  17213. main_callback(false);
  17214. main_callback = function () {};
  17215. }
  17216. callback();
  17217. });
  17218. }, function (err) {
  17219. main_callback(true);
  17220. });
  17221. };
  17222. // all alias
  17223. async.all = async.every;
  17224. async.sortBy = function (arr, iterator, callback) {
  17225. async.map(arr, function (x, callback) {
  17226. iterator(x, function (err, criteria) {
  17227. if (err) {
  17228. callback(err);
  17229. }
  17230. else {
  17231. callback(null, {value: x, criteria: criteria});
  17232. }
  17233. });
  17234. }, function (err, results) {
  17235. if (err) {
  17236. return callback(err);
  17237. }
  17238. else {
  17239. var fn = function (left, right) {
  17240. var a = left.criteria, b = right.criteria;
  17241. return a < b ? -1 : a > b ? 1 : 0;
  17242. };
  17243. callback(null, _map(results.sort(fn), function (x) {
  17244. return x.value;
  17245. }));
  17246. }
  17247. });
  17248. };
  17249. async.auto = function (tasks, callback) {
  17250. callback = callback || function () {};
  17251. var keys = _keys(tasks);
  17252. var remainingTasks = keys.length
  17253. if (!remainingTasks) {
  17254. return callback();
  17255. }
  17256. var results = {};
  17257. var listeners = [];
  17258. var addListener = function (fn) {
  17259. listeners.unshift(fn);
  17260. };
  17261. var removeListener = function (fn) {
  17262. for (var i = 0; i < listeners.length; i += 1) {
  17263. if (listeners[i] === fn) {
  17264. listeners.splice(i, 1);
  17265. return;
  17266. }
  17267. }
  17268. };
  17269. var taskComplete = function () {
  17270. remainingTasks--
  17271. _each(listeners.slice(0), function (fn) {
  17272. fn();
  17273. });
  17274. };
  17275. addListener(function () {
  17276. if (!remainingTasks) {
  17277. var theCallback = callback;
  17278. // prevent final callback from calling itself if it errors
  17279. callback = function () {};
  17280. theCallback(null, results);
  17281. }
  17282. });
  17283. _each(keys, function (k) {
  17284. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17285. var taskCallback = function (err) {
  17286. var args = Array.prototype.slice.call(arguments, 1);
  17287. if (args.length <= 1) {
  17288. args = args[0];
  17289. }
  17290. if (err) {
  17291. var safeResults = {};
  17292. _each(_keys(results), function(rkey) {
  17293. safeResults[rkey] = results[rkey];
  17294. });
  17295. safeResults[k] = args;
  17296. callback(err, safeResults);
  17297. // stop subsequent errors hitting callback multiple times
  17298. callback = function () {};
  17299. }
  17300. else {
  17301. results[k] = args;
  17302. async.setImmediate(taskComplete);
  17303. }
  17304. };
  17305. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17306. var ready = function () {
  17307. return _reduce(requires, function (a, x) {
  17308. return (a && results.hasOwnProperty(x));
  17309. }, true) && !results.hasOwnProperty(k);
  17310. };
  17311. if (ready()) {
  17312. task[task.length - 1](taskCallback, results);
  17313. }
  17314. else {
  17315. var listener = function () {
  17316. if (ready()) {
  17317. removeListener(listener);
  17318. task[task.length - 1](taskCallback, results);
  17319. }
  17320. };
  17321. addListener(listener);
  17322. }
  17323. });
  17324. };
  17325. async.retry = function(times, task, callback) {
  17326. var DEFAULT_TIMES = 5;
  17327. var attempts = [];
  17328. // Use defaults if times not passed
  17329. if (typeof times === 'function') {
  17330. callback = task;
  17331. task = times;
  17332. times = DEFAULT_TIMES;
  17333. }
  17334. // Make sure times is a number
  17335. times = parseInt(times, 10) || DEFAULT_TIMES;
  17336. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17337. var retryAttempt = function(task, finalAttempt) {
  17338. return function(seriesCallback) {
  17339. task(function(err, result){
  17340. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17341. }, wrappedResults);
  17342. };
  17343. };
  17344. while (times) {
  17345. attempts.push(retryAttempt(task, !(times-=1)));
  17346. }
  17347. async.series(attempts, function(done, data){
  17348. data = data[data.length - 1];
  17349. (wrappedCallback || callback)(data.err, data.result);
  17350. });
  17351. }
  17352. // If a callback is passed, run this as a controll flow
  17353. return callback ? wrappedTask() : wrappedTask
  17354. };
  17355. async.waterfall = function (tasks, callback) {
  17356. callback = callback || function () {};
  17357. if (!_isArray(tasks)) {
  17358. var err = new Error('First argument to waterfall must be an array of functions');
  17359. return callback(err);
  17360. }
  17361. if (!tasks.length) {
  17362. return callback();
  17363. }
  17364. var wrapIterator = function (iterator) {
  17365. return function (err) {
  17366. if (err) {
  17367. callback.apply(null, arguments);
  17368. callback = function () {};
  17369. }
  17370. else {
  17371. var args = Array.prototype.slice.call(arguments, 1);
  17372. var next = iterator.next();
  17373. if (next) {
  17374. args.push(wrapIterator(next));
  17375. }
  17376. else {
  17377. args.push(callback);
  17378. }
  17379. async.setImmediate(function () {
  17380. iterator.apply(null, args);
  17381. });
  17382. }
  17383. };
  17384. };
  17385. wrapIterator(async.iterator(tasks))();
  17386. };
  17387. var _parallel = function(eachfn, tasks, callback) {
  17388. callback = callback || function () {};
  17389. if (_isArray(tasks)) {
  17390. eachfn.map(tasks, function (fn, callback) {
  17391. if (fn) {
  17392. fn(function (err) {
  17393. var args = Array.prototype.slice.call(arguments, 1);
  17394. if (args.length <= 1) {
  17395. args = args[0];
  17396. }
  17397. callback.call(null, err, args);
  17398. });
  17399. }
  17400. }, callback);
  17401. }
  17402. else {
  17403. var results = {};
  17404. eachfn.each(_keys(tasks), function (k, callback) {
  17405. tasks[k](function (err) {
  17406. var args = Array.prototype.slice.call(arguments, 1);
  17407. if (args.length <= 1) {
  17408. args = args[0];
  17409. }
  17410. results[k] = args;
  17411. callback(err);
  17412. });
  17413. }, function (err) {
  17414. callback(err, results);
  17415. });
  17416. }
  17417. };
  17418. async.parallel = function (tasks, callback) {
  17419. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17420. };
  17421. async.parallelLimit = function(tasks, limit, callback) {
  17422. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17423. };
  17424. async.series = function (tasks, callback) {
  17425. callback = callback || function () {};
  17426. if (_isArray(tasks)) {
  17427. async.mapSeries(tasks, function (fn, callback) {
  17428. if (fn) {
  17429. fn(function (err) {
  17430. var args = Array.prototype.slice.call(arguments, 1);
  17431. if (args.length <= 1) {
  17432. args = args[0];
  17433. }
  17434. callback.call(null, err, args);
  17435. });
  17436. }
  17437. }, callback);
  17438. }
  17439. else {
  17440. var results = {};
  17441. async.eachSeries(_keys(tasks), function (k, callback) {
  17442. tasks[k](function (err) {
  17443. var args = Array.prototype.slice.call(arguments, 1);
  17444. if (args.length <= 1) {
  17445. args = args[0];
  17446. }
  17447. results[k] = args;
  17448. callback(err);
  17449. });
  17450. }, function (err) {
  17451. callback(err, results);
  17452. });
  17453. }
  17454. };
  17455. async.iterator = function (tasks) {
  17456. var makeCallback = function (index) {
  17457. var fn = function () {
  17458. if (tasks.length) {
  17459. tasks[index].apply(null, arguments);
  17460. }
  17461. return fn.next();
  17462. };
  17463. fn.next = function () {
  17464. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17465. };
  17466. return fn;
  17467. };
  17468. return makeCallback(0);
  17469. };
  17470. async.apply = function (fn) {
  17471. var args = Array.prototype.slice.call(arguments, 1);
  17472. return function () {
  17473. return fn.apply(
  17474. null, args.concat(Array.prototype.slice.call(arguments))
  17475. );
  17476. };
  17477. };
  17478. var _concat = function (eachfn, arr, fn, callback) {
  17479. var r = [];
  17480. eachfn(arr, function (x, cb) {
  17481. fn(x, function (err, y) {
  17482. r = r.concat(y || []);
  17483. cb(err);
  17484. });
  17485. }, function (err) {
  17486. callback(err, r);
  17487. });
  17488. };
  17489. async.concat = doParallel(_concat);
  17490. async.concatSeries = doSeries(_concat);
  17491. async.whilst = function (test, iterator, callback) {
  17492. if (test()) {
  17493. iterator(function (err) {
  17494. if (err) {
  17495. return callback(err);
  17496. }
  17497. async.whilst(test, iterator, callback);
  17498. });
  17499. }
  17500. else {
  17501. callback();
  17502. }
  17503. };
  17504. async.doWhilst = function (iterator, test, callback) {
  17505. iterator(function (err) {
  17506. if (err) {
  17507. return callback(err);
  17508. }
  17509. var args = Array.prototype.slice.call(arguments, 1);
  17510. if (test.apply(null, args)) {
  17511. async.doWhilst(iterator, test, callback);
  17512. }
  17513. else {
  17514. callback();
  17515. }
  17516. });
  17517. };
  17518. async.until = function (test, iterator, callback) {
  17519. if (!test()) {
  17520. iterator(function (err) {
  17521. if (err) {
  17522. return callback(err);
  17523. }
  17524. async.until(test, iterator, callback);
  17525. });
  17526. }
  17527. else {
  17528. callback();
  17529. }
  17530. };
  17531. async.doUntil = function (iterator, test, callback) {
  17532. iterator(function (err) {
  17533. if (err) {
  17534. return callback(err);
  17535. }
  17536. var args = Array.prototype.slice.call(arguments, 1);
  17537. if (!test.apply(null, args)) {
  17538. async.doUntil(iterator, test, callback);
  17539. }
  17540. else {
  17541. callback();
  17542. }
  17543. });
  17544. };
  17545. async.queue = function (worker, concurrency) {
  17546. if (concurrency === undefined) {
  17547. concurrency = 1;
  17548. }
  17549. function _insert(q, data, pos, callback) {
  17550. if (!q.started){
  17551. q.started = true;
  17552. }
  17553. if (!_isArray(data)) {
  17554. data = [data];
  17555. }
  17556. if(data.length == 0) {
  17557. // call drain immediately if there are no tasks
  17558. return async.setImmediate(function() {
  17559. if (q.drain) {
  17560. q.drain();
  17561. }
  17562. });
  17563. }
  17564. _each(data, function(task) {
  17565. var item = {
  17566. data: task,
  17567. callback: typeof callback === 'function' ? callback : null
  17568. };
  17569. if (pos) {
  17570. q.tasks.unshift(item);
  17571. } else {
  17572. q.tasks.push(item);
  17573. }
  17574. if (q.saturated && q.tasks.length === q.concurrency) {
  17575. q.saturated();
  17576. }
  17577. async.setImmediate(q.process);
  17578. });
  17579. }
  17580. var workers = 0;
  17581. var q = {
  17582. tasks: [],
  17583. concurrency: concurrency,
  17584. saturated: null,
  17585. empty: null,
  17586. drain: null,
  17587. started: false,
  17588. paused: false,
  17589. push: function (data, callback) {
  17590. _insert(q, data, false, callback);
  17591. },
  17592. kill: function () {
  17593. q.drain = null;
  17594. q.tasks = [];
  17595. },
  17596. unshift: function (data, callback) {
  17597. _insert(q, data, true, callback);
  17598. },
  17599. process: function () {
  17600. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17601. var task = q.tasks.shift();
  17602. if (q.empty && q.tasks.length === 0) {
  17603. q.empty();
  17604. }
  17605. workers += 1;
  17606. var next = function () {
  17607. workers -= 1;
  17608. if (task.callback) {
  17609. task.callback.apply(task, arguments);
  17610. }
  17611. if (q.drain && q.tasks.length + workers === 0) {
  17612. q.drain();
  17613. }
  17614. q.process();
  17615. };
  17616. var cb = only_once(next);
  17617. worker(task.data, cb);
  17618. }
  17619. },
  17620. length: function () {
  17621. return q.tasks.length;
  17622. },
  17623. running: function () {
  17624. return workers;
  17625. },
  17626. idle: function() {
  17627. return q.tasks.length + workers === 0;
  17628. },
  17629. pause: function () {
  17630. if (q.paused === true) { return; }
  17631. q.paused = true;
  17632. q.process();
  17633. },
  17634. resume: function () {
  17635. if (q.paused === false) { return; }
  17636. q.paused = false;
  17637. q.process();
  17638. }
  17639. };
  17640. return q;
  17641. };
  17642. async.priorityQueue = function (worker, concurrency) {
  17643. function _compareTasks(a, b){
  17644. return a.priority - b.priority;
  17645. };
  17646. function _binarySearch(sequence, item, compare) {
  17647. var beg = -1,
  17648. end = sequence.length - 1;
  17649. while (beg < end) {
  17650. var mid = beg + ((end - beg + 1) >>> 1);
  17651. if (compare(item, sequence[mid]) >= 0) {
  17652. beg = mid;
  17653. } else {
  17654. end = mid - 1;
  17655. }
  17656. }
  17657. return beg;
  17658. }
  17659. function _insert(q, data, priority, callback) {
  17660. if (!q.started){
  17661. q.started = true;
  17662. }
  17663. if (!_isArray(data)) {
  17664. data = [data];
  17665. }
  17666. if(data.length == 0) {
  17667. // call drain immediately if there are no tasks
  17668. return async.setImmediate(function() {
  17669. if (q.drain) {
  17670. q.drain();
  17671. }
  17672. });
  17673. }
  17674. _each(data, function(task) {
  17675. var item = {
  17676. data: task,
  17677. priority: priority,
  17678. callback: typeof callback === 'function' ? callback : null
  17679. };
  17680. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17681. if (q.saturated && q.tasks.length === q.concurrency) {
  17682. q.saturated();
  17683. }
  17684. async.setImmediate(q.process);
  17685. });
  17686. }
  17687. // Start with a normal queue
  17688. var q = async.queue(worker, concurrency);
  17689. // Override push to accept second parameter representing priority
  17690. q.push = function (data, priority, callback) {
  17691. _insert(q, data, priority, callback);
  17692. };
  17693. // Remove unshift function
  17694. delete q.unshift;
  17695. return q;
  17696. };
  17697. async.cargo = function (worker, payload) {
  17698. var working = false,
  17699. tasks = [];
  17700. var cargo = {
  17701. tasks: tasks,
  17702. payload: payload,
  17703. saturated: null,
  17704. empty: null,
  17705. drain: null,
  17706. drained: true,
  17707. push: function (data, callback) {
  17708. if (!_isArray(data)) {
  17709. data = [data];
  17710. }
  17711. _each(data, function(task) {
  17712. tasks.push({
  17713. data: task,
  17714. callback: typeof callback === 'function' ? callback : null
  17715. });
  17716. cargo.drained = false;
  17717. if (cargo.saturated && tasks.length === payload) {
  17718. cargo.saturated();
  17719. }
  17720. });
  17721. async.setImmediate(cargo.process);
  17722. },
  17723. process: function process() {
  17724. if (working) return;
  17725. if (tasks.length === 0) {
  17726. if(cargo.drain && !cargo.drained) cargo.drain();
  17727. cargo.drained = true;
  17728. return;
  17729. }
  17730. var ts = typeof payload === 'number'
  17731. ? tasks.splice(0, payload)
  17732. : tasks.splice(0, tasks.length);
  17733. var ds = _map(ts, function (task) {
  17734. return task.data;
  17735. });
  17736. if(cargo.empty) cargo.empty();
  17737. working = true;
  17738. worker(ds, function () {
  17739. working = false;
  17740. var args = arguments;
  17741. _each(ts, function (data) {
  17742. if (data.callback) {
  17743. data.callback.apply(null, args);
  17744. }
  17745. });
  17746. process();
  17747. });
  17748. },
  17749. length: function () {
  17750. return tasks.length;
  17751. },
  17752. running: function () {
  17753. return working;
  17754. }
  17755. };
  17756. return cargo;
  17757. };
  17758. var _console_fn = function (name) {
  17759. return function (fn) {
  17760. var args = Array.prototype.slice.call(arguments, 1);
  17761. fn.apply(null, args.concat([function (err) {
  17762. var args = Array.prototype.slice.call(arguments, 1);
  17763. if (typeof console !== 'undefined') {
  17764. if (err) {
  17765. if (console.error) {
  17766. console.error(err);
  17767. }
  17768. }
  17769. else if (console[name]) {
  17770. _each(args, function (x) {
  17771. console[name](x);
  17772. });
  17773. }
  17774. }
  17775. }]));
  17776. };
  17777. };
  17778. async.log = _console_fn('log');
  17779. async.dir = _console_fn('dir');
  17780. /*async.info = _console_fn('info');
  17781. async.warn = _console_fn('warn');
  17782. async.error = _console_fn('error');*/
  17783. async.memoize = function (fn, hasher) {
  17784. var memo = {};
  17785. var queues = {};
  17786. hasher = hasher || function (x) {
  17787. return x;
  17788. };
  17789. var memoized = function () {
  17790. var args = Array.prototype.slice.call(arguments);
  17791. var callback = args.pop();
  17792. var key = hasher.apply(null, args);
  17793. if (key in memo) {
  17794. async.nextTick(function () {
  17795. callback.apply(null, memo[key]);
  17796. });
  17797. }
  17798. else if (key in queues) {
  17799. queues[key].push(callback);
  17800. }
  17801. else {
  17802. queues[key] = [callback];
  17803. fn.apply(null, args.concat([function () {
  17804. memo[key] = arguments;
  17805. var q = queues[key];
  17806. delete queues[key];
  17807. for (var i = 0, l = q.length; i < l; i++) {
  17808. q[i].apply(null, arguments);
  17809. }
  17810. }]));
  17811. }
  17812. };
  17813. memoized.memo = memo;
  17814. memoized.unmemoized = fn;
  17815. return memoized;
  17816. };
  17817. async.unmemoize = function (fn) {
  17818. return function () {
  17819. return (fn.unmemoized || fn).apply(null, arguments);
  17820. };
  17821. };
  17822. async.times = function (count, iterator, callback) {
  17823. var counter = [];
  17824. for (var i = 0; i < count; i++) {
  17825. counter.push(i);
  17826. }
  17827. return async.map(counter, iterator, callback);
  17828. };
  17829. async.timesSeries = function (count, iterator, callback) {
  17830. var counter = [];
  17831. for (var i = 0; i < count; i++) {
  17832. counter.push(i);
  17833. }
  17834. return async.mapSeries(counter, iterator, callback);
  17835. };
  17836. async.seq = function (/* functions... */) {
  17837. var fns = arguments;
  17838. return function () {
  17839. var that = this;
  17840. var args = Array.prototype.slice.call(arguments);
  17841. var callback = args.pop();
  17842. async.reduce(fns, args, function (newargs, fn, cb) {
  17843. fn.apply(that, newargs.concat([function () {
  17844. var err = arguments[0];
  17845. var nextargs = Array.prototype.slice.call(arguments, 1);
  17846. cb(err, nextargs);
  17847. }]))
  17848. },
  17849. function (err, results) {
  17850. callback.apply(that, [err].concat(results));
  17851. });
  17852. };
  17853. };
  17854. async.compose = function (/* functions... */) {
  17855. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17856. };
  17857. var _applyEach = function (eachfn, fns /*args...*/) {
  17858. var go = function () {
  17859. var that = this;
  17860. var args = Array.prototype.slice.call(arguments);
  17861. var callback = args.pop();
  17862. return eachfn(fns, function (fn, cb) {
  17863. fn.apply(that, args.concat([cb]));
  17864. },
  17865. callback);
  17866. };
  17867. if (arguments.length > 2) {
  17868. var args = Array.prototype.slice.call(arguments, 2);
  17869. return go.apply(this, args);
  17870. }
  17871. else {
  17872. return go;
  17873. }
  17874. };
  17875. async.applyEach = doParallel(_applyEach);
  17876. async.applyEachSeries = doSeries(_applyEach);
  17877. async.forever = function (fn, callback) {
  17878. function next(err) {
  17879. if (err) {
  17880. if (callback) {
  17881. return callback(err);
  17882. }
  17883. throw err;
  17884. }
  17885. fn(next);
  17886. }
  17887. next();
  17888. };
  17889. // Node.js
  17890. if (typeof module !== 'undefined' && module.exports) {
  17891. module.exports = async;
  17892. }
  17893. // AMD / RequireJS
  17894. else if (typeof define !== 'undefined' && define.amd) {
  17895. define([], function () {
  17896. return async;
  17897. });
  17898. }
  17899. // included directly via <script> tag
  17900. else {
  17901. root.async = async;
  17902. }
  17903. }());
  17904. }).call(this,require('_process'))
  17905. },{"_process":112}],70:[function(require,module,exports){
  17906. // i18next, v1.7.7
  17907. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17908. // Distributed under MIT license
  17909. // http://i18next.com
  17910. (function() {
  17911. // add indexOf to non ECMA-262 standard compliant browsers
  17912. if (!Array.prototype.indexOf) {
  17913. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17914. "use strict";
  17915. if (this == null) {
  17916. throw new TypeError();
  17917. }
  17918. var t = Object(this);
  17919. var len = t.length >>> 0;
  17920. if (len === 0) {
  17921. return -1;
  17922. }
  17923. var n = 0;
  17924. if (arguments.length > 0) {
  17925. n = Number(arguments[1]);
  17926. if (n != n) { // shortcut for verifying if it's NaN
  17927. n = 0;
  17928. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17929. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17930. }
  17931. }
  17932. if (n >= len) {
  17933. return -1;
  17934. }
  17935. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17936. for (; k < len; k++) {
  17937. if (k in t && t[k] === searchElement) {
  17938. return k;
  17939. }
  17940. }
  17941. return -1;
  17942. }
  17943. }
  17944. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17945. if (!Array.prototype.lastIndexOf) {
  17946. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17947. "use strict";
  17948. if (this == null) {
  17949. throw new TypeError();
  17950. }
  17951. var t = Object(this);
  17952. var len = t.length >>> 0;
  17953. if (len === 0) {
  17954. return -1;
  17955. }
  17956. var n = len;
  17957. if (arguments.length > 1) {
  17958. n = Number(arguments[1]);
  17959. if (n != n) {
  17960. n = 0;
  17961. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17962. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17963. }
  17964. }
  17965. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17966. for (; k >= 0; k--) {
  17967. if (k in t && t[k] === searchElement) {
  17968. return k;
  17969. }
  17970. }
  17971. return -1;
  17972. };
  17973. }
  17974. // Add string trim for IE8.
  17975. if (typeof String.prototype.trim !== 'function') {
  17976. String.prototype.trim = function() {
  17977. return this.replace(/^\s+|\s+$/g, '');
  17978. }
  17979. }
  17980. var root = this
  17981. , $ = root.jQuery || root.Zepto
  17982. , i18n = {}
  17983. , resStore = {}
  17984. , currentLng
  17985. , replacementCounter = 0
  17986. , languages = []
  17987. , initialized = false
  17988. , sync = {};
  17989. // Export the i18next object for **CommonJS**.
  17990. // If we're not in CommonJS, add `i18n` to the
  17991. // global object or to jquery.
  17992. if (typeof module !== 'undefined' && module.exports) {
  17993. if (!$) {
  17994. try {
  17995. $ = require('jquery');
  17996. } catch(e) {
  17997. // just ignore
  17998. }
  17999. }
  18000. if ($) {
  18001. $.i18n = $.i18n || i18n;
  18002. }
  18003. module.exports = i18n;
  18004. } else {
  18005. if ($) {
  18006. $.i18n = $.i18n || i18n;
  18007. }
  18008. root.i18n = root.i18n || i18n;
  18009. }
  18010. sync = {
  18011. load: function(lngs, options, cb) {
  18012. if (options.useLocalStorage) {
  18013. sync._loadLocal(lngs, options, function(err, store) {
  18014. var missingLngs = [];
  18015. for (var i = 0, len = lngs.length; i < len; i++) {
  18016. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  18017. }
  18018. if (missingLngs.length > 0) {
  18019. sync._fetch(missingLngs, options, function(err, fetched) {
  18020. f.extend(store, fetched);
  18021. sync._storeLocal(fetched);
  18022. cb(null, store);
  18023. });
  18024. } else {
  18025. cb(null, store);
  18026. }
  18027. });
  18028. } else {
  18029. sync._fetch(lngs, options, function(err, store){
  18030. cb(null, store);
  18031. });
  18032. }
  18033. },
  18034. _loadLocal: function(lngs, options, cb) {
  18035. var store = {}
  18036. , nowMS = new Date().getTime();
  18037. if(window.localStorage) {
  18038. var todo = lngs.length;
  18039. f.each(lngs, function(key, lng) {
  18040. var local = window.localStorage.getItem('res_' + lng);
  18041. if (local) {
  18042. local = JSON.parse(local);
  18043. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  18044. store[lng] = local;
  18045. }
  18046. }
  18047. todo--; // wait for all done befor callback
  18048. if (todo === 0) cb(null, store);
  18049. });
  18050. }
  18051. },
  18052. _storeLocal: function(store) {
  18053. if(window.localStorage) {
  18054. for (var m in store) {
  18055. store[m].i18nStamp = new Date().getTime();
  18056. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  18057. }
  18058. }
  18059. return;
  18060. },
  18061. _fetch: function(lngs, options, cb) {
  18062. var ns = options.ns
  18063. , store = {};
  18064. if (!options.dynamicLoad) {
  18065. var todo = ns.namespaces.length * lngs.length
  18066. , errors;
  18067. // load each file individual
  18068. f.each(ns.namespaces, function(nsIndex, nsValue) {
  18069. f.each(lngs, function(lngIndex, lngValue) {
  18070. // Call this once our translation has returned.
  18071. var loadComplete = function(err, data) {
  18072. if (err) {
  18073. errors = errors || [];
  18074. errors.push(err);
  18075. }
  18076. store[lngValue] = store[lngValue] || {};
  18077. store[lngValue][nsValue] = data;
  18078. todo--; // wait for all done befor callback
  18079. if (todo === 0) cb(errors, store);
  18080. };
  18081. if(typeof options.customLoad == 'function'){
  18082. // Use the specified custom callback.
  18083. options.customLoad(lngValue, nsValue, options, loadComplete);
  18084. } else {
  18085. //~ // Use our inbuilt sync.
  18086. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  18087. }
  18088. });
  18089. });
  18090. } else {
  18091. // Call this once our translation has returned.
  18092. var loadComplete = function(err, data) {
  18093. cb(null, data);
  18094. };
  18095. if(typeof options.customLoad == 'function'){
  18096. // Use the specified custom callback.
  18097. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  18098. } else {
  18099. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  18100. // load all needed stuff once
  18101. f.ajax({
  18102. url: url,
  18103. success: function(data, status, xhr) {
  18104. f.log('loaded: ' + url);
  18105. loadComplete(null, data);
  18106. },
  18107. error : function(xhr, status, error) {
  18108. f.log('failed loading: ' + url);
  18109. loadComplete('failed loading resource.json error: ' + error);
  18110. },
  18111. dataType: "json",
  18112. async : options.getAsync
  18113. });
  18114. }
  18115. }
  18116. },
  18117. _fetchOne: function(lng, ns, options, done) {
  18118. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  18119. f.ajax({
  18120. url: url,
  18121. success: function(data, status, xhr) {
  18122. f.log('loaded: ' + url);
  18123. done(null, data);
  18124. },
  18125. error : function(xhr, status, error) {
  18126. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  18127. // file loaded but invalid json, stop waste time !
  18128. f.error('There is a typo in: ' + url);
  18129. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  18130. f.log('Does not exist: ' + url);
  18131. } else {
  18132. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  18133. f.log(theStatus + ' when loading ' + url);
  18134. }
  18135. done(error, {});
  18136. },
  18137. dataType: "json",
  18138. async : options.getAsync
  18139. });
  18140. },
  18141. postMissing: function(lng, ns, key, defaultValue, lngs) {
  18142. var payload = {};
  18143. payload[key] = defaultValue;
  18144. var urls = [];
  18145. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  18146. for (var i = 0; i < o.fallbackLng.length; i++) {
  18147. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  18148. }
  18149. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  18150. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  18151. } else if (o.sendMissingTo === 'all') {
  18152. for (var i = 0, l = lngs.length; i < l; i++) {
  18153. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  18154. }
  18155. }
  18156. for (var y = 0, len = urls.length; y < len; y++) {
  18157. var item = urls[y];
  18158. f.ajax({
  18159. url: item.url,
  18160. type: o.sendType,
  18161. data: payload,
  18162. success: function(data, status, xhr) {
  18163. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18164. // add key to resStore
  18165. var keys = key.split('.');
  18166. var x = 0;
  18167. var value = resStore[item.lng][ns];
  18168. while (keys[x]) {
  18169. if (x === keys.length - 1) {
  18170. value = value[keys[x]] = defaultValue;
  18171. } else {
  18172. value = value[keys[x]] = value[keys[x]] || {};
  18173. }
  18174. x++;
  18175. }
  18176. },
  18177. error : function(xhr, status, error) {
  18178. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18179. },
  18180. dataType: "json",
  18181. async : o.postAsync
  18182. });
  18183. }
  18184. },
  18185. reload: reload
  18186. };
  18187. // defaults
  18188. var o = {
  18189. lng: undefined,
  18190. load: 'all',
  18191. preload: [],
  18192. lowerCaseLng: false,
  18193. returnObjectTrees: false,
  18194. fallbackLng: ['dev'],
  18195. fallbackNS: [],
  18196. detectLngQS: 'setLng',
  18197. detectLngFromLocalStorage: false,
  18198. ns: 'translation',
  18199. fallbackOnNull: true,
  18200. fallbackOnEmpty: false,
  18201. fallbackToDefaultNS: false,
  18202. nsseparator: ':',
  18203. keyseparator: '.',
  18204. selectorAttr: 'data-i18n',
  18205. debug: false,
  18206. resGetPath: 'locales/__lng__/__ns__.json',
  18207. resPostPath: 'locales/add/__lng__/__ns__',
  18208. getAsync: true,
  18209. postAsync: true,
  18210. resStore: undefined,
  18211. useLocalStorage: false,
  18212. localStorageExpirationTime: 7*24*60*60*1000,
  18213. dynamicLoad: false,
  18214. sendMissing: false,
  18215. sendMissingTo: 'fallback', // current | all
  18216. sendType: 'POST',
  18217. interpolationPrefix: '__',
  18218. interpolationSuffix: '__',
  18219. defaultVariables: false,
  18220. reusePrefix: '$t(',
  18221. reuseSuffix: ')',
  18222. pluralSuffix: '_plural',
  18223. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18224. contextNotFound: ['context_not_found', Math.random()].join(''),
  18225. escapeInterpolation: false,
  18226. indefiniteSuffix: '_indefinite',
  18227. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18228. setJqueryExt: true,
  18229. defaultValueFromContent: true,
  18230. useDataAttrOptions: false,
  18231. cookieExpirationTime: undefined,
  18232. useCookie: true,
  18233. cookieName: 'i18next',
  18234. cookieDomain: undefined,
  18235. objectTreeKeyHandler: undefined,
  18236. postProcess: undefined,
  18237. parseMissingKey: undefined,
  18238. missingKeyHandler: sync.postMissing,
  18239. shortcutFunction: 'sprintf' // or: defaultValue
  18240. };
  18241. function _extend(target, source) {
  18242. if (!source || typeof source === 'function') {
  18243. return target;
  18244. }
  18245. for (var attr in source) { target[attr] = source[attr]; }
  18246. return target;
  18247. }
  18248. function _deepExtend(target, source) {
  18249. for (var prop in source)
  18250. if (prop in target)
  18251. _deepExtend(target[prop], source[prop]);
  18252. else
  18253. target[prop] = source[prop];
  18254. return target;
  18255. }
  18256. function _each(object, callback, args) {
  18257. var name, i = 0,
  18258. length = object.length,
  18259. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18260. if (args) {
  18261. if (isObj) {
  18262. for (name in object) {
  18263. if (callback.apply(object[name], args) === false) {
  18264. break;
  18265. }
  18266. }
  18267. } else {
  18268. for ( ; i < length; ) {
  18269. if (callback.apply(object[i++], args) === false) {
  18270. break;
  18271. }
  18272. }
  18273. }
  18274. // A special, fast, case for the most common use of each
  18275. } else {
  18276. if (isObj) {
  18277. for (name in object) {
  18278. if (callback.call(object[name], name, object[name]) === false) {
  18279. break;
  18280. }
  18281. }
  18282. } else {
  18283. for ( ; i < length; ) {
  18284. if (callback.call(object[i], i, object[i++]) === false) {
  18285. break;
  18286. }
  18287. }
  18288. }
  18289. }
  18290. return object;
  18291. }
  18292. var _entityMap = {
  18293. "&": "&amp;",
  18294. "<": "&lt;",
  18295. ">": "&gt;",
  18296. '"': '&quot;',
  18297. "'": '&#39;',
  18298. "/": '&#x2F;'
  18299. };
  18300. function _escape(data) {
  18301. if (typeof data === 'string') {
  18302. return data.replace(/[&<>"'\/]/g, function (s) {
  18303. return _entityMap[s];
  18304. });
  18305. }else{
  18306. return data;
  18307. }
  18308. }
  18309. function _ajax(options) {
  18310. // v0.5.0 of https://github.com/goloroden/http.js
  18311. var getXhr = function (callback) {
  18312. // Use the native XHR object if the browser supports it.
  18313. if (window.XMLHttpRequest) {
  18314. return callback(null, new XMLHttpRequest());
  18315. } else if (window.ActiveXObject) {
  18316. // In Internet Explorer check for ActiveX versions of the XHR object.
  18317. try {
  18318. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18319. } catch (e) {
  18320. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18321. }
  18322. }
  18323. // If no XHR support was found, throw an error.
  18324. return callback(new Error());
  18325. };
  18326. var encodeUsingUrlEncoding = function (data) {
  18327. if(typeof data === 'string') {
  18328. return data;
  18329. }
  18330. var result = [];
  18331. for(var dataItem in data) {
  18332. if(data.hasOwnProperty(dataItem)) {
  18333. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18334. }
  18335. }
  18336. return result.join('&');
  18337. };
  18338. var utf8 = function (text) {
  18339. text = text.replace(/\r\n/g, '\n');
  18340. var result = '';
  18341. for(var i = 0; i < text.length; i++) {
  18342. var c = text.charCodeAt(i);
  18343. if(c < 128) {
  18344. result += String.fromCharCode(c);
  18345. } else if((c > 127) && (c < 2048)) {
  18346. result += String.fromCharCode((c >> 6) | 192);
  18347. result += String.fromCharCode((c & 63) | 128);
  18348. } else {
  18349. result += String.fromCharCode((c >> 12) | 224);
  18350. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18351. result += String.fromCharCode((c & 63) | 128);
  18352. }
  18353. }
  18354. return result;
  18355. };
  18356. var base64 = function (text) {
  18357. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18358. text = utf8(text);
  18359. var result = '',
  18360. chr1, chr2, chr3,
  18361. enc1, enc2, enc3, enc4,
  18362. i = 0;
  18363. do {
  18364. chr1 = text.charCodeAt(i++);
  18365. chr2 = text.charCodeAt(i++);
  18366. chr3 = text.charCodeAt(i++);
  18367. enc1 = chr1 >> 2;
  18368. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18369. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18370. enc4 = chr3 & 63;
  18371. if(isNaN(chr2)) {
  18372. enc3 = enc4 = 64;
  18373. } else if(isNaN(chr3)) {
  18374. enc4 = 64;
  18375. }
  18376. result +=
  18377. keyStr.charAt(enc1) +
  18378. keyStr.charAt(enc2) +
  18379. keyStr.charAt(enc3) +
  18380. keyStr.charAt(enc4);
  18381. chr1 = chr2 = chr3 = '';
  18382. enc1 = enc2 = enc3 = enc4 = '';
  18383. } while(i < text.length);
  18384. return result;
  18385. };
  18386. var mergeHeaders = function () {
  18387. // Use the first header object as base.
  18388. var result = arguments[0];
  18389. // Iterate through the remaining header objects and add them.
  18390. for(var i = 1; i < arguments.length; i++) {
  18391. var currentHeaders = arguments[i];
  18392. for(var header in currentHeaders) {
  18393. if(currentHeaders.hasOwnProperty(header)) {
  18394. result[header] = currentHeaders[header];
  18395. }
  18396. }
  18397. }
  18398. // Return the merged headers.
  18399. return result;
  18400. };
  18401. var ajax = function (method, url, options, callback) {
  18402. // Adjust parameters.
  18403. if(typeof options === 'function') {
  18404. callback = options;
  18405. options = {};
  18406. }
  18407. // Set default parameter values.
  18408. options.cache = options.cache || false;
  18409. options.data = options.data || {};
  18410. options.headers = options.headers || {};
  18411. options.jsonp = options.jsonp || false;
  18412. options.async = options.async === undefined ? true : options.async;
  18413. // Merge the various header objects.
  18414. var headers = mergeHeaders({
  18415. 'accept': '*/*',
  18416. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18417. }, ajax.headers, options.headers);
  18418. // Encode the data according to the content-type.
  18419. var payload;
  18420. if (headers['content-type'] === 'application/json') {
  18421. payload = JSON.stringify(options.data);
  18422. } else {
  18423. payload = encodeUsingUrlEncoding(options.data);
  18424. }
  18425. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18426. // if neccessary.
  18427. if(method === 'GET') {
  18428. // Setup the query string.
  18429. var queryString = [];
  18430. if(payload) {
  18431. queryString.push(payload);
  18432. payload = null;
  18433. }
  18434. // Handle caching.
  18435. if(!options.cache) {
  18436. queryString.push('_=' + (new Date()).getTime());
  18437. }
  18438. // If neccessary prepare the query string for a JSONP call.
  18439. if(options.jsonp) {
  18440. queryString.push('callback=' + options.jsonp);
  18441. queryString.push('jsonp=' + options.jsonp);
  18442. }
  18443. // Merge the query string and attach it to the url.
  18444. queryString = queryString.join('&');
  18445. if (queryString.length > 1) {
  18446. if (url.indexOf('?') > -1) {
  18447. url += '&' + queryString;
  18448. } else {
  18449. url += '?' + queryString;
  18450. }
  18451. }
  18452. // Make a JSONP call if neccessary.
  18453. if(options.jsonp) {
  18454. var head = document.getElementsByTagName('head')[0];
  18455. var script = document.createElement('script');
  18456. script.type = 'text/javascript';
  18457. script.src = url;
  18458. head.appendChild(script);
  18459. return;
  18460. }
  18461. }
  18462. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18463. getXhr(function (err, xhr) {
  18464. if(err) return callback(err);
  18465. // Open the request.
  18466. xhr.open(method, url, options.async);
  18467. // Set the request headers.
  18468. for(var header in headers) {
  18469. if(headers.hasOwnProperty(header)) {
  18470. xhr.setRequestHeader(header, headers[header]);
  18471. }
  18472. }
  18473. // Handle the request events.
  18474. xhr.onreadystatechange = function () {
  18475. if(xhr.readyState === 4) {
  18476. var data = xhr.responseText || '';
  18477. // If no callback is given, return.
  18478. if(!callback) {
  18479. return;
  18480. }
  18481. // Return an object that provides access to the data as text and JSON.
  18482. callback(xhr.status, {
  18483. text: function () {
  18484. return data;
  18485. },
  18486. json: function () {
  18487. try {
  18488. return JSON.parse(data)
  18489. } catch (e) {
  18490. f.error('Can not parse JSON. URL: ' + url);
  18491. return {};
  18492. }
  18493. }
  18494. });
  18495. }
  18496. };
  18497. // Actually send the XHR request.
  18498. xhr.send(payload);
  18499. });
  18500. };
  18501. // Define the external interface.
  18502. var http = {
  18503. authBasic: function (username, password) {
  18504. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18505. },
  18506. connect: function (url, options, callback) {
  18507. return ajax('CONNECT', url, options, callback);
  18508. },
  18509. del: function (url, options, callback) {
  18510. return ajax('DELETE', url, options, callback);
  18511. },
  18512. get: function (url, options, callback) {
  18513. return ajax('GET', url, options, callback);
  18514. },
  18515. head: function (url, options, callback) {
  18516. return ajax('HEAD', url, options, callback);
  18517. },
  18518. headers: function (headers) {
  18519. ajax.headers = headers || {};
  18520. },
  18521. isAllowed: function (url, verb, callback) {
  18522. this.options(url, function (status, data) {
  18523. callback(data.text().indexOf(verb) !== -1);
  18524. });
  18525. },
  18526. options: function (url, options, callback) {
  18527. return ajax('OPTIONS', url, options, callback);
  18528. },
  18529. patch: function (url, options, callback) {
  18530. return ajax('PATCH', url, options, callback);
  18531. },
  18532. post: function (url, options, callback) {
  18533. return ajax('POST', url, options, callback);
  18534. },
  18535. put: function (url, options, callback) {
  18536. return ajax('PUT', url, options, callback);
  18537. },
  18538. trace: function (url, options, callback) {
  18539. return ajax('TRACE', url, options, callback);
  18540. }
  18541. };
  18542. var methode = options.type ? options.type.toLowerCase() : 'get';
  18543. http[methode](options.url, options, function (status, data) {
  18544. // file: protocol always gives status code 0, so check for data
  18545. if (status === 200 || (status === 0 && data.text())) {
  18546. options.success(data.json(), status, null);
  18547. } else {
  18548. options.error(data.text(), status, null);
  18549. }
  18550. });
  18551. }
  18552. var _cookie = {
  18553. create: function(name,value,minutes,domain) {
  18554. var expires;
  18555. if (minutes) {
  18556. var date = new Date();
  18557. date.setTime(date.getTime()+(minutes*60*1000));
  18558. expires = "; expires="+date.toGMTString();
  18559. }
  18560. else expires = "";
  18561. domain = (domain)? "domain="+domain+";" : "";
  18562. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18563. },
  18564. read: function(name) {
  18565. var nameEQ = name + "=";
  18566. var ca = document.cookie.split(';');
  18567. for(var i=0;i < ca.length;i++) {
  18568. var c = ca[i];
  18569. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18570. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18571. }
  18572. return null;
  18573. },
  18574. remove: function(name) {
  18575. this.create(name,"",-1);
  18576. }
  18577. };
  18578. var cookie_noop = {
  18579. create: function(name,value,minutes,domain) {},
  18580. read: function(name) { return null; },
  18581. remove: function(name) {}
  18582. };
  18583. // move dependent functions to a container so that
  18584. // they can be overriden easier in no jquery environment (node.js)
  18585. var f = {
  18586. extend: $ ? $.extend : _extend,
  18587. deepExtend: _deepExtend,
  18588. each: $ ? $.each : _each,
  18589. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18590. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18591. detectLanguage: detectLanguage,
  18592. escape: _escape,
  18593. log: function(str) {
  18594. if (o.debug && typeof console !== "undefined") console.log(str);
  18595. },
  18596. error: function(str) {
  18597. if (typeof console !== "undefined") console.error(str);
  18598. },
  18599. getCountyIndexOfLng: function(lng) {
  18600. var lng_index = 0;
  18601. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18602. return lng_index;
  18603. },
  18604. toLanguages: function(lng) {
  18605. var log = this.log;
  18606. function applyCase(l) {
  18607. var ret = l;
  18608. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18609. var parts = l.split('-');
  18610. ret = o.lowerCaseLng ?
  18611. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18612. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18613. } else {
  18614. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18615. }
  18616. return ret;
  18617. }
  18618. var languages = [];
  18619. var whitelist = o.lngWhitelist || false;
  18620. var addLanguage = function(language){
  18621. //reject langs not whitelisted
  18622. if(!whitelist || whitelist.indexOf(language) > -1){
  18623. languages.push(language);
  18624. }else{
  18625. log('rejecting non-whitelisted language: ' + language);
  18626. }
  18627. };
  18628. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18629. var parts = lng.split('-');
  18630. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18631. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18632. } else {
  18633. addLanguage(applyCase(lng));
  18634. }
  18635. for (var i = 0; i < o.fallbackLng.length; i++) {
  18636. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18637. }
  18638. return languages;
  18639. },
  18640. regexEscape: function(str) {
  18641. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18642. },
  18643. regexReplacementEscape: function(strOrFn) {
  18644. if (typeof strOrFn === 'string') {
  18645. return strOrFn.replace(/\$/g, "$$$$");
  18646. } else {
  18647. return strOrFn;
  18648. }
  18649. },
  18650. localStorage: {
  18651. setItem: function(key, value) {
  18652. if (window.localStorage) {
  18653. try {
  18654. window.localStorage.setItem(key, value);
  18655. } catch (e) {
  18656. f.log('failed to set value for key "' + key + '" to localStorage.');
  18657. }
  18658. }
  18659. }
  18660. }
  18661. };
  18662. function init(options, cb) {
  18663. if (typeof options === 'function') {
  18664. cb = options;
  18665. options = {};
  18666. }
  18667. options = options || {};
  18668. // override defaults with passed in options
  18669. f.extend(o, options);
  18670. delete o.fixLng; /* passed in each time */
  18671. // override functions: .log(), .detectLanguage(), etc
  18672. if (o.functions) {
  18673. delete o.functions;
  18674. f.extend(f, options.functions);
  18675. }
  18676. // create namespace object if namespace is passed in as string
  18677. if (typeof o.ns == 'string') {
  18678. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18679. }
  18680. // fallback namespaces
  18681. if (typeof o.fallbackNS == 'string') {
  18682. o.fallbackNS = [o.fallbackNS];
  18683. }
  18684. // fallback languages
  18685. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18686. o.fallbackLng = [o.fallbackLng];
  18687. }
  18688. // escape prefix/suffix
  18689. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18690. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18691. if (!o.lng) o.lng = f.detectLanguage();
  18692. languages = f.toLanguages(o.lng);
  18693. currentLng = languages[0];
  18694. f.log('currentLng set to: ' + currentLng);
  18695. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18696. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18697. }
  18698. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18699. f.localStorage.setItem('i18next_lng', currentLng);
  18700. }
  18701. var lngTranslate = translate;
  18702. if (options.fixLng) {
  18703. lngTranslate = function(key, options) {
  18704. options = options || {};
  18705. options.lng = options.lng || lngTranslate.lng;
  18706. return translate(key, options);
  18707. };
  18708. lngTranslate.lng = currentLng;
  18709. }
  18710. pluralExtensions.setCurrentLng(currentLng);
  18711. // add JQuery extensions
  18712. if ($ && o.setJqueryExt) addJqueryFunct();
  18713. // jQuery deferred
  18714. var deferred;
  18715. if ($ && $.Deferred) {
  18716. deferred = $.Deferred();
  18717. }
  18718. // return immidiatly if res are passed in
  18719. if (o.resStore) {
  18720. resStore = o.resStore;
  18721. initialized = true;
  18722. if (cb) cb(lngTranslate);
  18723. if (deferred) deferred.resolve(lngTranslate);
  18724. if (deferred) return deferred.promise();
  18725. return;
  18726. }
  18727. // languages to load
  18728. var lngsToLoad = f.toLanguages(o.lng);
  18729. if (typeof o.preload === 'string') o.preload = [o.preload];
  18730. for (var i = 0, l = o.preload.length; i < l; i++) {
  18731. var pres = f.toLanguages(o.preload[i]);
  18732. for (var y = 0, len = pres.length; y < len; y++) {
  18733. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18734. lngsToLoad.push(pres[y]);
  18735. }
  18736. }
  18737. }
  18738. // else load them
  18739. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18740. resStore = store;
  18741. initialized = true;
  18742. if (cb) cb(lngTranslate);
  18743. if (deferred) deferred.resolve(lngTranslate);
  18744. });
  18745. if (deferred) return deferred.promise();
  18746. }
  18747. function preload(lngs, cb) {
  18748. if (typeof lngs === 'string') lngs = [lngs];
  18749. for (var i = 0, l = lngs.length; i < l; i++) {
  18750. if (o.preload.indexOf(lngs[i]) < 0) {
  18751. o.preload.push(lngs[i]);
  18752. }
  18753. }
  18754. return init(cb);
  18755. }
  18756. function addResourceBundle(lng, ns, resources, deep) {
  18757. if (typeof ns !== 'string') {
  18758. resources = ns;
  18759. ns = o.ns.defaultNs;
  18760. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18761. o.ns.namespaces.push(ns);
  18762. }
  18763. resStore[lng] = resStore[lng] || {};
  18764. resStore[lng][ns] = resStore[lng][ns] || {};
  18765. if (deep) {
  18766. f.deepExtend(resStore[lng][ns], resources);
  18767. } else {
  18768. f.extend(resStore[lng][ns], resources);
  18769. }
  18770. }
  18771. function hasResourceBundle(lng, ns) {
  18772. if (typeof ns !== 'string') {
  18773. ns = o.ns.defaultNs;
  18774. }
  18775. resStore[lng] = resStore[lng] || {};
  18776. var res = resStore[lng][ns] || {};
  18777. var hasValues = false;
  18778. for(var prop in res) {
  18779. if (res.hasOwnProperty(prop)) {
  18780. hasValues = true;
  18781. }
  18782. }
  18783. return hasValues;
  18784. }
  18785. function removeResourceBundle(lng, ns) {
  18786. if (typeof ns !== 'string') {
  18787. ns = o.ns.defaultNs;
  18788. }
  18789. resStore[lng] = resStore[lng] || {};
  18790. resStore[lng][ns] = {};
  18791. }
  18792. function addResource(lng, ns, key, value) {
  18793. if (typeof ns !== 'string') {
  18794. resource = ns;
  18795. ns = o.ns.defaultNs;
  18796. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18797. o.ns.namespaces.push(ns);
  18798. }
  18799. resStore[lng] = resStore[lng] || {};
  18800. resStore[lng][ns] = resStore[lng][ns] || {};
  18801. var keys = key.split(o.keyseparator);
  18802. var x = 0;
  18803. var node = resStore[lng][ns];
  18804. var origRef = node;
  18805. while (keys[x]) {
  18806. if (x == keys.length - 1)
  18807. node[keys[x]] = value;
  18808. else {
  18809. if (node[keys[x]] == null)
  18810. node[keys[x]] = {};
  18811. node = node[keys[x]];
  18812. }
  18813. x++;
  18814. }
  18815. }
  18816. function addResources(lng, ns, resources) {
  18817. if (typeof ns !== 'string') {
  18818. resource = ns;
  18819. ns = o.ns.defaultNs;
  18820. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18821. o.ns.namespaces.push(ns);
  18822. }
  18823. for (var m in resources) {
  18824. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18825. }
  18826. }
  18827. function setDefaultNamespace(ns) {
  18828. o.ns.defaultNs = ns;
  18829. }
  18830. function loadNamespace(namespace, cb) {
  18831. loadNamespaces([namespace], cb);
  18832. }
  18833. function loadNamespaces(namespaces, cb) {
  18834. var opts = {
  18835. dynamicLoad: o.dynamicLoad,
  18836. resGetPath: o.resGetPath,
  18837. getAsync: o.getAsync,
  18838. customLoad: o.customLoad,
  18839. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18840. };
  18841. // languages to load
  18842. var lngsToLoad = f.toLanguages(o.lng);
  18843. if (typeof o.preload === 'string') o.preload = [o.preload];
  18844. for (var i = 0, l = o.preload.length; i < l; i++) {
  18845. var pres = f.toLanguages(o.preload[i]);
  18846. for (var y = 0, len = pres.length; y < len; y++) {
  18847. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18848. lngsToLoad.push(pres[y]);
  18849. }
  18850. }
  18851. }
  18852. // check if we have to load
  18853. var lngNeedLoad = [];
  18854. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18855. var needLoad = false;
  18856. var resSet = resStore[lngsToLoad[a]];
  18857. if (resSet) {
  18858. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18859. if (!resSet[namespaces[b]]) needLoad = true;
  18860. }
  18861. } else {
  18862. needLoad = true;
  18863. }
  18864. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18865. }
  18866. if (lngNeedLoad.length) {
  18867. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18868. var todo = namespaces.length * lngNeedLoad.length;
  18869. // load each file individual
  18870. f.each(namespaces, function(nsIndex, nsValue) {
  18871. // append namespace to namespace array
  18872. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18873. o.ns.namespaces.push(nsValue);
  18874. }
  18875. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18876. resStore[lngValue] = resStore[lngValue] || {};
  18877. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18878. todo--; // wait for all done befor callback
  18879. if (todo === 0 && cb) {
  18880. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18881. cb();
  18882. }
  18883. });
  18884. });
  18885. });
  18886. } else {
  18887. if (cb) cb();
  18888. }
  18889. }
  18890. function setLng(lng, options, cb) {
  18891. if (typeof options === 'function') {
  18892. cb = options;
  18893. options = {};
  18894. } else if (!options) {
  18895. options = {};
  18896. }
  18897. options.lng = lng;
  18898. return init(options, cb);
  18899. }
  18900. function lng() {
  18901. return currentLng;
  18902. }
  18903. function reload(cb) {
  18904. resStore = {};
  18905. setLng(currentLng, cb);
  18906. }
  18907. function addJqueryFunct() {
  18908. // $.t shortcut
  18909. $.t = $.t || translate;
  18910. function parse(ele, key, options) {
  18911. if (key.length === 0) return;
  18912. var attr = 'text';
  18913. if (key.indexOf('[') === 0) {
  18914. var parts = key.split(']');
  18915. key = parts[1];
  18916. attr = parts[0].substr(1, parts[0].length-1);
  18917. }
  18918. if (key.indexOf(';') === key.length-1) {
  18919. key = key.substr(0, key.length-2);
  18920. }
  18921. var optionsToUse;
  18922. if (attr === 'html') {
  18923. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18924. ele.html($.t(key, optionsToUse));
  18925. } else if (attr === 'text') {
  18926. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18927. ele.text($.t(key, optionsToUse));
  18928. } else if (attr === 'prepend') {
  18929. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18930. ele.prepend($.t(key, optionsToUse));
  18931. } else if (attr === 'append') {
  18932. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18933. ele.append($.t(key, optionsToUse));
  18934. } else if (attr.indexOf("data-") === 0) {
  18935. var dataAttr = attr.substr(("data-").length);
  18936. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18937. var translated = $.t(key, optionsToUse);
  18938. //we change into the data cache
  18939. ele.data(dataAttr, translated);
  18940. //we change into the dom
  18941. ele.attr(attr, translated);
  18942. } else {
  18943. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18944. ele.attr(attr, $.t(key, optionsToUse));
  18945. }
  18946. }
  18947. function localize(ele, options) {
  18948. var key = ele.attr(o.selectorAttr);
  18949. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18950. if (!key) return;
  18951. var target = ele
  18952. , targetSelector = ele.data("i18n-target");
  18953. if (targetSelector) {
  18954. target = ele.find(targetSelector) || ele;
  18955. }
  18956. if (!options && o.useDataAttrOptions === true) {
  18957. options = ele.data("i18n-options");
  18958. }
  18959. options = options || {};
  18960. if (key.indexOf(';') >= 0) {
  18961. var keys = key.split(';');
  18962. $.each(keys, function(m, k) {
  18963. if (k !== '') parse(target, k, options);
  18964. });
  18965. } else {
  18966. parse(target, key, options);
  18967. }
  18968. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18969. }
  18970. // fn
  18971. $.fn.i18n = function (options) {
  18972. return this.each(function() {
  18973. // localize element itself
  18974. localize($(this), options);
  18975. // localize childs
  18976. var elements = $(this).find('[' + o.selectorAttr + ']');
  18977. elements.each(function() {
  18978. localize($(this), options);
  18979. });
  18980. });
  18981. };
  18982. }
  18983. function applyReplacement(str, replacementHash, nestedKey, options) {
  18984. if (!str) return str;
  18985. options = options || replacementHash; // first call uses replacement hash combined with options
  18986. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18987. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18988. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18989. , unEscapingSuffix = 'HTML'+suffix;
  18990. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18991. f.each(hash, function(key, value) {
  18992. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18993. if (typeof value === 'object' && value !== null) {
  18994. str = applyReplacement(str, value, nextKey, options);
  18995. } else {
  18996. if (options.escapeInterpolation || o.escapeInterpolation) {
  18997. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18998. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18999. } else {
  19000. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  19001. }
  19002. // str = options.escapeInterpolation;
  19003. }
  19004. });
  19005. return str;
  19006. }
  19007. // append it to functions
  19008. f.applyReplacement = applyReplacement;
  19009. function applyReuse(translated, options) {
  19010. var comma = ',';
  19011. var options_open = '{';
  19012. var options_close = '}';
  19013. var opts = f.extend({}, options);
  19014. delete opts.postProcess;
  19015. while (translated.indexOf(o.reusePrefix) != -1) {
  19016. replacementCounter++;
  19017. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  19018. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  19019. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  19020. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  19021. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  19022. if (index_of_end_of_closing <= index_of_opening) {
  19023. f.error('there is an missing closing in following translation value', translated);
  19024. return '';
  19025. }
  19026. if (token_without_symbols.indexOf(comma) != -1) {
  19027. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  19028. 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) {
  19029. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  19030. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  19031. try {
  19032. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  19033. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  19034. } catch (e) {
  19035. }
  19036. }
  19037. }
  19038. var translated_token = _translate(token_without_symbols, opts);
  19039. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  19040. }
  19041. return translated;
  19042. }
  19043. function hasContext(options) {
  19044. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  19045. }
  19046. function needsPlural(options, lng) {
  19047. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  19048. }
  19049. function needsIndefiniteArticle(options) {
  19050. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  19051. }
  19052. function exists(key, options) {
  19053. options = options || {};
  19054. var notFound = _getDefaultValue(key, options)
  19055. , found = _find(key, options);
  19056. return found !== undefined || found === notFound;
  19057. }
  19058. function translate(key, options) {
  19059. options = options || {};
  19060. if (!initialized) {
  19061. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  19062. return options.defaultValue || '';
  19063. };
  19064. replacementCounter = 0;
  19065. return _translate.apply(null, arguments);
  19066. }
  19067. function _getDefaultValue(key, options) {
  19068. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  19069. }
  19070. function _injectSprintfProcessor() {
  19071. var values = [];
  19072. // mh: build array from second argument onwards
  19073. for (var i = 1; i < arguments.length; i++) {
  19074. values.push(arguments[i]);
  19075. }
  19076. return {
  19077. postProcess: 'sprintf',
  19078. sprintf: values
  19079. };
  19080. }
  19081. function _translate(potentialKeys, options) {
  19082. if (options && typeof options !== 'object') {
  19083. if (o.shortcutFunction === 'sprintf') {
  19084. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  19085. options = _injectSprintfProcessor.apply(null, arguments);
  19086. } else if (o.shortcutFunction === 'defaultValue') {
  19087. options = {
  19088. defaultValue: options
  19089. }
  19090. }
  19091. } else {
  19092. options = options || {};
  19093. }
  19094. if (typeof o.defaultVariables === 'object') {
  19095. options = f.extend({}, o.defaultVariables, options);
  19096. }
  19097. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  19098. if (typeof potentialKeys === 'string') {
  19099. potentialKeys = [potentialKeys];
  19100. }
  19101. var key = potentialKeys[0];
  19102. if (potentialKeys.length > 1) {
  19103. for (var i = 0; i < potentialKeys.length; i++) {
  19104. key = potentialKeys[i];
  19105. if (exists(key, options)) {
  19106. break;
  19107. }
  19108. }
  19109. }
  19110. var notFound = _getDefaultValue(key, options)
  19111. , found = _find(key, options)
  19112. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  19113. , ns = options.ns || o.ns.defaultNs
  19114. , parts;
  19115. // split ns and key
  19116. if (key.indexOf(o.nsseparator) > -1) {
  19117. parts = key.split(o.nsseparator);
  19118. ns = parts[0];
  19119. key = parts[1];
  19120. }
  19121. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  19122. if (options.lng) {
  19123. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  19124. } else {
  19125. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  19126. }
  19127. }
  19128. var postProcessor = options.postProcess || o.postProcess;
  19129. if (found !== undefined && postProcessor) {
  19130. if (postProcessors[postProcessor]) {
  19131. found = postProcessors[postProcessor](found, key, options);
  19132. }
  19133. }
  19134. // process notFound if function exists
  19135. var splitNotFound = notFound;
  19136. if (notFound.indexOf(o.nsseparator) > -1) {
  19137. parts = notFound.split(o.nsseparator);
  19138. splitNotFound = parts[1];
  19139. }
  19140. if (splitNotFound === key && o.parseMissingKey) {
  19141. notFound = o.parseMissingKey(notFound);
  19142. }
  19143. if (found === undefined) {
  19144. notFound = applyReplacement(notFound, options);
  19145. notFound = applyReuse(notFound, options);
  19146. if (postProcessor && postProcessors[postProcessor]) {
  19147. var val = _getDefaultValue(key, options);
  19148. found = postProcessors[postProcessor](val, key, options);
  19149. }
  19150. }
  19151. return (found !== undefined) ? found : notFound;
  19152. }
  19153. function _find(key, options) {
  19154. options = options || {};
  19155. var optionWithoutCount, translated
  19156. , notFound = _getDefaultValue(key, options)
  19157. , lngs = languages;
  19158. if (!resStore) { return notFound; } // no resStore to translate from
  19159. // CI mode
  19160. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19161. // passed in lng
  19162. if (options.lngs) lngs = options.lngs;
  19163. if (options.lng) {
  19164. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19165. if (!resStore[lngs[0]]) {
  19166. var oldAsync = o.getAsync;
  19167. o.getAsync = false;
  19168. i18n.sync.load(lngs, o, function(err, store) {
  19169. f.extend(resStore, store);
  19170. o.getAsync = oldAsync;
  19171. });
  19172. }
  19173. }
  19174. var ns = options.ns || o.ns.defaultNs;
  19175. if (key.indexOf(o.nsseparator) > -1) {
  19176. var parts = key.split(o.nsseparator);
  19177. ns = parts[0];
  19178. key = parts[1];
  19179. }
  19180. if (hasContext(options)) {
  19181. optionWithoutCount = f.extend({}, options);
  19182. delete optionWithoutCount.context;
  19183. optionWithoutCount.defaultValue = o.contextNotFound;
  19184. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19185. translated = translate(contextKey, optionWithoutCount);
  19186. if (translated != o.contextNotFound) {
  19187. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19188. } // else continue translation with original/nonContext key
  19189. }
  19190. if (needsPlural(options, lngs[0])) {
  19191. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19192. delete optionWithoutCount.count;
  19193. delete optionWithoutCount.lng;
  19194. optionWithoutCount.defaultValue = o.pluralNotFound;
  19195. var pluralKey;
  19196. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19197. pluralKey = ns + o.nsseparator + key;
  19198. } else {
  19199. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19200. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19201. if (pluralExtension >= 0) {
  19202. pluralKey = pluralKey + '_' + pluralExtension;
  19203. } else if (pluralExtension === 1) {
  19204. pluralKey = ns + o.nsseparator + key; // singular
  19205. }
  19206. }
  19207. translated = translate(pluralKey, optionWithoutCount);
  19208. if (translated != o.pluralNotFound) {
  19209. return applyReplacement(translated, {
  19210. count: options.count,
  19211. interpolationPrefix: options.interpolationPrefix,
  19212. interpolationSuffix: options.interpolationSuffix
  19213. }); // apply replacement for count only
  19214. } else if (lngs.length > 1) {
  19215. // remove failed lng
  19216. var clone = lngs.slice();
  19217. clone.shift();
  19218. options = f.extend(options, { lngs: clone });
  19219. delete options.lng;
  19220. // retry with fallbacks
  19221. translated = translate(ns + o.nsseparator + key, options);
  19222. if (translated != o.pluralNotFound) return translated;
  19223. } else {
  19224. return translated;
  19225. }
  19226. }
  19227. if (needsIndefiniteArticle(options)) {
  19228. var optionsWithoutIndef = f.extend({}, options);
  19229. delete optionsWithoutIndef.indefinite_article;
  19230. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19231. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19232. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19233. translated = translate(indefiniteKey, optionsWithoutIndef);
  19234. if (translated != o.indefiniteNotFound) {
  19235. return translated;
  19236. }
  19237. }
  19238. var found;
  19239. var keys = key.split(o.keyseparator);
  19240. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19241. if (found !== undefined) break;
  19242. var l = lngs[i];
  19243. var x = 0;
  19244. var value = resStore[l] && resStore[l][ns];
  19245. while (keys[x]) {
  19246. value = value && value[keys[x]];
  19247. x++;
  19248. }
  19249. if (value !== undefined) {
  19250. var valueType = Object.prototype.toString.apply(value);
  19251. if (typeof value === 'string') {
  19252. value = applyReplacement(value, options);
  19253. value = applyReuse(value, options);
  19254. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19255. value = value.join('\n');
  19256. value = applyReplacement(value, options);
  19257. value = applyReuse(value, options);
  19258. } else if (value === null && o.fallbackOnNull === true) {
  19259. value = undefined;
  19260. } else if (value !== null) {
  19261. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19262. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19263. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19264. } else {
  19265. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19266. 'returned an object instead of string.';
  19267. f.log(value);
  19268. }
  19269. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19270. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19271. f.each(value, function(m) {
  19272. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19273. });
  19274. value = copy;
  19275. }
  19276. }
  19277. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19278. value = undefined;
  19279. found = value;
  19280. }
  19281. }
  19282. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19283. // set flag for fallback lookup - avoid recursion
  19284. options.isFallbackLookup = true;
  19285. if (o.fallbackNS.length) {
  19286. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19287. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19288. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19289. /* compare value without namespace */
  19290. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19291. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19292. if (foundValue !== notFoundValue) break;
  19293. }
  19294. }
  19295. } else {
  19296. found = _find(key, options); // fallback to default NS
  19297. }
  19298. options.isFallbackLookup = false;
  19299. }
  19300. return found;
  19301. }
  19302. function detectLanguage() {
  19303. var detectedLng;
  19304. var whitelist = o.lngWhitelist || [];
  19305. var userLngChoices = [];
  19306. // get from qs
  19307. var qsParm = [];
  19308. if (typeof window !== 'undefined') {
  19309. (function() {
  19310. var query = window.location.search.substring(1);
  19311. var params = query.split('&');
  19312. for (var i=0; i<params.length; i++) {
  19313. var pos = params[i].indexOf('=');
  19314. if (pos > 0) {
  19315. var key = params[i].substring(0,pos);
  19316. if (key == o.detectLngQS) {
  19317. userLngChoices.push(params[i].substring(pos+1));
  19318. }
  19319. }
  19320. }
  19321. })();
  19322. }
  19323. // get from cookie
  19324. if (o.useCookie && typeof document !== 'undefined') {
  19325. var c = f.cookie.read(o.cookieName);
  19326. if (c) userLngChoices.push(c);
  19327. }
  19328. // get from localStorage
  19329. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19330. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19331. }
  19332. // get from navigator
  19333. if (typeof navigator !== 'undefined') {
  19334. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19335. for (var i=0;i<navigator.languages.length;i++) {
  19336. userLngChoices.push(navigator.languages[i]);
  19337. }
  19338. }
  19339. if (navigator.userLanguage) {
  19340. userLngChoices.push(navigator.userLanguage);
  19341. }
  19342. if (navigator.language) {
  19343. userLngChoices.push(navigator.language);
  19344. }
  19345. }
  19346. (function() {
  19347. for (var i=0;i<userLngChoices.length;i++) {
  19348. var lng = userLngChoices[i];
  19349. if (lng.indexOf('-') > -1) {
  19350. var parts = lng.split('-');
  19351. lng = o.lowerCaseLng ?
  19352. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19353. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19354. }
  19355. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19356. detectedLng = lng;
  19357. break;
  19358. }
  19359. }
  19360. })();
  19361. //fallback
  19362. if (!detectedLng){
  19363. detectedLng = o.fallbackLng[0];
  19364. }
  19365. return detectedLng;
  19366. }
  19367. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19368. /* [code, name, numbers, pluralsType] */
  19369. var _rules = [
  19370. ["ach", "Acholi", [1,2], 1],
  19371. ["af", "Afrikaans",[1,2], 2],
  19372. ["ak", "Akan", [1,2], 1],
  19373. ["am", "Amharic", [1,2], 1],
  19374. ["an", "Aragonese",[1,2], 2],
  19375. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19376. ["arn", "Mapudungun",[1,2], 1],
  19377. ["ast", "Asturian", [1,2], 2],
  19378. ["ay", "Aymará", [1], 3],
  19379. ["az", "Azerbaijani",[1,2],2],
  19380. ["be", "Belarusian",[1,2,5],4],
  19381. ["bg", "Bulgarian",[1,2], 2],
  19382. ["bn", "Bengali", [1,2], 2],
  19383. ["bo", "Tibetan", [1], 3],
  19384. ["br", "Breton", [1,2], 1],
  19385. ["bs", "Bosnian", [1,2,5],4],
  19386. ["ca", "Catalan", [1,2], 2],
  19387. ["cgg", "Chiga", [1], 3],
  19388. ["cs", "Czech", [1,2,5],6],
  19389. ["csb", "Kashubian",[1,2,5],7],
  19390. ["cy", "Welsh", [1,2,3,8],8],
  19391. ["da", "Danish", [1,2], 2],
  19392. ["de", "German", [1,2], 2],
  19393. ["dev", "Development Fallback", [1,2], 2],
  19394. ["dz", "Dzongkha", [1], 3],
  19395. ["el", "Greek", [1,2], 2],
  19396. ["en", "English", [1,2], 2],
  19397. ["eo", "Esperanto",[1,2], 2],
  19398. ["es", "Spanish", [1,2], 2],
  19399. ["es_ar","Argentinean Spanish", [1,2], 2],
  19400. ["et", "Estonian", [1,2], 2],
  19401. ["eu", "Basque", [1,2], 2],
  19402. ["fa", "Persian", [1], 3],
  19403. ["fi", "Finnish", [1,2], 2],
  19404. ["fil", "Filipino", [1,2], 1],
  19405. ["fo", "Faroese", [1,2], 2],
  19406. ["fr", "French", [1,2], 9],
  19407. ["fur", "Friulian", [1,2], 2],
  19408. ["fy", "Frisian", [1,2], 2],
  19409. ["ga", "Irish", [1,2,3,7,11],10],
  19410. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19411. ["gl", "Galician", [1,2], 2],
  19412. ["gu", "Gujarati", [1,2], 2],
  19413. ["gun", "Gun", [1,2], 1],
  19414. ["ha", "Hausa", [1,2], 2],
  19415. ["he", "Hebrew", [1,2], 2],
  19416. ["hi", "Hindi", [1,2], 2],
  19417. ["hr", "Croatian", [1,2,5],4],
  19418. ["hu", "Hungarian",[1,2], 2],
  19419. ["hy", "Armenian", [1,2], 2],
  19420. ["ia", "Interlingua",[1,2],2],
  19421. ["id", "Indonesian",[1], 3],
  19422. ["is", "Icelandic",[1,2], 12],
  19423. ["it", "Italian", [1,2], 2],
  19424. ["ja", "Japanese", [1], 3],
  19425. ["jbo", "Lojban", [1], 3],
  19426. ["jv", "Javanese", [0,1], 13],
  19427. ["ka", "Georgian", [1], 3],
  19428. ["kk", "Kazakh", [1], 3],
  19429. ["km", "Khmer", [1], 3],
  19430. ["kn", "Kannada", [1,2], 2],
  19431. ["ko", "Korean", [1], 3],
  19432. ["ku", "Kurdish", [1,2], 2],
  19433. ["kw", "Cornish", [1,2,3,4],14],
  19434. ["ky", "Kyrgyz", [1], 3],
  19435. ["lb", "Letzeburgesch",[1,2],2],
  19436. ["ln", "Lingala", [1,2], 1],
  19437. ["lo", "Lao", [1], 3],
  19438. ["lt", "Lithuanian",[1,2,10],15],
  19439. ["lv", "Latvian", [1,2,0],16],
  19440. ["mai", "Maithili", [1,2], 2],
  19441. ["mfe", "Mauritian Creole",[1,2],1],
  19442. ["mg", "Malagasy", [1,2], 1],
  19443. ["mi", "Maori", [1,2], 1],
  19444. ["mk", "Macedonian",[1,2],17],
  19445. ["ml", "Malayalam",[1,2], 2],
  19446. ["mn", "Mongolian",[1,2], 2],
  19447. ["mnk", "Mandinka", [0,1,2],18],
  19448. ["mr", "Marathi", [1,2], 2],
  19449. ["ms", "Malay", [1], 3],
  19450. ["mt", "Maltese", [1,2,11,20],19],
  19451. ["nah", "Nahuatl", [1,2], 2],
  19452. ["nap", "Neapolitan",[1,2], 2],
  19453. ["nb", "Norwegian Bokmal",[1,2],2],
  19454. ["ne", "Nepali", [1,2], 2],
  19455. ["nl", "Dutch", [1,2], 2],
  19456. ["nn", "Norwegian Nynorsk",[1,2],2],
  19457. ["no", "Norwegian",[1,2], 2],
  19458. ["nso", "Northern Sotho",[1,2],2],
  19459. ["oc", "Occitan", [1,2], 1],
  19460. ["or", "Oriya", [2,1], 2],
  19461. ["pa", "Punjabi", [1,2], 2],
  19462. ["pap", "Papiamento",[1,2], 2],
  19463. ["pl", "Polish", [1,2,5],7],
  19464. ["pms", "Piemontese",[1,2], 2],
  19465. ["ps", "Pashto", [1,2], 2],
  19466. ["pt", "Portuguese",[1,2], 2],
  19467. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19468. ["rm", "Romansh", [1,2], 2],
  19469. ["ro", "Romanian", [1,2,20],20],
  19470. ["ru", "Russian", [1,2,5],4],
  19471. ["sah", "Yakut", [1], 3],
  19472. ["sco", "Scots", [1,2], 2],
  19473. ["se", "Northern Sami",[1,2], 2],
  19474. ["si", "Sinhala", [1,2], 2],
  19475. ["sk", "Slovak", [1,2,5],6],
  19476. ["sl", "Slovenian",[5,1,2,3],21],
  19477. ["so", "Somali", [1,2], 2],
  19478. ["son", "Songhay", [1,2], 2],
  19479. ["sq", "Albanian", [1,2], 2],
  19480. ["sr", "Serbian", [1,2,5],4],
  19481. ["su", "Sundanese",[1], 3],
  19482. ["sv", "Swedish", [1,2], 2],
  19483. ["sw", "Swahili", [1,2], 2],
  19484. ["ta", "Tamil", [1,2], 2],
  19485. ["te", "Telugu", [1,2], 2],
  19486. ["tg", "Tajik", [1,2], 1],
  19487. ["th", "Thai", [1], 3],
  19488. ["ti", "Tigrinya", [1,2], 1],
  19489. ["tk", "Turkmen", [1,2], 2],
  19490. ["tr", "Turkish", [1,2], 1],
  19491. ["tt", "Tatar", [1], 3],
  19492. ["ug", "Uyghur", [1], 3],
  19493. ["uk", "Ukrainian",[1,2,5],4],
  19494. ["ur", "Urdu", [1,2], 2],
  19495. ["uz", "Uzbek", [1,2], 1],
  19496. ["vi", "Vietnamese",[1], 3],
  19497. ["wa", "Walloon", [1,2], 1],
  19498. ["wo", "Wolof", [1], 3],
  19499. ["yo", "Yoruba", [1,2], 2],
  19500. ["zh", "Chinese", [1], 3]
  19501. ];
  19502. var _rulesPluralsTypes = {
  19503. 1: function(n) {return Number(n > 1);},
  19504. 2: function(n) {return Number(n != 1);},
  19505. 3: function(n) {return 0;},
  19506. 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);},
  19507. 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);},
  19508. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19509. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19510. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19511. 9: function(n) {return Number(n >= 2);},
  19512. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19513. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19514. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19515. 13: function(n) {return Number(n !== 0);},
  19516. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19517. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19518. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19519. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19520. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19521. 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);},
  19522. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19523. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19524. };
  19525. var pluralExtensions = {
  19526. rules: (function () {
  19527. var l, rules = {};
  19528. for (l=_rules.length; l-- ;) {
  19529. rules[_rules[l][0]] = {
  19530. name: _rules[l][1],
  19531. numbers: _rules[l][2],
  19532. plurals: _rulesPluralsTypes[_rules[l][3]]
  19533. }
  19534. }
  19535. return rules;
  19536. }()),
  19537. // you can add your own pluralExtensions
  19538. addRule: function(lng, obj) {
  19539. pluralExtensions.rules[lng] = obj;
  19540. },
  19541. setCurrentLng: function(lng) {
  19542. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19543. var parts = lng.split('-');
  19544. pluralExtensions.currentRule = {
  19545. lng: lng,
  19546. rule: pluralExtensions.rules[parts[0]]
  19547. };
  19548. }
  19549. },
  19550. needsPlural: function(lng, count) {
  19551. var parts = lng.split('-');
  19552. var ext;
  19553. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19554. ext = pluralExtensions.currentRule.rule;
  19555. } else {
  19556. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19557. }
  19558. if (ext && ext.numbers.length <= 1) {
  19559. return false;
  19560. } else {
  19561. return this.get(lng, count) !== 1;
  19562. }
  19563. },
  19564. get: function(lng, count) {
  19565. var parts = lng.split('-');
  19566. function getResult(l, c) {
  19567. var ext;
  19568. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19569. ext = pluralExtensions.currentRule.rule;
  19570. } else {
  19571. ext = pluralExtensions.rules[l];
  19572. }
  19573. if (ext) {
  19574. var i;
  19575. if (ext.noAbs) {
  19576. i = ext.plurals(c);
  19577. } else {
  19578. i = ext.plurals(Math.abs(c));
  19579. }
  19580. var number = ext.numbers[i];
  19581. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19582. if (number === 2) {
  19583. number = -1; // regular plural
  19584. } else if (number === 1) {
  19585. number = 1; // singular
  19586. }
  19587. }//console.log(count + '-' + number);
  19588. return number;
  19589. } else {
  19590. return c === 1 ? '1' : '-1';
  19591. }
  19592. }
  19593. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19594. }
  19595. };
  19596. var postProcessors = {};
  19597. var addPostProcessor = function(name, fc) {
  19598. postProcessors[name] = fc;
  19599. };
  19600. // sprintf support
  19601. var sprintf = (function() {
  19602. function get_type(variable) {
  19603. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19604. }
  19605. function str_repeat(input, multiplier) {
  19606. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19607. return output.join('');
  19608. }
  19609. var str_format = function() {
  19610. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19611. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19612. }
  19613. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19614. };
  19615. str_format.format = function(parse_tree, argv) {
  19616. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19617. for (i = 0; i < tree_length; i++) {
  19618. node_type = get_type(parse_tree[i]);
  19619. if (node_type === 'string') {
  19620. output.push(parse_tree[i]);
  19621. }
  19622. else if (node_type === 'array') {
  19623. match = parse_tree[i]; // convenience purposes only
  19624. if (match[2]) { // keyword argument
  19625. arg = argv[cursor];
  19626. for (k = 0; k < match[2].length; k++) {
  19627. if (!arg.hasOwnProperty(match[2][k])) {
  19628. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19629. }
  19630. arg = arg[match[2][k]];
  19631. }
  19632. }
  19633. else if (match[1]) { // positional argument (explicit)
  19634. arg = argv[match[1]];
  19635. }
  19636. else { // positional argument (implicit)
  19637. arg = argv[cursor++];
  19638. }
  19639. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19640. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19641. }
  19642. switch (match[8]) {
  19643. case 'b': arg = arg.toString(2); break;
  19644. case 'c': arg = String.fromCharCode(arg); break;
  19645. case 'd': arg = parseInt(arg, 10); break;
  19646. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19647. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19648. case 'o': arg = arg.toString(8); break;
  19649. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19650. case 'u': arg = Math.abs(arg); break;
  19651. case 'x': arg = arg.toString(16); break;
  19652. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19653. }
  19654. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19655. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19656. pad_length = match[6] - String(arg).length;
  19657. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19658. output.push(match[5] ? arg + pad : pad + arg);
  19659. }
  19660. }
  19661. return output.join('');
  19662. };
  19663. str_format.cache = {};
  19664. str_format.parse = function(fmt) {
  19665. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19666. while (_fmt) {
  19667. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19668. parse_tree.push(match[0]);
  19669. }
  19670. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19671. parse_tree.push('%');
  19672. }
  19673. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19674. if (match[2]) {
  19675. arg_names |= 1;
  19676. var field_list = [], replacement_field = match[2], field_match = [];
  19677. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19678. field_list.push(field_match[1]);
  19679. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19680. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19681. field_list.push(field_match[1]);
  19682. }
  19683. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19684. field_list.push(field_match[1]);
  19685. }
  19686. else {
  19687. throw('[sprintf] huh?');
  19688. }
  19689. }
  19690. }
  19691. else {
  19692. throw('[sprintf] huh?');
  19693. }
  19694. match[2] = field_list;
  19695. }
  19696. else {
  19697. arg_names |= 2;
  19698. }
  19699. if (arg_names === 3) {
  19700. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19701. }
  19702. parse_tree.push(match);
  19703. }
  19704. else {
  19705. throw('[sprintf] huh?');
  19706. }
  19707. _fmt = _fmt.substring(match[0].length);
  19708. }
  19709. return parse_tree;
  19710. };
  19711. return str_format;
  19712. })();
  19713. var vsprintf = function(fmt, argv) {
  19714. argv.unshift(fmt);
  19715. return sprintf.apply(null, argv);
  19716. };
  19717. addPostProcessor("sprintf", function(val, key, opts) {
  19718. if (!opts.sprintf) return val;
  19719. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19720. return vsprintf(val, opts.sprintf);
  19721. } else if (typeof opts.sprintf === 'object') {
  19722. return sprintf(val, opts.sprintf);
  19723. }
  19724. return val;
  19725. });
  19726. // public api interface
  19727. i18n.init = init;
  19728. i18n.setLng = setLng;
  19729. i18n.preload = preload;
  19730. i18n.addResourceBundle = addResourceBundle;
  19731. i18n.hasResourceBundle = hasResourceBundle;
  19732. i18n.addResource = addResource;
  19733. i18n.addResources = addResources;
  19734. i18n.removeResourceBundle = removeResourceBundle;
  19735. i18n.loadNamespace = loadNamespace;
  19736. i18n.loadNamespaces = loadNamespaces;
  19737. i18n.setDefaultNamespace = setDefaultNamespace;
  19738. i18n.t = translate;
  19739. i18n.translate = translate;
  19740. i18n.exists = exists;
  19741. i18n.detectLanguage = f.detectLanguage;
  19742. i18n.pluralExtensions = pluralExtensions;
  19743. i18n.sync = sync;
  19744. i18n.functions = f;
  19745. i18n.lng = lng;
  19746. i18n.addPostProcessor = addPostProcessor;
  19747. i18n.options = o;
  19748. })();
  19749. },{"jquery":"jquery"}],71:[function(require,module,exports){
  19750. // Top level file is just a mixin of submodules & constants
  19751. 'use strict';
  19752. var assign = require('./lib/utils/common').assign;
  19753. var deflate = require('./lib/deflate');
  19754. var inflate = require('./lib/inflate');
  19755. var constants = require('./lib/zlib/constants');
  19756. var pako = {};
  19757. assign(pako, deflate, inflate, constants);
  19758. module.exports = pako;
  19759. },{"./lib/deflate":72,"./lib/inflate":73,"./lib/utils/common":74,"./lib/zlib/constants":77}],72:[function(require,module,exports){
  19760. 'use strict';
  19761. var zlib_deflate = require('./zlib/deflate.js');
  19762. var utils = require('./utils/common');
  19763. var strings = require('./utils/strings');
  19764. var msg = require('./zlib/messages');
  19765. var zstream = require('./zlib/zstream');
  19766. var toString = Object.prototype.toString;
  19767. /* Public constants ==========================================================*/
  19768. /* ===========================================================================*/
  19769. var Z_NO_FLUSH = 0;
  19770. var Z_FINISH = 4;
  19771. var Z_OK = 0;
  19772. var Z_STREAM_END = 1;
  19773. var Z_SYNC_FLUSH = 2;
  19774. var Z_DEFAULT_COMPRESSION = -1;
  19775. var Z_DEFAULT_STRATEGY = 0;
  19776. var Z_DEFLATED = 8;
  19777. /* ===========================================================================*/
  19778. /**
  19779. * class Deflate
  19780. *
  19781. * Generic JS-style wrapper for zlib calls. If you don't need
  19782. * streaming behaviour - use more simple functions: [[deflate]],
  19783. * [[deflateRaw]] and [[gzip]].
  19784. **/
  19785. /* internal
  19786. * Deflate.chunks -> Array
  19787. *
  19788. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19789. **/
  19790. /**
  19791. * Deflate.result -> Uint8Array|Array
  19792. *
  19793. * Compressed result, generated by default [[Deflate#onData]]
  19794. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19795. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19796. * push a chunk with explicit flush (call [[Deflate#push]] with
  19797. * `Z_SYNC_FLUSH` param).
  19798. **/
  19799. /**
  19800. * Deflate.err -> Number
  19801. *
  19802. * Error code after deflate finished. 0 (Z_OK) on success.
  19803. * You will not need it in real life, because deflate errors
  19804. * are possible only on wrong options or bad `onData` / `onEnd`
  19805. * custom handlers.
  19806. **/
  19807. /**
  19808. * Deflate.msg -> String
  19809. *
  19810. * Error message, if [[Deflate.err]] != 0
  19811. **/
  19812. /**
  19813. * new Deflate(options)
  19814. * - options (Object): zlib deflate options.
  19815. *
  19816. * Creates new deflator instance with specified params. Throws exception
  19817. * on bad params. Supported options:
  19818. *
  19819. * - `level`
  19820. * - `windowBits`
  19821. * - `memLevel`
  19822. * - `strategy`
  19823. *
  19824. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19825. * for more information on these.
  19826. *
  19827. * Additional options, for internal needs:
  19828. *
  19829. * - `chunkSize` - size of generated data chunks (16K by default)
  19830. * - `raw` (Boolean) - do raw deflate
  19831. * - `gzip` (Boolean) - create gzip wrapper
  19832. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19833. * (each char code [0..255])
  19834. * - `header` (Object) - custom header for gzip
  19835. * - `text` (Boolean) - true if compressed data believed to be text
  19836. * - `time` (Number) - modification time, unix timestamp
  19837. * - `os` (Number) - operation system code
  19838. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19839. * - `name` (String) - file name (binary string)
  19840. * - `comment` (String) - comment (binary string)
  19841. * - `hcrc` (Boolean) - true if header crc should be added
  19842. *
  19843. * ##### Example:
  19844. *
  19845. * ```javascript
  19846. * var pako = require('pako')
  19847. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19848. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19849. *
  19850. * var deflate = new pako.Deflate({ level: 3});
  19851. *
  19852. * deflate.push(chunk1, false);
  19853. * deflate.push(chunk2, true); // true -> last chunk
  19854. *
  19855. * if (deflate.err) { throw new Error(deflate.err); }
  19856. *
  19857. * console.log(deflate.result);
  19858. * ```
  19859. **/
  19860. var Deflate = function(options) {
  19861. this.options = utils.assign({
  19862. level: Z_DEFAULT_COMPRESSION,
  19863. method: Z_DEFLATED,
  19864. chunkSize: 16384,
  19865. windowBits: 15,
  19866. memLevel: 8,
  19867. strategy: Z_DEFAULT_STRATEGY,
  19868. to: ''
  19869. }, options || {});
  19870. var opt = this.options;
  19871. if (opt.raw && (opt.windowBits > 0)) {
  19872. opt.windowBits = -opt.windowBits;
  19873. }
  19874. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19875. opt.windowBits += 16;
  19876. }
  19877. this.err = 0; // error code, if happens (0 = Z_OK)
  19878. this.msg = ''; // error message
  19879. this.ended = false; // used to avoid multiple onEnd() calls
  19880. this.chunks = []; // chunks of compressed data
  19881. this.strm = new zstream();
  19882. this.strm.avail_out = 0;
  19883. var status = zlib_deflate.deflateInit2(
  19884. this.strm,
  19885. opt.level,
  19886. opt.method,
  19887. opt.windowBits,
  19888. opt.memLevel,
  19889. opt.strategy
  19890. );
  19891. if (status !== Z_OK) {
  19892. throw new Error(msg[status]);
  19893. }
  19894. if (opt.header) {
  19895. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19896. }
  19897. };
  19898. /**
  19899. * Deflate#push(data[, mode]) -> Boolean
  19900. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19901. * converted to utf8 byte sequence.
  19902. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19903. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19904. *
  19905. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19906. * new compressed chunks. Returns `true` on success. The last data block must have
  19907. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19908. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19909. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19910. *
  19911. * On fail call [[Deflate#onEnd]] with error code and return false.
  19912. *
  19913. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19914. * array format is detected automatically). Also, don't skip last param and always
  19915. * use the same type in your code (boolean or number). That will improve JS speed.
  19916. *
  19917. * For regular `Array`-s make sure all elements are [0..255].
  19918. *
  19919. * ##### Example
  19920. *
  19921. * ```javascript
  19922. * push(chunk, false); // push one of data chunks
  19923. * ...
  19924. * push(chunk, true); // push last chunk
  19925. * ```
  19926. **/
  19927. Deflate.prototype.push = function(data, mode) {
  19928. var strm = this.strm;
  19929. var chunkSize = this.options.chunkSize;
  19930. var status, _mode;
  19931. if (this.ended) { return false; }
  19932. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19933. // Convert data if needed
  19934. if (typeof data === 'string') {
  19935. // If we need to compress text, change encoding to utf8.
  19936. strm.input = strings.string2buf(data);
  19937. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19938. strm.input = new Uint8Array(data);
  19939. } else {
  19940. strm.input = data;
  19941. }
  19942. strm.next_in = 0;
  19943. strm.avail_in = strm.input.length;
  19944. do {
  19945. if (strm.avail_out === 0) {
  19946. strm.output = new utils.Buf8(chunkSize);
  19947. strm.next_out = 0;
  19948. strm.avail_out = chunkSize;
  19949. }
  19950. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19951. if (status !== Z_STREAM_END && status !== Z_OK) {
  19952. this.onEnd(status);
  19953. this.ended = true;
  19954. return false;
  19955. }
  19956. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19957. if (this.options.to === 'string') {
  19958. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19959. } else {
  19960. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19961. }
  19962. }
  19963. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19964. // Finalize on the last chunk.
  19965. if (_mode === Z_FINISH) {
  19966. status = zlib_deflate.deflateEnd(this.strm);
  19967. this.onEnd(status);
  19968. this.ended = true;
  19969. return status === Z_OK;
  19970. }
  19971. // callback interim results if Z_SYNC_FLUSH.
  19972. if (_mode === Z_SYNC_FLUSH) {
  19973. this.onEnd(Z_OK);
  19974. strm.avail_out = 0;
  19975. return true;
  19976. }
  19977. return true;
  19978. };
  19979. /**
  19980. * Deflate#onData(chunk) -> Void
  19981. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19982. * on js engine support. When string output requested, each chunk
  19983. * will be string.
  19984. *
  19985. * By default, stores data blocks in `chunks[]` property and glue
  19986. * those in `onEnd`. Override this handler, if you need another behaviour.
  19987. **/
  19988. Deflate.prototype.onData = function(chunk) {
  19989. this.chunks.push(chunk);
  19990. };
  19991. /**
  19992. * Deflate#onEnd(status) -> Void
  19993. * - status (Number): deflate status. 0 (Z_OK) on success,
  19994. * other if not.
  19995. *
  19996. * Called once after you tell deflate that the input stream is
  19997. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19998. * or if an error happened. By default - join collected chunks,
  19999. * free memory and fill `results` / `err` properties.
  20000. **/
  20001. Deflate.prototype.onEnd = function(status) {
  20002. // On success - join
  20003. if (status === Z_OK) {
  20004. if (this.options.to === 'string') {
  20005. this.result = this.chunks.join('');
  20006. } else {
  20007. this.result = utils.flattenChunks(this.chunks);
  20008. }
  20009. }
  20010. this.chunks = [];
  20011. this.err = status;
  20012. this.msg = this.strm.msg;
  20013. };
  20014. /**
  20015. * deflate(data[, options]) -> Uint8Array|Array|String
  20016. * - data (Uint8Array|Array|String): input data to compress.
  20017. * - options (Object): zlib deflate options.
  20018. *
  20019. * Compress `data` with deflate alrorythm and `options`.
  20020. *
  20021. * Supported options are:
  20022. *
  20023. * - level
  20024. * - windowBits
  20025. * - memLevel
  20026. * - strategy
  20027. *
  20028. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20029. * for more information on these.
  20030. *
  20031. * Sugar (options):
  20032. *
  20033. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20034. * negative windowBits implicitly.
  20035. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20036. * (each char code [0..255])
  20037. *
  20038. * ##### Example:
  20039. *
  20040. * ```javascript
  20041. * var pako = require('pako')
  20042. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  20043. *
  20044. * console.log(pako.deflate(data));
  20045. * ```
  20046. **/
  20047. function deflate(input, options) {
  20048. var deflator = new Deflate(options);
  20049. deflator.push(input, true);
  20050. // That will never happens, if you don't cheat with options :)
  20051. if (deflator.err) { throw deflator.msg; }
  20052. return deflator.result;
  20053. }
  20054. /**
  20055. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  20056. * - data (Uint8Array|Array|String): input data to compress.
  20057. * - options (Object): zlib deflate options.
  20058. *
  20059. * The same as [[deflate]], but creates raw data, without wrapper
  20060. * (header and adler32 crc).
  20061. **/
  20062. function deflateRaw(input, options) {
  20063. options = options || {};
  20064. options.raw = true;
  20065. return deflate(input, options);
  20066. }
  20067. /**
  20068. * gzip(data[, options]) -> Uint8Array|Array|String
  20069. * - data (Uint8Array|Array|String): input data to compress.
  20070. * - options (Object): zlib deflate options.
  20071. *
  20072. * The same as [[deflate]], but create gzip wrapper instead of
  20073. * deflate one.
  20074. **/
  20075. function gzip(input, options) {
  20076. options = options || {};
  20077. options.gzip = true;
  20078. return deflate(input, options);
  20079. }
  20080. exports.Deflate = Deflate;
  20081. exports.deflate = deflate;
  20082. exports.deflateRaw = deflateRaw;
  20083. exports.gzip = gzip;
  20084. },{"./utils/common":74,"./utils/strings":75,"./zlib/deflate.js":79,"./zlib/messages":84,"./zlib/zstream":86}],73:[function(require,module,exports){
  20085. 'use strict';
  20086. var zlib_inflate = require('./zlib/inflate.js');
  20087. var utils = require('./utils/common');
  20088. var strings = require('./utils/strings');
  20089. var c = require('./zlib/constants');
  20090. var msg = require('./zlib/messages');
  20091. var zstream = require('./zlib/zstream');
  20092. var gzheader = require('./zlib/gzheader');
  20093. var toString = Object.prototype.toString;
  20094. /**
  20095. * class Inflate
  20096. *
  20097. * Generic JS-style wrapper for zlib calls. If you don't need
  20098. * streaming behaviour - use more simple functions: [[inflate]]
  20099. * and [[inflateRaw]].
  20100. **/
  20101. /* internal
  20102. * inflate.chunks -> Array
  20103. *
  20104. * Chunks of output data, if [[Inflate#onData]] not overriden.
  20105. **/
  20106. /**
  20107. * Inflate.result -> Uint8Array|Array|String
  20108. *
  20109. * Uncompressed result, generated by default [[Inflate#onData]]
  20110. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  20111. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  20112. * push a chunk with explicit flush (call [[Inflate#push]] with
  20113. * `Z_SYNC_FLUSH` param).
  20114. **/
  20115. /**
  20116. * Inflate.err -> Number
  20117. *
  20118. * Error code after inflate finished. 0 (Z_OK) on success.
  20119. * Should be checked if broken data possible.
  20120. **/
  20121. /**
  20122. * Inflate.msg -> String
  20123. *
  20124. * Error message, if [[Inflate.err]] != 0
  20125. **/
  20126. /**
  20127. * new Inflate(options)
  20128. * - options (Object): zlib inflate options.
  20129. *
  20130. * Creates new inflator instance with specified params. Throws exception
  20131. * on bad params. Supported options:
  20132. *
  20133. * - `windowBits`
  20134. *
  20135. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20136. * for more information on these.
  20137. *
  20138. * Additional options, for internal needs:
  20139. *
  20140. * - `chunkSize` - size of generated data chunks (16K by default)
  20141. * - `raw` (Boolean) - do raw inflate
  20142. * - `to` (String) - if equal to 'string', then result will be converted
  20143. * from utf8 to utf16 (javascript) string. When string output requested,
  20144. * chunk length can differ from `chunkSize`, depending on content.
  20145. *
  20146. * By default, when no options set, autodetect deflate/gzip data format via
  20147. * wrapper header.
  20148. *
  20149. * ##### Example:
  20150. *
  20151. * ```javascript
  20152. * var pako = require('pako')
  20153. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20154. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20155. *
  20156. * var inflate = new pako.Inflate({ level: 3});
  20157. *
  20158. * inflate.push(chunk1, false);
  20159. * inflate.push(chunk2, true); // true -> last chunk
  20160. *
  20161. * if (inflate.err) { throw new Error(inflate.err); }
  20162. *
  20163. * console.log(inflate.result);
  20164. * ```
  20165. **/
  20166. var Inflate = function(options) {
  20167. this.options = utils.assign({
  20168. chunkSize: 16384,
  20169. windowBits: 0,
  20170. to: ''
  20171. }, options || {});
  20172. var opt = this.options;
  20173. // Force window size for `raw` data, if not set directly,
  20174. // because we have no header for autodetect.
  20175. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20176. opt.windowBits = -opt.windowBits;
  20177. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20178. }
  20179. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20180. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20181. !(options && options.windowBits)) {
  20182. opt.windowBits += 32;
  20183. }
  20184. // Gzip header has no info about windows size, we can do autodetect only
  20185. // for deflate. So, if window size not set, force it to max when gzip possible
  20186. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20187. // bit 3 (16) -> gzipped data
  20188. // bit 4 (32) -> autodetect gzip/deflate
  20189. if ((opt.windowBits & 15) === 0) {
  20190. opt.windowBits |= 15;
  20191. }
  20192. }
  20193. this.err = 0; // error code, if happens (0 = Z_OK)
  20194. this.msg = ''; // error message
  20195. this.ended = false; // used to avoid multiple onEnd() calls
  20196. this.chunks = []; // chunks of compressed data
  20197. this.strm = new zstream();
  20198. this.strm.avail_out = 0;
  20199. var status = zlib_inflate.inflateInit2(
  20200. this.strm,
  20201. opt.windowBits
  20202. );
  20203. if (status !== c.Z_OK) {
  20204. throw new Error(msg[status]);
  20205. }
  20206. this.header = new gzheader();
  20207. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20208. };
  20209. /**
  20210. * Inflate#push(data[, mode]) -> Boolean
  20211. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20212. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20213. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20214. *
  20215. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20216. * new output chunks. Returns `true` on success. The last data block must have
  20217. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20218. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20219. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20220. *
  20221. * On fail call [[Inflate#onEnd]] with error code and return false.
  20222. *
  20223. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20224. * format is detected automatically). Also, don't skip last param and always
  20225. * use the same type in your code (boolean or number). That will improve JS speed.
  20226. *
  20227. * For regular `Array`-s make sure all elements are [0..255].
  20228. *
  20229. * ##### Example
  20230. *
  20231. * ```javascript
  20232. * push(chunk, false); // push one of data chunks
  20233. * ...
  20234. * push(chunk, true); // push last chunk
  20235. * ```
  20236. **/
  20237. Inflate.prototype.push = function(data, mode) {
  20238. var strm = this.strm;
  20239. var chunkSize = this.options.chunkSize;
  20240. var status, _mode;
  20241. var next_out_utf8, tail, utf8str;
  20242. if (this.ended) { return false; }
  20243. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20244. // Convert data if needed
  20245. if (typeof data === 'string') {
  20246. // Only binary strings can be decompressed on practice
  20247. strm.input = strings.binstring2buf(data);
  20248. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20249. strm.input = new Uint8Array(data);
  20250. } else {
  20251. strm.input = data;
  20252. }
  20253. strm.next_in = 0;
  20254. strm.avail_in = strm.input.length;
  20255. do {
  20256. if (strm.avail_out === 0) {
  20257. strm.output = new utils.Buf8(chunkSize);
  20258. strm.next_out = 0;
  20259. strm.avail_out = chunkSize;
  20260. }
  20261. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20262. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20263. this.onEnd(status);
  20264. this.ended = true;
  20265. return false;
  20266. }
  20267. if (strm.next_out) {
  20268. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20269. if (this.options.to === 'string') {
  20270. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20271. tail = strm.next_out - next_out_utf8;
  20272. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20273. // move tail
  20274. strm.next_out = tail;
  20275. strm.avail_out = chunkSize - tail;
  20276. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20277. this.onData(utf8str);
  20278. } else {
  20279. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20280. }
  20281. }
  20282. }
  20283. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20284. if (status === c.Z_STREAM_END) {
  20285. _mode = c.Z_FINISH;
  20286. }
  20287. // Finalize on the last chunk.
  20288. if (_mode === c.Z_FINISH) {
  20289. status = zlib_inflate.inflateEnd(this.strm);
  20290. this.onEnd(status);
  20291. this.ended = true;
  20292. return status === c.Z_OK;
  20293. }
  20294. // callback interim results if Z_SYNC_FLUSH.
  20295. if (_mode === c.Z_SYNC_FLUSH) {
  20296. this.onEnd(c.Z_OK);
  20297. strm.avail_out = 0;
  20298. return true;
  20299. }
  20300. return true;
  20301. };
  20302. /**
  20303. * Inflate#onData(chunk) -> Void
  20304. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20305. * on js engine support. When string output requested, each chunk
  20306. * will be string.
  20307. *
  20308. * By default, stores data blocks in `chunks[]` property and glue
  20309. * those in `onEnd`. Override this handler, if you need another behaviour.
  20310. **/
  20311. Inflate.prototype.onData = function(chunk) {
  20312. this.chunks.push(chunk);
  20313. };
  20314. /**
  20315. * Inflate#onEnd(status) -> Void
  20316. * - status (Number): inflate status. 0 (Z_OK) on success,
  20317. * other if not.
  20318. *
  20319. * Called either after you tell inflate that the input stream is
  20320. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20321. * or if an error happened. By default - join collected chunks,
  20322. * free memory and fill `results` / `err` properties.
  20323. **/
  20324. Inflate.prototype.onEnd = function(status) {
  20325. // On success - join
  20326. if (status === c.Z_OK) {
  20327. if (this.options.to === 'string') {
  20328. // Glue & convert here, until we teach pako to send
  20329. // utf8 alligned strings to onData
  20330. this.result = this.chunks.join('');
  20331. } else {
  20332. this.result = utils.flattenChunks(this.chunks);
  20333. }
  20334. }
  20335. this.chunks = [];
  20336. this.err = status;
  20337. this.msg = this.strm.msg;
  20338. };
  20339. /**
  20340. * inflate(data[, options]) -> Uint8Array|Array|String
  20341. * - data (Uint8Array|Array|String): input data to decompress.
  20342. * - options (Object): zlib inflate options.
  20343. *
  20344. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20345. * format via wrapper header by default. That's why we don't provide
  20346. * separate `ungzip` method.
  20347. *
  20348. * Supported options are:
  20349. *
  20350. * - windowBits
  20351. *
  20352. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20353. * for more information.
  20354. *
  20355. * Sugar (options):
  20356. *
  20357. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20358. * negative windowBits implicitly.
  20359. * - `to` (String) - if equal to 'string', then result will be converted
  20360. * from utf8 to utf16 (javascript) string. When string output requested,
  20361. * chunk length can differ from `chunkSize`, depending on content.
  20362. *
  20363. *
  20364. * ##### Example:
  20365. *
  20366. * ```javascript
  20367. * var pako = require('pako')
  20368. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20369. * , output;
  20370. *
  20371. * try {
  20372. * output = pako.inflate(input);
  20373. * } catch (err)
  20374. * console.log(err);
  20375. * }
  20376. * ```
  20377. **/
  20378. function inflate(input, options) {
  20379. var inflator = new Inflate(options);
  20380. inflator.push(input, true);
  20381. // That will never happens, if you don't cheat with options :)
  20382. if (inflator.err) { throw inflator.msg; }
  20383. return inflator.result;
  20384. }
  20385. /**
  20386. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20387. * - data (Uint8Array|Array|String): input data to decompress.
  20388. * - options (Object): zlib inflate options.
  20389. *
  20390. * The same as [[inflate]], but creates raw data, without wrapper
  20391. * (header and adler32 crc).
  20392. **/
  20393. function inflateRaw(input, options) {
  20394. options = options || {};
  20395. options.raw = true;
  20396. return inflate(input, options);
  20397. }
  20398. /**
  20399. * ungzip(data[, options]) -> Uint8Array|Array|String
  20400. * - data (Uint8Array|Array|String): input data to decompress.
  20401. * - options (Object): zlib inflate options.
  20402. *
  20403. * Just shortcut to [[inflate]], because it autodetects format
  20404. * by header.content. Done for convenience.
  20405. **/
  20406. exports.Inflate = Inflate;
  20407. exports.inflate = inflate;
  20408. exports.inflateRaw = inflateRaw;
  20409. exports.ungzip = inflate;
  20410. },{"./utils/common":74,"./utils/strings":75,"./zlib/constants":77,"./zlib/gzheader":80,"./zlib/inflate.js":82,"./zlib/messages":84,"./zlib/zstream":86}],74:[function(require,module,exports){
  20411. 'use strict';
  20412. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20413. (typeof Uint16Array !== 'undefined') &&
  20414. (typeof Int32Array !== 'undefined');
  20415. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20416. var sources = Array.prototype.slice.call(arguments, 1);
  20417. while (sources.length) {
  20418. var source = sources.shift();
  20419. if (!source) { continue; }
  20420. if (typeof source !== 'object') {
  20421. throw new TypeError(source + 'must be non-object');
  20422. }
  20423. for (var p in source) {
  20424. if (source.hasOwnProperty(p)) {
  20425. obj[p] = source[p];
  20426. }
  20427. }
  20428. }
  20429. return obj;
  20430. };
  20431. // reduce buffer size, avoiding mem copy
  20432. exports.shrinkBuf = function (buf, size) {
  20433. if (buf.length === size) { return buf; }
  20434. if (buf.subarray) { return buf.subarray(0, size); }
  20435. buf.length = size;
  20436. return buf;
  20437. };
  20438. var fnTyped = {
  20439. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20440. if (src.subarray && dest.subarray) {
  20441. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20442. return;
  20443. }
  20444. // Fallback to ordinary array
  20445. for (var i=0; i<len; i++) {
  20446. dest[dest_offs + i] = src[src_offs + i];
  20447. }
  20448. },
  20449. // Join array of chunks to single array.
  20450. flattenChunks: function(chunks) {
  20451. var i, l, len, pos, chunk, result;
  20452. // calculate data length
  20453. len = 0;
  20454. for (i=0, l=chunks.length; i<l; i++) {
  20455. len += chunks[i].length;
  20456. }
  20457. // join chunks
  20458. result = new Uint8Array(len);
  20459. pos = 0;
  20460. for (i=0, l=chunks.length; i<l; i++) {
  20461. chunk = chunks[i];
  20462. result.set(chunk, pos);
  20463. pos += chunk.length;
  20464. }
  20465. return result;
  20466. }
  20467. };
  20468. var fnUntyped = {
  20469. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20470. for (var i=0; i<len; i++) {
  20471. dest[dest_offs + i] = src[src_offs + i];
  20472. }
  20473. },
  20474. // Join array of chunks to single array.
  20475. flattenChunks: function(chunks) {
  20476. return [].concat.apply([], chunks);
  20477. }
  20478. };
  20479. // Enable/Disable typed arrays use, for testing
  20480. //
  20481. exports.setTyped = function (on) {
  20482. if (on) {
  20483. exports.Buf8 = Uint8Array;
  20484. exports.Buf16 = Uint16Array;
  20485. exports.Buf32 = Int32Array;
  20486. exports.assign(exports, fnTyped);
  20487. } else {
  20488. exports.Buf8 = Array;
  20489. exports.Buf16 = Array;
  20490. exports.Buf32 = Array;
  20491. exports.assign(exports, fnUntyped);
  20492. }
  20493. };
  20494. exports.setTyped(TYPED_OK);
  20495. },{}],75:[function(require,module,exports){
  20496. // String encode/decode helpers
  20497. 'use strict';
  20498. var utils = require('./common');
  20499. // Quick check if we can use fast array to bin string conversion
  20500. //
  20501. // - apply(Array) can fail on Android 2.2
  20502. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20503. //
  20504. var STR_APPLY_OK = true;
  20505. var STR_APPLY_UIA_OK = true;
  20506. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20507. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20508. // Table with utf8 lengths (calculated by first byte of sequence)
  20509. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20510. // because max possible codepoint is 0x10ffff
  20511. var _utf8len = new utils.Buf8(256);
  20512. for (var q=0; q<256; q++) {
  20513. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20514. }
  20515. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20516. // convert string to array (typed, when possible)
  20517. exports.string2buf = function (str) {
  20518. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20519. // count binary size
  20520. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20521. c = str.charCodeAt(m_pos);
  20522. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20523. c2 = str.charCodeAt(m_pos+1);
  20524. if ((c2 & 0xfc00) === 0xdc00) {
  20525. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20526. m_pos++;
  20527. }
  20528. }
  20529. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20530. }
  20531. // allocate buffer
  20532. buf = new utils.Buf8(buf_len);
  20533. // convert
  20534. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20535. c = str.charCodeAt(m_pos);
  20536. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20537. c2 = str.charCodeAt(m_pos+1);
  20538. if ((c2 & 0xfc00) === 0xdc00) {
  20539. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20540. m_pos++;
  20541. }
  20542. }
  20543. if (c < 0x80) {
  20544. /* one byte */
  20545. buf[i++] = c;
  20546. } else if (c < 0x800) {
  20547. /* two bytes */
  20548. buf[i++] = 0xC0 | (c >>> 6);
  20549. buf[i++] = 0x80 | (c & 0x3f);
  20550. } else if (c < 0x10000) {
  20551. /* three bytes */
  20552. buf[i++] = 0xE0 | (c >>> 12);
  20553. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20554. buf[i++] = 0x80 | (c & 0x3f);
  20555. } else {
  20556. /* four bytes */
  20557. buf[i++] = 0xf0 | (c >>> 18);
  20558. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20559. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20560. buf[i++] = 0x80 | (c & 0x3f);
  20561. }
  20562. }
  20563. return buf;
  20564. };
  20565. // Helper (used in 2 places)
  20566. function buf2binstring(buf, len) {
  20567. // use fallback for big arrays to avoid stack overflow
  20568. if (len < 65537) {
  20569. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20570. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20571. }
  20572. }
  20573. var result = '';
  20574. for (var i=0; i < len; i++) {
  20575. result += String.fromCharCode(buf[i]);
  20576. }
  20577. return result;
  20578. }
  20579. // Convert byte array to binary string
  20580. exports.buf2binstring = function(buf) {
  20581. return buf2binstring(buf, buf.length);
  20582. };
  20583. // Convert binary string (typed, when possible)
  20584. exports.binstring2buf = function(str) {
  20585. var buf = new utils.Buf8(str.length);
  20586. for (var i=0, len=buf.length; i < len; i++) {
  20587. buf[i] = str.charCodeAt(i);
  20588. }
  20589. return buf;
  20590. };
  20591. // convert array to string
  20592. exports.buf2string = function (buf, max) {
  20593. var i, out, c, c_len;
  20594. var len = max || buf.length;
  20595. // Reserve max possible length (2 words per char)
  20596. // NB: by unknown reasons, Array is significantly faster for
  20597. // String.fromCharCode.apply than Uint16Array.
  20598. var utf16buf = new Array(len*2);
  20599. for (out=0, i=0; i<len;) {
  20600. c = buf[i++];
  20601. // quick process ascii
  20602. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20603. c_len = _utf8len[c];
  20604. // skip 5 & 6 byte codes
  20605. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20606. // apply mask on first byte
  20607. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20608. // join the rest
  20609. while (c_len > 1 && i < len) {
  20610. c = (c << 6) | (buf[i++] & 0x3f);
  20611. c_len--;
  20612. }
  20613. // terminated by end of string?
  20614. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20615. if (c < 0x10000) {
  20616. utf16buf[out++] = c;
  20617. } else {
  20618. c -= 0x10000;
  20619. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20620. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20621. }
  20622. }
  20623. return buf2binstring(utf16buf, out);
  20624. };
  20625. // Calculate max possible position in utf8 buffer,
  20626. // that will not break sequence. If that's not possible
  20627. // - (very small limits) return max size as is.
  20628. //
  20629. // buf[] - utf8 bytes array
  20630. // max - length limit (mandatory);
  20631. exports.utf8border = function(buf, max) {
  20632. var pos;
  20633. max = max || buf.length;
  20634. if (max > buf.length) { max = buf.length; }
  20635. // go back from last position, until start of sequence found
  20636. pos = max-1;
  20637. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20638. // Fuckup - very small and broken sequence,
  20639. // return max, because we should return something anyway.
  20640. if (pos < 0) { return max; }
  20641. // If we came to start of buffer - that means vuffer is too small,
  20642. // return max too.
  20643. if (pos === 0) { return max; }
  20644. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20645. };
  20646. },{"./common":74}],76:[function(require,module,exports){
  20647. 'use strict';
  20648. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20649. // It doesn't worth to make additional optimizationa as in original.
  20650. // Small size is preferable.
  20651. function adler32(adler, buf, len, pos) {
  20652. var s1 = (adler & 0xffff) |0,
  20653. s2 = ((adler >>> 16) & 0xffff) |0,
  20654. n = 0;
  20655. while (len !== 0) {
  20656. // Set limit ~ twice less than 5552, to keep
  20657. // s2 in 31-bits, because we force signed ints.
  20658. // in other case %= will fail.
  20659. n = len > 2000 ? 2000 : len;
  20660. len -= n;
  20661. do {
  20662. s1 = (s1 + buf[pos++]) |0;
  20663. s2 = (s2 + s1) |0;
  20664. } while (--n);
  20665. s1 %= 65521;
  20666. s2 %= 65521;
  20667. }
  20668. return (s1 | (s2 << 16)) |0;
  20669. }
  20670. module.exports = adler32;
  20671. },{}],77:[function(require,module,exports){
  20672. module.exports = {
  20673. /* Allowed flush values; see deflate() and inflate() below for details */
  20674. Z_NO_FLUSH: 0,
  20675. Z_PARTIAL_FLUSH: 1,
  20676. Z_SYNC_FLUSH: 2,
  20677. Z_FULL_FLUSH: 3,
  20678. Z_FINISH: 4,
  20679. Z_BLOCK: 5,
  20680. Z_TREES: 6,
  20681. /* Return codes for the compression/decompression functions. Negative values
  20682. * are errors, positive values are used for special but normal events.
  20683. */
  20684. Z_OK: 0,
  20685. Z_STREAM_END: 1,
  20686. Z_NEED_DICT: 2,
  20687. Z_ERRNO: -1,
  20688. Z_STREAM_ERROR: -2,
  20689. Z_DATA_ERROR: -3,
  20690. //Z_MEM_ERROR: -4,
  20691. Z_BUF_ERROR: -5,
  20692. //Z_VERSION_ERROR: -6,
  20693. /* compression levels */
  20694. Z_NO_COMPRESSION: 0,
  20695. Z_BEST_SPEED: 1,
  20696. Z_BEST_COMPRESSION: 9,
  20697. Z_DEFAULT_COMPRESSION: -1,
  20698. Z_FILTERED: 1,
  20699. Z_HUFFMAN_ONLY: 2,
  20700. Z_RLE: 3,
  20701. Z_FIXED: 4,
  20702. Z_DEFAULT_STRATEGY: 0,
  20703. /* Possible values of the data_type field (though see inflate()) */
  20704. Z_BINARY: 0,
  20705. Z_TEXT: 1,
  20706. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20707. Z_UNKNOWN: 2,
  20708. /* The deflate compression method */
  20709. Z_DEFLATED: 8
  20710. //Z_NULL: null // Use -1 or null inline, depending on var type
  20711. };
  20712. },{}],78:[function(require,module,exports){
  20713. 'use strict';
  20714. // Note: we can't get significant speed boost here.
  20715. // So write code to minimize size - no pregenerated tables
  20716. // and array tools dependencies.
  20717. // Use ordinary array, since untyped makes no boost here
  20718. function makeTable() {
  20719. var c, table = [];
  20720. for (var n =0; n < 256; n++) {
  20721. c = n;
  20722. for (var k =0; k < 8; k++) {
  20723. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20724. }
  20725. table[n] = c;
  20726. }
  20727. return table;
  20728. }
  20729. // Create table on load. Just 255 signed longs. Not a problem.
  20730. var crcTable = makeTable();
  20731. function crc32(crc, buf, len, pos) {
  20732. var t = crcTable,
  20733. end = pos + len;
  20734. crc = crc ^ (-1);
  20735. for (var i = pos; i < end; i++) {
  20736. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20737. }
  20738. return (crc ^ (-1)); // >>> 0;
  20739. }
  20740. module.exports = crc32;
  20741. },{}],79:[function(require,module,exports){
  20742. 'use strict';
  20743. var utils = require('../utils/common');
  20744. var trees = require('./trees');
  20745. var adler32 = require('./adler32');
  20746. var crc32 = require('./crc32');
  20747. var msg = require('./messages');
  20748. /* Public constants ==========================================================*/
  20749. /* ===========================================================================*/
  20750. /* Allowed flush values; see deflate() and inflate() below for details */
  20751. var Z_NO_FLUSH = 0;
  20752. var Z_PARTIAL_FLUSH = 1;
  20753. //var Z_SYNC_FLUSH = 2;
  20754. var Z_FULL_FLUSH = 3;
  20755. var Z_FINISH = 4;
  20756. var Z_BLOCK = 5;
  20757. //var Z_TREES = 6;
  20758. /* Return codes for the compression/decompression functions. Negative values
  20759. * are errors, positive values are used for special but normal events.
  20760. */
  20761. var Z_OK = 0;
  20762. var Z_STREAM_END = 1;
  20763. //var Z_NEED_DICT = 2;
  20764. //var Z_ERRNO = -1;
  20765. var Z_STREAM_ERROR = -2;
  20766. var Z_DATA_ERROR = -3;
  20767. //var Z_MEM_ERROR = -4;
  20768. var Z_BUF_ERROR = -5;
  20769. //var Z_VERSION_ERROR = -6;
  20770. /* compression levels */
  20771. //var Z_NO_COMPRESSION = 0;
  20772. //var Z_BEST_SPEED = 1;
  20773. //var Z_BEST_COMPRESSION = 9;
  20774. var Z_DEFAULT_COMPRESSION = -1;
  20775. var Z_FILTERED = 1;
  20776. var Z_HUFFMAN_ONLY = 2;
  20777. var Z_RLE = 3;
  20778. var Z_FIXED = 4;
  20779. var Z_DEFAULT_STRATEGY = 0;
  20780. /* Possible values of the data_type field (though see inflate()) */
  20781. //var Z_BINARY = 0;
  20782. //var Z_TEXT = 1;
  20783. //var Z_ASCII = 1; // = Z_TEXT
  20784. var Z_UNKNOWN = 2;
  20785. /* The deflate compression method */
  20786. var Z_DEFLATED = 8;
  20787. /*============================================================================*/
  20788. var MAX_MEM_LEVEL = 9;
  20789. /* Maximum value for memLevel in deflateInit2 */
  20790. var MAX_WBITS = 15;
  20791. /* 32K LZ77 window */
  20792. var DEF_MEM_LEVEL = 8;
  20793. var LENGTH_CODES = 29;
  20794. /* number of length codes, not counting the special END_BLOCK code */
  20795. var LITERALS = 256;
  20796. /* number of literal bytes 0..255 */
  20797. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20798. /* number of Literal or Length codes, including the END_BLOCK code */
  20799. var D_CODES = 30;
  20800. /* number of distance codes */
  20801. var BL_CODES = 19;
  20802. /* number of codes used to transfer the bit lengths */
  20803. var HEAP_SIZE = 2*L_CODES + 1;
  20804. /* maximum heap size */
  20805. var MAX_BITS = 15;
  20806. /* All codes must not exceed MAX_BITS bits */
  20807. var MIN_MATCH = 3;
  20808. var MAX_MATCH = 258;
  20809. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20810. var PRESET_DICT = 0x20;
  20811. var INIT_STATE = 42;
  20812. var EXTRA_STATE = 69;
  20813. var NAME_STATE = 73;
  20814. var COMMENT_STATE = 91;
  20815. var HCRC_STATE = 103;
  20816. var BUSY_STATE = 113;
  20817. var FINISH_STATE = 666;
  20818. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20819. var BS_BLOCK_DONE = 2; /* block flush performed */
  20820. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20821. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20822. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20823. function err(strm, errorCode) {
  20824. strm.msg = msg[errorCode];
  20825. return errorCode;
  20826. }
  20827. function rank(f) {
  20828. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20829. }
  20830. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20831. /* =========================================================================
  20832. * Flush as much pending output as possible. All deflate() output goes
  20833. * through this function so some applications may wish to modify it
  20834. * to avoid allocating a large strm->output buffer and copying into it.
  20835. * (See also read_buf()).
  20836. */
  20837. function flush_pending(strm) {
  20838. var s = strm.state;
  20839. //_tr_flush_bits(s);
  20840. var len = s.pending;
  20841. if (len > strm.avail_out) {
  20842. len = strm.avail_out;
  20843. }
  20844. if (len === 0) { return; }
  20845. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20846. strm.next_out += len;
  20847. s.pending_out += len;
  20848. strm.total_out += len;
  20849. strm.avail_out -= len;
  20850. s.pending -= len;
  20851. if (s.pending === 0) {
  20852. s.pending_out = 0;
  20853. }
  20854. }
  20855. function flush_block_only (s, last) {
  20856. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20857. s.block_start = s.strstart;
  20858. flush_pending(s.strm);
  20859. }
  20860. function put_byte(s, b) {
  20861. s.pending_buf[s.pending++] = b;
  20862. }
  20863. /* =========================================================================
  20864. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20865. * IN assertion: the stream state is correct and there is enough room in
  20866. * pending_buf.
  20867. */
  20868. function putShortMSB(s, b) {
  20869. // put_byte(s, (Byte)(b >> 8));
  20870. // put_byte(s, (Byte)(b & 0xff));
  20871. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20872. s.pending_buf[s.pending++] = b & 0xff;
  20873. }
  20874. /* ===========================================================================
  20875. * Read a new buffer from the current input stream, update the adler32
  20876. * and total number of bytes read. All deflate() input goes through
  20877. * this function so some applications may wish to modify it to avoid
  20878. * allocating a large strm->input buffer and copying from it.
  20879. * (See also flush_pending()).
  20880. */
  20881. function read_buf(strm, buf, start, size) {
  20882. var len = strm.avail_in;
  20883. if (len > size) { len = size; }
  20884. if (len === 0) { return 0; }
  20885. strm.avail_in -= len;
  20886. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20887. if (strm.state.wrap === 1) {
  20888. strm.adler = adler32(strm.adler, buf, len, start);
  20889. }
  20890. else if (strm.state.wrap === 2) {
  20891. strm.adler = crc32(strm.adler, buf, len, start);
  20892. }
  20893. strm.next_in += len;
  20894. strm.total_in += len;
  20895. return len;
  20896. }
  20897. /* ===========================================================================
  20898. * Set match_start to the longest match starting at the given string and
  20899. * return its length. Matches shorter or equal to prev_length are discarded,
  20900. * in which case the result is equal to prev_length and match_start is
  20901. * garbage.
  20902. * IN assertions: cur_match is the head of the hash chain for the current
  20903. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20904. * OUT assertion: the match length is not greater than s->lookahead.
  20905. */
  20906. function longest_match(s, cur_match) {
  20907. var chain_length = s.max_chain_length; /* max hash chain length */
  20908. var scan = s.strstart; /* current string */
  20909. var match; /* matched string */
  20910. var len; /* length of current match */
  20911. var best_len = s.prev_length; /* best match length so far */
  20912. var nice_match = s.nice_match; /* stop if match long enough */
  20913. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20914. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20915. var _win = s.window; // shortcut
  20916. var wmask = s.w_mask;
  20917. var prev = s.prev;
  20918. /* Stop when cur_match becomes <= limit. To simplify the code,
  20919. * we prevent matches with the string of window index 0.
  20920. */
  20921. var strend = s.strstart + MAX_MATCH;
  20922. var scan_end1 = _win[scan + best_len - 1];
  20923. var scan_end = _win[scan + best_len];
  20924. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20925. * It is easy to get rid of this optimization if necessary.
  20926. */
  20927. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20928. /* Do not waste too much time if we already have a good match: */
  20929. if (s.prev_length >= s.good_match) {
  20930. chain_length >>= 2;
  20931. }
  20932. /* Do not look for matches beyond the end of the input. This is necessary
  20933. * to make deflate deterministic.
  20934. */
  20935. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20936. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20937. do {
  20938. // Assert(cur_match < s->strstart, "no future");
  20939. match = cur_match;
  20940. /* Skip to next match if the match length cannot increase
  20941. * or if the match length is less than 2. Note that the checks below
  20942. * for insufficient lookahead only occur occasionally for performance
  20943. * reasons. Therefore uninitialized memory will be accessed, and
  20944. * conditional jumps will be made that depend on those values.
  20945. * However the length of the match is limited to the lookahead, so
  20946. * the output of deflate is not affected by the uninitialized values.
  20947. */
  20948. if (_win[match + best_len] !== scan_end ||
  20949. _win[match + best_len - 1] !== scan_end1 ||
  20950. _win[match] !== _win[scan] ||
  20951. _win[++match] !== _win[scan + 1]) {
  20952. continue;
  20953. }
  20954. /* The check at best_len-1 can be removed because it will be made
  20955. * again later. (This heuristic is not always a win.)
  20956. * It is not necessary to compare scan[2] and match[2] since they
  20957. * are always equal when the other bytes match, given that
  20958. * the hash keys are equal and that HASH_BITS >= 8.
  20959. */
  20960. scan += 2;
  20961. match++;
  20962. // Assert(*scan == *match, "match[2]?");
  20963. /* We check for insufficient lookahead only every 8th comparison;
  20964. * the 256th check will be made at strstart+258.
  20965. */
  20966. do {
  20967. /*jshint noempty:false*/
  20968. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20969. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20970. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20971. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20972. scan < strend);
  20973. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20974. len = MAX_MATCH - (strend - scan);
  20975. scan = strend - MAX_MATCH;
  20976. if (len > best_len) {
  20977. s.match_start = cur_match;
  20978. best_len = len;
  20979. if (len >= nice_match) {
  20980. break;
  20981. }
  20982. scan_end1 = _win[scan + best_len - 1];
  20983. scan_end = _win[scan + best_len];
  20984. }
  20985. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20986. if (best_len <= s.lookahead) {
  20987. return best_len;
  20988. }
  20989. return s.lookahead;
  20990. }
  20991. /* ===========================================================================
  20992. * Fill the window when the lookahead becomes insufficient.
  20993. * Updates strstart and lookahead.
  20994. *
  20995. * IN assertion: lookahead < MIN_LOOKAHEAD
  20996. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20997. * At least one byte has been read, or avail_in == 0; reads are
  20998. * performed for at least two bytes (required for the zip translate_eol
  20999. * option -- not supported here).
  21000. */
  21001. function fill_window(s) {
  21002. var _w_size = s.w_size;
  21003. var p, n, m, more, str;
  21004. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  21005. do {
  21006. more = s.window_size - s.lookahead - s.strstart;
  21007. // JS ints have 32 bit, block below not needed
  21008. /* Deal with !@#$% 64K limit: */
  21009. //if (sizeof(int) <= 2) {
  21010. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  21011. // more = wsize;
  21012. //
  21013. // } else if (more == (unsigned)(-1)) {
  21014. // /* Very unlikely, but possible on 16 bit machine if
  21015. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  21016. // */
  21017. // more--;
  21018. // }
  21019. //}
  21020. /* If the window is almost full and there is insufficient lookahead,
  21021. * move the upper half to the lower one to make room in the upper half.
  21022. */
  21023. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  21024. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  21025. s.match_start -= _w_size;
  21026. s.strstart -= _w_size;
  21027. /* we now have strstart >= MAX_DIST */
  21028. s.block_start -= _w_size;
  21029. /* Slide the hash table (could be avoided with 32 bit values
  21030. at the expense of memory usage). We slide even when level == 0
  21031. to keep the hash table consistent if we switch back to level > 0
  21032. later. (Using level 0 permanently is not an optimal usage of
  21033. zlib, so we don't care about this pathological case.)
  21034. */
  21035. n = s.hash_size;
  21036. p = n;
  21037. do {
  21038. m = s.head[--p];
  21039. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  21040. } while (--n);
  21041. n = _w_size;
  21042. p = n;
  21043. do {
  21044. m = s.prev[--p];
  21045. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  21046. /* If n is not on any hash chain, prev[n] is garbage but
  21047. * its value will never be used.
  21048. */
  21049. } while (--n);
  21050. more += _w_size;
  21051. }
  21052. if (s.strm.avail_in === 0) {
  21053. break;
  21054. }
  21055. /* If there was no sliding:
  21056. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  21057. * more == window_size - lookahead - strstart
  21058. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  21059. * => more >= window_size - 2*WSIZE + 2
  21060. * In the BIG_MEM or MMAP case (not yet supported),
  21061. * window_size == input_size + MIN_LOOKAHEAD &&
  21062. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  21063. * Otherwise, window_size == 2*WSIZE so more >= 2.
  21064. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  21065. */
  21066. //Assert(more >= 2, "more < 2");
  21067. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  21068. s.lookahead += n;
  21069. /* Initialize the hash value now that we have some input: */
  21070. if (s.lookahead + s.insert >= MIN_MATCH) {
  21071. str = s.strstart - s.insert;
  21072. s.ins_h = s.window[str];
  21073. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  21074. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  21075. //#if MIN_MATCH != 3
  21076. // Call update_hash() MIN_MATCH-3 more times
  21077. //#endif
  21078. while (s.insert) {
  21079. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21080. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  21081. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21082. s.head[s.ins_h] = str;
  21083. str++;
  21084. s.insert--;
  21085. if (s.lookahead + s.insert < MIN_MATCH) {
  21086. break;
  21087. }
  21088. }
  21089. }
  21090. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  21091. * but this is not important since only literal bytes will be emitted.
  21092. */
  21093. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  21094. /* If the WIN_INIT bytes after the end of the current data have never been
  21095. * written, then zero those bytes in order to avoid memory check reports of
  21096. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  21097. * the longest match routines. Update the high water mark for the next
  21098. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  21099. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  21100. */
  21101. // if (s.high_water < s.window_size) {
  21102. // var curr = s.strstart + s.lookahead;
  21103. // var init = 0;
  21104. //
  21105. // if (s.high_water < curr) {
  21106. // /* Previous high water mark below current data -- zero WIN_INIT
  21107. // * bytes or up to end of window, whichever is less.
  21108. // */
  21109. // init = s.window_size - curr;
  21110. // if (init > WIN_INIT)
  21111. // init = WIN_INIT;
  21112. // zmemzero(s->window + curr, (unsigned)init);
  21113. // s->high_water = curr + init;
  21114. // }
  21115. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  21116. // /* High water mark at or above current data, but below current data
  21117. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  21118. // * to end of window, whichever is less.
  21119. // */
  21120. // init = (ulg)curr + WIN_INIT - s->high_water;
  21121. // if (init > s->window_size - s->high_water)
  21122. // init = s->window_size - s->high_water;
  21123. // zmemzero(s->window + s->high_water, (unsigned)init);
  21124. // s->high_water += init;
  21125. // }
  21126. // }
  21127. //
  21128. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  21129. // "not enough room for search");
  21130. }
  21131. /* ===========================================================================
  21132. * Copy without compression as much as possible from the input stream, return
  21133. * the current block state.
  21134. * This function does not insert new strings in the dictionary since
  21135. * uncompressible data is probably not useful. This function is used
  21136. * only for the level=0 compression option.
  21137. * NOTE: this function should be optimized to avoid extra copying from
  21138. * window to pending_buf.
  21139. */
  21140. function deflate_stored(s, flush) {
  21141. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  21142. * to pending_buf_size, and each stored block has a 5 byte header:
  21143. */
  21144. var max_block_size = 0xffff;
  21145. if (max_block_size > s.pending_buf_size - 5) {
  21146. max_block_size = s.pending_buf_size - 5;
  21147. }
  21148. /* Copy as much as possible from input to output: */
  21149. for (;;) {
  21150. /* Fill the window as much as possible: */
  21151. if (s.lookahead <= 1) {
  21152. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  21153. // s->block_start >= (long)s->w_size, "slide too late");
  21154. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21155. // s.block_start >= s.w_size)) {
  21156. // throw new Error("slide too late");
  21157. // }
  21158. fill_window(s);
  21159. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21160. return BS_NEED_MORE;
  21161. }
  21162. if (s.lookahead === 0) {
  21163. break;
  21164. }
  21165. /* flush the current block */
  21166. }
  21167. //Assert(s->block_start >= 0L, "block gone");
  21168. // if (s.block_start < 0) throw new Error("block gone");
  21169. s.strstart += s.lookahead;
  21170. s.lookahead = 0;
  21171. /* Emit a stored block if pending_buf will be full: */
  21172. var max_start = s.block_start + max_block_size;
  21173. if (s.strstart === 0 || s.strstart >= max_start) {
  21174. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21175. s.lookahead = s.strstart - max_start;
  21176. s.strstart = max_start;
  21177. /*** FLUSH_BLOCK(s, 0); ***/
  21178. flush_block_only(s, false);
  21179. if (s.strm.avail_out === 0) {
  21180. return BS_NEED_MORE;
  21181. }
  21182. /***/
  21183. }
  21184. /* Flush if we may have to slide, otherwise block_start may become
  21185. * negative and the data will be gone:
  21186. */
  21187. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21188. /*** FLUSH_BLOCK(s, 0); ***/
  21189. flush_block_only(s, false);
  21190. if (s.strm.avail_out === 0) {
  21191. return BS_NEED_MORE;
  21192. }
  21193. /***/
  21194. }
  21195. }
  21196. s.insert = 0;
  21197. if (flush === Z_FINISH) {
  21198. /*** FLUSH_BLOCK(s, 1); ***/
  21199. flush_block_only(s, true);
  21200. if (s.strm.avail_out === 0) {
  21201. return BS_FINISH_STARTED;
  21202. }
  21203. /***/
  21204. return BS_FINISH_DONE;
  21205. }
  21206. if (s.strstart > s.block_start) {
  21207. /*** FLUSH_BLOCK(s, 0); ***/
  21208. flush_block_only(s, false);
  21209. if (s.strm.avail_out === 0) {
  21210. return BS_NEED_MORE;
  21211. }
  21212. /***/
  21213. }
  21214. return BS_NEED_MORE;
  21215. }
  21216. /* ===========================================================================
  21217. * Compress as much as possible from the input stream, return the current
  21218. * block state.
  21219. * This function does not perform lazy evaluation of matches and inserts
  21220. * new strings in the dictionary only for unmatched strings or for short
  21221. * matches. It is used only for the fast compression options.
  21222. */
  21223. function deflate_fast(s, flush) {
  21224. var hash_head; /* head of the hash chain */
  21225. var bflush; /* set if current block must be flushed */
  21226. for (;;) {
  21227. /* Make sure that we always have enough lookahead, except
  21228. * at the end of the input file. We need MAX_MATCH bytes
  21229. * for the next match, plus MIN_MATCH bytes to insert the
  21230. * string following the next match.
  21231. */
  21232. if (s.lookahead < MIN_LOOKAHEAD) {
  21233. fill_window(s);
  21234. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21235. return BS_NEED_MORE;
  21236. }
  21237. if (s.lookahead === 0) {
  21238. break; /* flush the current block */
  21239. }
  21240. }
  21241. /* Insert the string window[strstart .. strstart+2] in the
  21242. * dictionary, and set hash_head to the head of the hash chain:
  21243. */
  21244. hash_head = 0/*NIL*/;
  21245. if (s.lookahead >= MIN_MATCH) {
  21246. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21247. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21248. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21249. s.head[s.ins_h] = s.strstart;
  21250. /***/
  21251. }
  21252. /* Find the longest match, discarding those <= prev_length.
  21253. * At this point we have always match_length < MIN_MATCH
  21254. */
  21255. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21256. /* To simplify the code, we prevent matches with the string
  21257. * of window index 0 (in particular we have to avoid a match
  21258. * of the string with itself at the start of the input file).
  21259. */
  21260. s.match_length = longest_match(s, hash_head);
  21261. /* longest_match() sets match_start */
  21262. }
  21263. if (s.match_length >= MIN_MATCH) {
  21264. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21265. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21266. s.match_length - MIN_MATCH, bflush); ***/
  21267. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21268. s.lookahead -= s.match_length;
  21269. /* Insert new strings in the hash table only if the match length
  21270. * is not too large. This saves time but degrades compression.
  21271. */
  21272. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21273. s.match_length--; /* string at strstart already in table */
  21274. do {
  21275. s.strstart++;
  21276. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21277. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21278. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21279. s.head[s.ins_h] = s.strstart;
  21280. /***/
  21281. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21282. * always MIN_MATCH bytes ahead.
  21283. */
  21284. } while (--s.match_length !== 0);
  21285. s.strstart++;
  21286. } else
  21287. {
  21288. s.strstart += s.match_length;
  21289. s.match_length = 0;
  21290. s.ins_h = s.window[s.strstart];
  21291. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21292. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21293. //#if MIN_MATCH != 3
  21294. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21295. //#endif
  21296. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21297. * matter since it will be recomputed at next deflate call.
  21298. */
  21299. }
  21300. } else {
  21301. /* No match, output a literal byte */
  21302. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21303. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21304. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21305. s.lookahead--;
  21306. s.strstart++;
  21307. }
  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 = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  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. /* ===========================================================================
  21338. * Same as above, but achieves better compression. We use a lazy
  21339. * evaluation for matches: a match is finally adopted only if there is
  21340. * no better match at the next window position.
  21341. */
  21342. function deflate_slow(s, flush) {
  21343. var hash_head; /* head of hash chain */
  21344. var bflush; /* set if current block must be flushed */
  21345. var max_insert;
  21346. /* Process the input block. */
  21347. for (;;) {
  21348. /* Make sure that we always have enough lookahead, except
  21349. * at the end of the input file. We need MAX_MATCH bytes
  21350. * for the next match, plus MIN_MATCH bytes to insert the
  21351. * string following the next match.
  21352. */
  21353. if (s.lookahead < MIN_LOOKAHEAD) {
  21354. fill_window(s);
  21355. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21356. return BS_NEED_MORE;
  21357. }
  21358. if (s.lookahead === 0) { break; } /* flush the current block */
  21359. }
  21360. /* Insert the string window[strstart .. strstart+2] in the
  21361. * dictionary, and set hash_head to the head of the hash chain:
  21362. */
  21363. hash_head = 0/*NIL*/;
  21364. if (s.lookahead >= MIN_MATCH) {
  21365. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21366. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21367. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21368. s.head[s.ins_h] = s.strstart;
  21369. /***/
  21370. }
  21371. /* Find the longest match, discarding those <= prev_length.
  21372. */
  21373. s.prev_length = s.match_length;
  21374. s.prev_match = s.match_start;
  21375. s.match_length = MIN_MATCH-1;
  21376. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21377. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21378. /* To simplify the code, we prevent matches with the string
  21379. * of window index 0 (in particular we have to avoid a match
  21380. * of the string with itself at the start of the input file).
  21381. */
  21382. s.match_length = longest_match(s, hash_head);
  21383. /* longest_match() sets match_start */
  21384. if (s.match_length <= 5 &&
  21385. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21386. /* If prev_match is also MIN_MATCH, match_start is garbage
  21387. * but we will ignore the current match anyway.
  21388. */
  21389. s.match_length = MIN_MATCH-1;
  21390. }
  21391. }
  21392. /* If there was a match at the previous step and the current
  21393. * match is not better, output the previous match:
  21394. */
  21395. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21396. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21397. /* Do not insert strings in hash table beyond this. */
  21398. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21399. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21400. s.prev_length - MIN_MATCH, bflush);***/
  21401. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21402. /* Insert in hash table all strings up to the end of the match.
  21403. * strstart-1 and strstart are already inserted. If there is not
  21404. * enough lookahead, the last two strings are not inserted in
  21405. * the hash table.
  21406. */
  21407. s.lookahead -= s.prev_length-1;
  21408. s.prev_length -= 2;
  21409. do {
  21410. if (++s.strstart <= max_insert) {
  21411. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21412. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21413. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21414. s.head[s.ins_h] = s.strstart;
  21415. /***/
  21416. }
  21417. } while (--s.prev_length !== 0);
  21418. s.match_available = 0;
  21419. s.match_length = MIN_MATCH-1;
  21420. s.strstart++;
  21421. if (bflush) {
  21422. /*** FLUSH_BLOCK(s, 0); ***/
  21423. flush_block_only(s, false);
  21424. if (s.strm.avail_out === 0) {
  21425. return BS_NEED_MORE;
  21426. }
  21427. /***/
  21428. }
  21429. } else if (s.match_available) {
  21430. /* If there was no match at the previous position, output a
  21431. * single literal. If there was a match but the current match
  21432. * is longer, truncate the previous match to a single literal.
  21433. */
  21434. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21435. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21436. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21437. if (bflush) {
  21438. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21439. flush_block_only(s, false);
  21440. /***/
  21441. }
  21442. s.strstart++;
  21443. s.lookahead--;
  21444. if (s.strm.avail_out === 0) {
  21445. return BS_NEED_MORE;
  21446. }
  21447. } else {
  21448. /* There is no previous match to compare with, wait for
  21449. * the next step to decide.
  21450. */
  21451. s.match_available = 1;
  21452. s.strstart++;
  21453. s.lookahead--;
  21454. }
  21455. }
  21456. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21457. if (s.match_available) {
  21458. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21459. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21460. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21461. s.match_available = 0;
  21462. }
  21463. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21464. if (flush === Z_FINISH) {
  21465. /*** FLUSH_BLOCK(s, 1); ***/
  21466. flush_block_only(s, true);
  21467. if (s.strm.avail_out === 0) {
  21468. return BS_FINISH_STARTED;
  21469. }
  21470. /***/
  21471. return BS_FINISH_DONE;
  21472. }
  21473. if (s.last_lit) {
  21474. /*** FLUSH_BLOCK(s, 0); ***/
  21475. flush_block_only(s, false);
  21476. if (s.strm.avail_out === 0) {
  21477. return BS_NEED_MORE;
  21478. }
  21479. /***/
  21480. }
  21481. return BS_BLOCK_DONE;
  21482. }
  21483. /* ===========================================================================
  21484. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21485. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21486. * deflate switches away from Z_RLE.)
  21487. */
  21488. function deflate_rle(s, flush) {
  21489. var bflush; /* set if current block must be flushed */
  21490. var prev; /* byte at distance one to match */
  21491. var scan, strend; /* scan goes up to strend for length of run */
  21492. var _win = s.window;
  21493. for (;;) {
  21494. /* Make sure that we always have enough lookahead, except
  21495. * at the end of the input file. We need MAX_MATCH bytes
  21496. * for the longest run, plus one for the unrolled loop.
  21497. */
  21498. if (s.lookahead <= MAX_MATCH) {
  21499. fill_window(s);
  21500. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21501. return BS_NEED_MORE;
  21502. }
  21503. if (s.lookahead === 0) { break; } /* flush the current block */
  21504. }
  21505. /* See how many times the previous byte repeats */
  21506. s.match_length = 0;
  21507. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21508. scan = s.strstart - 1;
  21509. prev = _win[scan];
  21510. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21511. strend = s.strstart + MAX_MATCH;
  21512. do {
  21513. /*jshint noempty:false*/
  21514. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21515. prev === _win[++scan] && prev === _win[++scan] &&
  21516. prev === _win[++scan] && prev === _win[++scan] &&
  21517. prev === _win[++scan] && prev === _win[++scan] &&
  21518. scan < strend);
  21519. s.match_length = MAX_MATCH - (strend - scan);
  21520. if (s.match_length > s.lookahead) {
  21521. s.match_length = s.lookahead;
  21522. }
  21523. }
  21524. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21525. }
  21526. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21527. if (s.match_length >= MIN_MATCH) {
  21528. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21529. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21530. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21531. s.lookahead -= s.match_length;
  21532. s.strstart += s.match_length;
  21533. s.match_length = 0;
  21534. } else {
  21535. /* No match, output a literal byte */
  21536. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21537. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21538. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21539. s.lookahead--;
  21540. s.strstart++;
  21541. }
  21542. if (bflush) {
  21543. /*** FLUSH_BLOCK(s, 0); ***/
  21544. flush_block_only(s, false);
  21545. if (s.strm.avail_out === 0) {
  21546. return BS_NEED_MORE;
  21547. }
  21548. /***/
  21549. }
  21550. }
  21551. s.insert = 0;
  21552. if (flush === Z_FINISH) {
  21553. /*** FLUSH_BLOCK(s, 1); ***/
  21554. flush_block_only(s, true);
  21555. if (s.strm.avail_out === 0) {
  21556. return BS_FINISH_STARTED;
  21557. }
  21558. /***/
  21559. return BS_FINISH_DONE;
  21560. }
  21561. if (s.last_lit) {
  21562. /*** FLUSH_BLOCK(s, 0); ***/
  21563. flush_block_only(s, false);
  21564. if (s.strm.avail_out === 0) {
  21565. return BS_NEED_MORE;
  21566. }
  21567. /***/
  21568. }
  21569. return BS_BLOCK_DONE;
  21570. }
  21571. /* ===========================================================================
  21572. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21573. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21574. */
  21575. function deflate_huff(s, flush) {
  21576. var bflush; /* set if current block must be flushed */
  21577. for (;;) {
  21578. /* Make sure that we have a literal to write. */
  21579. if (s.lookahead === 0) {
  21580. fill_window(s);
  21581. if (s.lookahead === 0) {
  21582. if (flush === Z_NO_FLUSH) {
  21583. return BS_NEED_MORE;
  21584. }
  21585. break; /* flush the current block */
  21586. }
  21587. }
  21588. /* Output a literal byte */
  21589. s.match_length = 0;
  21590. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21591. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21592. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21593. s.lookahead--;
  21594. s.strstart++;
  21595. if (bflush) {
  21596. /*** FLUSH_BLOCK(s, 0); ***/
  21597. flush_block_only(s, false);
  21598. if (s.strm.avail_out === 0) {
  21599. return BS_NEED_MORE;
  21600. }
  21601. /***/
  21602. }
  21603. }
  21604. s.insert = 0;
  21605. if (flush === Z_FINISH) {
  21606. /*** FLUSH_BLOCK(s, 1); ***/
  21607. flush_block_only(s, true);
  21608. if (s.strm.avail_out === 0) {
  21609. return BS_FINISH_STARTED;
  21610. }
  21611. /***/
  21612. return BS_FINISH_DONE;
  21613. }
  21614. if (s.last_lit) {
  21615. /*** FLUSH_BLOCK(s, 0); ***/
  21616. flush_block_only(s, false);
  21617. if (s.strm.avail_out === 0) {
  21618. return BS_NEED_MORE;
  21619. }
  21620. /***/
  21621. }
  21622. return BS_BLOCK_DONE;
  21623. }
  21624. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21625. * the desired pack level (0..9). The values given below have been tuned to
  21626. * exclude worst case performance for pathological files. Better values may be
  21627. * found for specific files.
  21628. */
  21629. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21630. this.good_length = good_length;
  21631. this.max_lazy = max_lazy;
  21632. this.nice_length = nice_length;
  21633. this.max_chain = max_chain;
  21634. this.func = func;
  21635. };
  21636. var configuration_table;
  21637. configuration_table = [
  21638. /* good lazy nice chain */
  21639. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21640. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21641. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21642. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21643. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21644. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21645. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21646. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21647. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21648. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21649. ];
  21650. /* ===========================================================================
  21651. * Initialize the "longest match" routines for a new zlib stream
  21652. */
  21653. function lm_init(s) {
  21654. s.window_size = 2 * s.w_size;
  21655. /*** CLEAR_HASH(s); ***/
  21656. zero(s.head); // Fill with NIL (= 0);
  21657. /* Set the default configuration parameters:
  21658. */
  21659. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21660. s.good_match = configuration_table[s.level].good_length;
  21661. s.nice_match = configuration_table[s.level].nice_length;
  21662. s.max_chain_length = configuration_table[s.level].max_chain;
  21663. s.strstart = 0;
  21664. s.block_start = 0;
  21665. s.lookahead = 0;
  21666. s.insert = 0;
  21667. s.match_length = s.prev_length = MIN_MATCH - 1;
  21668. s.match_available = 0;
  21669. s.ins_h = 0;
  21670. }
  21671. function DeflateState() {
  21672. this.strm = null; /* pointer back to this zlib stream */
  21673. this.status = 0; /* as the name implies */
  21674. this.pending_buf = null; /* output still pending */
  21675. this.pending_buf_size = 0; /* size of pending_buf */
  21676. this.pending_out = 0; /* next pending byte to output to the stream */
  21677. this.pending = 0; /* nb of bytes in the pending buffer */
  21678. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21679. this.gzhead = null; /* gzip header information to write */
  21680. this.gzindex = 0; /* where in extra, name, or comment */
  21681. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21682. this.last_flush = -1; /* value of flush param for previous deflate call */
  21683. this.w_size = 0; /* LZ77 window size (32K by default) */
  21684. this.w_bits = 0; /* log2(w_size) (8..16) */
  21685. this.w_mask = 0; /* w_size - 1 */
  21686. this.window = null;
  21687. /* Sliding window. Input bytes are read into the second half of the window,
  21688. * and move to the first half later to keep a dictionary of at least wSize
  21689. * bytes. With this organization, matches are limited to a distance of
  21690. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21691. * performed with a length multiple of the block size.
  21692. */
  21693. this.window_size = 0;
  21694. /* Actual size of window: 2*wSize, except when the user input buffer
  21695. * is directly used as sliding window.
  21696. */
  21697. this.prev = null;
  21698. /* Link to older string with same hash index. To limit the size of this
  21699. * array to 64K, this link is maintained only for the last 32K strings.
  21700. * An index in this array is thus a window index modulo 32K.
  21701. */
  21702. this.head = null; /* Heads of the hash chains or NIL. */
  21703. this.ins_h = 0; /* hash index of string to be inserted */
  21704. this.hash_size = 0; /* number of elements in hash table */
  21705. this.hash_bits = 0; /* log2(hash_size) */
  21706. this.hash_mask = 0; /* hash_size-1 */
  21707. this.hash_shift = 0;
  21708. /* Number of bits by which ins_h must be shifted at each input
  21709. * step. It must be such that after MIN_MATCH steps, the oldest
  21710. * byte no longer takes part in the hash key, that is:
  21711. * hash_shift * MIN_MATCH >= hash_bits
  21712. */
  21713. this.block_start = 0;
  21714. /* Window position at the beginning of the current output block. Gets
  21715. * negative when the window is moved backwards.
  21716. */
  21717. this.match_length = 0; /* length of best match */
  21718. this.prev_match = 0; /* previous match */
  21719. this.match_available = 0; /* set if previous match exists */
  21720. this.strstart = 0; /* start of string to insert */
  21721. this.match_start = 0; /* start of matching string */
  21722. this.lookahead = 0; /* number of valid bytes ahead in window */
  21723. this.prev_length = 0;
  21724. /* Length of the best match at previous step. Matches not greater than this
  21725. * are discarded. This is used in the lazy match evaluation.
  21726. */
  21727. this.max_chain_length = 0;
  21728. /* To speed up deflation, hash chains are never searched beyond this
  21729. * length. A higher limit improves compression ratio but degrades the
  21730. * speed.
  21731. */
  21732. this.max_lazy_match = 0;
  21733. /* Attempt to find a better match only when the current match is strictly
  21734. * smaller than this value. This mechanism is used only for compression
  21735. * levels >= 4.
  21736. */
  21737. // That's alias to max_lazy_match, don't use directly
  21738. //this.max_insert_length = 0;
  21739. /* Insert new strings in the hash table only if the match length is not
  21740. * greater than this length. This saves time but degrades compression.
  21741. * max_insert_length is used only for compression levels <= 3.
  21742. */
  21743. this.level = 0; /* compression level (1..9) */
  21744. this.strategy = 0; /* favor or force Huffman coding*/
  21745. this.good_match = 0;
  21746. /* Use a faster search when the previous match is longer than this */
  21747. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21748. /* used by trees.c: */
  21749. /* Didn't use ct_data typedef below to suppress compiler warning */
  21750. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21751. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21752. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21753. // Use flat array of DOUBLE size, with interleaved fata,
  21754. // because JS does not support effective
  21755. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21756. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21757. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21758. zero(this.dyn_ltree);
  21759. zero(this.dyn_dtree);
  21760. zero(this.bl_tree);
  21761. this.l_desc = null; /* desc. for literal tree */
  21762. this.d_desc = null; /* desc. for distance tree */
  21763. this.bl_desc = null; /* desc. for bit length tree */
  21764. //ush bl_count[MAX_BITS+1];
  21765. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21766. /* number of codes at each bit length for an optimal tree */
  21767. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21768. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21769. zero(this.heap);
  21770. this.heap_len = 0; /* number of elements in the heap */
  21771. this.heap_max = 0; /* element of largest frequency */
  21772. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21773. * The same heap array is used to build all trees.
  21774. */
  21775. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21776. zero(this.depth);
  21777. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21778. */
  21779. this.l_buf = 0; /* buffer index for literals or lengths */
  21780. this.lit_bufsize = 0;
  21781. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21782. * limiting lit_bufsize to 64K:
  21783. * - frequencies can be kept in 16 bit counters
  21784. * - if compression is not successful for the first block, all input
  21785. * data is still in the window so we can still emit a stored block even
  21786. * when input comes from standard input. (This can also be done for
  21787. * all blocks if lit_bufsize is not greater than 32K.)
  21788. * - if compression is not successful for a file smaller than 64K, we can
  21789. * even emit a stored file instead of a stored block (saving 5 bytes).
  21790. * This is applicable only for zip (not gzip or zlib).
  21791. * - creating new Huffman trees less frequently may not provide fast
  21792. * adaptation to changes in the input data statistics. (Take for
  21793. * example a binary file with poorly compressible code followed by
  21794. * a highly compressible string table.) Smaller buffer sizes give
  21795. * fast adaptation but have of course the overhead of transmitting
  21796. * trees more frequently.
  21797. * - I can't count above 4
  21798. */
  21799. this.last_lit = 0; /* running index in l_buf */
  21800. this.d_buf = 0;
  21801. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21802. * the same number of elements. To use different lengths, an extra flag
  21803. * array would be necessary.
  21804. */
  21805. this.opt_len = 0; /* bit length of current block with optimal trees */
  21806. this.static_len = 0; /* bit length of current block with static trees */
  21807. this.matches = 0; /* number of string matches in current block */
  21808. this.insert = 0; /* bytes at end of window left to insert */
  21809. this.bi_buf = 0;
  21810. /* Output buffer. bits are inserted starting at the bottom (least
  21811. * significant bits).
  21812. */
  21813. this.bi_valid = 0;
  21814. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21815. * are always zero.
  21816. */
  21817. // Used for window memory init. We safely ignore it for JS. That makes
  21818. // sense only for pointers and memory check tools.
  21819. //this.high_water = 0;
  21820. /* High water mark offset in window for initialized bytes -- bytes above
  21821. * this are set to zero in order to avoid memory check warnings when
  21822. * longest match routines access bytes past the input. This is then
  21823. * updated to the new high water mark.
  21824. */
  21825. }
  21826. function deflateResetKeep(strm) {
  21827. var s;
  21828. if (!strm || !strm.state) {
  21829. return err(strm, Z_STREAM_ERROR);
  21830. }
  21831. strm.total_in = strm.total_out = 0;
  21832. strm.data_type = Z_UNKNOWN;
  21833. s = strm.state;
  21834. s.pending = 0;
  21835. s.pending_out = 0;
  21836. if (s.wrap < 0) {
  21837. s.wrap = -s.wrap;
  21838. /* was made negative by deflate(..., Z_FINISH); */
  21839. }
  21840. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21841. strm.adler = (s.wrap === 2) ?
  21842. 0 // crc32(0, Z_NULL, 0)
  21843. :
  21844. 1; // adler32(0, Z_NULL, 0)
  21845. s.last_flush = Z_NO_FLUSH;
  21846. trees._tr_init(s);
  21847. return Z_OK;
  21848. }
  21849. function deflateReset(strm) {
  21850. var ret = deflateResetKeep(strm);
  21851. if (ret === Z_OK) {
  21852. lm_init(strm.state);
  21853. }
  21854. return ret;
  21855. }
  21856. function deflateSetHeader(strm, head) {
  21857. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21858. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21859. strm.state.gzhead = head;
  21860. return Z_OK;
  21861. }
  21862. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21863. if (!strm) { // === Z_NULL
  21864. return Z_STREAM_ERROR;
  21865. }
  21866. var wrap = 1;
  21867. if (level === Z_DEFAULT_COMPRESSION) {
  21868. level = 6;
  21869. }
  21870. if (windowBits < 0) { /* suppress zlib wrapper */
  21871. wrap = 0;
  21872. windowBits = -windowBits;
  21873. }
  21874. else if (windowBits > 15) {
  21875. wrap = 2; /* write gzip wrapper instead */
  21876. windowBits -= 16;
  21877. }
  21878. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21879. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21880. strategy < 0 || strategy > Z_FIXED) {
  21881. return err(strm, Z_STREAM_ERROR);
  21882. }
  21883. if (windowBits === 8) {
  21884. windowBits = 9;
  21885. }
  21886. /* until 256-byte window bug fixed */
  21887. var s = new DeflateState();
  21888. strm.state = s;
  21889. s.strm = strm;
  21890. s.wrap = wrap;
  21891. s.gzhead = null;
  21892. s.w_bits = windowBits;
  21893. s.w_size = 1 << s.w_bits;
  21894. s.w_mask = s.w_size - 1;
  21895. s.hash_bits = memLevel + 7;
  21896. s.hash_size = 1 << s.hash_bits;
  21897. s.hash_mask = s.hash_size - 1;
  21898. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21899. s.window = new utils.Buf8(s.w_size * 2);
  21900. s.head = new utils.Buf16(s.hash_size);
  21901. s.prev = new utils.Buf16(s.w_size);
  21902. // Don't need mem init magic for JS.
  21903. //s.high_water = 0; /* nothing written to s->window yet */
  21904. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21905. s.pending_buf_size = s.lit_bufsize * 4;
  21906. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21907. s.d_buf = s.lit_bufsize >> 1;
  21908. s.l_buf = (1 + 2) * s.lit_bufsize;
  21909. s.level = level;
  21910. s.strategy = strategy;
  21911. s.method = method;
  21912. return deflateReset(strm);
  21913. }
  21914. function deflateInit(strm, level) {
  21915. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21916. }
  21917. function deflate(strm, flush) {
  21918. var old_flush, s;
  21919. var beg, val; // for gzip header write only
  21920. if (!strm || !strm.state ||
  21921. flush > Z_BLOCK || flush < 0) {
  21922. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21923. }
  21924. s = strm.state;
  21925. if (!strm.output ||
  21926. (!strm.input && strm.avail_in !== 0) ||
  21927. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21928. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21929. }
  21930. s.strm = strm; /* just in case */
  21931. old_flush = s.last_flush;
  21932. s.last_flush = flush;
  21933. /* Write the header */
  21934. if (s.status === INIT_STATE) {
  21935. if (s.wrap === 2) { // GZIP header
  21936. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21937. put_byte(s, 31);
  21938. put_byte(s, 139);
  21939. put_byte(s, 8);
  21940. if (!s.gzhead) { // s->gzhead == Z_NULL
  21941. put_byte(s, 0);
  21942. put_byte(s, 0);
  21943. put_byte(s, 0);
  21944. put_byte(s, 0);
  21945. put_byte(s, 0);
  21946. put_byte(s, s.level === 9 ? 2 :
  21947. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21948. 4 : 0));
  21949. put_byte(s, OS_CODE);
  21950. s.status = BUSY_STATE;
  21951. }
  21952. else {
  21953. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21954. (s.gzhead.hcrc ? 2 : 0) +
  21955. (!s.gzhead.extra ? 0 : 4) +
  21956. (!s.gzhead.name ? 0 : 8) +
  21957. (!s.gzhead.comment ? 0 : 16)
  21958. );
  21959. put_byte(s, s.gzhead.time & 0xff);
  21960. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21961. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21962. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21963. put_byte(s, s.level === 9 ? 2 :
  21964. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21965. 4 : 0));
  21966. put_byte(s, s.gzhead.os & 0xff);
  21967. if (s.gzhead.extra && s.gzhead.extra.length) {
  21968. put_byte(s, s.gzhead.extra.length & 0xff);
  21969. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21970. }
  21971. if (s.gzhead.hcrc) {
  21972. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21973. }
  21974. s.gzindex = 0;
  21975. s.status = EXTRA_STATE;
  21976. }
  21977. }
  21978. else // DEFLATE header
  21979. {
  21980. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21981. var level_flags = -1;
  21982. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21983. level_flags = 0;
  21984. } else if (s.level < 6) {
  21985. level_flags = 1;
  21986. } else if (s.level === 6) {
  21987. level_flags = 2;
  21988. } else {
  21989. level_flags = 3;
  21990. }
  21991. header |= (level_flags << 6);
  21992. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21993. header += 31 - (header % 31);
  21994. s.status = BUSY_STATE;
  21995. putShortMSB(s, header);
  21996. /* Save the adler32 of the preset dictionary: */
  21997. if (s.strstart !== 0) {
  21998. putShortMSB(s, strm.adler >>> 16);
  21999. putShortMSB(s, strm.adler & 0xffff);
  22000. }
  22001. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  22002. }
  22003. }
  22004. //#ifdef GZIP
  22005. if (s.status === EXTRA_STATE) {
  22006. if (s.gzhead.extra/* != Z_NULL*/) {
  22007. beg = s.pending; /* start of bytes to update crc */
  22008. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  22009. if (s.pending === s.pending_buf_size) {
  22010. if (s.gzhead.hcrc && s.pending > beg) {
  22011. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22012. }
  22013. flush_pending(strm);
  22014. beg = s.pending;
  22015. if (s.pending === s.pending_buf_size) {
  22016. break;
  22017. }
  22018. }
  22019. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  22020. s.gzindex++;
  22021. }
  22022. if (s.gzhead.hcrc && s.pending > beg) {
  22023. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22024. }
  22025. if (s.gzindex === s.gzhead.extra.length) {
  22026. s.gzindex = 0;
  22027. s.status = NAME_STATE;
  22028. }
  22029. }
  22030. else {
  22031. s.status = NAME_STATE;
  22032. }
  22033. }
  22034. if (s.status === NAME_STATE) {
  22035. if (s.gzhead.name/* != Z_NULL*/) {
  22036. beg = s.pending; /* start of bytes to update crc */
  22037. //int val;
  22038. do {
  22039. if (s.pending === s.pending_buf_size) {
  22040. if (s.gzhead.hcrc && s.pending > beg) {
  22041. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22042. }
  22043. flush_pending(strm);
  22044. beg = s.pending;
  22045. if (s.pending === s.pending_buf_size) {
  22046. val = 1;
  22047. break;
  22048. }
  22049. }
  22050. // JS specific: little magic to add zero terminator to end of string
  22051. if (s.gzindex < s.gzhead.name.length) {
  22052. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  22053. } else {
  22054. val = 0;
  22055. }
  22056. put_byte(s, val);
  22057. } while (val !== 0);
  22058. if (s.gzhead.hcrc && s.pending > beg) {
  22059. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22060. }
  22061. if (val === 0) {
  22062. s.gzindex = 0;
  22063. s.status = COMMENT_STATE;
  22064. }
  22065. }
  22066. else {
  22067. s.status = COMMENT_STATE;
  22068. }
  22069. }
  22070. if (s.status === COMMENT_STATE) {
  22071. if (s.gzhead.comment/* != Z_NULL*/) {
  22072. beg = s.pending; /* start of bytes to update crc */
  22073. //int val;
  22074. do {
  22075. if (s.pending === s.pending_buf_size) {
  22076. if (s.gzhead.hcrc && s.pending > beg) {
  22077. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22078. }
  22079. flush_pending(strm);
  22080. beg = s.pending;
  22081. if (s.pending === s.pending_buf_size) {
  22082. val = 1;
  22083. break;
  22084. }
  22085. }
  22086. // JS specific: little magic to add zero terminator to end of string
  22087. if (s.gzindex < s.gzhead.comment.length) {
  22088. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  22089. } else {
  22090. val = 0;
  22091. }
  22092. put_byte(s, val);
  22093. } while (val !== 0);
  22094. if (s.gzhead.hcrc && s.pending > beg) {
  22095. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22096. }
  22097. if (val === 0) {
  22098. s.status = HCRC_STATE;
  22099. }
  22100. }
  22101. else {
  22102. s.status = HCRC_STATE;
  22103. }
  22104. }
  22105. if (s.status === HCRC_STATE) {
  22106. if (s.gzhead.hcrc) {
  22107. if (s.pending + 2 > s.pending_buf_size) {
  22108. flush_pending(strm);
  22109. }
  22110. if (s.pending + 2 <= s.pending_buf_size) {
  22111. put_byte(s, strm.adler & 0xff);
  22112. put_byte(s, (strm.adler >> 8) & 0xff);
  22113. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22114. s.status = BUSY_STATE;
  22115. }
  22116. }
  22117. else {
  22118. s.status = BUSY_STATE;
  22119. }
  22120. }
  22121. //#endif
  22122. /* Flush as much pending output as possible */
  22123. if (s.pending !== 0) {
  22124. flush_pending(strm);
  22125. if (strm.avail_out === 0) {
  22126. /* Since avail_out is 0, deflate will be called again with
  22127. * more output space, but possibly with both pending and
  22128. * avail_in equal to zero. There won't be anything to do,
  22129. * but this is not an error situation so make sure we
  22130. * return OK instead of BUF_ERROR at next call of deflate:
  22131. */
  22132. s.last_flush = -1;
  22133. return Z_OK;
  22134. }
  22135. /* Make sure there is something to do and avoid duplicate consecutive
  22136. * flushes. For repeated and useless calls with Z_FINISH, we keep
  22137. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  22138. */
  22139. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  22140. flush !== Z_FINISH) {
  22141. return err(strm, Z_BUF_ERROR);
  22142. }
  22143. /* User must not provide more input after the first FINISH: */
  22144. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  22145. return err(strm, Z_BUF_ERROR);
  22146. }
  22147. /* Start a new block or continue the current one.
  22148. */
  22149. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  22150. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  22151. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  22152. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  22153. configuration_table[s.level].func(s, flush));
  22154. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22155. s.status = FINISH_STATE;
  22156. }
  22157. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22158. if (strm.avail_out === 0) {
  22159. s.last_flush = -1;
  22160. /* avoid BUF_ERROR next call, see above */
  22161. }
  22162. return Z_OK;
  22163. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22164. * of deflate should use the same flush parameter to make sure
  22165. * that the flush is complete. So we don't have to output an
  22166. * empty block here, this will be done at next call. This also
  22167. * ensures that for a very small output buffer, we emit at most
  22168. * one empty block.
  22169. */
  22170. }
  22171. if (bstate === BS_BLOCK_DONE) {
  22172. if (flush === Z_PARTIAL_FLUSH) {
  22173. trees._tr_align(s);
  22174. }
  22175. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22176. trees._tr_stored_block(s, 0, 0, false);
  22177. /* For a full flush, this empty block will be recognized
  22178. * as a special marker by inflate_sync().
  22179. */
  22180. if (flush === Z_FULL_FLUSH) {
  22181. /*** CLEAR_HASH(s); ***/ /* forget history */
  22182. zero(s.head); // Fill with NIL (= 0);
  22183. if (s.lookahead === 0) {
  22184. s.strstart = 0;
  22185. s.block_start = 0;
  22186. s.insert = 0;
  22187. }
  22188. }
  22189. }
  22190. flush_pending(strm);
  22191. if (strm.avail_out === 0) {
  22192. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22193. return Z_OK;
  22194. }
  22195. }
  22196. }
  22197. //Assert(strm->avail_out > 0, "bug2");
  22198. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22199. if (flush !== Z_FINISH) { return Z_OK; }
  22200. if (s.wrap <= 0) { return Z_STREAM_END; }
  22201. /* Write the trailer */
  22202. if (s.wrap === 2) {
  22203. put_byte(s, strm.adler & 0xff);
  22204. put_byte(s, (strm.adler >> 8) & 0xff);
  22205. put_byte(s, (strm.adler >> 16) & 0xff);
  22206. put_byte(s, (strm.adler >> 24) & 0xff);
  22207. put_byte(s, strm.total_in & 0xff);
  22208. put_byte(s, (strm.total_in >> 8) & 0xff);
  22209. put_byte(s, (strm.total_in >> 16) & 0xff);
  22210. put_byte(s, (strm.total_in >> 24) & 0xff);
  22211. }
  22212. else
  22213. {
  22214. putShortMSB(s, strm.adler >>> 16);
  22215. putShortMSB(s, strm.adler & 0xffff);
  22216. }
  22217. flush_pending(strm);
  22218. /* If avail_out is zero, the application will call deflate again
  22219. * to flush the rest.
  22220. */
  22221. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22222. /* write the trailer only once! */
  22223. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22224. }
  22225. function deflateEnd(strm) {
  22226. var status;
  22227. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22228. return Z_STREAM_ERROR;
  22229. }
  22230. status = strm.state.status;
  22231. if (status !== INIT_STATE &&
  22232. status !== EXTRA_STATE &&
  22233. status !== NAME_STATE &&
  22234. status !== COMMENT_STATE &&
  22235. status !== HCRC_STATE &&
  22236. status !== BUSY_STATE &&
  22237. status !== FINISH_STATE
  22238. ) {
  22239. return err(strm, Z_STREAM_ERROR);
  22240. }
  22241. strm.state = null;
  22242. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22243. }
  22244. /* =========================================================================
  22245. * Copy the source state to the destination state
  22246. */
  22247. //function deflateCopy(dest, source) {
  22248. //
  22249. //}
  22250. exports.deflateInit = deflateInit;
  22251. exports.deflateInit2 = deflateInit2;
  22252. exports.deflateReset = deflateReset;
  22253. exports.deflateResetKeep = deflateResetKeep;
  22254. exports.deflateSetHeader = deflateSetHeader;
  22255. exports.deflate = deflate;
  22256. exports.deflateEnd = deflateEnd;
  22257. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22258. /* Not implemented
  22259. exports.deflateBound = deflateBound;
  22260. exports.deflateCopy = deflateCopy;
  22261. exports.deflateSetDictionary = deflateSetDictionary;
  22262. exports.deflateParams = deflateParams;
  22263. exports.deflatePending = deflatePending;
  22264. exports.deflatePrime = deflatePrime;
  22265. exports.deflateTune = deflateTune;
  22266. */
  22267. },{"../utils/common":74,"./adler32":76,"./crc32":78,"./messages":84,"./trees":85}],80:[function(require,module,exports){
  22268. 'use strict';
  22269. function GZheader() {
  22270. /* true if compressed data believed to be text */
  22271. this.text = 0;
  22272. /* modification time */
  22273. this.time = 0;
  22274. /* extra flags (not used when writing a gzip file) */
  22275. this.xflags = 0;
  22276. /* operating system */
  22277. this.os = 0;
  22278. /* pointer to extra field or Z_NULL if none */
  22279. this.extra = null;
  22280. /* extra field length (valid if extra != Z_NULL) */
  22281. this.extra_len = 0; // Actually, we don't need it in JS,
  22282. // but leave for few code modifications
  22283. //
  22284. // Setup limits is not necessary because in js we should not preallocate memory
  22285. // for inflate use constant limit in 65536 bytes
  22286. //
  22287. /* space at extra (only when reading header) */
  22288. // this.extra_max = 0;
  22289. /* pointer to zero-terminated file name or Z_NULL */
  22290. this.name = '';
  22291. /* space at name (only when reading header) */
  22292. // this.name_max = 0;
  22293. /* pointer to zero-terminated comment or Z_NULL */
  22294. this.comment = '';
  22295. /* space at comment (only when reading header) */
  22296. // this.comm_max = 0;
  22297. /* true if there was or will be a header crc */
  22298. this.hcrc = 0;
  22299. /* true when done reading gzip header (not used when writing a gzip file) */
  22300. this.done = false;
  22301. }
  22302. module.exports = GZheader;
  22303. },{}],81:[function(require,module,exports){
  22304. 'use strict';
  22305. // See state defs from inflate.js
  22306. var BAD = 30; /* got a data error -- remain here until reset */
  22307. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22308. /*
  22309. Decode literal, length, and distance codes and write out the resulting
  22310. literal and match bytes until either not enough input or output is
  22311. available, an end-of-block is encountered, or a data error is encountered.
  22312. When large enough input and output buffers are supplied to inflate(), for
  22313. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22314. inflate execution time is spent in this routine.
  22315. Entry assumptions:
  22316. state.mode === LEN
  22317. strm.avail_in >= 6
  22318. strm.avail_out >= 258
  22319. start >= strm.avail_out
  22320. state.bits < 8
  22321. On return, state.mode is one of:
  22322. LEN -- ran out of enough output space or enough available input
  22323. TYPE -- reached end of block code, inflate() to interpret next block
  22324. BAD -- error in block data
  22325. Notes:
  22326. - The maximum input bits used by a length/distance pair is 15 bits for the
  22327. length code, 5 bits for the length extra, 15 bits for the distance code,
  22328. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22329. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22330. checking for available input while decoding.
  22331. - The maximum bytes that a single length/distance pair can output is 258
  22332. bytes, which is the maximum length that can be coded. inflate_fast()
  22333. requires strm.avail_out >= 258 for each loop to avoid checking for
  22334. output space.
  22335. */
  22336. module.exports = function inflate_fast(strm, start) {
  22337. var state;
  22338. var _in; /* local strm.input */
  22339. var last; /* have enough input while in < last */
  22340. var _out; /* local strm.output */
  22341. var beg; /* inflate()'s initial strm.output */
  22342. var end; /* while out < end, enough space available */
  22343. //#ifdef INFLATE_STRICT
  22344. var dmax; /* maximum distance from zlib header */
  22345. //#endif
  22346. var wsize; /* window size or zero if not using window */
  22347. var whave; /* valid bytes in the window */
  22348. var wnext; /* window write index */
  22349. var window; /* allocated sliding window, if wsize != 0 */
  22350. var hold; /* local strm.hold */
  22351. var bits; /* local strm.bits */
  22352. var lcode; /* local strm.lencode */
  22353. var dcode; /* local strm.distcode */
  22354. var lmask; /* mask for first level of length codes */
  22355. var dmask; /* mask for first level of distance codes */
  22356. var here; /* retrieved table entry */
  22357. var op; /* code bits, operation, extra bits, or */
  22358. /* window position, window bytes to copy */
  22359. var len; /* match length, unused bytes */
  22360. var dist; /* match distance */
  22361. var from; /* where to copy match from */
  22362. var from_source;
  22363. var input, output; // JS specific, because we have no pointers
  22364. /* copy state to local variables */
  22365. state = strm.state;
  22366. //here = state.here;
  22367. _in = strm.next_in;
  22368. input = strm.input;
  22369. last = _in + (strm.avail_in - 5);
  22370. _out = strm.next_out;
  22371. output = strm.output;
  22372. beg = _out - (start - strm.avail_out);
  22373. end = _out + (strm.avail_out - 257);
  22374. //#ifdef INFLATE_STRICT
  22375. dmax = state.dmax;
  22376. //#endif
  22377. wsize = state.wsize;
  22378. whave = state.whave;
  22379. wnext = state.wnext;
  22380. window = state.window;
  22381. hold = state.hold;
  22382. bits = state.bits;
  22383. lcode = state.lencode;
  22384. dcode = state.distcode;
  22385. lmask = (1 << state.lenbits) - 1;
  22386. dmask = (1 << state.distbits) - 1;
  22387. /* decode literals and length/distances until end-of-block or not enough
  22388. input data or output space */
  22389. top:
  22390. do {
  22391. if (bits < 15) {
  22392. hold += input[_in++] << bits;
  22393. bits += 8;
  22394. hold += input[_in++] << bits;
  22395. bits += 8;
  22396. }
  22397. here = lcode[hold & lmask];
  22398. dolen:
  22399. for (;;) { // Goto emulation
  22400. op = here >>> 24/*here.bits*/;
  22401. hold >>>= op;
  22402. bits -= op;
  22403. op = (here >>> 16) & 0xff/*here.op*/;
  22404. if (op === 0) { /* literal */
  22405. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22406. // "inflate: literal '%c'\n" :
  22407. // "inflate: literal 0x%02x\n", here.val));
  22408. output[_out++] = here & 0xffff/*here.val*/;
  22409. }
  22410. else if (op & 16) { /* length base */
  22411. len = here & 0xffff/*here.val*/;
  22412. op &= 15; /* number of extra bits */
  22413. if (op) {
  22414. if (bits < op) {
  22415. hold += input[_in++] << bits;
  22416. bits += 8;
  22417. }
  22418. len += hold & ((1 << op) - 1);
  22419. hold >>>= op;
  22420. bits -= op;
  22421. }
  22422. //Tracevv((stderr, "inflate: length %u\n", len));
  22423. if (bits < 15) {
  22424. hold += input[_in++] << bits;
  22425. bits += 8;
  22426. hold += input[_in++] << bits;
  22427. bits += 8;
  22428. }
  22429. here = dcode[hold & dmask];
  22430. dodist:
  22431. for (;;) { // goto emulation
  22432. op = here >>> 24/*here.bits*/;
  22433. hold >>>= op;
  22434. bits -= op;
  22435. op = (here >>> 16) & 0xff/*here.op*/;
  22436. if (op & 16) { /* distance base */
  22437. dist = here & 0xffff/*here.val*/;
  22438. op &= 15; /* number of extra bits */
  22439. if (bits < op) {
  22440. hold += input[_in++] << bits;
  22441. bits += 8;
  22442. if (bits < op) {
  22443. hold += input[_in++] << bits;
  22444. bits += 8;
  22445. }
  22446. }
  22447. dist += hold & ((1 << op) - 1);
  22448. //#ifdef INFLATE_STRICT
  22449. if (dist > dmax) {
  22450. strm.msg = 'invalid distance too far back';
  22451. state.mode = BAD;
  22452. break top;
  22453. }
  22454. //#endif
  22455. hold >>>= op;
  22456. bits -= op;
  22457. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22458. op = _out - beg; /* max distance in output */
  22459. if (dist > op) { /* see if copy from window */
  22460. op = dist - op; /* distance back in window */
  22461. if (op > whave) {
  22462. if (state.sane) {
  22463. strm.msg = 'invalid distance too far back';
  22464. state.mode = BAD;
  22465. break top;
  22466. }
  22467. // (!) This block is disabled in zlib defailts,
  22468. // don't enable it for binary compatibility
  22469. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22470. // if (len <= op - whave) {
  22471. // do {
  22472. // output[_out++] = 0;
  22473. // } while (--len);
  22474. // continue top;
  22475. // }
  22476. // len -= op - whave;
  22477. // do {
  22478. // output[_out++] = 0;
  22479. // } while (--op > whave);
  22480. // if (op === 0) {
  22481. // from = _out - dist;
  22482. // do {
  22483. // output[_out++] = output[from++];
  22484. // } while (--len);
  22485. // continue top;
  22486. // }
  22487. //#endif
  22488. }
  22489. from = 0; // window index
  22490. from_source = window;
  22491. if (wnext === 0) { /* very common case */
  22492. from += wsize - op;
  22493. if (op < len) { /* some from window */
  22494. len -= op;
  22495. do {
  22496. output[_out++] = window[from++];
  22497. } while (--op);
  22498. from = _out - dist; /* rest from output */
  22499. from_source = output;
  22500. }
  22501. }
  22502. else if (wnext < op) { /* wrap around window */
  22503. from += wsize + wnext - op;
  22504. op -= wnext;
  22505. if (op < len) { /* some from end of window */
  22506. len -= op;
  22507. do {
  22508. output[_out++] = window[from++];
  22509. } while (--op);
  22510. from = 0;
  22511. if (wnext < len) { /* some from start of window */
  22512. op = wnext;
  22513. len -= op;
  22514. do {
  22515. output[_out++] = window[from++];
  22516. } while (--op);
  22517. from = _out - dist; /* rest from output */
  22518. from_source = output;
  22519. }
  22520. }
  22521. }
  22522. else { /* contiguous in window */
  22523. from += wnext - op;
  22524. if (op < len) { /* some from window */
  22525. len -= op;
  22526. do {
  22527. output[_out++] = window[from++];
  22528. } while (--op);
  22529. from = _out - dist; /* rest from output */
  22530. from_source = output;
  22531. }
  22532. }
  22533. while (len > 2) {
  22534. output[_out++] = from_source[from++];
  22535. output[_out++] = from_source[from++];
  22536. output[_out++] = from_source[from++];
  22537. len -= 3;
  22538. }
  22539. if (len) {
  22540. output[_out++] = from_source[from++];
  22541. if (len > 1) {
  22542. output[_out++] = from_source[from++];
  22543. }
  22544. }
  22545. }
  22546. else {
  22547. from = _out - dist; /* copy direct from output */
  22548. do { /* minimum length is three */
  22549. output[_out++] = output[from++];
  22550. output[_out++] = output[from++];
  22551. output[_out++] = output[from++];
  22552. len -= 3;
  22553. } while (len > 2);
  22554. if (len) {
  22555. output[_out++] = output[from++];
  22556. if (len > 1) {
  22557. output[_out++] = output[from++];
  22558. }
  22559. }
  22560. }
  22561. }
  22562. else if ((op & 64) === 0) { /* 2nd level distance code */
  22563. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22564. continue dodist;
  22565. }
  22566. else {
  22567. strm.msg = 'invalid distance code';
  22568. state.mode = BAD;
  22569. break top;
  22570. }
  22571. break; // need to emulate goto via "continue"
  22572. }
  22573. }
  22574. else if ((op & 64) === 0) { /* 2nd level length code */
  22575. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22576. continue dolen;
  22577. }
  22578. else if (op & 32) { /* end-of-block */
  22579. //Tracevv((stderr, "inflate: end of block\n"));
  22580. state.mode = TYPE;
  22581. break top;
  22582. }
  22583. else {
  22584. strm.msg = 'invalid literal/length code';
  22585. state.mode = BAD;
  22586. break top;
  22587. }
  22588. break; // need to emulate goto via "continue"
  22589. }
  22590. } while (_in < last && _out < end);
  22591. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22592. len = bits >> 3;
  22593. _in -= len;
  22594. bits -= len << 3;
  22595. hold &= (1 << bits) - 1;
  22596. /* update state and return */
  22597. strm.next_in = _in;
  22598. strm.next_out = _out;
  22599. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22600. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22601. state.hold = hold;
  22602. state.bits = bits;
  22603. return;
  22604. };
  22605. },{}],82:[function(require,module,exports){
  22606. 'use strict';
  22607. var utils = require('../utils/common');
  22608. var adler32 = require('./adler32');
  22609. var crc32 = require('./crc32');
  22610. var inflate_fast = require('./inffast');
  22611. var inflate_table = require('./inftrees');
  22612. var CODES = 0;
  22613. var LENS = 1;
  22614. var DISTS = 2;
  22615. /* Public constants ==========================================================*/
  22616. /* ===========================================================================*/
  22617. /* Allowed flush values; see deflate() and inflate() below for details */
  22618. //var Z_NO_FLUSH = 0;
  22619. //var Z_PARTIAL_FLUSH = 1;
  22620. //var Z_SYNC_FLUSH = 2;
  22621. //var Z_FULL_FLUSH = 3;
  22622. var Z_FINISH = 4;
  22623. var Z_BLOCK = 5;
  22624. var Z_TREES = 6;
  22625. /* Return codes for the compression/decompression functions. Negative values
  22626. * are errors, positive values are used for special but normal events.
  22627. */
  22628. var Z_OK = 0;
  22629. var Z_STREAM_END = 1;
  22630. var Z_NEED_DICT = 2;
  22631. //var Z_ERRNO = -1;
  22632. var Z_STREAM_ERROR = -2;
  22633. var Z_DATA_ERROR = -3;
  22634. var Z_MEM_ERROR = -4;
  22635. var Z_BUF_ERROR = -5;
  22636. //var Z_VERSION_ERROR = -6;
  22637. /* The deflate compression method */
  22638. var Z_DEFLATED = 8;
  22639. /* STATES ====================================================================*/
  22640. /* ===========================================================================*/
  22641. var HEAD = 1; /* i: waiting for magic header */
  22642. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22643. var TIME = 3; /* i: waiting for modification time (gzip) */
  22644. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22645. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22646. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22647. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22648. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22649. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22650. var DICTID = 10; /* i: waiting for dictionary check value */
  22651. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22652. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22653. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22654. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22655. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22656. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22657. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22658. var LENLENS = 18; /* i: waiting for code length code lengths */
  22659. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22660. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22661. var LEN = 21; /* i: waiting for length/lit/eob code */
  22662. var LENEXT = 22; /* i: waiting for length extra bits */
  22663. var DIST = 23; /* i: waiting for distance code */
  22664. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22665. var MATCH = 25; /* o: waiting for output space to copy string */
  22666. var LIT = 26; /* o: waiting for output space to write literal */
  22667. var CHECK = 27; /* i: waiting for 32-bit check value */
  22668. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22669. var DONE = 29; /* finished check, done -- remain here until reset */
  22670. var BAD = 30; /* got a data error -- remain here until reset */
  22671. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22672. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22673. /* ===========================================================================*/
  22674. var ENOUGH_LENS = 852;
  22675. var ENOUGH_DISTS = 592;
  22676. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22677. var MAX_WBITS = 15;
  22678. /* 32K LZ77 window */
  22679. var DEF_WBITS = MAX_WBITS;
  22680. function ZSWAP32(q) {
  22681. return (((q >>> 24) & 0xff) +
  22682. ((q >>> 8) & 0xff00) +
  22683. ((q & 0xff00) << 8) +
  22684. ((q & 0xff) << 24));
  22685. }
  22686. function InflateState() {
  22687. this.mode = 0; /* current inflate mode */
  22688. this.last = false; /* true if processing last block */
  22689. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22690. this.havedict = false; /* true if dictionary provided */
  22691. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22692. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22693. this.check = 0; /* protected copy of check value */
  22694. this.total = 0; /* protected copy of output count */
  22695. // TODO: may be {}
  22696. this.head = null; /* where to save gzip header information */
  22697. /* sliding window */
  22698. this.wbits = 0; /* log base 2 of requested window size */
  22699. this.wsize = 0; /* window size or zero if not using window */
  22700. this.whave = 0; /* valid bytes in the window */
  22701. this.wnext = 0; /* window write index */
  22702. this.window = null; /* allocated sliding window, if needed */
  22703. /* bit accumulator */
  22704. this.hold = 0; /* input bit accumulator */
  22705. this.bits = 0; /* number of bits in "in" */
  22706. /* for string and stored block copying */
  22707. this.length = 0; /* literal or length of data to copy */
  22708. this.offset = 0; /* distance back to copy string from */
  22709. /* for table and code decoding */
  22710. this.extra = 0; /* extra bits needed */
  22711. /* fixed and dynamic code tables */
  22712. this.lencode = null; /* starting table for length/literal codes */
  22713. this.distcode = null; /* starting table for distance codes */
  22714. this.lenbits = 0; /* index bits for lencode */
  22715. this.distbits = 0; /* index bits for distcode */
  22716. /* dynamic table building */
  22717. this.ncode = 0; /* number of code length code lengths */
  22718. this.nlen = 0; /* number of length code lengths */
  22719. this.ndist = 0; /* number of distance code lengths */
  22720. this.have = 0; /* number of code lengths in lens[] */
  22721. this.next = null; /* next available space in codes[] */
  22722. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22723. this.work = new utils.Buf16(288); /* work area for code table building */
  22724. /*
  22725. because we don't have pointers in js, we use lencode and distcode directly
  22726. as buffers so we don't need codes
  22727. */
  22728. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22729. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22730. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22731. this.sane = 0; /* if false, allow invalid distance too far */
  22732. this.back = 0; /* bits back of last unprocessed length/lit */
  22733. this.was = 0; /* initial length of match */
  22734. }
  22735. function inflateResetKeep(strm) {
  22736. var state;
  22737. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22738. state = strm.state;
  22739. strm.total_in = strm.total_out = state.total = 0;
  22740. strm.msg = ''; /*Z_NULL*/
  22741. if (state.wrap) { /* to support ill-conceived Java test suite */
  22742. strm.adler = state.wrap & 1;
  22743. }
  22744. state.mode = HEAD;
  22745. state.last = 0;
  22746. state.havedict = 0;
  22747. state.dmax = 32768;
  22748. state.head = null/*Z_NULL*/;
  22749. state.hold = 0;
  22750. state.bits = 0;
  22751. //state.lencode = state.distcode = state.next = state.codes;
  22752. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22753. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22754. state.sane = 1;
  22755. state.back = -1;
  22756. //Tracev((stderr, "inflate: reset\n"));
  22757. return Z_OK;
  22758. }
  22759. function inflateReset(strm) {
  22760. var state;
  22761. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22762. state = strm.state;
  22763. state.wsize = 0;
  22764. state.whave = 0;
  22765. state.wnext = 0;
  22766. return inflateResetKeep(strm);
  22767. }
  22768. function inflateReset2(strm, windowBits) {
  22769. var wrap;
  22770. var state;
  22771. /* get the state */
  22772. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22773. state = strm.state;
  22774. /* extract wrap request from windowBits parameter */
  22775. if (windowBits < 0) {
  22776. wrap = 0;
  22777. windowBits = -windowBits;
  22778. }
  22779. else {
  22780. wrap = (windowBits >> 4) + 1;
  22781. if (windowBits < 48) {
  22782. windowBits &= 15;
  22783. }
  22784. }
  22785. /* set number of window bits, free window if different */
  22786. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22787. return Z_STREAM_ERROR;
  22788. }
  22789. if (state.window !== null && state.wbits !== windowBits) {
  22790. state.window = null;
  22791. }
  22792. /* update state and reset the rest of it */
  22793. state.wrap = wrap;
  22794. state.wbits = windowBits;
  22795. return inflateReset(strm);
  22796. }
  22797. function inflateInit2(strm, windowBits) {
  22798. var ret;
  22799. var state;
  22800. if (!strm) { return Z_STREAM_ERROR; }
  22801. //strm.msg = Z_NULL; /* in case we return an error */
  22802. state = new InflateState();
  22803. //if (state === Z_NULL) return Z_MEM_ERROR;
  22804. //Tracev((stderr, "inflate: allocated\n"));
  22805. strm.state = state;
  22806. state.window = null/*Z_NULL*/;
  22807. ret = inflateReset2(strm, windowBits);
  22808. if (ret !== Z_OK) {
  22809. strm.state = null/*Z_NULL*/;
  22810. }
  22811. return ret;
  22812. }
  22813. function inflateInit(strm) {
  22814. return inflateInit2(strm, DEF_WBITS);
  22815. }
  22816. /*
  22817. Return state with length and distance decoding tables and index sizes set to
  22818. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22819. If BUILDFIXED is defined, then instead this routine builds the tables the
  22820. first time it's called, and returns those tables the first time and
  22821. thereafter. This reduces the size of the code by about 2K bytes, in
  22822. exchange for a little execution time. However, BUILDFIXED should not be
  22823. used for threaded applications, since the rewriting of the tables and virgin
  22824. may not be thread-safe.
  22825. */
  22826. var virgin = true;
  22827. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22828. function fixedtables(state) {
  22829. /* build fixed huffman tables if first call (may not be thread safe) */
  22830. if (virgin) {
  22831. var sym;
  22832. lenfix = new utils.Buf32(512);
  22833. distfix = new utils.Buf32(32);
  22834. /* literal/length table */
  22835. sym = 0;
  22836. while (sym < 144) { state.lens[sym++] = 8; }
  22837. while (sym < 256) { state.lens[sym++] = 9; }
  22838. while (sym < 280) { state.lens[sym++] = 7; }
  22839. while (sym < 288) { state.lens[sym++] = 8; }
  22840. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22841. /* distance table */
  22842. sym = 0;
  22843. while (sym < 32) { state.lens[sym++] = 5; }
  22844. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22845. /* do this just once */
  22846. virgin = false;
  22847. }
  22848. state.lencode = lenfix;
  22849. state.lenbits = 9;
  22850. state.distcode = distfix;
  22851. state.distbits = 5;
  22852. }
  22853. /*
  22854. Update the window with the last wsize (normally 32K) bytes written before
  22855. returning. If window does not exist yet, create it. This is only called
  22856. when a window is already in use, or when output has been written during this
  22857. inflate call, but the end of the deflate stream has not been reached yet.
  22858. It is also called to create a window for dictionary data when a dictionary
  22859. is loaded.
  22860. Providing output buffers larger than 32K to inflate() should provide a speed
  22861. advantage, since only the last 32K of output is copied to the sliding window
  22862. upon return from inflate(), and since all distances after the first 32K of
  22863. output will fall in the output data, making match copies simpler and faster.
  22864. The advantage may be dependent on the size of the processor's data caches.
  22865. */
  22866. function updatewindow(strm, src, end, copy) {
  22867. var dist;
  22868. var state = strm.state;
  22869. /* if it hasn't been done already, allocate space for the window */
  22870. if (state.window === null) {
  22871. state.wsize = 1 << state.wbits;
  22872. state.wnext = 0;
  22873. state.whave = 0;
  22874. state.window = new utils.Buf8(state.wsize);
  22875. }
  22876. /* copy state->wsize or less output bytes into the circular window */
  22877. if (copy >= state.wsize) {
  22878. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22879. state.wnext = 0;
  22880. state.whave = state.wsize;
  22881. }
  22882. else {
  22883. dist = state.wsize - state.wnext;
  22884. if (dist > copy) {
  22885. dist = copy;
  22886. }
  22887. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22888. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22889. copy -= dist;
  22890. if (copy) {
  22891. //zmemcpy(state->window, end - copy, copy);
  22892. utils.arraySet(state.window,src, end - copy, copy, 0);
  22893. state.wnext = copy;
  22894. state.whave = state.wsize;
  22895. }
  22896. else {
  22897. state.wnext += dist;
  22898. if (state.wnext === state.wsize) { state.wnext = 0; }
  22899. if (state.whave < state.wsize) { state.whave += dist; }
  22900. }
  22901. }
  22902. return 0;
  22903. }
  22904. function inflate(strm, flush) {
  22905. var state;
  22906. var input, output; // input/output buffers
  22907. var next; /* next input INDEX */
  22908. var put; /* next output INDEX */
  22909. var have, left; /* available input and output */
  22910. var hold; /* bit buffer */
  22911. var bits; /* bits in bit buffer */
  22912. var _in, _out; /* save starting available input and output */
  22913. var copy; /* number of stored or match bytes to copy */
  22914. var from; /* where to copy match bytes from */
  22915. var from_source;
  22916. var here = 0; /* current decoding table entry */
  22917. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22918. //var last; /* parent table entry */
  22919. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22920. var len; /* length to copy for repeats, bits to drop */
  22921. var ret; /* return code */
  22922. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22923. var opts;
  22924. var n; // temporary var for NEED_BITS
  22925. var order = /* permutation of code lengths */
  22926. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22927. if (!strm || !strm.state || !strm.output ||
  22928. (!strm.input && strm.avail_in !== 0)) {
  22929. return Z_STREAM_ERROR;
  22930. }
  22931. state = strm.state;
  22932. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22933. //--- LOAD() ---
  22934. put = strm.next_out;
  22935. output = strm.output;
  22936. left = strm.avail_out;
  22937. next = strm.next_in;
  22938. input = strm.input;
  22939. have = strm.avail_in;
  22940. hold = state.hold;
  22941. bits = state.bits;
  22942. //---
  22943. _in = have;
  22944. _out = left;
  22945. ret = Z_OK;
  22946. inf_leave: // goto emulation
  22947. for (;;) {
  22948. switch (state.mode) {
  22949. case HEAD:
  22950. if (state.wrap === 0) {
  22951. state.mode = TYPEDO;
  22952. break;
  22953. }
  22954. //=== NEEDBITS(16);
  22955. while (bits < 16) {
  22956. if (have === 0) { break inf_leave; }
  22957. have--;
  22958. hold += input[next++] << bits;
  22959. bits += 8;
  22960. }
  22961. //===//
  22962. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22963. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22964. //=== CRC2(state.check, hold);
  22965. hbuf[0] = hold & 0xff;
  22966. hbuf[1] = (hold >>> 8) & 0xff;
  22967. state.check = crc32(state.check, hbuf, 2, 0);
  22968. //===//
  22969. //=== INITBITS();
  22970. hold = 0;
  22971. bits = 0;
  22972. //===//
  22973. state.mode = FLAGS;
  22974. break;
  22975. }
  22976. state.flags = 0; /* expect zlib header */
  22977. if (state.head) {
  22978. state.head.done = false;
  22979. }
  22980. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22981. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22982. strm.msg = 'incorrect header check';
  22983. state.mode = BAD;
  22984. break;
  22985. }
  22986. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22987. strm.msg = 'unknown compression method';
  22988. state.mode = BAD;
  22989. break;
  22990. }
  22991. //--- DROPBITS(4) ---//
  22992. hold >>>= 4;
  22993. bits -= 4;
  22994. //---//
  22995. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22996. if (state.wbits === 0) {
  22997. state.wbits = len;
  22998. }
  22999. else if (len > state.wbits) {
  23000. strm.msg = 'invalid window size';
  23001. state.mode = BAD;
  23002. break;
  23003. }
  23004. state.dmax = 1 << len;
  23005. //Tracev((stderr, "inflate: zlib header ok\n"));
  23006. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23007. state.mode = hold & 0x200 ? DICTID : TYPE;
  23008. //=== INITBITS();
  23009. hold = 0;
  23010. bits = 0;
  23011. //===//
  23012. break;
  23013. case FLAGS:
  23014. //=== NEEDBITS(16); */
  23015. while (bits < 16) {
  23016. if (have === 0) { break inf_leave; }
  23017. have--;
  23018. hold += input[next++] << bits;
  23019. bits += 8;
  23020. }
  23021. //===//
  23022. state.flags = hold;
  23023. if ((state.flags & 0xff) !== Z_DEFLATED) {
  23024. strm.msg = 'unknown compression method';
  23025. state.mode = BAD;
  23026. break;
  23027. }
  23028. if (state.flags & 0xe000) {
  23029. strm.msg = 'unknown header flags set';
  23030. state.mode = BAD;
  23031. break;
  23032. }
  23033. if (state.head) {
  23034. state.head.text = ((hold >> 8) & 1);
  23035. }
  23036. if (state.flags & 0x0200) {
  23037. //=== CRC2(state.check, hold);
  23038. hbuf[0] = hold & 0xff;
  23039. hbuf[1] = (hold >>> 8) & 0xff;
  23040. state.check = crc32(state.check, hbuf, 2, 0);
  23041. //===//
  23042. }
  23043. //=== INITBITS();
  23044. hold = 0;
  23045. bits = 0;
  23046. //===//
  23047. state.mode = TIME;
  23048. /* falls through */
  23049. case TIME:
  23050. //=== NEEDBITS(32); */
  23051. while (bits < 32) {
  23052. if (have === 0) { break inf_leave; }
  23053. have--;
  23054. hold += input[next++] << bits;
  23055. bits += 8;
  23056. }
  23057. //===//
  23058. if (state.head) {
  23059. state.head.time = hold;
  23060. }
  23061. if (state.flags & 0x0200) {
  23062. //=== CRC4(state.check, hold)
  23063. hbuf[0] = hold & 0xff;
  23064. hbuf[1] = (hold >>> 8) & 0xff;
  23065. hbuf[2] = (hold >>> 16) & 0xff;
  23066. hbuf[3] = (hold >>> 24) & 0xff;
  23067. state.check = crc32(state.check, hbuf, 4, 0);
  23068. //===
  23069. }
  23070. //=== INITBITS();
  23071. hold = 0;
  23072. bits = 0;
  23073. //===//
  23074. state.mode = OS;
  23075. /* falls through */
  23076. case OS:
  23077. //=== NEEDBITS(16); */
  23078. while (bits < 16) {
  23079. if (have === 0) { break inf_leave; }
  23080. have--;
  23081. hold += input[next++] << bits;
  23082. bits += 8;
  23083. }
  23084. //===//
  23085. if (state.head) {
  23086. state.head.xflags = (hold & 0xff);
  23087. state.head.os = (hold >> 8);
  23088. }
  23089. if (state.flags & 0x0200) {
  23090. //=== CRC2(state.check, hold);
  23091. hbuf[0] = hold & 0xff;
  23092. hbuf[1] = (hold >>> 8) & 0xff;
  23093. state.check = crc32(state.check, hbuf, 2, 0);
  23094. //===//
  23095. }
  23096. //=== INITBITS();
  23097. hold = 0;
  23098. bits = 0;
  23099. //===//
  23100. state.mode = EXLEN;
  23101. /* falls through */
  23102. case EXLEN:
  23103. if (state.flags & 0x0400) {
  23104. //=== NEEDBITS(16); */
  23105. while (bits < 16) {
  23106. if (have === 0) { break inf_leave; }
  23107. have--;
  23108. hold += input[next++] << bits;
  23109. bits += 8;
  23110. }
  23111. //===//
  23112. state.length = hold;
  23113. if (state.head) {
  23114. state.head.extra_len = hold;
  23115. }
  23116. if (state.flags & 0x0200) {
  23117. //=== CRC2(state.check, hold);
  23118. hbuf[0] = hold & 0xff;
  23119. hbuf[1] = (hold >>> 8) & 0xff;
  23120. state.check = crc32(state.check, hbuf, 2, 0);
  23121. //===//
  23122. }
  23123. //=== INITBITS();
  23124. hold = 0;
  23125. bits = 0;
  23126. //===//
  23127. }
  23128. else if (state.head) {
  23129. state.head.extra = null/*Z_NULL*/;
  23130. }
  23131. state.mode = EXTRA;
  23132. /* falls through */
  23133. case EXTRA:
  23134. if (state.flags & 0x0400) {
  23135. copy = state.length;
  23136. if (copy > have) { copy = have; }
  23137. if (copy) {
  23138. if (state.head) {
  23139. len = state.head.extra_len - state.length;
  23140. if (!state.head.extra) {
  23141. // Use untyped array for more conveniend processing later
  23142. state.head.extra = new Array(state.head.extra_len);
  23143. }
  23144. utils.arraySet(
  23145. state.head.extra,
  23146. input,
  23147. next,
  23148. // extra field is limited to 65536 bytes
  23149. // - no need for additional size check
  23150. copy,
  23151. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  23152. len
  23153. );
  23154. //zmemcpy(state.head.extra + len, next,
  23155. // len + copy > state.head.extra_max ?
  23156. // state.head.extra_max - len : copy);
  23157. }
  23158. if (state.flags & 0x0200) {
  23159. state.check = crc32(state.check, input, copy, next);
  23160. }
  23161. have -= copy;
  23162. next += copy;
  23163. state.length -= copy;
  23164. }
  23165. if (state.length) { break inf_leave; }
  23166. }
  23167. state.length = 0;
  23168. state.mode = NAME;
  23169. /* falls through */
  23170. case NAME:
  23171. if (state.flags & 0x0800) {
  23172. if (have === 0) { break inf_leave; }
  23173. copy = 0;
  23174. do {
  23175. // TODO: 2 or 1 bytes?
  23176. len = input[next + copy++];
  23177. /* use constant limit because in js we should not preallocate memory */
  23178. if (state.head && len &&
  23179. (state.length < 65536 /*state.head.name_max*/)) {
  23180. state.head.name += String.fromCharCode(len);
  23181. }
  23182. } while (len && copy < have);
  23183. if (state.flags & 0x0200) {
  23184. state.check = crc32(state.check, input, copy, next);
  23185. }
  23186. have -= copy;
  23187. next += copy;
  23188. if (len) { break inf_leave; }
  23189. }
  23190. else if (state.head) {
  23191. state.head.name = null;
  23192. }
  23193. state.length = 0;
  23194. state.mode = COMMENT;
  23195. /* falls through */
  23196. case COMMENT:
  23197. if (state.flags & 0x1000) {
  23198. if (have === 0) { break inf_leave; }
  23199. copy = 0;
  23200. do {
  23201. len = input[next + copy++];
  23202. /* use constant limit because in js we should not preallocate memory */
  23203. if (state.head && len &&
  23204. (state.length < 65536 /*state.head.comm_max*/)) {
  23205. state.head.comment += String.fromCharCode(len);
  23206. }
  23207. } while (len && copy < have);
  23208. if (state.flags & 0x0200) {
  23209. state.check = crc32(state.check, input, copy, next);
  23210. }
  23211. have -= copy;
  23212. next += copy;
  23213. if (len) { break inf_leave; }
  23214. }
  23215. else if (state.head) {
  23216. state.head.comment = null;
  23217. }
  23218. state.mode = HCRC;
  23219. /* falls through */
  23220. case HCRC:
  23221. if (state.flags & 0x0200) {
  23222. //=== NEEDBITS(16); */
  23223. while (bits < 16) {
  23224. if (have === 0) { break inf_leave; }
  23225. have--;
  23226. hold += input[next++] << bits;
  23227. bits += 8;
  23228. }
  23229. //===//
  23230. if (hold !== (state.check & 0xffff)) {
  23231. strm.msg = 'header crc mismatch';
  23232. state.mode = BAD;
  23233. break;
  23234. }
  23235. //=== INITBITS();
  23236. hold = 0;
  23237. bits = 0;
  23238. //===//
  23239. }
  23240. if (state.head) {
  23241. state.head.hcrc = ((state.flags >> 9) & 1);
  23242. state.head.done = true;
  23243. }
  23244. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23245. state.mode = TYPE;
  23246. break;
  23247. case DICTID:
  23248. //=== NEEDBITS(32); */
  23249. while (bits < 32) {
  23250. if (have === 0) { break inf_leave; }
  23251. have--;
  23252. hold += input[next++] << bits;
  23253. bits += 8;
  23254. }
  23255. //===//
  23256. strm.adler = state.check = ZSWAP32(hold);
  23257. //=== INITBITS();
  23258. hold = 0;
  23259. bits = 0;
  23260. //===//
  23261. state.mode = DICT;
  23262. /* falls through */
  23263. case DICT:
  23264. if (state.havedict === 0) {
  23265. //--- RESTORE() ---
  23266. strm.next_out = put;
  23267. strm.avail_out = left;
  23268. strm.next_in = next;
  23269. strm.avail_in = have;
  23270. state.hold = hold;
  23271. state.bits = bits;
  23272. //---
  23273. return Z_NEED_DICT;
  23274. }
  23275. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23276. state.mode = TYPE;
  23277. /* falls through */
  23278. case TYPE:
  23279. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23280. /* falls through */
  23281. case TYPEDO:
  23282. if (state.last) {
  23283. //--- BYTEBITS() ---//
  23284. hold >>>= bits & 7;
  23285. bits -= bits & 7;
  23286. //---//
  23287. state.mode = CHECK;
  23288. break;
  23289. }
  23290. //=== NEEDBITS(3); */
  23291. while (bits < 3) {
  23292. if (have === 0) { break inf_leave; }
  23293. have--;
  23294. hold += input[next++] << bits;
  23295. bits += 8;
  23296. }
  23297. //===//
  23298. state.last = (hold & 0x01)/*BITS(1)*/;
  23299. //--- DROPBITS(1) ---//
  23300. hold >>>= 1;
  23301. bits -= 1;
  23302. //---//
  23303. switch ((hold & 0x03)/*BITS(2)*/) {
  23304. case 0: /* stored block */
  23305. //Tracev((stderr, "inflate: stored block%s\n",
  23306. // state.last ? " (last)" : ""));
  23307. state.mode = STORED;
  23308. break;
  23309. case 1: /* fixed block */
  23310. fixedtables(state);
  23311. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23312. // state.last ? " (last)" : ""));
  23313. state.mode = LEN_; /* decode codes */
  23314. if (flush === Z_TREES) {
  23315. //--- DROPBITS(2) ---//
  23316. hold >>>= 2;
  23317. bits -= 2;
  23318. //---//
  23319. break inf_leave;
  23320. }
  23321. break;
  23322. case 2: /* dynamic block */
  23323. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23324. // state.last ? " (last)" : ""));
  23325. state.mode = TABLE;
  23326. break;
  23327. case 3:
  23328. strm.msg = 'invalid block type';
  23329. state.mode = BAD;
  23330. }
  23331. //--- DROPBITS(2) ---//
  23332. hold >>>= 2;
  23333. bits -= 2;
  23334. //---//
  23335. break;
  23336. case STORED:
  23337. //--- BYTEBITS() ---// /* go to byte boundary */
  23338. hold >>>= bits & 7;
  23339. bits -= bits & 7;
  23340. //---//
  23341. //=== NEEDBITS(32); */
  23342. while (bits < 32) {
  23343. if (have === 0) { break inf_leave; }
  23344. have--;
  23345. hold += input[next++] << bits;
  23346. bits += 8;
  23347. }
  23348. //===//
  23349. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23350. strm.msg = 'invalid stored block lengths';
  23351. state.mode = BAD;
  23352. break;
  23353. }
  23354. state.length = hold & 0xffff;
  23355. //Tracev((stderr, "inflate: stored length %u\n",
  23356. // state.length));
  23357. //=== INITBITS();
  23358. hold = 0;
  23359. bits = 0;
  23360. //===//
  23361. state.mode = COPY_;
  23362. if (flush === Z_TREES) { break inf_leave; }
  23363. /* falls through */
  23364. case COPY_:
  23365. state.mode = COPY;
  23366. /* falls through */
  23367. case COPY:
  23368. copy = state.length;
  23369. if (copy) {
  23370. if (copy > have) { copy = have; }
  23371. if (copy > left) { copy = left; }
  23372. if (copy === 0) { break inf_leave; }
  23373. //--- zmemcpy(put, next, copy); ---
  23374. utils.arraySet(output, input, next, copy, put);
  23375. //---//
  23376. have -= copy;
  23377. next += copy;
  23378. left -= copy;
  23379. put += copy;
  23380. state.length -= copy;
  23381. break;
  23382. }
  23383. //Tracev((stderr, "inflate: stored end\n"));
  23384. state.mode = TYPE;
  23385. break;
  23386. case TABLE:
  23387. //=== NEEDBITS(14); */
  23388. while (bits < 14) {
  23389. if (have === 0) { break inf_leave; }
  23390. have--;
  23391. hold += input[next++] << bits;
  23392. bits += 8;
  23393. }
  23394. //===//
  23395. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23396. //--- DROPBITS(5) ---//
  23397. hold >>>= 5;
  23398. bits -= 5;
  23399. //---//
  23400. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23401. //--- DROPBITS(5) ---//
  23402. hold >>>= 5;
  23403. bits -= 5;
  23404. //---//
  23405. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23406. //--- DROPBITS(4) ---//
  23407. hold >>>= 4;
  23408. bits -= 4;
  23409. //---//
  23410. //#ifndef PKZIP_BUG_WORKAROUND
  23411. if (state.nlen > 286 || state.ndist > 30) {
  23412. strm.msg = 'too many length or distance symbols';
  23413. state.mode = BAD;
  23414. break;
  23415. }
  23416. //#endif
  23417. //Tracev((stderr, "inflate: table sizes ok\n"));
  23418. state.have = 0;
  23419. state.mode = LENLENS;
  23420. /* falls through */
  23421. case LENLENS:
  23422. while (state.have < state.ncode) {
  23423. //=== NEEDBITS(3);
  23424. while (bits < 3) {
  23425. if (have === 0) { break inf_leave; }
  23426. have--;
  23427. hold += input[next++] << bits;
  23428. bits += 8;
  23429. }
  23430. //===//
  23431. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23432. //--- DROPBITS(3) ---//
  23433. hold >>>= 3;
  23434. bits -= 3;
  23435. //---//
  23436. }
  23437. while (state.have < 19) {
  23438. state.lens[order[state.have++]] = 0;
  23439. }
  23440. // We have separate tables & no pointers. 2 commented lines below not needed.
  23441. //state.next = state.codes;
  23442. //state.lencode = state.next;
  23443. // Switch to use dynamic table
  23444. state.lencode = state.lendyn;
  23445. state.lenbits = 7;
  23446. opts = {bits: state.lenbits};
  23447. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23448. state.lenbits = opts.bits;
  23449. if (ret) {
  23450. strm.msg = 'invalid code lengths set';
  23451. state.mode = BAD;
  23452. break;
  23453. }
  23454. //Tracev((stderr, "inflate: code lengths ok\n"));
  23455. state.have = 0;
  23456. state.mode = CODELENS;
  23457. /* falls through */
  23458. case CODELENS:
  23459. while (state.have < state.nlen + state.ndist) {
  23460. for (;;) {
  23461. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23462. here_bits = here >>> 24;
  23463. here_op = (here >>> 16) & 0xff;
  23464. here_val = here & 0xffff;
  23465. if ((here_bits) <= bits) { break; }
  23466. //--- PULLBYTE() ---//
  23467. if (have === 0) { break inf_leave; }
  23468. have--;
  23469. hold += input[next++] << bits;
  23470. bits += 8;
  23471. //---//
  23472. }
  23473. if (here_val < 16) {
  23474. //--- DROPBITS(here.bits) ---//
  23475. hold >>>= here_bits;
  23476. bits -= here_bits;
  23477. //---//
  23478. state.lens[state.have++] = here_val;
  23479. }
  23480. else {
  23481. if (here_val === 16) {
  23482. //=== NEEDBITS(here.bits + 2);
  23483. n = here_bits + 2;
  23484. while (bits < n) {
  23485. if (have === 0) { break inf_leave; }
  23486. have--;
  23487. hold += input[next++] << bits;
  23488. bits += 8;
  23489. }
  23490. //===//
  23491. //--- DROPBITS(here.bits) ---//
  23492. hold >>>= here_bits;
  23493. bits -= here_bits;
  23494. //---//
  23495. if (state.have === 0) {
  23496. strm.msg = 'invalid bit length repeat';
  23497. state.mode = BAD;
  23498. break;
  23499. }
  23500. len = state.lens[state.have - 1];
  23501. copy = 3 + (hold & 0x03);//BITS(2);
  23502. //--- DROPBITS(2) ---//
  23503. hold >>>= 2;
  23504. bits -= 2;
  23505. //---//
  23506. }
  23507. else if (here_val === 17) {
  23508. //=== NEEDBITS(here.bits + 3);
  23509. n = here_bits + 3;
  23510. while (bits < n) {
  23511. if (have === 0) { break inf_leave; }
  23512. have--;
  23513. hold += input[next++] << bits;
  23514. bits += 8;
  23515. }
  23516. //===//
  23517. //--- DROPBITS(here.bits) ---//
  23518. hold >>>= here_bits;
  23519. bits -= here_bits;
  23520. //---//
  23521. len = 0;
  23522. copy = 3 + (hold & 0x07);//BITS(3);
  23523. //--- DROPBITS(3) ---//
  23524. hold >>>= 3;
  23525. bits -= 3;
  23526. //---//
  23527. }
  23528. else {
  23529. //=== NEEDBITS(here.bits + 7);
  23530. n = here_bits + 7;
  23531. while (bits < n) {
  23532. if (have === 0) { break inf_leave; }
  23533. have--;
  23534. hold += input[next++] << bits;
  23535. bits += 8;
  23536. }
  23537. //===//
  23538. //--- DROPBITS(here.bits) ---//
  23539. hold >>>= here_bits;
  23540. bits -= here_bits;
  23541. //---//
  23542. len = 0;
  23543. copy = 11 + (hold & 0x7f);//BITS(7);
  23544. //--- DROPBITS(7) ---//
  23545. hold >>>= 7;
  23546. bits -= 7;
  23547. //---//
  23548. }
  23549. if (state.have + copy > state.nlen + state.ndist) {
  23550. strm.msg = 'invalid bit length repeat';
  23551. state.mode = BAD;
  23552. break;
  23553. }
  23554. while (copy--) {
  23555. state.lens[state.have++] = len;
  23556. }
  23557. }
  23558. }
  23559. /* handle error breaks in while */
  23560. if (state.mode === BAD) { break; }
  23561. /* check for end-of-block code (better have one) */
  23562. if (state.lens[256] === 0) {
  23563. strm.msg = 'invalid code -- missing end-of-block';
  23564. state.mode = BAD;
  23565. break;
  23566. }
  23567. /* build code tables -- note: do not change the lenbits or distbits
  23568. values here (9 and 6) without reading the comments in inftrees.h
  23569. concerning the ENOUGH constants, which depend on those values */
  23570. state.lenbits = 9;
  23571. opts = {bits: state.lenbits};
  23572. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23573. // We have separate tables & no pointers. 2 commented lines below not needed.
  23574. // state.next_index = opts.table_index;
  23575. state.lenbits = opts.bits;
  23576. // state.lencode = state.next;
  23577. if (ret) {
  23578. strm.msg = 'invalid literal/lengths set';
  23579. state.mode = BAD;
  23580. break;
  23581. }
  23582. state.distbits = 6;
  23583. //state.distcode.copy(state.codes);
  23584. // Switch to use dynamic table
  23585. state.distcode = state.distdyn;
  23586. opts = {bits: state.distbits};
  23587. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23588. // We have separate tables & no pointers. 2 commented lines below not needed.
  23589. // state.next_index = opts.table_index;
  23590. state.distbits = opts.bits;
  23591. // state.distcode = state.next;
  23592. if (ret) {
  23593. strm.msg = 'invalid distances set';
  23594. state.mode = BAD;
  23595. break;
  23596. }
  23597. //Tracev((stderr, 'inflate: codes ok\n'));
  23598. state.mode = LEN_;
  23599. if (flush === Z_TREES) { break inf_leave; }
  23600. /* falls through */
  23601. case LEN_:
  23602. state.mode = LEN;
  23603. /* falls through */
  23604. case LEN:
  23605. if (have >= 6 && left >= 258) {
  23606. //--- RESTORE() ---
  23607. strm.next_out = put;
  23608. strm.avail_out = left;
  23609. strm.next_in = next;
  23610. strm.avail_in = have;
  23611. state.hold = hold;
  23612. state.bits = bits;
  23613. //---
  23614. inflate_fast(strm, _out);
  23615. //--- LOAD() ---
  23616. put = strm.next_out;
  23617. output = strm.output;
  23618. left = strm.avail_out;
  23619. next = strm.next_in;
  23620. input = strm.input;
  23621. have = strm.avail_in;
  23622. hold = state.hold;
  23623. bits = state.bits;
  23624. //---
  23625. if (state.mode === TYPE) {
  23626. state.back = -1;
  23627. }
  23628. break;
  23629. }
  23630. state.back = 0;
  23631. for (;;) {
  23632. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23633. here_bits = here >>> 24;
  23634. here_op = (here >>> 16) & 0xff;
  23635. here_val = here & 0xffff;
  23636. if (here_bits <= bits) { break; }
  23637. //--- PULLBYTE() ---//
  23638. if (have === 0) { break inf_leave; }
  23639. have--;
  23640. hold += input[next++] << bits;
  23641. bits += 8;
  23642. //---//
  23643. }
  23644. if (here_op && (here_op & 0xf0) === 0) {
  23645. last_bits = here_bits;
  23646. last_op = here_op;
  23647. last_val = here_val;
  23648. for (;;) {
  23649. here = state.lencode[last_val +
  23650. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23651. here_bits = here >>> 24;
  23652. here_op = (here >>> 16) & 0xff;
  23653. here_val = here & 0xffff;
  23654. if ((last_bits + here_bits) <= bits) { break; }
  23655. //--- PULLBYTE() ---//
  23656. if (have === 0) { break inf_leave; }
  23657. have--;
  23658. hold += input[next++] << bits;
  23659. bits += 8;
  23660. //---//
  23661. }
  23662. //--- DROPBITS(last.bits) ---//
  23663. hold >>>= last_bits;
  23664. bits -= last_bits;
  23665. //---//
  23666. state.back += last_bits;
  23667. }
  23668. //--- DROPBITS(here.bits) ---//
  23669. hold >>>= here_bits;
  23670. bits -= here_bits;
  23671. //---//
  23672. state.back += here_bits;
  23673. state.length = here_val;
  23674. if (here_op === 0) {
  23675. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23676. // "inflate: literal '%c'\n" :
  23677. // "inflate: literal 0x%02x\n", here.val));
  23678. state.mode = LIT;
  23679. break;
  23680. }
  23681. if (here_op & 32) {
  23682. //Tracevv((stderr, "inflate: end of block\n"));
  23683. state.back = -1;
  23684. state.mode = TYPE;
  23685. break;
  23686. }
  23687. if (here_op & 64) {
  23688. strm.msg = 'invalid literal/length code';
  23689. state.mode = BAD;
  23690. break;
  23691. }
  23692. state.extra = here_op & 15;
  23693. state.mode = LENEXT;
  23694. /* falls through */
  23695. case LENEXT:
  23696. if (state.extra) {
  23697. //=== NEEDBITS(state.extra);
  23698. n = state.extra;
  23699. while (bits < n) {
  23700. if (have === 0) { break inf_leave; }
  23701. have--;
  23702. hold += input[next++] << bits;
  23703. bits += 8;
  23704. }
  23705. //===//
  23706. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23707. //--- DROPBITS(state.extra) ---//
  23708. hold >>>= state.extra;
  23709. bits -= state.extra;
  23710. //---//
  23711. state.back += state.extra;
  23712. }
  23713. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23714. state.was = state.length;
  23715. state.mode = DIST;
  23716. /* falls through */
  23717. case DIST:
  23718. for (;;) {
  23719. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23720. here_bits = here >>> 24;
  23721. here_op = (here >>> 16) & 0xff;
  23722. here_val = here & 0xffff;
  23723. if ((here_bits) <= bits) { break; }
  23724. //--- PULLBYTE() ---//
  23725. if (have === 0) { break inf_leave; }
  23726. have--;
  23727. hold += input[next++] << bits;
  23728. bits += 8;
  23729. //---//
  23730. }
  23731. if ((here_op & 0xf0) === 0) {
  23732. last_bits = here_bits;
  23733. last_op = here_op;
  23734. last_val = here_val;
  23735. for (;;) {
  23736. here = state.distcode[last_val +
  23737. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23738. here_bits = here >>> 24;
  23739. here_op = (here >>> 16) & 0xff;
  23740. here_val = here & 0xffff;
  23741. if ((last_bits + here_bits) <= bits) { break; }
  23742. //--- PULLBYTE() ---//
  23743. if (have === 0) { break inf_leave; }
  23744. have--;
  23745. hold += input[next++] << bits;
  23746. bits += 8;
  23747. //---//
  23748. }
  23749. //--- DROPBITS(last.bits) ---//
  23750. hold >>>= last_bits;
  23751. bits -= last_bits;
  23752. //---//
  23753. state.back += last_bits;
  23754. }
  23755. //--- DROPBITS(here.bits) ---//
  23756. hold >>>= here_bits;
  23757. bits -= here_bits;
  23758. //---//
  23759. state.back += here_bits;
  23760. if (here_op & 64) {
  23761. strm.msg = 'invalid distance code';
  23762. state.mode = BAD;
  23763. break;
  23764. }
  23765. state.offset = here_val;
  23766. state.extra = (here_op) & 15;
  23767. state.mode = DISTEXT;
  23768. /* falls through */
  23769. case DISTEXT:
  23770. if (state.extra) {
  23771. //=== NEEDBITS(state.extra);
  23772. n = state.extra;
  23773. while (bits < n) {
  23774. if (have === 0) { break inf_leave; }
  23775. have--;
  23776. hold += input[next++] << bits;
  23777. bits += 8;
  23778. }
  23779. //===//
  23780. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23781. //--- DROPBITS(state.extra) ---//
  23782. hold >>>= state.extra;
  23783. bits -= state.extra;
  23784. //---//
  23785. state.back += state.extra;
  23786. }
  23787. //#ifdef INFLATE_STRICT
  23788. if (state.offset > state.dmax) {
  23789. strm.msg = 'invalid distance too far back';
  23790. state.mode = BAD;
  23791. break;
  23792. }
  23793. //#endif
  23794. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23795. state.mode = MATCH;
  23796. /* falls through */
  23797. case MATCH:
  23798. if (left === 0) { break inf_leave; }
  23799. copy = _out - left;
  23800. if (state.offset > copy) { /* copy from window */
  23801. copy = state.offset - copy;
  23802. if (copy > state.whave) {
  23803. if (state.sane) {
  23804. strm.msg = 'invalid distance too far back';
  23805. state.mode = BAD;
  23806. break;
  23807. }
  23808. // (!) This block is disabled in zlib defailts,
  23809. // don't enable it for binary compatibility
  23810. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23811. // Trace((stderr, "inflate.c too far\n"));
  23812. // copy -= state.whave;
  23813. // if (copy > state.length) { copy = state.length; }
  23814. // if (copy > left) { copy = left; }
  23815. // left -= copy;
  23816. // state.length -= copy;
  23817. // do {
  23818. // output[put++] = 0;
  23819. // } while (--copy);
  23820. // if (state.length === 0) { state.mode = LEN; }
  23821. // break;
  23822. //#endif
  23823. }
  23824. if (copy > state.wnext) {
  23825. copy -= state.wnext;
  23826. from = state.wsize - copy;
  23827. }
  23828. else {
  23829. from = state.wnext - copy;
  23830. }
  23831. if (copy > state.length) { copy = state.length; }
  23832. from_source = state.window;
  23833. }
  23834. else { /* copy from output */
  23835. from_source = output;
  23836. from = put - state.offset;
  23837. copy = state.length;
  23838. }
  23839. if (copy > left) { copy = left; }
  23840. left -= copy;
  23841. state.length -= copy;
  23842. do {
  23843. output[put++] = from_source[from++];
  23844. } while (--copy);
  23845. if (state.length === 0) { state.mode = LEN; }
  23846. break;
  23847. case LIT:
  23848. if (left === 0) { break inf_leave; }
  23849. output[put++] = state.length;
  23850. left--;
  23851. state.mode = LEN;
  23852. break;
  23853. case CHECK:
  23854. if (state.wrap) {
  23855. //=== NEEDBITS(32);
  23856. while (bits < 32) {
  23857. if (have === 0) { break inf_leave; }
  23858. have--;
  23859. // Use '|' insdead of '+' to make sure that result is signed
  23860. hold |= input[next++] << bits;
  23861. bits += 8;
  23862. }
  23863. //===//
  23864. _out -= left;
  23865. strm.total_out += _out;
  23866. state.total += _out;
  23867. if (_out) {
  23868. strm.adler = state.check =
  23869. /*UPDATE(state.check, put - _out, _out);*/
  23870. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23871. }
  23872. _out = left;
  23873. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23874. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23875. strm.msg = 'incorrect data check';
  23876. state.mode = BAD;
  23877. break;
  23878. }
  23879. //=== INITBITS();
  23880. hold = 0;
  23881. bits = 0;
  23882. //===//
  23883. //Tracev((stderr, "inflate: check matches trailer\n"));
  23884. }
  23885. state.mode = LENGTH;
  23886. /* falls through */
  23887. case LENGTH:
  23888. if (state.wrap && state.flags) {
  23889. //=== NEEDBITS(32);
  23890. while (bits < 32) {
  23891. if (have === 0) { break inf_leave; }
  23892. have--;
  23893. hold += input[next++] << bits;
  23894. bits += 8;
  23895. }
  23896. //===//
  23897. if (hold !== (state.total & 0xffffffff)) {
  23898. strm.msg = 'incorrect length check';
  23899. state.mode = BAD;
  23900. break;
  23901. }
  23902. //=== INITBITS();
  23903. hold = 0;
  23904. bits = 0;
  23905. //===//
  23906. //Tracev((stderr, "inflate: length matches trailer\n"));
  23907. }
  23908. state.mode = DONE;
  23909. /* falls through */
  23910. case DONE:
  23911. ret = Z_STREAM_END;
  23912. break inf_leave;
  23913. case BAD:
  23914. ret = Z_DATA_ERROR;
  23915. break inf_leave;
  23916. case MEM:
  23917. return Z_MEM_ERROR;
  23918. case SYNC:
  23919. /* falls through */
  23920. default:
  23921. return Z_STREAM_ERROR;
  23922. }
  23923. }
  23924. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23925. /*
  23926. Return from inflate(), updating the total counts and the check value.
  23927. If there was no progress during the inflate() call, return a buffer
  23928. error. Call updatewindow() to create and/or update the window state.
  23929. Note: a memory error from inflate() is non-recoverable.
  23930. */
  23931. //--- RESTORE() ---
  23932. strm.next_out = put;
  23933. strm.avail_out = left;
  23934. strm.next_in = next;
  23935. strm.avail_in = have;
  23936. state.hold = hold;
  23937. state.bits = bits;
  23938. //---
  23939. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23940. (state.mode < CHECK || flush !== Z_FINISH))) {
  23941. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23942. state.mode = MEM;
  23943. return Z_MEM_ERROR;
  23944. }
  23945. }
  23946. _in -= strm.avail_in;
  23947. _out -= strm.avail_out;
  23948. strm.total_in += _in;
  23949. strm.total_out += _out;
  23950. state.total += _out;
  23951. if (state.wrap && _out) {
  23952. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23953. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23954. }
  23955. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23956. (state.mode === TYPE ? 128 : 0) +
  23957. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23958. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23959. ret = Z_BUF_ERROR;
  23960. }
  23961. return ret;
  23962. }
  23963. function inflateEnd(strm) {
  23964. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23965. return Z_STREAM_ERROR;
  23966. }
  23967. var state = strm.state;
  23968. if (state.window) {
  23969. state.window = null;
  23970. }
  23971. strm.state = null;
  23972. return Z_OK;
  23973. }
  23974. function inflateGetHeader(strm, head) {
  23975. var state;
  23976. /* check state */
  23977. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23978. state = strm.state;
  23979. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23980. /* save header structure */
  23981. state.head = head;
  23982. head.done = false;
  23983. return Z_OK;
  23984. }
  23985. exports.inflateReset = inflateReset;
  23986. exports.inflateReset2 = inflateReset2;
  23987. exports.inflateResetKeep = inflateResetKeep;
  23988. exports.inflateInit = inflateInit;
  23989. exports.inflateInit2 = inflateInit2;
  23990. exports.inflate = inflate;
  23991. exports.inflateEnd = inflateEnd;
  23992. exports.inflateGetHeader = inflateGetHeader;
  23993. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23994. /* Not implemented
  23995. exports.inflateCopy = inflateCopy;
  23996. exports.inflateGetDictionary = inflateGetDictionary;
  23997. exports.inflateMark = inflateMark;
  23998. exports.inflatePrime = inflatePrime;
  23999. exports.inflateSetDictionary = inflateSetDictionary;
  24000. exports.inflateSync = inflateSync;
  24001. exports.inflateSyncPoint = inflateSyncPoint;
  24002. exports.inflateUndermine = inflateUndermine;
  24003. */
  24004. },{"../utils/common":74,"./adler32":76,"./crc32":78,"./inffast":81,"./inftrees":83}],83:[function(require,module,exports){
  24005. 'use strict';
  24006. var utils = require('../utils/common');
  24007. var MAXBITS = 15;
  24008. var ENOUGH_LENS = 852;
  24009. var ENOUGH_DISTS = 592;
  24010. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  24011. var CODES = 0;
  24012. var LENS = 1;
  24013. var DISTS = 2;
  24014. var lbase = [ /* Length codes 257..285 base */
  24015. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  24016. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  24017. ];
  24018. var lext = [ /* Length codes 257..285 extra */
  24019. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  24020. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  24021. ];
  24022. var dbase = [ /* Distance codes 0..29 base */
  24023. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  24024. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  24025. 8193, 12289, 16385, 24577, 0, 0
  24026. ];
  24027. var dext = [ /* Distance codes 0..29 extra */
  24028. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  24029. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  24030. 28, 28, 29, 29, 64, 64
  24031. ];
  24032. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  24033. {
  24034. var bits = opts.bits;
  24035. //here = opts.here; /* table entry for duplication */
  24036. var len = 0; /* a code's length in bits */
  24037. var sym = 0; /* index of code symbols */
  24038. var min = 0, max = 0; /* minimum and maximum code lengths */
  24039. var root = 0; /* number of index bits for root table */
  24040. var curr = 0; /* number of index bits for current table */
  24041. var drop = 0; /* code bits to drop for sub-table */
  24042. var left = 0; /* number of prefix codes available */
  24043. var used = 0; /* code entries in table used */
  24044. var huff = 0; /* Huffman code */
  24045. var incr; /* for incrementing code, index */
  24046. var fill; /* index for replicating entries */
  24047. var low; /* low bits for current root entry */
  24048. var mask; /* mask for low root bits */
  24049. var next; /* next available space in table */
  24050. var base = null; /* base value table to use */
  24051. var base_index = 0;
  24052. // var shoextra; /* extra bits table to use */
  24053. var end; /* use base and extra for symbol > end */
  24054. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  24055. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  24056. var extra = null;
  24057. var extra_index = 0;
  24058. var here_bits, here_op, here_val;
  24059. /*
  24060. Process a set of code lengths to create a canonical Huffman code. The
  24061. code lengths are lens[0..codes-1]. Each length corresponds to the
  24062. symbols 0..codes-1. The Huffman code is generated by first sorting the
  24063. symbols by length from short to long, and retaining the symbol order
  24064. for codes with equal lengths. Then the code starts with all zero bits
  24065. for the first code of the shortest length, and the codes are integer
  24066. increments for the same length, and zeros are appended as the length
  24067. increases. For the deflate format, these bits are stored backwards
  24068. from their more natural integer increment ordering, and so when the
  24069. decoding tables are built in the large loop below, the integer codes
  24070. are incremented backwards.
  24071. This routine assumes, but does not check, that all of the entries in
  24072. lens[] are in the range 0..MAXBITS. The caller must assure this.
  24073. 1..MAXBITS is interpreted as that code length. zero means that that
  24074. symbol does not occur in this code.
  24075. The codes are sorted by computing a count of codes for each length,
  24076. creating from that a table of starting indices for each length in the
  24077. sorted table, and then entering the symbols in order in the sorted
  24078. table. The sorted table is work[], with that space being provided by
  24079. the caller.
  24080. The length counts are used for other purposes as well, i.e. finding
  24081. the minimum and maximum length codes, determining if there are any
  24082. codes at all, checking for a valid set of lengths, and looking ahead
  24083. at length counts to determine sub-table sizes when building the
  24084. decoding tables.
  24085. */
  24086. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  24087. for (len = 0; len <= MAXBITS; len++) {
  24088. count[len] = 0;
  24089. }
  24090. for (sym = 0; sym < codes; sym++) {
  24091. count[lens[lens_index + sym]]++;
  24092. }
  24093. /* bound code lengths, force root to be within code lengths */
  24094. root = bits;
  24095. for (max = MAXBITS; max >= 1; max--) {
  24096. if (count[max] !== 0) { break; }
  24097. }
  24098. if (root > max) {
  24099. root = max;
  24100. }
  24101. if (max === 0) { /* no symbols to code at all */
  24102. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  24103. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  24104. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  24105. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24106. //table.op[opts.table_index] = 64;
  24107. //table.bits[opts.table_index] = 1;
  24108. //table.val[opts.table_index++] = 0;
  24109. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24110. opts.bits = 1;
  24111. return 0; /* no symbols, but wait for decoding to report error */
  24112. }
  24113. for (min = 1; min < max; min++) {
  24114. if (count[min] !== 0) { break; }
  24115. }
  24116. if (root < min) {
  24117. root = min;
  24118. }
  24119. /* check for an over-subscribed or incomplete set of lengths */
  24120. left = 1;
  24121. for (len = 1; len <= MAXBITS; len++) {
  24122. left <<= 1;
  24123. left -= count[len];
  24124. if (left < 0) {
  24125. return -1;
  24126. } /* over-subscribed */
  24127. }
  24128. if (left > 0 && (type === CODES || max !== 1)) {
  24129. return -1; /* incomplete set */
  24130. }
  24131. /* generate offsets into symbol table for each length for sorting */
  24132. offs[1] = 0;
  24133. for (len = 1; len < MAXBITS; len++) {
  24134. offs[len + 1] = offs[len] + count[len];
  24135. }
  24136. /* sort symbols by length, by symbol order within each length */
  24137. for (sym = 0; sym < codes; sym++) {
  24138. if (lens[lens_index + sym] !== 0) {
  24139. work[offs[lens[lens_index + sym]]++] = sym;
  24140. }
  24141. }
  24142. /*
  24143. Create and fill in decoding tables. In this loop, the table being
  24144. filled is at next and has curr index bits. The code being used is huff
  24145. with length len. That code is converted to an index by dropping drop
  24146. bits off of the bottom. For codes where len is less than drop + curr,
  24147. those top drop + curr - len bits are incremented through all values to
  24148. fill the table with replicated entries.
  24149. root is the number of index bits for the root table. When len exceeds
  24150. root, sub-tables are created pointed to by the root entry with an index
  24151. of the low root bits of huff. This is saved in low to check for when a
  24152. new sub-table should be started. drop is zero when the root table is
  24153. being filled, and drop is root when sub-tables are being filled.
  24154. When a new sub-table is needed, it is necessary to look ahead in the
  24155. code lengths to determine what size sub-table is needed. The length
  24156. counts are used for this, and so count[] is decremented as codes are
  24157. entered in the tables.
  24158. used keeps track of how many table entries have been allocated from the
  24159. provided *table space. It is checked for LENS and DIST tables against
  24160. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24161. the initial root table size constants. See the comments in inftrees.h
  24162. for more information.
  24163. sym increments through all symbols, and the loop terminates when
  24164. all codes of length max, i.e. all codes, have been processed. This
  24165. routine permits incomplete codes, so another loop after this one fills
  24166. in the rest of the decoding tables with invalid code markers.
  24167. */
  24168. /* set up for code type */
  24169. // poor man optimization - use if-else instead of switch,
  24170. // to avoid deopts in old v8
  24171. if (type === CODES) {
  24172. base = extra = work; /* dummy value--not used */
  24173. end = 19;
  24174. } else if (type === LENS) {
  24175. base = lbase;
  24176. base_index -= 257;
  24177. extra = lext;
  24178. extra_index -= 257;
  24179. end = 256;
  24180. } else { /* DISTS */
  24181. base = dbase;
  24182. extra = dext;
  24183. end = -1;
  24184. }
  24185. /* initialize opts for loop */
  24186. huff = 0; /* starting code */
  24187. sym = 0; /* starting code symbol */
  24188. len = min; /* starting code length */
  24189. next = table_index; /* current table to fill in */
  24190. curr = root; /* current table index bits */
  24191. drop = 0; /* current bits to drop from code for index */
  24192. low = -1; /* trigger new sub-table when len > root */
  24193. used = 1 << root; /* use root table entries */
  24194. mask = used - 1; /* mask for comparing low */
  24195. /* check available table space */
  24196. if ((type === LENS && used > ENOUGH_LENS) ||
  24197. (type === DISTS && used > ENOUGH_DISTS)) {
  24198. return 1;
  24199. }
  24200. var i=0;
  24201. /* process all codes and make table entries */
  24202. for (;;) {
  24203. i++;
  24204. /* create table entry */
  24205. here_bits = len - drop;
  24206. if (work[sym] < end) {
  24207. here_op = 0;
  24208. here_val = work[sym];
  24209. }
  24210. else if (work[sym] > end) {
  24211. here_op = extra[extra_index + work[sym]];
  24212. here_val = base[base_index + work[sym]];
  24213. }
  24214. else {
  24215. here_op = 32 + 64; /* end of block */
  24216. here_val = 0;
  24217. }
  24218. /* replicate for those indices with low len bits equal to huff */
  24219. incr = 1 << (len - drop);
  24220. fill = 1 << curr;
  24221. min = fill; /* save offset to next table */
  24222. do {
  24223. fill -= incr;
  24224. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24225. } while (fill !== 0);
  24226. /* backwards increment the len-bit code huff */
  24227. incr = 1 << (len - 1);
  24228. while (huff & incr) {
  24229. incr >>= 1;
  24230. }
  24231. if (incr !== 0) {
  24232. huff &= incr - 1;
  24233. huff += incr;
  24234. } else {
  24235. huff = 0;
  24236. }
  24237. /* go to next symbol, update count, len */
  24238. sym++;
  24239. if (--count[len] === 0) {
  24240. if (len === max) { break; }
  24241. len = lens[lens_index + work[sym]];
  24242. }
  24243. /* create new sub-table if needed */
  24244. if (len > root && (huff & mask) !== low) {
  24245. /* if first time, transition to sub-tables */
  24246. if (drop === 0) {
  24247. drop = root;
  24248. }
  24249. /* increment past last table */
  24250. next += min; /* here min is 1 << curr */
  24251. /* determine length of next table */
  24252. curr = len - drop;
  24253. left = 1 << curr;
  24254. while (curr + drop < max) {
  24255. left -= count[curr + drop];
  24256. if (left <= 0) { break; }
  24257. curr++;
  24258. left <<= 1;
  24259. }
  24260. /* check for enough space */
  24261. used += 1 << curr;
  24262. if ((type === LENS && used > ENOUGH_LENS) ||
  24263. (type === DISTS && used > ENOUGH_DISTS)) {
  24264. return 1;
  24265. }
  24266. /* point entry in root table to sub-table */
  24267. low = huff & mask;
  24268. /*table.op[low] = curr;
  24269. table.bits[low] = root;
  24270. table.val[low] = next - opts.table_index;*/
  24271. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24272. }
  24273. }
  24274. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24275. at most one remaining entry, since if the code is incomplete, the
  24276. maximum code length that was allowed to get this far is one bit) */
  24277. if (huff !== 0) {
  24278. //table.op[next + huff] = 64; /* invalid code marker */
  24279. //table.bits[next + huff] = len - drop;
  24280. //table.val[next + huff] = 0;
  24281. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24282. }
  24283. /* set return parameters */
  24284. //opts.table_index += used;
  24285. opts.bits = root;
  24286. return 0;
  24287. };
  24288. },{"../utils/common":74}],84:[function(require,module,exports){
  24289. 'use strict';
  24290. module.exports = {
  24291. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24292. '1': 'stream end', /* Z_STREAM_END 1 */
  24293. '0': '', /* Z_OK 0 */
  24294. '-1': 'file error', /* Z_ERRNO (-1) */
  24295. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24296. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24297. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24298. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24299. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24300. };
  24301. },{}],85:[function(require,module,exports){
  24302. 'use strict';
  24303. var utils = require('../utils/common');
  24304. /* Public constants ==========================================================*/
  24305. /* ===========================================================================*/
  24306. //var Z_FILTERED = 1;
  24307. //var Z_HUFFMAN_ONLY = 2;
  24308. //var Z_RLE = 3;
  24309. var Z_FIXED = 4;
  24310. //var Z_DEFAULT_STRATEGY = 0;
  24311. /* Possible values of the data_type field (though see inflate()) */
  24312. var Z_BINARY = 0;
  24313. var Z_TEXT = 1;
  24314. //var Z_ASCII = 1; // = Z_TEXT
  24315. var Z_UNKNOWN = 2;
  24316. /*============================================================================*/
  24317. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24318. // From zutil.h
  24319. var STORED_BLOCK = 0;
  24320. var STATIC_TREES = 1;
  24321. var DYN_TREES = 2;
  24322. /* The three kinds of block type */
  24323. var MIN_MATCH = 3;
  24324. var MAX_MATCH = 258;
  24325. /* The minimum and maximum match lengths */
  24326. // From deflate.h
  24327. /* ===========================================================================
  24328. * Internal compression state.
  24329. */
  24330. var LENGTH_CODES = 29;
  24331. /* number of length codes, not counting the special END_BLOCK code */
  24332. var LITERALS = 256;
  24333. /* number of literal bytes 0..255 */
  24334. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24335. /* number of Literal or Length codes, including the END_BLOCK code */
  24336. var D_CODES = 30;
  24337. /* number of distance codes */
  24338. var BL_CODES = 19;
  24339. /* number of codes used to transfer the bit lengths */
  24340. var HEAP_SIZE = 2*L_CODES + 1;
  24341. /* maximum heap size */
  24342. var MAX_BITS = 15;
  24343. /* All codes must not exceed MAX_BITS bits */
  24344. var Buf_size = 16;
  24345. /* size of bit buffer in bi_buf */
  24346. /* ===========================================================================
  24347. * Constants
  24348. */
  24349. var MAX_BL_BITS = 7;
  24350. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24351. var END_BLOCK = 256;
  24352. /* end of block literal code */
  24353. var REP_3_6 = 16;
  24354. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24355. var REPZ_3_10 = 17;
  24356. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24357. var REPZ_11_138 = 18;
  24358. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24359. var extra_lbits = /* extra bits for each length code */
  24360. [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];
  24361. var extra_dbits = /* extra bits for each distance code */
  24362. [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];
  24363. var extra_blbits = /* extra bits for each bit length code */
  24364. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24365. var bl_order =
  24366. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24367. /* The lengths of the bit length codes are sent in order of decreasing
  24368. * probability, to avoid transmitting the lengths for unused bit length codes.
  24369. */
  24370. /* ===========================================================================
  24371. * Local data. These are initialized only once.
  24372. */
  24373. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24374. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24375. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24376. var static_ltree = new Array((L_CODES+2) * 2);
  24377. zero(static_ltree);
  24378. /* The static literal tree. Since the bit lengths are imposed, there is no
  24379. * need for the L_CODES extra codes used during heap construction. However
  24380. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24381. * below).
  24382. */
  24383. var static_dtree = new Array(D_CODES * 2);
  24384. zero(static_dtree);
  24385. /* The static distance tree. (Actually a trivial tree since all codes use
  24386. * 5 bits.)
  24387. */
  24388. var _dist_code = new Array(DIST_CODE_LEN);
  24389. zero(_dist_code);
  24390. /* Distance codes. The first 256 values correspond to the distances
  24391. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24392. * the 15 bit distances.
  24393. */
  24394. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24395. zero(_length_code);
  24396. /* length code for each normalized match length (0 == MIN_MATCH) */
  24397. var base_length = new Array(LENGTH_CODES);
  24398. zero(base_length);
  24399. /* First normalized length for each code (0 = MIN_MATCH) */
  24400. var base_dist = new Array(D_CODES);
  24401. zero(base_dist);
  24402. /* First normalized distance for each code (0 = distance of 1) */
  24403. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24404. this.static_tree = static_tree; /* static tree or NULL */
  24405. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24406. this.extra_base = extra_base; /* base index for extra_bits */
  24407. this.elems = elems; /* max number of elements in the tree */
  24408. this.max_length = max_length; /* max bit length for the codes */
  24409. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24410. this.has_stree = static_tree && static_tree.length;
  24411. };
  24412. var static_l_desc;
  24413. var static_d_desc;
  24414. var static_bl_desc;
  24415. var TreeDesc = function(dyn_tree, stat_desc) {
  24416. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24417. this.max_code = 0; /* largest code with non zero frequency */
  24418. this.stat_desc = stat_desc; /* the corresponding static tree */
  24419. };
  24420. function d_code(dist) {
  24421. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24422. }
  24423. /* ===========================================================================
  24424. * Output a short LSB first on the stream.
  24425. * IN assertion: there is enough room in pendingBuf.
  24426. */
  24427. function put_short (s, w) {
  24428. // put_byte(s, (uch)((w) & 0xff));
  24429. // put_byte(s, (uch)((ush)(w) >> 8));
  24430. s.pending_buf[s.pending++] = (w) & 0xff;
  24431. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24432. }
  24433. /* ===========================================================================
  24434. * Send a value on a given number of bits.
  24435. * IN assertion: length <= 16 and value fits in length bits.
  24436. */
  24437. function send_bits(s, value, length) {
  24438. if (s.bi_valid > (Buf_size - length)) {
  24439. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24440. put_short(s, s.bi_buf);
  24441. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24442. s.bi_valid += length - Buf_size;
  24443. } else {
  24444. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24445. s.bi_valid += length;
  24446. }
  24447. }
  24448. function send_code(s, c, tree) {
  24449. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24450. }
  24451. /* ===========================================================================
  24452. * Reverse the first len bits of a code, using straightforward code (a faster
  24453. * method would use a table)
  24454. * IN assertion: 1 <= len <= 15
  24455. */
  24456. function bi_reverse(code, len) {
  24457. var res = 0;
  24458. do {
  24459. res |= code & 1;
  24460. code >>>= 1;
  24461. res <<= 1;
  24462. } while (--len > 0);
  24463. return res >>> 1;
  24464. }
  24465. /* ===========================================================================
  24466. * Flush the bit buffer, keeping at most 7 bits in it.
  24467. */
  24468. function bi_flush(s) {
  24469. if (s.bi_valid === 16) {
  24470. put_short(s, s.bi_buf);
  24471. s.bi_buf = 0;
  24472. s.bi_valid = 0;
  24473. } else if (s.bi_valid >= 8) {
  24474. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24475. s.bi_buf >>= 8;
  24476. s.bi_valid -= 8;
  24477. }
  24478. }
  24479. /* ===========================================================================
  24480. * Compute the optimal bit lengths for a tree and update the total bit length
  24481. * for the current block.
  24482. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24483. * above are the tree nodes sorted by increasing frequency.
  24484. * OUT assertions: the field len is set to the optimal bit length, the
  24485. * array bl_count contains the frequencies for each bit length.
  24486. * The length opt_len is updated; static_len is also updated if stree is
  24487. * not null.
  24488. */
  24489. function gen_bitlen(s, desc)
  24490. // deflate_state *s;
  24491. // tree_desc *desc; /* the tree descriptor */
  24492. {
  24493. var tree = desc.dyn_tree;
  24494. var max_code = desc.max_code;
  24495. var stree = desc.stat_desc.static_tree;
  24496. var has_stree = desc.stat_desc.has_stree;
  24497. var extra = desc.stat_desc.extra_bits;
  24498. var base = desc.stat_desc.extra_base;
  24499. var max_length = desc.stat_desc.max_length;
  24500. var h; /* heap index */
  24501. var n, m; /* iterate over the tree elements */
  24502. var bits; /* bit length */
  24503. var xbits; /* extra bits */
  24504. var f; /* frequency */
  24505. var overflow = 0; /* number of elements with bit length too large */
  24506. for (bits = 0; bits <= MAX_BITS; bits++) {
  24507. s.bl_count[bits] = 0;
  24508. }
  24509. /* In a first pass, compute the optimal bit lengths (which may
  24510. * overflow in the case of the bit length tree).
  24511. */
  24512. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24513. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24514. n = s.heap[h];
  24515. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24516. if (bits > max_length) {
  24517. bits = max_length;
  24518. overflow++;
  24519. }
  24520. tree[n*2 + 1]/*.Len*/ = bits;
  24521. /* We overwrite tree[n].Dad which is no longer needed */
  24522. if (n > max_code) { continue; } /* not a leaf node */
  24523. s.bl_count[bits]++;
  24524. xbits = 0;
  24525. if (n >= base) {
  24526. xbits = extra[n-base];
  24527. }
  24528. f = tree[n * 2]/*.Freq*/;
  24529. s.opt_len += f * (bits + xbits);
  24530. if (has_stree) {
  24531. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24532. }
  24533. }
  24534. if (overflow === 0) { return; }
  24535. // Trace((stderr,"\nbit length overflow\n"));
  24536. /* This happens for example on obj2 and pic of the Calgary corpus */
  24537. /* Find the first bit length which could increase: */
  24538. do {
  24539. bits = max_length-1;
  24540. while (s.bl_count[bits] === 0) { bits--; }
  24541. s.bl_count[bits]--; /* move one leaf down the tree */
  24542. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24543. s.bl_count[max_length]--;
  24544. /* The brother of the overflow item also moves one step up,
  24545. * but this does not affect bl_count[max_length]
  24546. */
  24547. overflow -= 2;
  24548. } while (overflow > 0);
  24549. /* Now recompute all bit lengths, scanning in increasing frequency.
  24550. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24551. * lengths instead of fixing only the wrong ones. This idea is taken
  24552. * from 'ar' written by Haruhiko Okumura.)
  24553. */
  24554. for (bits = max_length; bits !== 0; bits--) {
  24555. n = s.bl_count[bits];
  24556. while (n !== 0) {
  24557. m = s.heap[--h];
  24558. if (m > max_code) { continue; }
  24559. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24560. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24561. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24562. tree[m*2 + 1]/*.Len*/ = bits;
  24563. }
  24564. n--;
  24565. }
  24566. }
  24567. }
  24568. /* ===========================================================================
  24569. * Generate the codes for a given tree and bit counts (which need not be
  24570. * optimal).
  24571. * IN assertion: the array bl_count contains the bit length statistics for
  24572. * the given tree and the field len is set for all tree elements.
  24573. * OUT assertion: the field code is set for all tree elements of non
  24574. * zero code length.
  24575. */
  24576. function gen_codes(tree, max_code, bl_count)
  24577. // ct_data *tree; /* the tree to decorate */
  24578. // int max_code; /* largest code with non zero frequency */
  24579. // ushf *bl_count; /* number of codes at each bit length */
  24580. {
  24581. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24582. var code = 0; /* running code value */
  24583. var bits; /* bit index */
  24584. var n; /* code index */
  24585. /* The distribution counts are first used to generate the code values
  24586. * without bit reversal.
  24587. */
  24588. for (bits = 1; bits <= MAX_BITS; bits++) {
  24589. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24590. }
  24591. /* Check that the bit counts in bl_count are consistent. The last code
  24592. * must be all ones.
  24593. */
  24594. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24595. // "inconsistent bit counts");
  24596. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24597. for (n = 0; n <= max_code; n++) {
  24598. var len = tree[n*2 + 1]/*.Len*/;
  24599. if (len === 0) { continue; }
  24600. /* Now reverse the bits */
  24601. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24602. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24603. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24604. }
  24605. }
  24606. /* ===========================================================================
  24607. * Initialize the various 'constant' tables.
  24608. */
  24609. function tr_static_init() {
  24610. var n; /* iterates over tree elements */
  24611. var bits; /* bit counter */
  24612. var length; /* length value */
  24613. var code; /* code value */
  24614. var dist; /* distance index */
  24615. var bl_count = new Array(MAX_BITS+1);
  24616. /* number of codes at each bit length for an optimal tree */
  24617. // do check in _tr_init()
  24618. //if (static_init_done) return;
  24619. /* For some embedded targets, global variables are not initialized: */
  24620. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24621. static_l_desc.static_tree = static_ltree;
  24622. static_l_desc.extra_bits = extra_lbits;
  24623. static_d_desc.static_tree = static_dtree;
  24624. static_d_desc.extra_bits = extra_dbits;
  24625. static_bl_desc.extra_bits = extra_blbits;
  24626. #endif*/
  24627. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24628. length = 0;
  24629. for (code = 0; code < LENGTH_CODES-1; code++) {
  24630. base_length[code] = length;
  24631. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24632. _length_code[length++] = code;
  24633. }
  24634. }
  24635. //Assert (length == 256, "tr_static_init: length != 256");
  24636. /* Note that the length 255 (match length 258) can be represented
  24637. * in two different ways: code 284 + 5 bits or code 285, so we
  24638. * overwrite length_code[255] to use the best encoding:
  24639. */
  24640. _length_code[length-1] = code;
  24641. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24642. dist = 0;
  24643. for (code = 0 ; code < 16; code++) {
  24644. base_dist[code] = dist;
  24645. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24646. _dist_code[dist++] = code;
  24647. }
  24648. }
  24649. //Assert (dist == 256, "tr_static_init: dist != 256");
  24650. dist >>= 7; /* from now on, all distances are divided by 128 */
  24651. for (; code < D_CODES; code++) {
  24652. base_dist[code] = dist << 7;
  24653. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24654. _dist_code[256 + dist++] = code;
  24655. }
  24656. }
  24657. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24658. /* Construct the codes of the static literal tree */
  24659. for (bits = 0; bits <= MAX_BITS; bits++) {
  24660. bl_count[bits] = 0;
  24661. }
  24662. n = 0;
  24663. while (n <= 143) {
  24664. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24665. n++;
  24666. bl_count[8]++;
  24667. }
  24668. while (n <= 255) {
  24669. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24670. n++;
  24671. bl_count[9]++;
  24672. }
  24673. while (n <= 279) {
  24674. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24675. n++;
  24676. bl_count[7]++;
  24677. }
  24678. while (n <= 287) {
  24679. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24680. n++;
  24681. bl_count[8]++;
  24682. }
  24683. /* Codes 286 and 287 do not exist, but we must include them in the
  24684. * tree construction to get a canonical Huffman tree (longest code
  24685. * all ones)
  24686. */
  24687. gen_codes(static_ltree, L_CODES+1, bl_count);
  24688. /* The static distance tree is trivial: */
  24689. for (n = 0; n < D_CODES; n++) {
  24690. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24691. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24692. }
  24693. // Now data ready and we can init static trees
  24694. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24695. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24696. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24697. //static_init_done = true;
  24698. }
  24699. /* ===========================================================================
  24700. * Initialize a new block.
  24701. */
  24702. function init_block(s) {
  24703. var n; /* iterates over tree elements */
  24704. /* Initialize the trees. */
  24705. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24706. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24707. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24708. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24709. s.opt_len = s.static_len = 0;
  24710. s.last_lit = s.matches = 0;
  24711. }
  24712. /* ===========================================================================
  24713. * Flush the bit buffer and align the output on a byte boundary
  24714. */
  24715. function bi_windup(s)
  24716. {
  24717. if (s.bi_valid > 8) {
  24718. put_short(s, s.bi_buf);
  24719. } else if (s.bi_valid > 0) {
  24720. //put_byte(s, (Byte)s->bi_buf);
  24721. s.pending_buf[s.pending++] = s.bi_buf;
  24722. }
  24723. s.bi_buf = 0;
  24724. s.bi_valid = 0;
  24725. }
  24726. /* ===========================================================================
  24727. * Copy a stored block, storing first the length and its
  24728. * one's complement if requested.
  24729. */
  24730. function copy_block(s, buf, len, header)
  24731. //DeflateState *s;
  24732. //charf *buf; /* the input data */
  24733. //unsigned len; /* its length */
  24734. //int header; /* true if block header must be written */
  24735. {
  24736. bi_windup(s); /* align on byte boundary */
  24737. if (header) {
  24738. put_short(s, len);
  24739. put_short(s, ~len);
  24740. }
  24741. // while (len--) {
  24742. // put_byte(s, *buf++);
  24743. // }
  24744. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24745. s.pending += len;
  24746. }
  24747. /* ===========================================================================
  24748. * Compares to subtrees, using the tree depth as tie breaker when
  24749. * the subtrees have equal frequency. This minimizes the worst case length.
  24750. */
  24751. function smaller(tree, n, m, depth) {
  24752. var _n2 = n*2;
  24753. var _m2 = m*2;
  24754. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24755. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24756. }
  24757. /* ===========================================================================
  24758. * Restore the heap property by moving down the tree starting at node k,
  24759. * exchanging a node with the smallest of its two sons if necessary, stopping
  24760. * when the heap property is re-established (each father smaller than its
  24761. * two sons).
  24762. */
  24763. function pqdownheap(s, tree, k)
  24764. // deflate_state *s;
  24765. // ct_data *tree; /* the tree to restore */
  24766. // int k; /* node to move down */
  24767. {
  24768. var v = s.heap[k];
  24769. var j = k << 1; /* left son of k */
  24770. while (j <= s.heap_len) {
  24771. /* Set j to the smallest of the two sons: */
  24772. if (j < s.heap_len &&
  24773. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24774. j++;
  24775. }
  24776. /* Exit if v is smaller than both sons */
  24777. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24778. /* Exchange v with the smallest son */
  24779. s.heap[k] = s.heap[j];
  24780. k = j;
  24781. /* And continue down the tree, setting j to the left son of k */
  24782. j <<= 1;
  24783. }
  24784. s.heap[k] = v;
  24785. }
  24786. // inlined manually
  24787. // var SMALLEST = 1;
  24788. /* ===========================================================================
  24789. * Send the block data compressed using the given Huffman trees
  24790. */
  24791. function compress_block(s, ltree, dtree)
  24792. // deflate_state *s;
  24793. // const ct_data *ltree; /* literal tree */
  24794. // const ct_data *dtree; /* distance tree */
  24795. {
  24796. var dist; /* distance of matched string */
  24797. var lc; /* match length or unmatched char (if dist == 0) */
  24798. var lx = 0; /* running index in l_buf */
  24799. var code; /* the code to send */
  24800. var extra; /* number of extra bits to send */
  24801. if (s.last_lit !== 0) {
  24802. do {
  24803. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24804. lc = s.pending_buf[s.l_buf + lx];
  24805. lx++;
  24806. if (dist === 0) {
  24807. send_code(s, lc, ltree); /* send a literal byte */
  24808. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24809. } else {
  24810. /* Here, lc is the match length - MIN_MATCH */
  24811. code = _length_code[lc];
  24812. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24813. extra = extra_lbits[code];
  24814. if (extra !== 0) {
  24815. lc -= base_length[code];
  24816. send_bits(s, lc, extra); /* send the extra length bits */
  24817. }
  24818. dist--; /* dist is now the match distance - 1 */
  24819. code = d_code(dist);
  24820. //Assert (code < D_CODES, "bad d_code");
  24821. send_code(s, code, dtree); /* send the distance code */
  24822. extra = extra_dbits[code];
  24823. if (extra !== 0) {
  24824. dist -= base_dist[code];
  24825. send_bits(s, dist, extra); /* send the extra distance bits */
  24826. }
  24827. } /* literal or match pair ? */
  24828. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24829. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24830. // "pendingBuf overflow");
  24831. } while (lx < s.last_lit);
  24832. }
  24833. send_code(s, END_BLOCK, ltree);
  24834. }
  24835. /* ===========================================================================
  24836. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24837. * Update the total bit length for the current block.
  24838. * IN assertion: the field freq is set for all tree elements.
  24839. * OUT assertions: the fields len and code are set to the optimal bit length
  24840. * and corresponding code. The length opt_len is updated; static_len is
  24841. * also updated if stree is not null. The field max_code is set.
  24842. */
  24843. function build_tree(s, desc)
  24844. // deflate_state *s;
  24845. // tree_desc *desc; /* the tree descriptor */
  24846. {
  24847. var tree = desc.dyn_tree;
  24848. var stree = desc.stat_desc.static_tree;
  24849. var has_stree = desc.stat_desc.has_stree;
  24850. var elems = desc.stat_desc.elems;
  24851. var n, m; /* iterate over heap elements */
  24852. var max_code = -1; /* largest code with non zero frequency */
  24853. var node; /* new node being created */
  24854. /* Construct the initial heap, with least frequent element in
  24855. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24856. * heap[0] is not used.
  24857. */
  24858. s.heap_len = 0;
  24859. s.heap_max = HEAP_SIZE;
  24860. for (n = 0; n < elems; n++) {
  24861. if (tree[n * 2]/*.Freq*/ !== 0) {
  24862. s.heap[++s.heap_len] = max_code = n;
  24863. s.depth[n] = 0;
  24864. } else {
  24865. tree[n*2 + 1]/*.Len*/ = 0;
  24866. }
  24867. }
  24868. /* The pkzip format requires that at least one distance code exists,
  24869. * and that at least one bit should be sent even if there is only one
  24870. * possible code. So to avoid special checks later on we force at least
  24871. * two codes of non zero frequency.
  24872. */
  24873. while (s.heap_len < 2) {
  24874. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24875. tree[node * 2]/*.Freq*/ = 1;
  24876. s.depth[node] = 0;
  24877. s.opt_len--;
  24878. if (has_stree) {
  24879. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24880. }
  24881. /* node is 0 or 1 so it does not have extra bits */
  24882. }
  24883. desc.max_code = max_code;
  24884. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24885. * establish sub-heaps of increasing lengths:
  24886. */
  24887. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24888. /* Construct the Huffman tree by repeatedly combining the least two
  24889. * frequent nodes.
  24890. */
  24891. node = elems; /* next internal node of the tree */
  24892. do {
  24893. //pqremove(s, tree, n); /* n = node of least frequency */
  24894. /*** pqremove ***/
  24895. n = s.heap[1/*SMALLEST*/];
  24896. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24897. pqdownheap(s, tree, 1/*SMALLEST*/);
  24898. /***/
  24899. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24900. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24901. s.heap[--s.heap_max] = m;
  24902. /* Create a new node father of n and m */
  24903. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24904. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24905. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24906. /* and insert the new node in the heap */
  24907. s.heap[1/*SMALLEST*/] = node++;
  24908. pqdownheap(s, tree, 1/*SMALLEST*/);
  24909. } while (s.heap_len >= 2);
  24910. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24911. /* At this point, the fields freq and dad are set. We can now
  24912. * generate the bit lengths.
  24913. */
  24914. gen_bitlen(s, desc);
  24915. /* The field len is now set, we can generate the bit codes */
  24916. gen_codes(tree, max_code, s.bl_count);
  24917. }
  24918. /* ===========================================================================
  24919. * Scan a literal or distance tree to determine the frequencies of the codes
  24920. * in the bit length tree.
  24921. */
  24922. function scan_tree(s, tree, max_code)
  24923. // deflate_state *s;
  24924. // ct_data *tree; /* the tree to be scanned */
  24925. // int max_code; /* and its largest code of non zero frequency */
  24926. {
  24927. var n; /* iterates over all tree elements */
  24928. var prevlen = -1; /* last emitted length */
  24929. var curlen; /* length of current code */
  24930. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24931. var count = 0; /* repeat count of the current code */
  24932. var max_count = 7; /* max repeat count */
  24933. var min_count = 4; /* min repeat count */
  24934. if (nextlen === 0) {
  24935. max_count = 138;
  24936. min_count = 3;
  24937. }
  24938. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24939. for (n = 0; n <= max_code; n++) {
  24940. curlen = nextlen;
  24941. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24942. if (++count < max_count && curlen === nextlen) {
  24943. continue;
  24944. } else if (count < min_count) {
  24945. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24946. } else if (curlen !== 0) {
  24947. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24948. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24949. } else if (count <= 10) {
  24950. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24951. } else {
  24952. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24953. }
  24954. count = 0;
  24955. prevlen = curlen;
  24956. if (nextlen === 0) {
  24957. max_count = 138;
  24958. min_count = 3;
  24959. } else if (curlen === nextlen) {
  24960. max_count = 6;
  24961. min_count = 3;
  24962. } else {
  24963. max_count = 7;
  24964. min_count = 4;
  24965. }
  24966. }
  24967. }
  24968. /* ===========================================================================
  24969. * Send a literal or distance tree in compressed form, using the codes in
  24970. * bl_tree.
  24971. */
  24972. function send_tree(s, tree, max_code)
  24973. // deflate_state *s;
  24974. // ct_data *tree; /* the tree to be scanned */
  24975. // int max_code; /* and its largest code of non zero frequency */
  24976. {
  24977. var n; /* iterates over all tree elements */
  24978. var prevlen = -1; /* last emitted length */
  24979. var curlen; /* length of current code */
  24980. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24981. var count = 0; /* repeat count of the current code */
  24982. var max_count = 7; /* max repeat count */
  24983. var min_count = 4; /* min repeat count */
  24984. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24985. if (nextlen === 0) {
  24986. max_count = 138;
  24987. min_count = 3;
  24988. }
  24989. for (n = 0; n <= max_code; n++) {
  24990. curlen = nextlen;
  24991. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24992. if (++count < max_count && curlen === nextlen) {
  24993. continue;
  24994. } else if (count < min_count) {
  24995. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24996. } else if (curlen !== 0) {
  24997. if (curlen !== prevlen) {
  24998. send_code(s, curlen, s.bl_tree);
  24999. count--;
  25000. }
  25001. //Assert(count >= 3 && count <= 6, " 3_6?");
  25002. send_code(s, REP_3_6, s.bl_tree);
  25003. send_bits(s, count-3, 2);
  25004. } else if (count <= 10) {
  25005. send_code(s, REPZ_3_10, s.bl_tree);
  25006. send_bits(s, count-3, 3);
  25007. } else {
  25008. send_code(s, REPZ_11_138, s.bl_tree);
  25009. send_bits(s, count-11, 7);
  25010. }
  25011. count = 0;
  25012. prevlen = curlen;
  25013. if (nextlen === 0) {
  25014. max_count = 138;
  25015. min_count = 3;
  25016. } else if (curlen === nextlen) {
  25017. max_count = 6;
  25018. min_count = 3;
  25019. } else {
  25020. max_count = 7;
  25021. min_count = 4;
  25022. }
  25023. }
  25024. }
  25025. /* ===========================================================================
  25026. * Construct the Huffman tree for the bit lengths and return the index in
  25027. * bl_order of the last bit length code to send.
  25028. */
  25029. function build_bl_tree(s) {
  25030. var max_blindex; /* index of last bit length code of non zero freq */
  25031. /* Determine the bit length frequencies for literal and distance trees */
  25032. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  25033. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  25034. /* Build the bit length tree: */
  25035. build_tree(s, s.bl_desc);
  25036. /* opt_len now includes the length of the tree representations, except
  25037. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  25038. */
  25039. /* Determine the number of bit length codes to send. The pkzip format
  25040. * requires that at least 4 bit length codes be sent. (appnote.txt says
  25041. * 3 but the actual value used is 4.)
  25042. */
  25043. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  25044. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  25045. break;
  25046. }
  25047. }
  25048. /* Update opt_len to include the bit length tree and counts */
  25049. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  25050. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  25051. // s->opt_len, s->static_len));
  25052. return max_blindex;
  25053. }
  25054. /* ===========================================================================
  25055. * Send the header for a block using dynamic Huffman trees: the counts, the
  25056. * lengths of the bit length codes, the literal tree and the distance tree.
  25057. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  25058. */
  25059. function send_all_trees(s, lcodes, dcodes, blcodes)
  25060. // deflate_state *s;
  25061. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  25062. {
  25063. var rank; /* index in bl_order */
  25064. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  25065. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  25066. // "too many codes");
  25067. //Tracev((stderr, "\nbl counts: "));
  25068. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  25069. send_bits(s, dcodes-1, 5);
  25070. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  25071. for (rank = 0; rank < blcodes; rank++) {
  25072. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  25073. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  25074. }
  25075. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  25076. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  25077. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  25078. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  25079. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  25080. }
  25081. /* ===========================================================================
  25082. * Check if the data type is TEXT or BINARY, using the following algorithm:
  25083. * - TEXT if the two conditions below are satisfied:
  25084. * a) There are no non-portable control characters belonging to the
  25085. * "black list" (0..6, 14..25, 28..31).
  25086. * b) There is at least one printable character belonging to the
  25087. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  25088. * - BINARY otherwise.
  25089. * - The following partially-portable control characters form a
  25090. * "gray list" that is ignored in this detection algorithm:
  25091. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  25092. * IN assertion: the fields Freq of dyn_ltree are set.
  25093. */
  25094. function detect_data_type(s) {
  25095. /* black_mask is the bit mask of black-listed bytes
  25096. * set bits 0..6, 14..25, and 28..31
  25097. * 0xf3ffc07f = binary 11110011111111111100000001111111
  25098. */
  25099. var black_mask = 0xf3ffc07f;
  25100. var n;
  25101. /* Check for non-textual ("black-listed") bytes. */
  25102. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  25103. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  25104. return Z_BINARY;
  25105. }
  25106. }
  25107. /* Check for textual ("white-listed") bytes. */
  25108. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  25109. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  25110. return Z_TEXT;
  25111. }
  25112. for (n = 32; n < LITERALS; n++) {
  25113. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  25114. return Z_TEXT;
  25115. }
  25116. }
  25117. /* There are no "black-listed" or "white-listed" bytes:
  25118. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  25119. */
  25120. return Z_BINARY;
  25121. }
  25122. var static_init_done = false;
  25123. /* ===========================================================================
  25124. * Initialize the tree data structures for a new zlib stream.
  25125. */
  25126. function _tr_init(s)
  25127. {
  25128. if (!static_init_done) {
  25129. tr_static_init();
  25130. static_init_done = true;
  25131. }
  25132. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  25133. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  25134. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  25135. s.bi_buf = 0;
  25136. s.bi_valid = 0;
  25137. /* Initialize the first block of the first file: */
  25138. init_block(s);
  25139. }
  25140. /* ===========================================================================
  25141. * Send a stored block
  25142. */
  25143. function _tr_stored_block(s, buf, stored_len, last)
  25144. //DeflateState *s;
  25145. //charf *buf; /* input block */
  25146. //ulg stored_len; /* length of input block */
  25147. //int last; /* one if this is the last block for a file */
  25148. {
  25149. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  25150. copy_block(s, buf, stored_len, true); /* with header */
  25151. }
  25152. /* ===========================================================================
  25153. * Send one empty static block to give enough lookahead for inflate.
  25154. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25155. */
  25156. function _tr_align(s) {
  25157. send_bits(s, STATIC_TREES<<1, 3);
  25158. send_code(s, END_BLOCK, static_ltree);
  25159. bi_flush(s);
  25160. }
  25161. /* ===========================================================================
  25162. * Determine the best encoding for the current block: dynamic trees, static
  25163. * trees or store, and output the encoded block to the zip file.
  25164. */
  25165. function _tr_flush_block(s, buf, stored_len, last)
  25166. //DeflateState *s;
  25167. //charf *buf; /* input block, or NULL if too old */
  25168. //ulg stored_len; /* length of input block */
  25169. //int last; /* one if this is the last block for a file */
  25170. {
  25171. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25172. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25173. /* Build the Huffman trees unless a stored block is forced */
  25174. if (s.level > 0) {
  25175. /* Check if the file is binary or text */
  25176. if (s.strm.data_type === Z_UNKNOWN) {
  25177. s.strm.data_type = detect_data_type(s);
  25178. }
  25179. /* Construct the literal and distance trees */
  25180. build_tree(s, s.l_desc);
  25181. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25182. // s->static_len));
  25183. build_tree(s, s.d_desc);
  25184. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25185. // s->static_len));
  25186. /* At this point, opt_len and static_len are the total bit lengths of
  25187. * the compressed block data, excluding the tree representations.
  25188. */
  25189. /* Build the bit length tree for the above two trees, and get the index
  25190. * in bl_order of the last bit length code to send.
  25191. */
  25192. max_blindex = build_bl_tree(s);
  25193. /* Determine the best encoding. Compute the block lengths in bytes. */
  25194. opt_lenb = (s.opt_len+3+7) >>> 3;
  25195. static_lenb = (s.static_len+3+7) >>> 3;
  25196. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25197. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25198. // s->last_lit));
  25199. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25200. } else {
  25201. // Assert(buf != (char*)0, "lost buf");
  25202. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25203. }
  25204. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25205. /* 4: two words for the lengths */
  25206. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25207. * Otherwise we can't have processed more than WSIZE input bytes since
  25208. * the last block flush, because compression would have been
  25209. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25210. * transform a block into a stored block.
  25211. */
  25212. _tr_stored_block(s, buf, stored_len, last);
  25213. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25214. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25215. compress_block(s, static_ltree, static_dtree);
  25216. } else {
  25217. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25218. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25219. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25220. }
  25221. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25222. /* The above check is made mod 2^32, for files larger than 512 MB
  25223. * and uLong implemented on 32 bits.
  25224. */
  25225. init_block(s);
  25226. if (last) {
  25227. bi_windup(s);
  25228. }
  25229. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25230. // s->compressed_len-7*last));
  25231. }
  25232. /* ===========================================================================
  25233. * Save the match info and tally the frequency counts. Return true if
  25234. * the current block must be flushed.
  25235. */
  25236. function _tr_tally(s, dist, lc)
  25237. // deflate_state *s;
  25238. // unsigned dist; /* distance of matched string */
  25239. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25240. {
  25241. //var out_length, in_length, dcode;
  25242. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25243. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25244. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25245. s.last_lit++;
  25246. if (dist === 0) {
  25247. /* lc is the unmatched char */
  25248. s.dyn_ltree[lc*2]/*.Freq*/++;
  25249. } else {
  25250. s.matches++;
  25251. /* Here, lc is the match length - MIN_MATCH */
  25252. dist--; /* dist = match distance - 1 */
  25253. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25254. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25255. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25256. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25257. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25258. }
  25259. // (!) This block is disabled in zlib defailts,
  25260. // don't enable it for binary compatibility
  25261. //#ifdef TRUNCATE_BLOCK
  25262. // /* Try to guess if it is profitable to stop the current block here */
  25263. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25264. // /* Compute an upper bound for the compressed length */
  25265. // out_length = s.last_lit*8;
  25266. // in_length = s.strstart - s.block_start;
  25267. //
  25268. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25269. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25270. // }
  25271. // out_length >>>= 3;
  25272. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25273. // // s->last_lit, in_length, out_length,
  25274. // // 100L - out_length*100L/in_length));
  25275. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25276. // return true;
  25277. // }
  25278. // }
  25279. //#endif
  25280. return (s.last_lit === s.lit_bufsize-1);
  25281. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25282. * on 16 bit machines and because stored blocks are restricted to
  25283. * 64K-1 bytes.
  25284. */
  25285. }
  25286. exports._tr_init = _tr_init;
  25287. exports._tr_stored_block = _tr_stored_block;
  25288. exports._tr_flush_block = _tr_flush_block;
  25289. exports._tr_tally = _tr_tally;
  25290. exports._tr_align = _tr_align;
  25291. },{"../utils/common":74}],86:[function(require,module,exports){
  25292. 'use strict';
  25293. function ZStream() {
  25294. /* next input byte */
  25295. this.input = null; // JS specific, because we have no pointers
  25296. this.next_in = 0;
  25297. /* number of bytes available at input */
  25298. this.avail_in = 0;
  25299. /* total number of input bytes read so far */
  25300. this.total_in = 0;
  25301. /* next output byte should be put there */
  25302. this.output = null; // JS specific, because we have no pointers
  25303. this.next_out = 0;
  25304. /* remaining free space at output */
  25305. this.avail_out = 0;
  25306. /* total number of bytes output so far */
  25307. this.total_out = 0;
  25308. /* last error message, NULL if no error */
  25309. this.msg = ''/*Z_NULL*/;
  25310. /* not visible by applications */
  25311. this.state = null;
  25312. /* best guess about the data type: binary or text */
  25313. this.data_type = 2/*Z_UNKNOWN*/;
  25314. /* adler32 value of the uncompressed data */
  25315. this.adler = 0;
  25316. }
  25317. module.exports = ZStream;
  25318. },{}],87:[function(require,module,exports){
  25319. module.exports = require('./lib/retry');
  25320. },{"./lib/retry":88}],88:[function(require,module,exports){
  25321. var RetryOperation = require('./retry_operation');
  25322. exports.operation = function(options) {
  25323. var timeouts = exports.timeouts(options);
  25324. return new RetryOperation(timeouts);
  25325. };
  25326. exports.timeouts = function(options) {
  25327. if (options instanceof Array) {
  25328. return [].concat(options);
  25329. }
  25330. var opts = {
  25331. retries: 10,
  25332. factor: 2,
  25333. minTimeout: 1 * 1000,
  25334. maxTimeout: Infinity,
  25335. randomize: false
  25336. };
  25337. for (var key in options) {
  25338. opts[key] = options[key];
  25339. }
  25340. if (opts.minTimeout > opts.maxTimeout) {
  25341. throw new Error('minTimeout is greater than maxTimeout');
  25342. }
  25343. var timeouts = [];
  25344. for (var i = 0; i < opts.retries; i++) {
  25345. timeouts.push(this._createTimeout(i, opts));
  25346. }
  25347. // sort the array numerically ascending
  25348. timeouts.sort(function(a,b) {
  25349. return a - b;
  25350. });
  25351. return timeouts;
  25352. };
  25353. exports._createTimeout = function(attempt, opts) {
  25354. var random = (opts.randomize)
  25355. ? (Math.random() + 1)
  25356. : 1;
  25357. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25358. timeout = Math.min(timeout, opts.maxTimeout);
  25359. return timeout;
  25360. };
  25361. },{"./retry_operation":89}],89:[function(require,module,exports){
  25362. function RetryOperation(timeouts) {
  25363. this._timeouts = timeouts;
  25364. this._fn = null;
  25365. this._errors = [];
  25366. this._attempts = 1;
  25367. this._operationTimeout = null;
  25368. this._operationTimeoutCb = null;
  25369. this._timeout = null;
  25370. }
  25371. module.exports = RetryOperation;
  25372. RetryOperation.prototype.retry = function(err) {
  25373. if (this._timeout) {
  25374. clearTimeout(this._timeout);
  25375. }
  25376. if (!err) {
  25377. return false;
  25378. }
  25379. this._errors.push(err);
  25380. var timeout = this._timeouts.shift();
  25381. if (timeout === undefined) {
  25382. return false;
  25383. }
  25384. this._attempts++;
  25385. var self = this;
  25386. setTimeout(function() {
  25387. self._fn(self._attempts);
  25388. if (self._operationTimeoutCb) {
  25389. self._timeout = setTimeout(function() {
  25390. self._operationTimeoutCb(self._attempts);
  25391. }, self._operationTimeout);
  25392. }
  25393. }, timeout);
  25394. return true;
  25395. };
  25396. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25397. this._fn = fn;
  25398. if (timeoutOps) {
  25399. if (timeoutOps.timeout) {
  25400. this._operationTimeout = timeoutOps.timeout;
  25401. }
  25402. if (timeoutOps.cb) {
  25403. this._operationTimeoutCb = timeoutOps.cb;
  25404. }
  25405. }
  25406. this._fn(this._attempts);
  25407. var self = this;
  25408. if (this._operationTimeoutCb) {
  25409. this._timeout = setTimeout(function() {
  25410. self._operationTimeoutCb();
  25411. }, self._operationTimeout);
  25412. }
  25413. };
  25414. RetryOperation.prototype.try = function(fn) {
  25415. console.log('Using RetryOperation.try() is deprecated');
  25416. this.attempt(fn);
  25417. };
  25418. RetryOperation.prototype.start = function(fn) {
  25419. console.log('Using RetryOperation.start() is deprecated');
  25420. this.attempt(fn);
  25421. };
  25422. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25423. RetryOperation.prototype.errors = function() {
  25424. return this._errors;
  25425. };
  25426. RetryOperation.prototype.attempts = function() {
  25427. return this._attempts;
  25428. };
  25429. RetryOperation.prototype.mainError = function() {
  25430. if (this._errors.length === 0) {
  25431. return null;
  25432. }
  25433. var counts = {};
  25434. var mainError = null;
  25435. var mainErrorCount = 0;
  25436. for (var i = 0; i < this._errors.length; i++) {
  25437. var error = this._errors[i];
  25438. var message = error.message;
  25439. var count = (counts[message] || 0) + 1;
  25440. counts[message] = count;
  25441. if (count >= mainErrorCount) {
  25442. mainError = error;
  25443. mainErrorCount = count;
  25444. }
  25445. }
  25446. return mainError;
  25447. };
  25448. },{}],90:[function(require,module,exports){
  25449. module.exports = function arrayEquals(array) {
  25450. // if the other array is a falsy value, return
  25451. if (!array)
  25452. return false;
  25453. // compare lengths - can save a lot of time
  25454. if (this.length != array.length)
  25455. return false;
  25456. for (var i = 0, l = this.length; i < l; i++) {
  25457. // Check if we have nested arrays
  25458. if (this[i] instanceof Array && array[i] instanceof Array) {
  25459. // recurse into the nested arrays
  25460. if (!arrayEquals.apply(this[i], [array[i]]))
  25461. return false;
  25462. } else if (this[i] != array[i]) {
  25463. // Warning - two different object instances will never be equal:
  25464. // {x:20} != {x:20}
  25465. return false;
  25466. }
  25467. }
  25468. return true;
  25469. }
  25470. },{}],91:[function(require,module,exports){
  25471. exports.Interop = require('./interop');
  25472. },{"./interop":92}],92:[function(require,module,exports){
  25473. "use strict";
  25474. var transform = require('./transform');
  25475. var arrayEquals = require('./array-equals');
  25476. function Interop() {
  25477. /**
  25478. * This map holds the most recent Unified Plan offer/answer SDP that was
  25479. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25480. * the SDP string as values.
  25481. *
  25482. * @type {{}}
  25483. */
  25484. this.cache = {};
  25485. }
  25486. module.exports = Interop;
  25487. /**
  25488. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25489. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25490. * application.
  25491. *
  25492. * @param desc
  25493. * @returns {*}
  25494. */
  25495. Interop.prototype.toPlanB = function(desc) {
  25496. //#region Preliminary input validation.
  25497. if (typeof desc !== 'object' || desc === null ||
  25498. typeof desc.sdp !== 'string') {
  25499. console.warn('An empty description was passed as an argument.');
  25500. return desc;
  25501. }
  25502. // Objectify the SDP for easier manipulation.
  25503. var session = transform.parse(desc.sdp);
  25504. // If the SDP contains no media, there's nothing to transform.
  25505. if (typeof session.media === 'undefined' ||
  25506. !Array.isArray(session.media) || session.media.length === 0) {
  25507. console.warn('The description has no media.');
  25508. return desc;
  25509. }
  25510. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25511. // SDP has a video, an audio and a data "channel" at most.
  25512. if (session.media.length <= 3 && session.media.every(function(m) {
  25513. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25514. })) {
  25515. console.warn('This description does not look like Unified Plan.');
  25516. return desc;
  25517. }
  25518. //#endregion
  25519. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25520. // -> Unified Plan transformation.
  25521. this.cache[desc.type] = desc.sdp;
  25522. //#region Convert from Unified Plan to Plan B.
  25523. // We rebuild the session.media array.
  25524. var media = session.media;
  25525. session.media = [];
  25526. // Associative array that maps channel types to channel objects for fast
  25527. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25528. // obj.
  25529. var type2bl = {};
  25530. // Used to build the group:BUNDLE value after the channels construction
  25531. // loop.
  25532. var types = [];
  25533. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25534. media.forEach(function(unifiedLine) {
  25535. // rtcp-mux is required in the Plan B SDP.
  25536. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25537. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25538. unifiedLine.direction !== 'inactive') {
  25539. throw new Error('Cannot convert to Plan B because m-lines ' +
  25540. 'without the rtcp-mux attribute were found.');
  25541. }
  25542. if (unifiedLine.type === 'application') {
  25543. session.media.push(unifiedLine);
  25544. types.push(unifiedLine.mid);
  25545. return;
  25546. }
  25547. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25548. // as the channel basis.
  25549. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25550. type2bl[unifiedLine.type] = unifiedLine;
  25551. }
  25552. // Add sources to the channel and handle a=msid.
  25553. if (typeof unifiedLine.sources === 'object') {
  25554. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25555. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25556. type2bl[unifiedLine.type].sources = {};
  25557. // Assign the sources to the channel.
  25558. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25559. if (typeof unifiedLine.msid !== 'undefined') {
  25560. // In Plan B the msid is an SSRC attribute. Also, we don't
  25561. // care about the obsolete label and mslabel attributes.
  25562. //
  25563. // Note that it is not guaranteed that the unifiedLine will have
  25564. // an msid. recvonly channels in particular don't have one.
  25565. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25566. }
  25567. // NOTE ssrcs in ssrc groups will share msids, as
  25568. // draft-uberti-rtcweb-plan-00 mandates.
  25569. });
  25570. }
  25571. // Add ssrc groups to the channel.
  25572. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25573. Array.isArray(unifiedLine.ssrcGroups)) {
  25574. // Create the ssrcGroups array, if it's not defined.
  25575. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25576. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25577. type2bl[unifiedLine.type].ssrcGroups = [];
  25578. }
  25579. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25580. }
  25581. if (type2bl[unifiedLine.type] === unifiedLine) {
  25582. // Copy ICE related stuff from the principal media line.
  25583. unifiedLine.candidates = media[0].candidates;
  25584. unifiedLine.iceUfrag = media[0].iceUfrag;
  25585. unifiedLine.icePwd = media[0].icePwd;
  25586. unifiedLine.fingerprint = media[0].fingerprint;
  25587. // Plan B mids are in ['audio', 'video', 'data']
  25588. unifiedLine.mid = unifiedLine.type;
  25589. // Plan B doesn't support/need the bundle-only attribute.
  25590. delete unifiedLine.bundleOnly;
  25591. // In Plan B the msid is an SSRC attribute.
  25592. delete unifiedLine.msid;
  25593. // Used to build the group:BUNDLE value after this loop.
  25594. types.push(unifiedLine.type);
  25595. // Add the channel to the new media array.
  25596. session.media.push(unifiedLine);
  25597. }
  25598. });
  25599. // We regenerate the BUNDLE group with the new mids.
  25600. session.groups.some(function(group) {
  25601. if (group.type === 'BUNDLE') {
  25602. group.mids = types.join(' ');
  25603. return true;
  25604. }
  25605. });
  25606. // msid semantic
  25607. session.msidSemantic = {
  25608. semantic: 'WMS',
  25609. token: '*'
  25610. };
  25611. var resStr = transform.write(session);
  25612. return new RTCSessionDescription({
  25613. type: desc.type,
  25614. sdp: resStr
  25615. });
  25616. //#endregion
  25617. };
  25618. /**
  25619. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25620. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25621. * to FF.
  25622. *
  25623. * @param desc
  25624. * @returns {*}
  25625. */
  25626. Interop.prototype.toUnifiedPlan = function(desc) {
  25627. //#region Preliminary input validation.
  25628. if (typeof desc !== 'object' || desc === null ||
  25629. typeof desc.sdp !== 'string') {
  25630. console.warn('An empty description was passed as an argument.');
  25631. return desc;
  25632. }
  25633. var session = transform.parse(desc.sdp);
  25634. // If the SDP contains no media, there's nothing to transform.
  25635. if (typeof session.media === 'undefined' ||
  25636. !Array.isArray(session.media) || session.media.length === 0) {
  25637. console.warn('The description has no media.');
  25638. return desc;
  25639. }
  25640. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25641. // a video, an audio and a data "channel" at most.
  25642. if (session.media.length > 3 || !session.media.every(function(m) {
  25643. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25644. })) {
  25645. console.warn('This description does not look like Plan B.');
  25646. return desc;
  25647. }
  25648. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25649. var mids = [];
  25650. session.media.forEach(function(m) {
  25651. mids.push(m.mid);
  25652. });
  25653. var hasBundle = false;
  25654. if (typeof session.groups !== 'undefined' &&
  25655. Array.isArray(session.groups)) {
  25656. hasBundle = session.groups.every(function(g) {
  25657. return g.type !== 'BUNDLE' ||
  25658. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25659. });
  25660. }
  25661. if (!hasBundle) {
  25662. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25663. " are not bundled were found.");
  25664. }
  25665. //#endregion
  25666. //#region Convert from Plan B to Unified Plan.
  25667. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25668. // rebuild an equivalent Unified Plan offer/answer.
  25669. //
  25670. // For example, if this is a local answer (in Unified Plan style) that we
  25671. // convert to Plan B prior to handing it over to the application (the
  25672. // PeerConnection wrapper called us, for instance, after a successful
  25673. // createAnswer), we want to remember the m-line at which we've seen the
  25674. // (local) SSRC. That's because when the application wants to do call the
  25675. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25676. // Unified Plan), we need to know to which m-line to assign the (local)
  25677. // SSRC. We also need to know all the other m-lines that the original
  25678. // answer had and include them in the transformed answer as well.
  25679. //
  25680. // Another example is if this is a remote offer that we convert to Plan B
  25681. // prior to giving it to the application, we want to remember the mid at
  25682. // which we've seen the (remote) SSRC.
  25683. //
  25684. // In the iteration that follows, we use the cached Unified Plan (if it
  25685. // exists) to assign mids to ssrcs.
  25686. var cached;
  25687. if (typeof this.cache[desc.type] !== 'undefined') {
  25688. cached = transform.parse(this.cache[desc.type]);
  25689. }
  25690. // A helper map that sends mids to m-line objects. We use it later to
  25691. // rebuild the Unified Plan style session.media array.
  25692. var mid2ul = {};
  25693. session.media.forEach(function(bLine) {
  25694. if ((typeof bLine.rtcpMux !== 'string' ||
  25695. bLine.rtcpMux !== 'rtcp-mux') &&
  25696. bLine.direction !== 'inactive') {
  25697. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25698. "without the rtcp-mux attribute were found.");
  25699. }
  25700. if (bLine.type === 'application') {
  25701. mid2ul[bLine.mid] = bLine;
  25702. return;
  25703. }
  25704. // With rtcp-mux and bundle all the channels should have the same ICE
  25705. // stuff.
  25706. var sources = bLine.sources;
  25707. var ssrcGroups = bLine.ssrcGroups;
  25708. var candidates = bLine.candidates;
  25709. var iceUfrag = bLine.iceUfrag;
  25710. var icePwd = bLine.icePwd;
  25711. var fingerprint = bLine.fingerprint;
  25712. var port = bLine.port;
  25713. // We'll use the "bLine" object as a prototype for each new "mLine"
  25714. // that we create, but first we need to clean it up a bit.
  25715. delete bLine.sources;
  25716. delete bLine.ssrcGroups;
  25717. delete bLine.candidates;
  25718. delete bLine.iceUfrag;
  25719. delete bLine.icePwd;
  25720. delete bLine.fingerprint;
  25721. delete bLine.port;
  25722. delete bLine.mid;
  25723. // inverted ssrc group map
  25724. var ssrc2group = {};
  25725. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25726. ssrcGroups.forEach(function (ssrcGroup) {
  25727. // TODO(gp) find out how to receive simulcast with FF. For the
  25728. // time being, hide it.
  25729. if (ssrcGroup.semantics === 'SIM') {
  25730. return;
  25731. }
  25732. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25733. Array.isArray(ssrcGroup.ssrcs)) {
  25734. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25735. if (typeof ssrc2group[ssrc] === 'undefined') {
  25736. ssrc2group[ssrc] = [];
  25737. }
  25738. ssrc2group[ssrc].push(ssrcGroup);
  25739. });
  25740. }
  25741. });
  25742. }
  25743. // ssrc to m-line index.
  25744. var ssrc2ml = {};
  25745. if (typeof sources === 'object') {
  25746. // Explode the Plan B channel sources with one m-line per source.
  25747. Object.keys(sources).forEach(function(ssrc) {
  25748. // The (unified) m-line for this SSRC. We either create it from
  25749. // scratch or, if it's a grouped SSRC, we re-use a related
  25750. // mline. In other words, if the source is grouped with another
  25751. // source, put the two together in the same m-line.
  25752. var unifiedLine;
  25753. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25754. Array.isArray(ssrc2group[ssrc])) {
  25755. ssrc2group[ssrc].some(function (ssrcGroup) {
  25756. // ssrcGroup.ssrcs *is* an Array, no need to check
  25757. // again here.
  25758. return ssrcGroup.ssrcs.some(function (related) {
  25759. if (typeof ssrc2ml[related] === 'object') {
  25760. unifiedLine = ssrc2ml[related];
  25761. return true;
  25762. }
  25763. });
  25764. });
  25765. }
  25766. if (typeof unifiedLine === 'object') {
  25767. // the m-line already exists. Just add the source.
  25768. unifiedLine.sources[ssrc] = sources[ssrc];
  25769. delete sources[ssrc].msid;
  25770. } else {
  25771. // Use the "bLine" as a prototype for the "unifiedLine".
  25772. unifiedLine = Object.create(bLine);
  25773. ssrc2ml[ssrc] = unifiedLine;
  25774. if (typeof sources[ssrc].msid !== 'undefined') {
  25775. // Assign the msid of the source to the m-line. Note
  25776. // that it is not guaranteed that the source will have
  25777. // msid. In particular "recvonly" sources don't have an
  25778. // msid. Note that "recvonly" is a term only defined
  25779. // for m-lines.
  25780. unifiedLine.msid = sources[ssrc].msid;
  25781. delete sources[ssrc].msid;
  25782. }
  25783. // We assign one SSRC per media line.
  25784. unifiedLine.sources = {};
  25785. unifiedLine.sources[ssrc] = sources[ssrc];
  25786. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25787. // Use the cached Unified Plan SDP (if it exists) to assign
  25788. // SSRCs to mids.
  25789. if (typeof cached !== 'undefined' &&
  25790. typeof cached.media !== 'undefined' &&
  25791. Array.isArray(cached.media)) {
  25792. cached.media.forEach(function (m) {
  25793. if (typeof m.sources === 'object') {
  25794. Object.keys(m.sources).forEach(function (s) {
  25795. if (s === ssrc) {
  25796. unifiedLine.mid = m.mid;
  25797. }
  25798. });
  25799. }
  25800. });
  25801. }
  25802. if (typeof unifiedLine.mid === 'undefined') {
  25803. // If this is an SSRC that we see for the first time
  25804. // assign it a new mid. This is typically the case when
  25805. // this method is called to transform a remote
  25806. // description for the first time or when there is a
  25807. // new SSRC in the remote description because a new
  25808. // peer has joined the conference. Local SSRCs should
  25809. // have already been added to the map in the toPlanB
  25810. // method.
  25811. //
  25812. // Because FF generates answers in Unified Plan style,
  25813. // we MUST already have a cached answer with all the
  25814. // local SSRCs mapped to some m-line/mid.
  25815. if (desc.type === 'answer') {
  25816. throw new Error("An unmapped SSRC was found.");
  25817. }
  25818. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25819. }
  25820. // Include the candidates in the 1st media line.
  25821. unifiedLine.candidates = candidates;
  25822. unifiedLine.iceUfrag = iceUfrag;
  25823. unifiedLine.icePwd = icePwd;
  25824. unifiedLine.fingerprint = fingerprint;
  25825. unifiedLine.port = port;
  25826. mid2ul[unifiedLine.mid] = unifiedLine;
  25827. }
  25828. });
  25829. }
  25830. });
  25831. // Rebuild the media array in the right order and add the missing mLines
  25832. // (missing from the Plan B SDP).
  25833. session.media = [];
  25834. mids = []; // reuse
  25835. if (desc.type === 'answer') {
  25836. // The media lines in the answer must match the media lines in the
  25837. // offer. The order is important too. Here we assume that Firefox is the
  25838. // answerer, so we merely have to use the reconstructed (unified) answer
  25839. // to update the cached (unified) answer accordingly.
  25840. //
  25841. // In the general case, one would have to use the cached (unified) offer
  25842. // to find the m-lines that are missing from the reconstructed answer,
  25843. // potentially grabbing them from the cached (unified) answer. One has
  25844. // to be carefull with this approach because inactive m-lines do not
  25845. // always have an mid, making it tricky (impossible?) to find where
  25846. // exactly and which m-lines are missing from the reconstructed answer.
  25847. for (var i = 0; i < cached.media.length; i++) {
  25848. var unifiedLine = cached.media[i];
  25849. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25850. // The mid isn't in the reconstructed (unified) answer.
  25851. // This is either a (unified) m-line containing a remote
  25852. // track only, or a (unified) m-line containing a remote
  25853. // track and a local track that has been removed.
  25854. // In either case, it MUST exist in the cached
  25855. // (unified) answer.
  25856. //
  25857. // In case this is a removed local track, clean-up
  25858. // the (unified) m-line and make sure it's 'recvonly' or
  25859. // 'inactive'.
  25860. delete unifiedLine.msid;
  25861. delete unifiedLine.sources;
  25862. delete unifiedLine.ssrcGroups;
  25863. if (!unifiedLine.direction
  25864. || unifiedLine.direction === 'sendrecv')
  25865. unifiedLine.direction = 'recvonly';
  25866. if (!unifiedLine.direction
  25867. || unifiedLine.direction === 'sendonly')
  25868. unifiedLine.direction = 'inactive';
  25869. } else {
  25870. // This is an (unified) m-line/channel that contains a local
  25871. // track (sendrecv or sendonly channel) or it's a unified
  25872. // recvonly m-line/channel. In either case, since we're
  25873. // going from PlanB -> Unified Plan this m-line MUST
  25874. // exist in the cached answer.
  25875. }
  25876. session.media.push(unifiedLine);
  25877. if (typeof unifiedLine.mid === 'string') {
  25878. // inactive lines don't/may not have an mid.
  25879. mids.push(unifiedLine.mid);
  25880. }
  25881. }
  25882. } else {
  25883. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25884. // under any circumstances. If we are no longer interested in sending a
  25885. // track, we just remove the msid and ssrc attributes and set it to
  25886. // either a=recvonly (as the reofferer, we must use recvonly if the
  25887. // other side was previously sending on the m-section, but we can also
  25888. // leave the possibility open if it wasn't previously in use), or
  25889. // a=inacive.
  25890. if (typeof cached !== 'undefined' &&
  25891. typeof cached.media !== 'undefined' &&
  25892. Array.isArray(cached.media)) {
  25893. cached.media.forEach(function(unifiedLine) {
  25894. mids.push(unifiedLine.mid);
  25895. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25896. session.media.push(mid2ul[unifiedLine.mid]);
  25897. } else {
  25898. delete unifiedLine.msid;
  25899. delete unifiedLine.sources;
  25900. delete unifiedLine.ssrcGroups;
  25901. if (!unifiedLine.direction
  25902. || unifiedLine.direction === 'sendrecv')
  25903. unifiedLine.direction = 'recvonly';
  25904. if (!unifiedLine.direction
  25905. || unifiedLine.direction === 'sendonly')
  25906. unifiedLine.direction = 'inactive';
  25907. session.media.push(unifiedLine);
  25908. }
  25909. });
  25910. }
  25911. // Add all the remaining (new) m-lines of the transformed SDP.
  25912. Object.keys(mid2ul).forEach(function(mid) {
  25913. if (mids.indexOf(mid) === -1) {
  25914. mids.push(mid);
  25915. if (typeof mid2ul[mid].direction === 'recvonly') {
  25916. // This is a remote recvonly channel. Add its SSRC to the
  25917. // appropriate sendrecv or sendonly channel.
  25918. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25919. session.media.some(function (unifiedLine) {
  25920. if ((unifiedLine.direction === 'sendrecv' ||
  25921. unifiedLine.direction === 'sendonly') &&
  25922. unifiedLine.type === mid2ul[mid].type) {
  25923. // mid2ul[mid] shouldn't have any ssrc-groups
  25924. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25925. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25926. });
  25927. return true;
  25928. }
  25929. });
  25930. } else {
  25931. session.media.push(mid2ul[mid]);
  25932. }
  25933. }
  25934. });
  25935. }
  25936. // We regenerate the BUNDLE group (since we regenerated the mids)
  25937. session.groups.some(function(group) {
  25938. if (group.type === 'BUNDLE') {
  25939. group.mids = mids.join(' ');
  25940. return true;
  25941. }
  25942. });
  25943. // msid semantic
  25944. session.msidSemantic = {
  25945. semantic: 'WMS',
  25946. token: '*'
  25947. };
  25948. var resStr = transform.write(session);
  25949. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25950. // function.
  25951. this.cache[desc.type] = resStr;
  25952. return new RTCSessionDescription({
  25953. type: desc.type,
  25954. sdp: resStr
  25955. });
  25956. //#endregion
  25957. };
  25958. },{"./array-equals":90,"./transform":93}],93:[function(require,module,exports){
  25959. var transform = require('sdp-transform');
  25960. exports.write = function(session, opts) {
  25961. if (typeof session !== 'undefined' &&
  25962. typeof session.media !== 'undefined' &&
  25963. Array.isArray(session.media)) {
  25964. session.media.forEach(function (mLine) {
  25965. // expand sources to ssrcs
  25966. if (typeof mLine.sources !== 'undefined' &&
  25967. Object.keys(mLine.sources).length !== 0) {
  25968. mLine.ssrcs = [];
  25969. Object.keys(mLine.sources).forEach(function (ssrc) {
  25970. var source = mLine.sources[ssrc];
  25971. Object.keys(source).forEach(function (attribute) {
  25972. mLine.ssrcs.push({
  25973. id: ssrc,
  25974. attribute: attribute,
  25975. value: source[attribute]
  25976. });
  25977. });
  25978. });
  25979. delete mLine.sources;
  25980. }
  25981. // join ssrcs in ssrc groups
  25982. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25983. Array.isArray(mLine.ssrcGroups)) {
  25984. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25985. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25986. Array.isArray(ssrcGroup.ssrcs)) {
  25987. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25988. }
  25989. });
  25990. }
  25991. });
  25992. }
  25993. // join group mids
  25994. if (typeof session !== 'undefined' &&
  25995. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25996. session.groups.forEach(function (g) {
  25997. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25998. g.mids = g.mids.join(' ');
  25999. }
  26000. });
  26001. }
  26002. return transform.write(session, opts);
  26003. };
  26004. exports.parse = function(sdp) {
  26005. var session = transform.parse(sdp);
  26006. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  26007. Array.isArray(session.media)) {
  26008. session.media.forEach(function (mLine) {
  26009. // group sources attributes by ssrc
  26010. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26011. mLine.sources = {};
  26012. mLine.ssrcs.forEach(function (ssrc) {
  26013. if (!mLine.sources[ssrc.id])
  26014. mLine.sources[ssrc.id] = {};
  26015. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26016. });
  26017. delete mLine.ssrcs;
  26018. }
  26019. // split ssrcs in ssrc groups
  26020. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26021. Array.isArray(mLine.ssrcGroups)) {
  26022. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26023. if (typeof ssrcGroup.ssrcs === 'string') {
  26024. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  26025. }
  26026. });
  26027. }
  26028. });
  26029. }
  26030. // split group mids
  26031. if (typeof session !== 'undefined' &&
  26032. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26033. session.groups.forEach(function (g) {
  26034. if (typeof g.mids === 'string') {
  26035. g.mids = g.mids.split(' ');
  26036. }
  26037. });
  26038. }
  26039. return session;
  26040. };
  26041. },{"sdp-transform":97}],94:[function(require,module,exports){
  26042. var transform = require('sdp-transform');
  26043. var transformUtils = require('./transform-utils');
  26044. var parseSsrcs = transformUtils.parseSsrcs;
  26045. var writeSsrcs = transformUtils.writeSsrcs;
  26046. //region Constants
  26047. var DEFAULT_NUM_OF_LAYERS = 3;
  26048. //endregion
  26049. //region Ctor
  26050. function Simulcast(options) {
  26051. this.options = options ? options : {};
  26052. if (!this.options.numOfLayers) {
  26053. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26054. }
  26055. this.layers = [];
  26056. }
  26057. //endregion
  26058. //region Stateless private utility functions
  26059. /**
  26060. * Returns a random integer between min (included) and max (excluded)
  26061. * Using Math.round() gives a non-uniform distribution!
  26062. * @returns {number}
  26063. */
  26064. function generateSSRC() {
  26065. var min = 0, max = 0xffffffff;
  26066. return Math.floor(Math.random() * (max - min)) + min;
  26067. };
  26068. function processVideo(session, action) {
  26069. if (session == null || !Array.isArray(session.media)) {
  26070. return;
  26071. }
  26072. session.media.forEach(function (mLine) {
  26073. if (mLine.type === 'video') {
  26074. action(mLine);
  26075. }
  26076. });
  26077. }
  26078. function validateDescription(desc)
  26079. {
  26080. return desc && desc != null
  26081. && desc.type && desc.type != ''
  26082. && desc.sdp && desc.sdp != '';
  26083. }
  26084. function explodeRemoteSimulcast(mLine) {
  26085. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26086. return;
  26087. }
  26088. var sources = parseSsrcs(mLine);
  26089. var order = [];
  26090. // Find the SIM group and explode its sources.
  26091. var j = mLine.ssrcGroups.length;
  26092. while (j--) {
  26093. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26094. continue;
  26095. }
  26096. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26097. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26098. var ssrc = simulcastSsrcs[i];
  26099. order.push(ssrc);
  26100. var parts = sources[ssrc].msid.split(' ');
  26101. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26102. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26103. // Remove all the groups that this SSRC participates in.
  26104. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26105. if (relatedGroup.semantics === 'SIM') {
  26106. return;
  26107. }
  26108. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26109. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26110. return;
  26111. }
  26112. // Nuke all the related SSRCs.
  26113. relatedSsrcs.forEach(function (relatedSSRC) {
  26114. sources[relatedSSRC].msid = sources[ssrc].msid;
  26115. sources[relatedSSRC].cname = sources[ssrc].cname;
  26116. if (relatedSSRC !== ssrc) {
  26117. order.push(relatedSSRC);
  26118. }
  26119. });
  26120. // Schedule the related group for nuking.
  26121. })
  26122. }
  26123. mLine.ssrcs = writeSsrcs(sources, order);
  26124. mLine.ssrcGroups.splice(j, 1);
  26125. };
  26126. }
  26127. function squeezeRemoteSimulcast(mLine) {
  26128. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26129. return;
  26130. }
  26131. var sources = parseSsrcs(mLine);
  26132. // Find the SIM group and nuke it.
  26133. mLine.ssrcGroups.some(function (simulcastGroup) {
  26134. if (simulcastGroup.semantics !== 'SIM') {
  26135. return false;
  26136. }
  26137. // Schedule the SIM group for nuking.
  26138. simulcastGroup.nuke = true;
  26139. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26140. // Nuke all the higher layer SSRCs.
  26141. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26142. var ssrc = simulcastSsrcs[i];
  26143. delete sources[ssrc];
  26144. // Remove all the groups that this SSRC participates in.
  26145. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26146. if (relatedGroup.semantics === 'SIM') {
  26147. return;
  26148. }
  26149. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26150. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26151. return;
  26152. }
  26153. // Nuke all the related SSRCs.
  26154. relatedSsrcs.forEach(function (relatedSSRC) {
  26155. delete sources[relatedSSRC];
  26156. });
  26157. // Schedule the related group for nuking.
  26158. relatedGroup.nuke = true;
  26159. })
  26160. }
  26161. return true;
  26162. });
  26163. mLine.ssrcs = writeSsrcs(sources);
  26164. // Nuke all the scheduled groups.
  26165. var i = mLine.ssrcGroups.length;
  26166. while (i--) {
  26167. if (mLine.ssrcGroups[i].nuke) {
  26168. mLine.ssrcGroups.splice(i, 1);
  26169. }
  26170. }
  26171. }
  26172. function removeGoogConference(mLine) {
  26173. if (!mLine || !Array.isArray(mLine.invalid)) {
  26174. return;
  26175. }
  26176. var i = mLine.invalid.length;
  26177. while (i--) {
  26178. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26179. mLine.invalid.splice(i, 1);
  26180. }
  26181. }
  26182. }
  26183. function assertGoogConference(mLine) {
  26184. if (!mLine) {
  26185. return;
  26186. }
  26187. if (!Array.isArray(mLine.invalid)) {
  26188. mLine.invalid = [];
  26189. }
  26190. if (!mLine.invalid.some(
  26191. function (i) { return i.value === 'x-google-flag:conference' })) {
  26192. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26193. }
  26194. }
  26195. //endregion
  26196. //region "Private" functions
  26197. /**
  26198. *
  26199. * @param mLine
  26200. * @private
  26201. */
  26202. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26203. if (!mLine || mLine.type !== 'video') {
  26204. return;
  26205. }
  26206. var sources = parseSsrcs(mLine);
  26207. if (Object.keys(sources).length === 0) {
  26208. // no sources, disable simulcast.
  26209. if (this.layers.length !== 0) {
  26210. this.layers = [];
  26211. }
  26212. return;
  26213. }
  26214. // find the base layer (we'll reuse its msid and cname).
  26215. var baseLayerSSRC = Object.keys(sources)[0];
  26216. var baseLayer = sources[baseLayerSSRC];
  26217. // todo(gp) handle screen sharing.
  26218. // check if base CNAME has changed and reinitialise layers.
  26219. if (this.layers.length > 0
  26220. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26221. this.layers = [];
  26222. }
  26223. // (re)initialise layers
  26224. if (this.layers.length < 1) {
  26225. // first push the base layer.
  26226. this.layers.push({
  26227. ssrc: baseLayerSSRC,
  26228. msid: baseLayer.msid,
  26229. cname: baseLayer.cname
  26230. });
  26231. var rtx = false; // RFC 4588
  26232. if (Array.isArray(mLine.rtp)) {
  26233. rtx = mLine.rtp.some(
  26234. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26235. }
  26236. if (rtx) {
  26237. this.layers[0].rtx = generateSSRC();
  26238. }
  26239. // now push additional layers.
  26240. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26241. var layer = { ssrc: generateSSRC() };
  26242. if (rtx) {
  26243. layer.rtx = generateSSRC();
  26244. }
  26245. this.layers.push(layer);
  26246. }
  26247. }
  26248. };
  26249. /**
  26250. *
  26251. * @param mLine
  26252. * @private
  26253. */
  26254. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26255. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26256. var sources = {};
  26257. var msid = this.layers[0].msid;
  26258. var cname = this.layers[0].cname;
  26259. var simulcastSsrcs = [];
  26260. var ssrcGroups = [];
  26261. for (var i = 0; i < this.layers.length; i++) {
  26262. var layer = this.layers[i];
  26263. sources[layer.ssrc] = { msid: msid, cname: cname };
  26264. simulcastSsrcs.push(layer.ssrc);
  26265. if (layer.rtx) {
  26266. sources[layer.rtx] = {
  26267. msid: msid,
  26268. cname: cname
  26269. }
  26270. ssrcGroups.push({
  26271. semantics: 'FID',
  26272. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26273. });
  26274. }
  26275. }
  26276. ssrcGroups.push({
  26277. semantics: 'SIM',
  26278. ssrcs: simulcastSsrcs.join(' ')
  26279. });
  26280. mLine.ssrcGroups = ssrcGroups;
  26281. mLine.ssrcs = writeSsrcs(sources);
  26282. }
  26283. }
  26284. //endregion
  26285. //region "Public" functions
  26286. Simulcast.prototype.isSupported = function () {
  26287. return window.chrome;
  26288. // TODO this needs improvements. For example I doubt that Chrome in Android
  26289. // has simulcast support. Also, only recent versions of Chromium have native
  26290. // simulcast support.
  26291. }
  26292. /**
  26293. *
  26294. * @param desc
  26295. * @returns {RTCSessionDescription}
  26296. */
  26297. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26298. if (!validateDescription(desc)) {
  26299. return desc;
  26300. }
  26301. var session = transform.parse(desc.sdp);
  26302. var self = this;
  26303. processVideo(session, function (mLine) {
  26304. // Handle simulcast reception.
  26305. if (self.options.explodeRemoteSimulcast) {
  26306. explodeRemoteSimulcast(mLine);
  26307. } else {
  26308. squeezeRemoteSimulcast(mLine);
  26309. }
  26310. // If native simulcast is enabled, we must append the x-goog-conference
  26311. // attribute to the SDP.
  26312. if (self.layers.length < 1) {
  26313. removeGoogConference(mLine);
  26314. } else {
  26315. assertGoogConference(mLine);
  26316. }
  26317. });
  26318. return new RTCSessionDescription({
  26319. type: desc.type,
  26320. sdp: transform.write(session)
  26321. });
  26322. };
  26323. /**
  26324. *
  26325. * @param desc
  26326. * @returns {RTCSessionDescription}
  26327. */
  26328. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26329. if (!validateDescription(desc) || !this.isSupported()) {
  26330. return desc;
  26331. }
  26332. var session = transform.parse(desc.sdp);
  26333. var self = this;
  26334. processVideo(session, function (mLine) {
  26335. // Initialize native simulcast layers, if not already done.
  26336. self._maybeInitializeLayers(mLine);
  26337. // Update the SDP with the simulcast layers.
  26338. self._restoreSimulcastView(mLine);
  26339. });
  26340. return new RTCSessionDescription({
  26341. type: desc.type,
  26342. sdp: transform.write(session)
  26343. });
  26344. };
  26345. //endregion
  26346. module.exports = Simulcast;
  26347. },{"./transform-utils":95,"sdp-transform":97}],95:[function(require,module,exports){
  26348. exports.writeSsrcs = function(sources, order) {
  26349. var ssrcs = [];
  26350. // expand sources to ssrcs
  26351. if (typeof sources !== 'undefined' &&
  26352. Object.keys(sources).length !== 0) {
  26353. if (Array.isArray(order)) {
  26354. for (var i = 0; i < order.length; i++) {
  26355. var ssrc = order[i];
  26356. var source = sources[ssrc];
  26357. Object.keys(source).forEach(function (attribute) {
  26358. ssrcs.push({
  26359. id: ssrc,
  26360. attribute: attribute,
  26361. value: source[attribute]
  26362. });
  26363. });
  26364. }
  26365. } else {
  26366. Object.keys(sources).forEach(function (ssrc) {
  26367. var source = sources[ssrc];
  26368. Object.keys(source).forEach(function (attribute) {
  26369. ssrcs.push({
  26370. id: ssrc,
  26371. attribute: attribute,
  26372. value: source[attribute]
  26373. });
  26374. });
  26375. });
  26376. }
  26377. }
  26378. return ssrcs;
  26379. };
  26380. exports.parseSsrcs = function (mLine) {
  26381. var sources = {};
  26382. // group sources attributes by ssrc.
  26383. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26384. mLine.ssrcs.forEach(function (ssrc) {
  26385. if (!sources[ssrc.id])
  26386. sources[ssrc.id] = {};
  26387. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26388. });
  26389. }
  26390. return sources;
  26391. };
  26392. },{}],96:[function(require,module,exports){
  26393. var grammar = module.exports = {
  26394. v: [{
  26395. name: 'version',
  26396. reg: /^(\d*)$/
  26397. }],
  26398. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26399. // NB: sessionId will be a String in most cases because it is huge
  26400. name: 'origin',
  26401. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26402. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26403. format: "%s %s %d %s IP%d %s"
  26404. }],
  26405. // default parsing of these only (though some of these feel outdated)
  26406. s: [{ name: 'name' }],
  26407. i: [{ name: 'description' }],
  26408. u: [{ name: 'uri' }],
  26409. e: [{ name: 'email' }],
  26410. p: [{ name: 'phone' }],
  26411. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26412. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26413. //k: [{}], // outdated thing ignored
  26414. t: [{ //t=0 0
  26415. name: 'timing',
  26416. reg: /^(\d*) (\d*)/,
  26417. names: ['start', 'stop'],
  26418. format: "%d %d"
  26419. }],
  26420. c: [{ //c=IN IP4 10.47.197.26
  26421. name: 'connection',
  26422. reg: /^IN IP(\d) (\S*)/,
  26423. names: ['version', 'ip'],
  26424. format: "IN IP%d %s"
  26425. }],
  26426. b: [{ //b=AS:4000
  26427. push: 'bandwidth',
  26428. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26429. names: ['type', 'limit'],
  26430. format: "%s:%s"
  26431. }],
  26432. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26433. // NB: special - pushes to session
  26434. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26435. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26436. names: ['type', 'port', 'protocol', 'payloads'],
  26437. format: "%s %d %s %s"
  26438. }],
  26439. a: [
  26440. { //a=rtpmap:110 opus/48000/2
  26441. push: 'rtp',
  26442. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26443. names: ['payload', 'codec', 'rate', 'encoding'],
  26444. format: function (o) {
  26445. return (o.encoding) ?
  26446. "rtpmap:%d %s/%s/%s":
  26447. "rtpmap:%d %s/%s";
  26448. }
  26449. },
  26450. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26451. push: 'fmtp',
  26452. reg: /^fmtp:(\d*) (\S*)/,
  26453. names: ['payload', 'config'],
  26454. format: "fmtp:%d %s"
  26455. },
  26456. { //a=control:streamid=0
  26457. name: 'control',
  26458. reg: /^control:(.*)/,
  26459. format: "control:%s"
  26460. },
  26461. { //a=rtcp:65179 IN IP4 193.84.77.194
  26462. name: 'rtcp',
  26463. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26464. names: ['port', 'netType', 'ipVer', 'address'],
  26465. format: function (o) {
  26466. return (o.address != null) ?
  26467. "rtcp:%d %s IP%d %s":
  26468. "rtcp:%d";
  26469. }
  26470. },
  26471. { //a=rtcp-fb:98 trr-int 100
  26472. push: 'rtcpFbTrrInt',
  26473. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26474. names: ['payload', 'value'],
  26475. format: "rtcp-fb:%d trr-int %d"
  26476. },
  26477. { //a=rtcp-fb:98 nack rpsi
  26478. push: 'rtcpFb',
  26479. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26480. names: ['payload', 'type', 'subtype'],
  26481. format: function (o) {
  26482. return (o.subtype != null) ?
  26483. "rtcp-fb:%s %s %s":
  26484. "rtcp-fb:%s %s";
  26485. }
  26486. },
  26487. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26488. //a=extmap:1/recvonly URI-gps-string
  26489. push: 'ext',
  26490. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26491. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26492. format: function (o) {
  26493. return (o.config != null) ?
  26494. "extmap:%s %s %s":
  26495. "extmap:%s %s";
  26496. }
  26497. },
  26498. {
  26499. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26500. push: 'crypto',
  26501. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26502. names: ['id', 'suite', 'config', 'sessionConfig'],
  26503. format: function (o) {
  26504. return (o.sessionConfig != null) ?
  26505. "crypto:%d %s %s %s":
  26506. "crypto:%d %s %s";
  26507. }
  26508. },
  26509. { //a=setup:actpass
  26510. name: 'setup',
  26511. reg: /^setup:(\w*)/,
  26512. format: "setup:%s"
  26513. },
  26514. { //a=mid:1
  26515. name: 'mid',
  26516. reg: /^mid:([^\s]*)/,
  26517. format: "mid:%s"
  26518. },
  26519. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26520. name: 'msid',
  26521. reg: /^msid:(.*)/,
  26522. format: "msid:%s"
  26523. },
  26524. { //a=ptime:20
  26525. name: 'ptime',
  26526. reg: /^ptime:(\d*)/,
  26527. format: "ptime:%d"
  26528. },
  26529. { //a=maxptime:60
  26530. name: 'maxptime',
  26531. reg: /^maxptime:(\d*)/,
  26532. format: "maxptime:%d"
  26533. },
  26534. { //a=sendrecv
  26535. name: 'direction',
  26536. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26537. },
  26538. { //a=ice-lite
  26539. name: 'icelite',
  26540. reg: /^(ice-lite)/
  26541. },
  26542. { //a=ice-ufrag:F7gI
  26543. name: 'iceUfrag',
  26544. reg: /^ice-ufrag:(\S*)/,
  26545. format: "ice-ufrag:%s"
  26546. },
  26547. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26548. name: 'icePwd',
  26549. reg: /^ice-pwd:(\S*)/,
  26550. format: "ice-pwd:%s"
  26551. },
  26552. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26553. name: 'fingerprint',
  26554. reg: /^fingerprint:(\S*) (\S*)/,
  26555. names: ['type', 'hash'],
  26556. format: "fingerprint:%s %s"
  26557. },
  26558. {
  26559. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26560. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26561. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26562. push:'candidates',
  26563. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26564. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26565. format: function (o) {
  26566. var str = "candidate:%s %d %s %d %s %d typ %s";
  26567. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26568. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26569. if (o.generation != null) {
  26570. str += " generation %d";
  26571. }
  26572. return str;
  26573. }
  26574. },
  26575. { //a=end-of-candidates (keep after the candidates line for readability)
  26576. name: 'endOfCandidates',
  26577. reg: /^(end-of-candidates)/
  26578. },
  26579. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26580. name: 'remoteCandidates',
  26581. reg: /^remote-candidates:(.*)/,
  26582. format: "remote-candidates:%s"
  26583. },
  26584. { //a=ice-options:google-ice
  26585. name: 'iceOptions',
  26586. reg: /^ice-options:(\S*)/,
  26587. format: "ice-options:%s"
  26588. },
  26589. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26590. push: "ssrcs",
  26591. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26592. names: ['id', 'attribute', 'value'],
  26593. format: "ssrc:%d %s:%s"
  26594. },
  26595. { //a=ssrc-group:FEC 1 2
  26596. push: "ssrcGroups",
  26597. reg: /^ssrc-group:(\w*) (.*)/,
  26598. names: ['semantics', 'ssrcs'],
  26599. format: "ssrc-group:%s %s"
  26600. },
  26601. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26602. name: "msidSemantic",
  26603. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26604. names: ['semantic', 'token'],
  26605. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26606. },
  26607. { //a=group:BUNDLE audio video
  26608. push: 'groups',
  26609. reg: /^group:(\w*) (.*)/,
  26610. names: ['type', 'mids'],
  26611. format: "group:%s %s"
  26612. },
  26613. { //a=rtcp-mux
  26614. name: 'rtcpMux',
  26615. reg: /^(rtcp-mux)/
  26616. },
  26617. { //a=rtcp-rsize
  26618. name: 'rtcpRsize',
  26619. reg: /^(rtcp-rsize)/
  26620. },
  26621. { // any a= that we don't understand is kepts verbatim on media.invalid
  26622. push: 'invalid',
  26623. names: ["value"]
  26624. }
  26625. ]
  26626. };
  26627. // set sensible defaults to avoid polluting the grammar with boring details
  26628. Object.keys(grammar).forEach(function (key) {
  26629. var objs = grammar[key];
  26630. objs.forEach(function (obj) {
  26631. if (!obj.reg) {
  26632. obj.reg = /(.*)/;
  26633. }
  26634. if (!obj.format) {
  26635. obj.format = "%s";
  26636. }
  26637. });
  26638. });
  26639. },{}],97:[function(require,module,exports){
  26640. var parser = require('./parser');
  26641. var writer = require('./writer');
  26642. exports.write = writer;
  26643. exports.parse = parser.parse;
  26644. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26645. exports.parsePayloads = parser.parsePayloads;
  26646. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26647. },{"./parser":98,"./writer":99}],98:[function(require,module,exports){
  26648. var toIntIfInt = function (v) {
  26649. return String(Number(v)) === v ? Number(v) : v;
  26650. };
  26651. var attachProperties = function (match, location, names, rawName) {
  26652. if (rawName && !names) {
  26653. location[rawName] = toIntIfInt(match[1]);
  26654. }
  26655. else {
  26656. for (var i = 0; i < names.length; i += 1) {
  26657. if (match[i+1] != null) {
  26658. location[names[i]] = toIntIfInt(match[i+1]);
  26659. }
  26660. }
  26661. }
  26662. };
  26663. var parseReg = function (obj, location, content) {
  26664. var needsBlank = obj.name && obj.names;
  26665. if (obj.push && !location[obj.push]) {
  26666. location[obj.push] = [];
  26667. }
  26668. else if (needsBlank && !location[obj.name]) {
  26669. location[obj.name] = {};
  26670. }
  26671. var keyLocation = obj.push ?
  26672. {} : // blank object that will be pushed
  26673. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26674. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26675. if (obj.push) {
  26676. location[obj.push].push(keyLocation);
  26677. }
  26678. };
  26679. var grammar = require('./grammar');
  26680. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26681. exports.parse = function (sdp) {
  26682. var session = {}
  26683. , media = []
  26684. , location = session; // points at where properties go under (one of the above)
  26685. // parse lines we understand
  26686. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26687. var type = l[0];
  26688. var content = l.slice(2);
  26689. if (type === 'm') {
  26690. media.push({rtp: [], fmtp: []});
  26691. location = media[media.length-1]; // point at latest media line
  26692. }
  26693. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26694. var obj = grammar[type][j];
  26695. if (obj.reg.test(content)) {
  26696. return parseReg(obj, location, content);
  26697. }
  26698. }
  26699. });
  26700. session.media = media; // link it up
  26701. return session;
  26702. };
  26703. var fmtpReducer = function (acc, expr) {
  26704. var s = expr.split('=');
  26705. if (s.length === 2) {
  26706. acc[s[0]] = toIntIfInt(s[1]);
  26707. }
  26708. return acc;
  26709. };
  26710. exports.parseFmtpConfig = function (str) {
  26711. return str.split(';').reduce(fmtpReducer, {});
  26712. };
  26713. exports.parsePayloads = function (str) {
  26714. return str.split(' ').map(Number);
  26715. };
  26716. exports.parseRemoteCandidates = function (str) {
  26717. var candidates = [];
  26718. var parts = str.split(' ').map(toIntIfInt);
  26719. for (var i = 0; i < parts.length; i += 3) {
  26720. candidates.push({
  26721. component: parts[i],
  26722. ip: parts[i + 1],
  26723. port: parts[i + 2]
  26724. });
  26725. }
  26726. return candidates;
  26727. };
  26728. },{"./grammar":96}],99:[function(require,module,exports){
  26729. var grammar = require('./grammar');
  26730. // customized util.format - discards excess arguments and can void middle ones
  26731. var formatRegExp = /%[sdv%]/g;
  26732. var format = function (formatStr) {
  26733. var i = 1;
  26734. var args = arguments;
  26735. var len = args.length;
  26736. return formatStr.replace(formatRegExp, function (x) {
  26737. if (i >= len) {
  26738. return x; // missing argument
  26739. }
  26740. var arg = args[i];
  26741. i += 1;
  26742. switch (x) {
  26743. case '%%':
  26744. return '%';
  26745. case '%s':
  26746. return String(arg);
  26747. case '%d':
  26748. return Number(arg);
  26749. case '%v':
  26750. return '';
  26751. }
  26752. });
  26753. // NB: we discard excess arguments - they are typically undefined from makeLine
  26754. };
  26755. var makeLine = function (type, obj, location) {
  26756. var str = obj.format instanceof Function ?
  26757. (obj.format(obj.push ? location : location[obj.name])) :
  26758. obj.format;
  26759. var args = [type + '=' + str];
  26760. if (obj.names) {
  26761. for (var i = 0; i < obj.names.length; i += 1) {
  26762. var n = obj.names[i];
  26763. if (obj.name) {
  26764. args.push(location[obj.name][n]);
  26765. }
  26766. else { // for mLine and push attributes
  26767. args.push(location[obj.names[i]]);
  26768. }
  26769. }
  26770. }
  26771. else {
  26772. args.push(location[obj.name]);
  26773. }
  26774. return format.apply(null, args);
  26775. };
  26776. // RFC specified order
  26777. // TODO: extend this with all the rest
  26778. var defaultOuterOrder = [
  26779. 'v', 'o', 's', 'i',
  26780. 'u', 'e', 'p', 'c',
  26781. 'b', 't', 'r', 'z', 'a'
  26782. ];
  26783. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26784. module.exports = function (session, opts) {
  26785. opts = opts || {};
  26786. // ensure certain properties exist
  26787. if (session.version == null) {
  26788. session.version = 0; // "v=0" must be there (only defined version atm)
  26789. }
  26790. if (session.name == null) {
  26791. session.name = " "; // "s= " must be there if no meaningful name set
  26792. }
  26793. session.media.forEach(function (mLine) {
  26794. if (mLine.payloads == null) {
  26795. mLine.payloads = "";
  26796. }
  26797. });
  26798. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26799. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26800. var sdp = [];
  26801. // loop through outerOrder for matching properties on session
  26802. outerOrder.forEach(function (type) {
  26803. grammar[type].forEach(function (obj) {
  26804. if (obj.name in session && session[obj.name] != null) {
  26805. sdp.push(makeLine(type, obj, session));
  26806. }
  26807. else if (obj.push in session && session[obj.push] != null) {
  26808. session[obj.push].forEach(function (el) {
  26809. sdp.push(makeLine(type, obj, el));
  26810. });
  26811. }
  26812. });
  26813. });
  26814. // then for each media line, follow the innerOrder
  26815. session.media.forEach(function (mLine) {
  26816. sdp.push(makeLine('m', grammar.m[0], mLine));
  26817. innerOrder.forEach(function (type) {
  26818. grammar[type].forEach(function (obj) {
  26819. if (obj.name in mLine && mLine[obj.name] != null) {
  26820. sdp.push(makeLine(type, obj, mLine));
  26821. }
  26822. else if (obj.push in mLine && mLine[obj.push] != null) {
  26823. mLine[obj.push].forEach(function (el) {
  26824. sdp.push(makeLine(type, obj, el));
  26825. });
  26826. }
  26827. });
  26828. });
  26829. });
  26830. return sdp.join('\r\n') + '\r\n';
  26831. };
  26832. },{"./grammar":96}],100:[function(require,module,exports){
  26833. var MediaStreamType = {
  26834. VIDEO_TYPE: "Video",
  26835. AUDIO_TYPE: "Audio"
  26836. };
  26837. module.exports = MediaStreamType;
  26838. },{}],101:[function(require,module,exports){
  26839. var RTCEvents = {
  26840. RTC_READY: "rtc.ready",
  26841. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  26842. LASTN_CHANGED: "rtc.lastn_changed",
  26843. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26844. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26845. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26846. AUDIO_MUTE: "rtc.audio_mute",
  26847. VIDEO_MUTE: "rtc.video_mute"
  26848. };
  26849. module.exports = RTCEvents;
  26850. },{}],102:[function(require,module,exports){
  26851. var Resolutions = {
  26852. "1080": {
  26853. width: 1920,
  26854. height: 1080,
  26855. order: 7
  26856. },
  26857. "fullhd": {
  26858. width: 1920,
  26859. height: 1080,
  26860. order: 7
  26861. },
  26862. "720": {
  26863. width: 1280,
  26864. height: 720,
  26865. order: 6
  26866. },
  26867. "hd": {
  26868. width: 1280,
  26869. height: 720,
  26870. order: 6
  26871. },
  26872. "960": {
  26873. width: 960,
  26874. height: 720,
  26875. order: 5
  26876. },
  26877. "640": {
  26878. width: 640,
  26879. height: 480,
  26880. order: 4
  26881. },
  26882. "vga": {
  26883. width: 640,
  26884. height: 480,
  26885. order: 4
  26886. },
  26887. "360": {
  26888. width: 640,
  26889. height: 360,
  26890. order: 3
  26891. },
  26892. "320": {
  26893. width: 320,
  26894. height: 240,
  26895. order: 2
  26896. },
  26897. "180": {
  26898. width: 320,
  26899. height: 180,
  26900. order: 1
  26901. }
  26902. };
  26903. module.exports = Resolutions;
  26904. },{}],103:[function(require,module,exports){
  26905. var StreamEventTypes = {
  26906. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26907. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26908. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26909. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26910. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  26911. };
  26912. module.exports = StreamEventTypes;
  26913. },{}],104:[function(require,module,exports){
  26914. var UIEvents = {
  26915. NICKNAME_CHANGED: "UI.nickname_changed",
  26916. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26917. PINNED_ENDPOINT: "UI.pinned_endpoint",
  26918. LARGEVIDEO_INIT: "UI.largevideo_init"
  26919. };
  26920. module.exports = UIEvents;
  26921. },{}],105:[function(require,module,exports){
  26922. var AuthenticationEvents = {
  26923. /**
  26924. * Event callback arguments:
  26925. * function(authenticationEnabled, userIdentity)
  26926. * authenticationEnabled - indicates whether authentication has been enabled
  26927. * in this session
  26928. * userIdentity - if user has been logged in then it contains user name. If
  26929. * contains 'null' or 'undefined' then user is not logged in.
  26930. */
  26931. IDENTITY_UPDATED: "authentication.identity_updated"
  26932. };
  26933. module.exports = AuthenticationEvents;
  26934. },{}],106:[function(require,module,exports){
  26935. var CQEvents = {
  26936. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26937. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26938. STOP: "cq.stop"
  26939. };
  26940. module.exports = CQEvents;
  26941. },{}],107:[function(require,module,exports){
  26942. var DesktopSharingEventTypes = {
  26943. INIT: "ds.init",
  26944. SWITCHING_DONE: "ds.switching_done",
  26945. NEW_STREAM_CREATED: "ds.new_stream_created"
  26946. };
  26947. module.exports = DesktopSharingEventTypes;
  26948. },{}],108:[function(require,module,exports){
  26949. var Events = {
  26950. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26951. };
  26952. module.exports = Events;
  26953. },{}],109:[function(require,module,exports){
  26954. module.exports = {
  26955. getLanguages : function () {
  26956. var languages = [];
  26957. for(var lang in this)
  26958. {
  26959. if(typeof this[lang] === "string")
  26960. languages.push(this[lang]);
  26961. }
  26962. return languages;
  26963. },
  26964. EN: "en",
  26965. BG: "bg",
  26966. DE: "de",
  26967. TR: "tr",
  26968. FR: "fr"
  26969. }
  26970. },{}],110:[function(require,module,exports){
  26971. var XMPPEvents = {
  26972. CONNECTION_FAILED: "xmpp.connection.failed",
  26973. // Indicates an interrupted connection event.
  26974. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  26975. // Indicates a restored connection event.
  26976. CONNECTION_RESTORED: "xmpp.connection.restored",
  26977. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26978. CALL_INCOMING: "xmpp.callincoming.jingle",
  26979. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26980. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26981. KICKED: "xmpp.kicked",
  26982. BRIDGE_DOWN: "xmpp.bridge_down",
  26983. USER_ID_CHANGED: "xmpp.user_id_changed",
  26984. // We joined the MUC
  26985. MUC_JOINED: "xmpp.muc_joined",
  26986. // A member joined the MUC
  26987. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26988. // A member left the MUC
  26989. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26990. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26991. MUC_DESTROYED: "xmpp.muc_destroyed",
  26992. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26993. REMOTE_STATS: "xmpp.remote_stats",
  26994. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26995. PRESENCE_STATUS: "xmpp.presence_status",
  26996. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26997. SUBJECT_CHANGED: "xmpp.subject_changed",
  26998. MESSAGE_RECEIVED: "xmpp.message_received",
  26999. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27000. PASSWORD_REQUIRED: "xmpp.password_required",
  27001. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27002. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27003. ETHERPAD: "xmpp.etherpad",
  27004. DEVICE_AVAILABLE: "xmpp.device_available",
  27005. VIDEO_TYPE: "xmpp.video_type",
  27006. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27007. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27008. AUDIO_MUTED: "xmpp.audio_muted",
  27009. VIDEO_MUTED: "xmpp.video_muted",
  27010. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27011. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  27012. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27013. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27014. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27015. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27016. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27017. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27018. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27019. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27020. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27021. // xmpp is connected and obtained user media
  27022. READY_TO_JOIN: 'xmpp.ready_to_join'
  27023. };
  27024. module.exports = XMPPEvents;
  27025. },{}],111:[function(require,module,exports){
  27026. // Copyright Joyent, Inc. and other Node contributors.
  27027. //
  27028. // Permission is hereby granted, free of charge, to any person obtaining a
  27029. // copy of this software and associated documentation files (the
  27030. // "Software"), to deal in the Software without restriction, including
  27031. // without limitation the rights to use, copy, modify, merge, publish,
  27032. // distribute, sublicense, and/or sell copies of the Software, and to permit
  27033. // persons to whom the Software is furnished to do so, subject to the
  27034. // following conditions:
  27035. //
  27036. // The above copyright notice and this permission notice shall be included
  27037. // in all copies or substantial portions of the Software.
  27038. //
  27039. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  27040. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27041. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  27042. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  27043. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  27044. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  27045. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  27046. function EventEmitter() {
  27047. this._events = this._events || {};
  27048. this._maxListeners = this._maxListeners || undefined;
  27049. }
  27050. module.exports = EventEmitter;
  27051. // Backwards-compat with node 0.10.x
  27052. EventEmitter.EventEmitter = EventEmitter;
  27053. EventEmitter.prototype._events = undefined;
  27054. EventEmitter.prototype._maxListeners = undefined;
  27055. // By default EventEmitters will print a warning if more than 10 listeners are
  27056. // added to it. This is a useful default which helps finding memory leaks.
  27057. EventEmitter.defaultMaxListeners = 10;
  27058. // Obviously not all Emitters should be limited to 10. This function allows
  27059. // that to be increased. Set to zero for unlimited.
  27060. EventEmitter.prototype.setMaxListeners = function(n) {
  27061. if (!isNumber(n) || n < 0 || isNaN(n))
  27062. throw TypeError('n must be a positive number');
  27063. this._maxListeners = n;
  27064. return this;
  27065. };
  27066. EventEmitter.prototype.emit = function(type) {
  27067. var er, handler, len, args, i, listeners;
  27068. if (!this._events)
  27069. this._events = {};
  27070. // If there is no 'error' event listener then throw.
  27071. if (type === 'error') {
  27072. if (!this._events.error ||
  27073. (isObject(this._events.error) && !this._events.error.length)) {
  27074. er = arguments[1];
  27075. if (er instanceof Error) {
  27076. throw er; // Unhandled 'error' event
  27077. }
  27078. throw TypeError('Uncaught, unspecified "error" event.');
  27079. }
  27080. }
  27081. handler = this._events[type];
  27082. if (isUndefined(handler))
  27083. return false;
  27084. if (isFunction(handler)) {
  27085. switch (arguments.length) {
  27086. // fast cases
  27087. case 1:
  27088. handler.call(this);
  27089. break;
  27090. case 2:
  27091. handler.call(this, arguments[1]);
  27092. break;
  27093. case 3:
  27094. handler.call(this, arguments[1], arguments[2]);
  27095. break;
  27096. // slower
  27097. default:
  27098. len = arguments.length;
  27099. args = new Array(len - 1);
  27100. for (i = 1; i < len; i++)
  27101. args[i - 1] = arguments[i];
  27102. handler.apply(this, args);
  27103. }
  27104. } else if (isObject(handler)) {
  27105. len = arguments.length;
  27106. args = new Array(len - 1);
  27107. for (i = 1; i < len; i++)
  27108. args[i - 1] = arguments[i];
  27109. listeners = handler.slice();
  27110. len = listeners.length;
  27111. for (i = 0; i < len; i++)
  27112. listeners[i].apply(this, args);
  27113. }
  27114. return true;
  27115. };
  27116. EventEmitter.prototype.addListener = function(type, listener) {
  27117. var m;
  27118. if (!isFunction(listener))
  27119. throw TypeError('listener must be a function');
  27120. if (!this._events)
  27121. this._events = {};
  27122. // To avoid recursion in the case that type === "newListener"! Before
  27123. // adding it to the listeners, first emit "newListener".
  27124. if (this._events.newListener)
  27125. this.emit('newListener', type,
  27126. isFunction(listener.listener) ?
  27127. listener.listener : listener);
  27128. if (!this._events[type])
  27129. // Optimize the case of one listener. Don't need the extra array object.
  27130. this._events[type] = listener;
  27131. else if (isObject(this._events[type]))
  27132. // If we've already got an array, just append.
  27133. this._events[type].push(listener);
  27134. else
  27135. // Adding the second element, need to change to array.
  27136. this._events[type] = [this._events[type], listener];
  27137. // Check for listener leak
  27138. if (isObject(this._events[type]) && !this._events[type].warned) {
  27139. var m;
  27140. if (!isUndefined(this._maxListeners)) {
  27141. m = this._maxListeners;
  27142. } else {
  27143. m = EventEmitter.defaultMaxListeners;
  27144. }
  27145. if (m && m > 0 && this._events[type].length > m) {
  27146. this._events[type].warned = true;
  27147. console.error('(node) warning: possible EventEmitter memory ' +
  27148. 'leak detected. %d listeners added. ' +
  27149. 'Use emitter.setMaxListeners() to increase limit.',
  27150. this._events[type].length);
  27151. if (typeof console.trace === 'function') {
  27152. // not supported in IE 10
  27153. console.trace();
  27154. }
  27155. }
  27156. }
  27157. return this;
  27158. };
  27159. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  27160. EventEmitter.prototype.once = function(type, listener) {
  27161. if (!isFunction(listener))
  27162. throw TypeError('listener must be a function');
  27163. var fired = false;
  27164. function g() {
  27165. this.removeListener(type, g);
  27166. if (!fired) {
  27167. fired = true;
  27168. listener.apply(this, arguments);
  27169. }
  27170. }
  27171. g.listener = listener;
  27172. this.on(type, g);
  27173. return this;
  27174. };
  27175. // emits a 'removeListener' event iff the listener was removed
  27176. EventEmitter.prototype.removeListener = function(type, listener) {
  27177. var list, position, length, i;
  27178. if (!isFunction(listener))
  27179. throw TypeError('listener must be a function');
  27180. if (!this._events || !this._events[type])
  27181. return this;
  27182. list = this._events[type];
  27183. length = list.length;
  27184. position = -1;
  27185. if (list === listener ||
  27186. (isFunction(list.listener) && list.listener === listener)) {
  27187. delete this._events[type];
  27188. if (this._events.removeListener)
  27189. this.emit('removeListener', type, listener);
  27190. } else if (isObject(list)) {
  27191. for (i = length; i-- > 0;) {
  27192. if (list[i] === listener ||
  27193. (list[i].listener && list[i].listener === listener)) {
  27194. position = i;
  27195. break;
  27196. }
  27197. }
  27198. if (position < 0)
  27199. return this;
  27200. if (list.length === 1) {
  27201. list.length = 0;
  27202. delete this._events[type];
  27203. } else {
  27204. list.splice(position, 1);
  27205. }
  27206. if (this._events.removeListener)
  27207. this.emit('removeListener', type, listener);
  27208. }
  27209. return this;
  27210. };
  27211. EventEmitter.prototype.removeAllListeners = function(type) {
  27212. var key, listeners;
  27213. if (!this._events)
  27214. return this;
  27215. // not listening for removeListener, no need to emit
  27216. if (!this._events.removeListener) {
  27217. if (arguments.length === 0)
  27218. this._events = {};
  27219. else if (this._events[type])
  27220. delete this._events[type];
  27221. return this;
  27222. }
  27223. // emit removeListener for all listeners on all events
  27224. if (arguments.length === 0) {
  27225. for (key in this._events) {
  27226. if (key === 'removeListener') continue;
  27227. this.removeAllListeners(key);
  27228. }
  27229. this.removeAllListeners('removeListener');
  27230. this._events = {};
  27231. return this;
  27232. }
  27233. listeners = this._events[type];
  27234. if (isFunction(listeners)) {
  27235. this.removeListener(type, listeners);
  27236. } else {
  27237. // LIFO order
  27238. while (listeners.length)
  27239. this.removeListener(type, listeners[listeners.length - 1]);
  27240. }
  27241. delete this._events[type];
  27242. return this;
  27243. };
  27244. EventEmitter.prototype.listeners = function(type) {
  27245. var ret;
  27246. if (!this._events || !this._events[type])
  27247. ret = [];
  27248. else if (isFunction(this._events[type]))
  27249. ret = [this._events[type]];
  27250. else
  27251. ret = this._events[type].slice();
  27252. return ret;
  27253. };
  27254. EventEmitter.listenerCount = function(emitter, type) {
  27255. var ret;
  27256. if (!emitter._events || !emitter._events[type])
  27257. ret = 0;
  27258. else if (isFunction(emitter._events[type]))
  27259. ret = 1;
  27260. else
  27261. ret = emitter._events[type].length;
  27262. return ret;
  27263. };
  27264. function isFunction(arg) {
  27265. return typeof arg === 'function';
  27266. }
  27267. function isNumber(arg) {
  27268. return typeof arg === 'number';
  27269. }
  27270. function isObject(arg) {
  27271. return typeof arg === 'object' && arg !== null;
  27272. }
  27273. function isUndefined(arg) {
  27274. return arg === void 0;
  27275. }
  27276. },{}],112:[function(require,module,exports){
  27277. // shim for using process in browser
  27278. var process = module.exports = {};
  27279. var queue = [];
  27280. var draining = false;
  27281. var currentQueue;
  27282. var queueIndex = -1;
  27283. function cleanUpNextTick() {
  27284. draining = false;
  27285. if (currentQueue.length) {
  27286. queue = currentQueue.concat(queue);
  27287. } else {
  27288. queueIndex = -1;
  27289. }
  27290. if (queue.length) {
  27291. drainQueue();
  27292. }
  27293. }
  27294. function drainQueue() {
  27295. if (draining) {
  27296. return;
  27297. }
  27298. var timeout = setTimeout(cleanUpNextTick);
  27299. draining = true;
  27300. var len = queue.length;
  27301. while(len) {
  27302. currentQueue = queue;
  27303. queue = [];
  27304. while (++queueIndex < len) {
  27305. currentQueue[queueIndex].run();
  27306. }
  27307. queueIndex = -1;
  27308. len = queue.length;
  27309. }
  27310. currentQueue = null;
  27311. draining = false;
  27312. clearTimeout(timeout);
  27313. }
  27314. process.nextTick = function (fun) {
  27315. var args = new Array(arguments.length - 1);
  27316. if (arguments.length > 1) {
  27317. for (var i = 1; i < arguments.length; i++) {
  27318. args[i - 1] = arguments[i];
  27319. }
  27320. }
  27321. queue.push(new Item(fun, args));
  27322. if (queue.length === 1 && !draining) {
  27323. setTimeout(drainQueue, 0);
  27324. }
  27325. };
  27326. // v8 likes predictible objects
  27327. function Item(fun, array) {
  27328. this.fun = fun;
  27329. this.array = array;
  27330. }
  27331. Item.prototype.run = function () {
  27332. this.fun.apply(null, this.array);
  27333. };
  27334. process.title = 'browser';
  27335. process.browser = true;
  27336. process.env = {};
  27337. process.argv = [];
  27338. process.version = ''; // empty string to avoid regexp issues
  27339. process.versions = {};
  27340. function noop() {}
  27341. process.on = noop;
  27342. process.addListener = noop;
  27343. process.once = noop;
  27344. process.off = noop;
  27345. process.removeListener = noop;
  27346. process.removeAllListeners = noop;
  27347. process.emit = noop;
  27348. process.binding = function (name) {
  27349. throw new Error('process.binding is not supported');
  27350. };
  27351. // TODO(shtylman)
  27352. process.cwd = function () { return '/' };
  27353. process.chdir = function (dir) {
  27354. throw new Error('process.chdir is not supported');
  27355. };
  27356. process.umask = function() { return 0; };
  27357. },{}]},{},[1])(1)
  27358. });