您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

app.bundle.js 1.0MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. function EventEmitter() {
  23. this._events = this._events || {};
  24. this._maxListeners = this._maxListeners || undefined;
  25. }
  26. module.exports = EventEmitter;
  27. // Backwards-compat with node 0.10.x
  28. EventEmitter.EventEmitter = EventEmitter;
  29. EventEmitter.prototype._events = undefined;
  30. EventEmitter.prototype._maxListeners = undefined;
  31. // By default EventEmitters will print a warning if more than 10 listeners are
  32. // added to it. This is a useful default which helps finding memory leaks.
  33. EventEmitter.defaultMaxListeners = 10;
  34. // Obviously not all Emitters should be limited to 10. This function allows
  35. // that to be increased. Set to zero for unlimited.
  36. EventEmitter.prototype.setMaxListeners = function(n) {
  37. if (!isNumber(n) || n < 0 || isNaN(n))
  38. throw TypeError('n must be a positive number');
  39. this._maxListeners = n;
  40. return this;
  41. };
  42. EventEmitter.prototype.emit = function(type) {
  43. var er, handler, len, args, i, listeners;
  44. if (!this._events)
  45. this._events = {};
  46. // If there is no 'error' event listener then throw.
  47. if (type === 'error') {
  48. if (!this._events.error ||
  49. (isObject(this._events.error) && !this._events.error.length)) {
  50. er = arguments[1];
  51. if (er instanceof Error) {
  52. throw er; // Unhandled 'error' event
  53. }
  54. throw TypeError('Uncaught, unspecified "error" event.');
  55. }
  56. }
  57. handler = this._events[type];
  58. if (isUndefined(handler))
  59. return false;
  60. if (isFunction(handler)) {
  61. switch (arguments.length) {
  62. // fast cases
  63. case 1:
  64. handler.call(this);
  65. break;
  66. case 2:
  67. handler.call(this, arguments[1]);
  68. break;
  69. case 3:
  70. handler.call(this, arguments[1], arguments[2]);
  71. break;
  72. // slower
  73. default:
  74. len = arguments.length;
  75. args = new Array(len - 1);
  76. for (i = 1; i < len; i++)
  77. args[i - 1] = arguments[i];
  78. handler.apply(this, args);
  79. }
  80. } else if (isObject(handler)) {
  81. len = arguments.length;
  82. args = new Array(len - 1);
  83. for (i = 1; i < len; i++)
  84. args[i - 1] = arguments[i];
  85. listeners = handler.slice();
  86. len = listeners.length;
  87. for (i = 0; i < len; i++)
  88. listeners[i].apply(this, args);
  89. }
  90. return true;
  91. };
  92. EventEmitter.prototype.addListener = function(type, listener) {
  93. var m;
  94. if (!isFunction(listener))
  95. throw TypeError('listener must be a function');
  96. if (!this._events)
  97. this._events = {};
  98. // To avoid recursion in the case that type === "newListener"! Before
  99. // adding it to the listeners, first emit "newListener".
  100. if (this._events.newListener)
  101. this.emit('newListener', type,
  102. isFunction(listener.listener) ?
  103. listener.listener : listener);
  104. if (!this._events[type])
  105. // Optimize the case of one listener. Don't need the extra array object.
  106. this._events[type] = listener;
  107. else if (isObject(this._events[type]))
  108. // If we've already got an array, just append.
  109. this._events[type].push(listener);
  110. else
  111. // Adding the second element, need to change to array.
  112. this._events[type] = [this._events[type], listener];
  113. // Check for listener leak
  114. if (isObject(this._events[type]) && !this._events[type].warned) {
  115. var m;
  116. if (!isUndefined(this._maxListeners)) {
  117. m = this._maxListeners;
  118. } else {
  119. m = EventEmitter.defaultMaxListeners;
  120. }
  121. if (m && m > 0 && this._events[type].length > m) {
  122. this._events[type].warned = true;
  123. console.error('(node) warning: possible EventEmitter memory ' +
  124. 'leak detected. %d listeners added. ' +
  125. 'Use emitter.setMaxListeners() to increase limit.',
  126. this._events[type].length);
  127. if (typeof console.trace === 'function') {
  128. // not supported in IE 10
  129. console.trace();
  130. }
  131. }
  132. }
  133. return this;
  134. };
  135. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  136. EventEmitter.prototype.once = function(type, listener) {
  137. if (!isFunction(listener))
  138. throw TypeError('listener must be a function');
  139. var fired = false;
  140. function g() {
  141. this.removeListener(type, g);
  142. if (!fired) {
  143. fired = true;
  144. listener.apply(this, arguments);
  145. }
  146. }
  147. g.listener = listener;
  148. this.on(type, g);
  149. return this;
  150. };
  151. // emits a 'removeListener' event iff the listener was removed
  152. EventEmitter.prototype.removeListener = function(type, listener) {
  153. var list, position, length, i;
  154. if (!isFunction(listener))
  155. throw TypeError('listener must be a function');
  156. if (!this._events || !this._events[type])
  157. return this;
  158. list = this._events[type];
  159. length = list.length;
  160. position = -1;
  161. if (list === listener ||
  162. (isFunction(list.listener) && list.listener === listener)) {
  163. delete this._events[type];
  164. if (this._events.removeListener)
  165. this.emit('removeListener', type, listener);
  166. } else if (isObject(list)) {
  167. for (i = length; i-- > 0;) {
  168. if (list[i] === listener ||
  169. (list[i].listener && list[i].listener === listener)) {
  170. position = i;
  171. break;
  172. }
  173. }
  174. if (position < 0)
  175. return this;
  176. if (list.length === 1) {
  177. list.length = 0;
  178. delete this._events[type];
  179. } else {
  180. list.splice(position, 1);
  181. }
  182. if (this._events.removeListener)
  183. this.emit('removeListener', type, listener);
  184. }
  185. return this;
  186. };
  187. EventEmitter.prototype.removeAllListeners = function(type) {
  188. var key, listeners;
  189. if (!this._events)
  190. return this;
  191. // not listening for removeListener, no need to emit
  192. if (!this._events.removeListener) {
  193. if (arguments.length === 0)
  194. this._events = {};
  195. else if (this._events[type])
  196. delete this._events[type];
  197. return this;
  198. }
  199. // emit removeListener for all listeners on all events
  200. if (arguments.length === 0) {
  201. for (key in this._events) {
  202. if (key === 'removeListener') continue;
  203. this.removeAllListeners(key);
  204. }
  205. this.removeAllListeners('removeListener');
  206. this._events = {};
  207. return this;
  208. }
  209. listeners = this._events[type];
  210. if (isFunction(listeners)) {
  211. this.removeListener(type, listeners);
  212. } else {
  213. // LIFO order
  214. while (listeners.length)
  215. this.removeListener(type, listeners[listeners.length - 1]);
  216. }
  217. delete this._events[type];
  218. return this;
  219. };
  220. EventEmitter.prototype.listeners = function(type) {
  221. var ret;
  222. if (!this._events || !this._events[type])
  223. ret = [];
  224. else if (isFunction(this._events[type]))
  225. ret = [this._events[type]];
  226. else
  227. ret = this._events[type].slice();
  228. return ret;
  229. };
  230. EventEmitter.listenerCount = function(emitter, type) {
  231. var ret;
  232. if (!emitter._events || !emitter._events[type])
  233. ret = 0;
  234. else if (isFunction(emitter._events[type]))
  235. ret = 1;
  236. else
  237. ret = emitter._events[type].length;
  238. return ret;
  239. };
  240. function isFunction(arg) {
  241. return typeof arg === 'function';
  242. }
  243. function isNumber(arg) {
  244. return typeof arg === 'number';
  245. }
  246. function isObject(arg) {
  247. return typeof arg === 'object' && arg !== null;
  248. }
  249. function isUndefined(arg) {
  250. return arg === void 0;
  251. }
  252. },{}],2:[function(require,module,exports){
  253. // shim for using process in browser
  254. var process = module.exports = {};
  255. var queue = [];
  256. var draining = false;
  257. var currentQueue;
  258. var queueIndex = -1;
  259. function cleanUpNextTick() {
  260. draining = false;
  261. if (currentQueue.length) {
  262. queue = currentQueue.concat(queue);
  263. } else {
  264. queueIndex = -1;
  265. }
  266. if (queue.length) {
  267. drainQueue();
  268. }
  269. }
  270. function drainQueue() {
  271. if (draining) {
  272. return;
  273. }
  274. var timeout = setTimeout(cleanUpNextTick);
  275. draining = true;
  276. var len = queue.length;
  277. while(len) {
  278. currentQueue = queue;
  279. queue = [];
  280. while (++queueIndex < len) {
  281. currentQueue[queueIndex].run();
  282. }
  283. queueIndex = -1;
  284. len = queue.length;
  285. }
  286. currentQueue = null;
  287. draining = false;
  288. clearTimeout(timeout);
  289. }
  290. process.nextTick = function (fun) {
  291. var args = new Array(arguments.length - 1);
  292. if (arguments.length > 1) {
  293. for (var i = 1; i < arguments.length; i++) {
  294. args[i - 1] = arguments[i];
  295. }
  296. }
  297. queue.push(new Item(fun, args));
  298. if (queue.length === 1 && !draining) {
  299. setTimeout(drainQueue, 0);
  300. }
  301. };
  302. // v8 likes predictible objects
  303. function Item(fun, array) {
  304. this.fun = fun;
  305. this.array = array;
  306. }
  307. Item.prototype.run = function () {
  308. this.fun.apply(null, this.array);
  309. };
  310. process.title = 'browser';
  311. process.browser = true;
  312. process.env = {};
  313. process.argv = [];
  314. process.version = ''; // empty string to avoid regexp issues
  315. process.versions = {};
  316. function noop() {}
  317. process.on = noop;
  318. process.addListener = noop;
  319. process.once = noop;
  320. process.off = noop;
  321. process.removeListener = noop;
  322. process.removeAllListeners = noop;
  323. process.emit = noop;
  324. process.binding = function (name) {
  325. throw new Error('process.binding is not supported');
  326. };
  327. // TODO(shtylman)
  328. process.cwd = function () { return '/' };
  329. process.chdir = function (dir) {
  330. throw new Error('process.chdir is not supported');
  331. };
  332. process.umask = function() { return 0; };
  333. },{}],3:[function(require,module,exports){
  334. /* jshint -W117 */
  335. /* application specific logic */
  336. var APP =
  337. {
  338. init: function () {
  339. this.UI = require("./modules/UI/UI");
  340. this.API = require("./modules/API/API");
  341. this.connectionquality = require("./modules/connectionquality/connectionquality");
  342. this.statistics = require("./modules/statistics/statistics");
  343. this.RTC = require("./modules/RTC/RTC");
  344. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  345. this.xmpp = require("./modules/xmpp/xmpp");
  346. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  347. this.translation = require("./modules/translation/translation");
  348. this.settings = require("./modules/settings/Settings");
  349. this.DTMF = require("./modules/DTMF/DTMF");
  350. this.members = require("./modules/members/MemberList");
  351. }
  352. };
  353. function init() {
  354. APP.desktopsharing.init();
  355. APP.RTC.start();
  356. APP.xmpp.start();
  357. APP.statistics.start();
  358. APP.connectionquality.init();
  359. APP.keyboardshortcut.init();
  360. APP.members.start();
  361. }
  362. $(document).ready(function () {
  363. var URLProcessor = require("./modules/URLProcessor/URLProcessor");
  364. URLProcessor.setConfigParametersFromUrl();
  365. APP.init();
  366. APP.translation.init();
  367. if(APP.API.isEnabled())
  368. APP.API.init();
  369. APP.UI.start(init);
  370. });
  371. $(window).bind('beforeunload', function () {
  372. if(APP.API.isEnabled())
  373. APP.API.dispose();
  374. });
  375. module.exports = APP;
  376. },{"./modules/API/API":4,"./modules/DTMF/DTMF":5,"./modules/RTC/RTC":9,"./modules/UI/UI":13,"./modules/URLProcessor/URLProcessor":44,"./modules/connectionquality/connectionquality":45,"./modules/desktopsharing/desktopsharing":46,"./modules/keyboardshortcut/keyboardshortcut":47,"./modules/members/MemberList":48,"./modules/settings/Settings":49,"./modules/statistics/statistics":53,"./modules/translation/translation":54,"./modules/xmpp/xmpp":70}],4:[function(require,module,exports){
  377. /* global APP */
  378. /**
  379. * Implements API class that communicates with external api class
  380. * and provides interface to access Jitsi Meet features by external
  381. * applications that embed Jitsi Meet
  382. */
  383. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  384. /**
  385. * List of the available commands.
  386. * @type {{
  387. * displayName: inputDisplayNameHandler,
  388. * toggleAudio: toggleAudio,
  389. * toggleVideo: toggleVideo,
  390. * toggleFilmStrip: toggleFilmStrip,
  391. * toggleChat: toggleChat,
  392. * toggleContactList: toggleContactList
  393. * }}
  394. */
  395. var commands = {};
  396. function initCommands() {
  397. commands = {
  398. displayName: APP.UI.inputDisplayNameHandler,
  399. toggleAudio: APP.UI.toggleAudio,
  400. toggleVideo: APP.UI.toggleVideo,
  401. toggleFilmStrip: APP.UI.toggleFilmStrip,
  402. toggleChat: APP.UI.toggleChat,
  403. toggleContactList: APP.UI.toggleContactList
  404. };
  405. }
  406. /**
  407. * Maps the supported events and their status
  408. * (true it the event is enabled and false if it is disabled)
  409. * @type {{
  410. * incomingMessage: boolean,
  411. * outgoingMessage: boolean,
  412. * displayNameChange: boolean,
  413. * participantJoined: boolean,
  414. * participantLeft: boolean
  415. * }}
  416. */
  417. var events = {
  418. incomingMessage: false,
  419. outgoingMessage:false,
  420. displayNameChange: false,
  421. participantJoined: false,
  422. participantLeft: false
  423. };
  424. var displayName = {};
  425. /**
  426. * Processes commands from external application.
  427. * @param message the object with the command
  428. */
  429. function processCommand(message) {
  430. if (message.action != "execute") {
  431. console.error("Unknown action of the message");
  432. return;
  433. }
  434. for (var key in message) {
  435. if(commands[key])
  436. commands[key].apply(null, message[key]);
  437. }
  438. }
  439. /**
  440. * Processes events objects from external applications
  441. * @param event the event
  442. */
  443. function processEvent(event) {
  444. if (!event.action) {
  445. console.error("Event with no action is received.");
  446. return;
  447. }
  448. var i = 0;
  449. switch(event.action) {
  450. case "add":
  451. for (; i < event.events.length; i++) {
  452. events[event.events[i]] = true;
  453. }
  454. break;
  455. case "remove":
  456. for (; i < event.events.length; i++) {
  457. events[event.events[i]] = false;
  458. }
  459. break;
  460. default:
  461. console.error("Unknown action for event.");
  462. }
  463. }
  464. /**
  465. * Sends message to the external application.
  466. * @param object
  467. */
  468. function sendMessage(object) {
  469. window.parent.postMessage(JSON.stringify(object), "*");
  470. }
  471. /**
  472. * Processes a message event from the external application
  473. * @param event the message event
  474. */
  475. function processMessage(event) {
  476. var message;
  477. try {
  478. message = JSON.parse(event.data);
  479. } catch (e) {}
  480. if(!message.type)
  481. return;
  482. switch (message.type) {
  483. case "command":
  484. processCommand(message);
  485. break;
  486. case "event":
  487. processEvent(message);
  488. break;
  489. default:
  490. console.error("Unknown type of the message");
  491. return;
  492. }
  493. }
  494. function setupListeners() {
  495. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  496. API.triggerEvent("participantJoined", {jid: from});
  497. });
  498. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  499. if (from != myjid)
  500. API.triggerEvent("incomingMessage",
  501. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  502. });
  503. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  504. API.triggerEvent("participantLeft", {jid: jid});
  505. });
  506. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  507. var name = displayName[jid];
  508. if(!name || name != newDisplayName) {
  509. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  510. displayName[jid] = newDisplayName;
  511. }
  512. });
  513. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  514. APP.API.triggerEvent("outgoingMessage", {"message": body});
  515. });
  516. }
  517. var API = {
  518. /**
  519. * Check whether the API should be enabled or not.
  520. * @returns {boolean}
  521. */
  522. isEnabled: function () {
  523. var hash = location.hash;
  524. if (hash && hash.indexOf("external") > -1 && window.postMessage)
  525. return true;
  526. return false;
  527. },
  528. /**
  529. * Initializes the APIConnector. Setups message event listeners that will
  530. * receive information from external applications that embed Jitsi Meet.
  531. * It also sends a message to the external application that APIConnector
  532. * is initialized.
  533. */
  534. init: function () {
  535. initCommands();
  536. if (window.addEventListener) {
  537. window.addEventListener('message',
  538. processMessage, false);
  539. }
  540. else {
  541. window.attachEvent('onmessage', processMessage);
  542. }
  543. sendMessage({type: "system", loaded: true});
  544. setupListeners();
  545. },
  546. /**
  547. * Checks whether the event is enabled ot not.
  548. * @param name the name of the event.
  549. * @returns {*}
  550. */
  551. isEventEnabled: function (name) {
  552. return events[name];
  553. },
  554. /**
  555. * Sends event object to the external application that has been subscribed
  556. * for that event.
  557. * @param name the name event
  558. * @param object data associated with the event
  559. */
  560. triggerEvent: function (name, object) {
  561. if(this.isEnabled() && this.isEventEnabled(name))
  562. sendMessage({
  563. type: "event", action: "result", event: name, result: object});
  564. },
  565. /**
  566. * Removes the listeners.
  567. */
  568. dispose: function () {
  569. if(window.removeEventListener) {
  570. window.removeEventListener("message",
  571. processMessage, false);
  572. }
  573. else {
  574. window.detachEvent('onmessage', processMessage);
  575. }
  576. }
  577. };
  578. module.exports = API;
  579. },{"../../service/xmpp/XMPPEvents":120}],5:[function(require,module,exports){
  580. /* global APP */
  581. /**
  582. * A module for sending DTMF tones.
  583. */
  584. var DTMFSender;
  585. var initDtmfSender = function() {
  586. // TODO: This needs to reset this if the peerconnection changes
  587. // (e.g. the call is re-made)
  588. if (DTMFSender)
  589. return;
  590. var localAudio = APP.RTC.localAudio;
  591. if (localAudio && localAudio.getTracks().length > 0)
  592. {
  593. var peerconnection
  594. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  595. if (peerconnection) {
  596. DTMFSender =
  597. peerconnection.peerconnection
  598. .createDTMFSender(localAudio.getTracks()[0]);
  599. console.log("Initialized DTMFSender");
  600. }
  601. else {
  602. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  603. }
  604. }
  605. else {
  606. console.log("Failed to initialize DTMFSender: no audio track.");
  607. }
  608. };
  609. var DTMF = {
  610. sendTones: function (tones, duration, pause) {
  611. if (!DTMFSender)
  612. initDtmfSender();
  613. if (DTMFSender){
  614. DTMFSender.insertDTMF(tones,
  615. (duration || 200),
  616. (pause || 200));
  617. }
  618. }
  619. };
  620. module.exports = DTMF;
  621. },{}],6:[function(require,module,exports){
  622. /* global config, APP, Strophe */
  623. // cache datachannels to avoid garbage collection
  624. // https://code.google.com/p/chromium/issues/detail?id=405545
  625. var RTCEvents = require("../../service/RTC/RTCEvents");
  626. var _dataChannels = [];
  627. var eventEmitter = null;
  628. var DataChannels = {
  629. /**
  630. * Callback triggered by PeerConnection when new data channel is opened
  631. * on the bridge.
  632. * @param event the event info object.
  633. */
  634. onDataChannel: function (event) {
  635. var dataChannel = event.channel;
  636. dataChannel.onopen = function () {
  637. console.info("Data channel opened by the Videobridge!", dataChannel);
  638. // Code sample for sending string and/or binary data
  639. // Sends String message to the bridge
  640. //dataChannel.send("Hello bridge!");
  641. // Sends 12 bytes binary message to the bridge
  642. //dataChannel.send(new ArrayBuffer(12));
  643. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  644. };
  645. dataChannel.onerror = function (error) {
  646. console.error("Data Channel Error:", error, dataChannel);
  647. };
  648. dataChannel.onmessage = function (event) {
  649. var data = event.data;
  650. // JSON
  651. var obj;
  652. try {
  653. obj = JSON.parse(data);
  654. }
  655. catch (e) {
  656. console.error(
  657. "Failed to parse data channel message as JSON: ",
  658. data,
  659. dataChannel);
  660. }
  661. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  662. var colibriClass = obj.colibriClass;
  663. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  664. // Endpoint ID from the Videobridge.
  665. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  666. console.info(
  667. "Data channel new dominant speaker event: ",
  668. dominantSpeakerEndpoint);
  669. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  670. }
  671. else if ("InLastNChangeEvent" === colibriClass) {
  672. var oldValue = obj.oldValue;
  673. var newValue = obj.newValue;
  674. // Make sure that oldValue and newValue are of type boolean.
  675. var type;
  676. if ((type = typeof oldValue) !== 'boolean') {
  677. if (type === 'string') {
  678. oldValue = (oldValue == "true");
  679. } else {
  680. oldValue = new Boolean(oldValue).valueOf();
  681. }
  682. }
  683. if ((type = typeof newValue) !== 'boolean') {
  684. if (type === 'string') {
  685. newValue = (newValue == "true");
  686. } else {
  687. newValue = new Boolean(newValue).valueOf();
  688. }
  689. }
  690. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  691. }
  692. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  693. // The new/latest list of last-n endpoint IDs.
  694. var lastNEndpoints = obj.lastNEndpoints;
  695. // The list of endpoint IDs which are entering the list of
  696. // last-n at this time i.e. were not in the old list of last-n
  697. // endpoint IDs.
  698. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  699. console.log(
  700. "Data channel new last-n event: ",
  701. lastNEndpoints, endpointsEnteringLastN, obj);
  702. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  703. lastNEndpoints, endpointsEnteringLastN, obj);
  704. }
  705. else {
  706. console.debug("Data channel JSON-formatted message: ", obj);
  707. }
  708. }
  709. };
  710. dataChannel.onclose = function () {
  711. console.info("The Data Channel closed", dataChannel);
  712. var idx = _dataChannels.indexOf(dataChannel);
  713. if (idx > -1)
  714. _dataChannels = _dataChannels.splice(idx, 1);
  715. };
  716. _dataChannels.push(dataChannel);
  717. },
  718. /**
  719. * Binds "ondatachannel" event listener to given PeerConnection instance.
  720. * @param peerConnection WebRTC peer connection instance.
  721. */
  722. init: function (peerConnection, emitter) {
  723. if(!config.openSctp)
  724. return;
  725. peerConnection.ondatachannel = this.onDataChannel;
  726. eventEmitter = emitter;
  727. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  728. // Although it's not a requirement to open separate channels from both bridge
  729. // and peer as single channel can be used for sending and receiving data.
  730. // So either channel opened by the bridge or the one opened here is enough
  731. // for communication with the bridge.
  732. /*var dataChannelOptions =
  733. {
  734. reliable: true
  735. };
  736. var dataChannel
  737. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  738. // Can be used only when is in open state
  739. dataChannel.onopen = function ()
  740. {
  741. dataChannel.send("My channel !!!");
  742. };
  743. dataChannel.onmessage = function (event)
  744. {
  745. var msgData = event.data;
  746. console.info("Got My Data Channel Message:", msgData, dataChannel);
  747. };*/
  748. },
  749. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  750. handlePinnedEndpointEvent: onPinnedEndpointChanged
  751. };
  752. function onSelectedEndpointChanged(userResource) {
  753. console.log('selected endpoint changed: ', userResource);
  754. if (_dataChannels && _dataChannels.length != 0) {
  755. _dataChannels.some(function (dataChannel) {
  756. if (dataChannel.readyState == 'open') {
  757. console.log('sending selected endpoint changed ' +
  758. 'notification to the bridge: ', userResource);
  759. dataChannel.send(JSON.stringify({
  760. 'colibriClass': 'SelectedEndpointChangedEvent',
  761. 'selectedEndpoint':
  762. (!userResource || userResource === null)?
  763. null : userResource
  764. }));
  765. return true;
  766. }
  767. });
  768. }
  769. }
  770. function onPinnedEndpointChanged(userResource) {
  771. console.log('pinned endpoint changed: ', userResource);
  772. if (_dataChannels && _dataChannels.length != 0) {
  773. _dataChannels.some(function (dataChannel) {
  774. if (dataChannel.readyState == 'open') {
  775. dataChannel.send(JSON.stringify({
  776. 'colibriClass': 'PinnedEndpointChangedEvent',
  777. 'pinnedEndpoint':
  778. (!userResource || userResource == null)?
  779. null : userResource
  780. }));
  781. return true;
  782. }
  783. });
  784. }
  785. }
  786. module.exports = DataChannels;
  787. },{"../../service/RTC/RTCEvents":111}],7:[function(require,module,exports){
  788. /* global APP */
  789. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  790. var RTCEvents = require("../../service/RTC/RTCEvents");
  791. var RTCBrowserType = require("./RTCBrowserType");
  792. /**
  793. * This implements 'onended' callback normally fired by WebRTC after the stream
  794. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  795. * @param stream original WebRTC stream object to which 'onended' handling
  796. * will be added.
  797. */
  798. function implementOnEndedHandling(stream) {
  799. var originalStop = stream.stop;
  800. stream.stop = function () {
  801. originalStop.apply(stream);
  802. if (!stream.ended) {
  803. stream.ended = true;
  804. stream.onended();
  805. }
  806. };
  807. }
  808. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  809. this.stream = stream;
  810. this.eventEmitter = eventEmitter;
  811. this.type = type;
  812. this.videoType = videoType;
  813. this.isGUMStream = true;
  814. if(isGUMStream === false)
  815. this.isGUMStream = isGUMStream;
  816. var self = this;
  817. if(type == "audio") {
  818. this.getTracks = function () {
  819. return self.stream.getAudioTracks();
  820. };
  821. } else {
  822. this.getTracks = function () {
  823. return self.stream.getVideoTracks();
  824. };
  825. }
  826. this.stream.onended = function () {
  827. self.streamEnded();
  828. };
  829. if (RTCBrowserType.isFirefox()) {
  830. implementOnEndedHandling(this.stream);
  831. }
  832. }
  833. LocalStream.prototype.streamEnded = function () {
  834. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  835. };
  836. LocalStream.prototype.getOriginalStream = function()
  837. {
  838. return this.stream;
  839. };
  840. LocalStream.prototype.isAudioStream = function () {
  841. return this.type === "audio";
  842. };
  843. LocalStream.prototype.setMute = function (mute)
  844. {
  845. var isAudio = this.isAudioStream();
  846. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  847. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  848. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  849. // FIXME FF does not support 'removeStream' method used to mute
  850. RTCBrowserType.isFirefox()) {
  851. var tracks = this.getTracks();
  852. for (var idx = 0; idx < tracks.length; idx++) {
  853. tracks[idx].enabled = !mute;
  854. }
  855. this.eventEmitter.emit(eventType, mute);
  856. } else {
  857. if (mute) {
  858. APP.xmpp.removeStream(this.stream);
  859. this.stream.stop();
  860. this.eventEmitter.emit(eventType, true);
  861. } else {
  862. var self = this;
  863. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  864. (this.isAudioStream() ? ["audio"] : ["video"]),
  865. function (stream) {
  866. if (isAudio) {
  867. APP.RTC.changeLocalAudio(stream,
  868. function () {
  869. self.eventEmitter.emit(eventType, false);
  870. });
  871. } else {
  872. APP.RTC.changeLocalVideo(stream, false,
  873. function () {
  874. self.eventEmitter.emit(eventType, false);
  875. });
  876. }
  877. });
  878. }
  879. }
  880. };
  881. LocalStream.prototype.isMuted = function () {
  882. var tracks = [];
  883. if (this.isAudioStream()) {
  884. tracks = this.stream.getAudioTracks();
  885. } else {
  886. if (this.stream.ended)
  887. return true;
  888. tracks = this.stream.getVideoTracks();
  889. }
  890. for (var idx = 0; idx < tracks.length; idx++) {
  891. if(tracks[idx].enabled)
  892. return false;
  893. }
  894. return true;
  895. };
  896. LocalStream.prototype.getId = function () {
  897. return this.stream.getTracks()[0].id;
  898. };
  899. module.exports = LocalStream;
  900. },{"../../service/RTC/RTCEvents":111,"../../service/RTC/StreamEventTypes.js":113,"./RTCBrowserType":10}],8:[function(require,module,exports){
  901. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  902. /**
  903. * Creates a MediaStream object for the given data, session id and ssrc.
  904. * It is a wrapper class for the MediaStream.
  905. *
  906. * @param data the data object from which we obtain the stream,
  907. * the peerjid, etc.
  908. * @param sid the session id
  909. * @param ssrc the ssrc corresponding to this MediaStream
  910. *
  911. * @constructor
  912. */
  913. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  914. // XXX(gp) to minimize headaches in the future, we should build our
  915. // abstractions around tracks and not streams. ORTC is track based API.
  916. // Mozilla expects m-lines to represent media tracks.
  917. //
  918. // Practically, what I'm saying is that we should have a MediaTrack class
  919. // and not a MediaStream class.
  920. //
  921. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  922. // a track might have an associated RTX and FEC sources.
  923. this.sid = sid;
  924. this.stream = data.stream;
  925. this.peerjid = data.peerjid;
  926. this.videoType = data.videoType;
  927. this.ssrc = ssrc;
  928. this.type = (this.stream.getVideoTracks().length > 0)?
  929. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  930. this.muted = false;
  931. this.eventEmitter = eventEmitter;
  932. }
  933. MediaStream.prototype.getOriginalStream = function() {
  934. return this.stream;
  935. };
  936. MediaStream.prototype.setMute = function (value) {
  937. this.stream.muted = value;
  938. this.muted = value;
  939. };
  940. module.exports = MediaStream;
  941. },{"../../service/RTC/MediaStreamTypes":110}],9:[function(require,module,exports){
  942. /* global APP */
  943. var EventEmitter = require("events");
  944. var RTCBrowserType = require("./RTCBrowserType");
  945. var RTCUtils = require("./RTCUtils.js");
  946. var LocalStream = require("./LocalStream.js");
  947. var DataChannels = require("./DataChannels");
  948. var MediaStream = require("./MediaStream.js");
  949. var DesktopSharingEventTypes
  950. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  951. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  952. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  953. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  954. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  955. var UIEvents = require("../../service/UI/UIEvents");
  956. var eventEmitter = new EventEmitter();
  957. function getMediaStreamUsage()
  958. {
  959. var result = {
  960. audio: true,
  961. video: true
  962. };
  963. /** There are some issues with the desktop sharing
  964. * when this property is enabled.
  965. * WARNING: We must change the implementation to start video/audio if we
  966. * receive from the focus that the peer is not muted.
  967. var isSecureConnection = window.location.protocol == "https:";
  968. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  969. {
  970. result = {
  971. audio: false,
  972. video: false
  973. };
  974. }
  975. **/
  976. return result;
  977. }
  978. var RTC = {
  979. rtcUtils: null,
  980. devices: {
  981. audio: true,
  982. video: true
  983. },
  984. localStreams: [],
  985. remoteStreams: {},
  986. localAudio: null,
  987. localVideo: null,
  988. addStreamListener: function (listener, eventType) {
  989. eventEmitter.on(eventType, listener);
  990. },
  991. addListener: function (type, listener) {
  992. eventEmitter.on(type, listener);
  993. },
  994. removeStreamListener: function (listener, eventType) {
  995. if(!(eventType instanceof StreamEventTypes))
  996. throw "Illegal argument";
  997. eventEmitter.removeListener(eventType, listener);
  998. },
  999. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  1000. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  1001. //in firefox we have only one stream object
  1002. if(this.localStreams.length == 0 ||
  1003. this.localStreams[0].getOriginalStream() != stream)
  1004. this.localStreams.push(localStream);
  1005. if(isMuted === true)
  1006. localStream.setMute(true);
  1007. if(type == "audio") {
  1008. this.localAudio = localStream;
  1009. } else {
  1010. this.localVideo = localStream;
  1011. }
  1012. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1013. if(change)
  1014. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1015. eventEmitter.emit(eventType, localStream, isMuted);
  1016. return localStream;
  1017. },
  1018. removeLocalStream: function (stream) {
  1019. for(var i = 0; i < this.localStreams.length; i++) {
  1020. if(this.localStreams[i].getOriginalStream() === stream) {
  1021. delete this.localStreams[i];
  1022. return;
  1023. }
  1024. }
  1025. },
  1026. createRemoteStream: function (data, sid, thessrc) {
  1027. var remoteStream = new MediaStream(data, sid, thessrc,
  1028. RTCBrowserType.getBrowserType(), eventEmitter);
  1029. var jid = data.peerjid || APP.xmpp.myJid();
  1030. if(!this.remoteStreams[jid]) {
  1031. this.remoteStreams[jid] = {};
  1032. }
  1033. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1034. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1035. return remoteStream;
  1036. },
  1037. getPCConstraints: function () {
  1038. return this.rtcUtils.pc_constraints;
  1039. },
  1040. getUserMediaWithConstraints:function(um, success_callback,
  1041. failure_callback, resolution,
  1042. bandwidth, fps, desktopStream)
  1043. {
  1044. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  1045. failure_callback, resolution, bandwidth, fps, desktopStream);
  1046. },
  1047. attachMediaStream: function (elSelector, stream) {
  1048. this.rtcUtils.attachMediaStream(elSelector, stream);
  1049. },
  1050. getStreamID: function (stream) {
  1051. return this.rtcUtils.getStreamID(stream);
  1052. },
  1053. getVideoSrc: function (element) {
  1054. return this.rtcUtils.getVideoSrc(element);
  1055. },
  1056. setVideoSrc: function (element, src) {
  1057. this.rtcUtils.setVideoSrc(element, src);
  1058. },
  1059. getVideoElementName: function () {
  1060. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1061. },
  1062. dispose: function() {
  1063. if (this.rtcUtils) {
  1064. this.rtcUtils = null;
  1065. }
  1066. },
  1067. stop: function () {
  1068. this.dispose();
  1069. },
  1070. start: function () {
  1071. var self = this;
  1072. APP.desktopsharing.addListener(
  1073. function (stream, isUsingScreenStream, callback) {
  1074. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1075. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1076. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  1077. DataChannels.init(event.peerconnection, eventEmitter);
  1078. });
  1079. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  1080. DataChannels.handleSelectedEndpointEvent);
  1081. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1082. DataChannels.handlePinnedEndpointEvent);
  1083. // In case of IE we continue from 'onReady' callback
  1084. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1085. // once it is initialized.
  1086. var onReady = function () {
  1087. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1088. self.rtcUtils.obtainAudioAndVideoPermissions(
  1089. null, null, getMediaStreamUsage());
  1090. };
  1091. this.rtcUtils = new RTCUtils(this, onReady);
  1092. // Call onReady() if Temasys plugin is not used
  1093. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1094. onReady();
  1095. }
  1096. },
  1097. muteRemoteVideoStream: function (jid, value) {
  1098. var stream;
  1099. if(this.remoteStreams[jid] &&
  1100. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1101. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1102. }
  1103. if(!stream)
  1104. return true;
  1105. if (value != stream.muted) {
  1106. stream.setMute(value);
  1107. return true;
  1108. }
  1109. return false;
  1110. },
  1111. switchVideoStreams: function (new_stream) {
  1112. this.localVideo.stream = new_stream;
  1113. this.localStreams = [];
  1114. //in firefox we have only one stream object
  1115. if (this.localAudio.getOriginalStream() != new_stream)
  1116. this.localStreams.push(this.localAudio);
  1117. this.localStreams.push(this.localVideo);
  1118. },
  1119. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  1120. var oldStream = this.localVideo.getOriginalStream();
  1121. var type = (isUsingScreenStream ? "screen" : "camera");
  1122. var localCallback = callback;
  1123. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1124. localCallback = function() {
  1125. APP.xmpp.setVideoMute(false, function(mute) {
  1126. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1127. });
  1128. callback();
  1129. };
  1130. }
  1131. // FIXME: Workaround for FF/IE/Safari
  1132. if (stream && stream.videoStream) {
  1133. stream = stream.videoStream;
  1134. }
  1135. var videoStream = this.rtcUtils.createStream(stream, true);
  1136. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1137. // Stop the stream to trigger onended event for old stream
  1138. oldStream.stop();
  1139. this.switchVideoStreams(videoStream, oldStream);
  1140. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  1141. },
  1142. changeLocalAudio: function (stream, callback) {
  1143. var oldStream = this.localAudio.getOriginalStream();
  1144. var newStream = this.rtcUtils.createStream(stream);
  1145. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1146. // Stop the stream to trigger onended event for old stream
  1147. oldStream.stop();
  1148. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  1149. },
  1150. isVideoMuted: function (jid) {
  1151. if (jid === APP.xmpp.myJid()) {
  1152. var localVideo = APP.RTC.localVideo;
  1153. return (!localVideo || localVideo.isMuted());
  1154. } else {
  1155. if (!APP.RTC.remoteStreams[jid] ||
  1156. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1157. return null;
  1158. }
  1159. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1160. }
  1161. },
  1162. setVideoMute: function (mute, callback, options) {
  1163. if (!this.localVideo)
  1164. return;
  1165. if (mute == APP.RTC.localVideo.isMuted())
  1166. {
  1167. APP.xmpp.sendVideoInfoPresence(mute);
  1168. if (callback)
  1169. callback(mute);
  1170. }
  1171. else
  1172. {
  1173. APP.RTC.localVideo.setMute(mute);
  1174. APP.xmpp.setVideoMute(
  1175. mute,
  1176. callback,
  1177. options);
  1178. }
  1179. },
  1180. setDeviceAvailability: function (devices) {
  1181. if(!devices)
  1182. return;
  1183. if(devices.audio === true || devices.audio === false)
  1184. this.devices.audio = devices.audio;
  1185. if(devices.video === true || devices.video === false)
  1186. this.devices.video = devices.video;
  1187. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1188. }
  1189. };
  1190. module.exports = RTC;
  1191. },{"../../service/RTC/MediaStreamTypes":110,"../../service/RTC/RTCEvents.js":111,"../../service/RTC/StreamEventTypes.js":113,"../../service/UI/UIEvents":114,"../../service/desktopsharing/DesktopSharingEventTypes":117,"../../service/xmpp/XMPPEvents":120,"./DataChannels":6,"./LocalStream.js":7,"./MediaStream.js":8,"./RTCBrowserType":10,"./RTCUtils.js":11,"events":1}],10:[function(require,module,exports){
  1192. var currentBrowser;
  1193. var browserVersion;
  1194. var RTCBrowserType = {
  1195. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1196. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1197. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1198. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1199. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1200. getBrowserType: function () {
  1201. return currentBrowser;
  1202. },
  1203. isChrome: function () {
  1204. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1205. },
  1206. isOpera: function () {
  1207. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1208. },
  1209. isFirefox: function () {
  1210. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1211. },
  1212. isIExplorer: function () {
  1213. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1214. },
  1215. isSafari: function () {
  1216. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1217. },
  1218. isTemasysPluginUsed: function () {
  1219. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1220. },
  1221. getFirefoxVersion: function () {
  1222. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1223. },
  1224. getChromeVersion: function () {
  1225. return RTCBrowserType.isChrome() ? browserVersion : null;
  1226. },
  1227. usesPlanB: function() {
  1228. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1229. RTCBrowserType.isTemasysPluginUsed();
  1230. },
  1231. usesUnifiedPlan: function() {
  1232. return RTCBrowserType.isFirefox();
  1233. }
  1234. // Add version getters for other browsers when needed
  1235. };
  1236. // detectOpera() must be called before detectChrome() !!!
  1237. // otherwise Opera wil be detected as Chrome
  1238. function detectChrome() {
  1239. if (navigator.webkitGetUserMedia) {
  1240. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1241. var userAgent = navigator.userAgent.toLowerCase();
  1242. // We can assume that user agent is chrome, because it's
  1243. // enforced when 'ext' streaming method is set
  1244. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1245. console.log("This appears to be Chrome, ver: " + ver);
  1246. return ver;
  1247. }
  1248. return null;
  1249. }
  1250. function detectOpera() {
  1251. var userAgent = navigator.userAgent;
  1252. if (userAgent.match(/Opera|OPR/)) {
  1253. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1254. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1255. console.info("This appears to be Opera, ver: " + version);
  1256. return version;
  1257. }
  1258. return null;
  1259. }
  1260. function detectFirefox() {
  1261. if (navigator.mozGetUserMedia) {
  1262. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1263. var version = parseInt(
  1264. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1265. console.log('This appears to be Firefox, ver: ' + version);
  1266. return version;
  1267. }
  1268. return null;
  1269. }
  1270. function detectSafari() {
  1271. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1272. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1273. console.info("This appears to be Safari");
  1274. // FIXME detect Safari version when needed
  1275. return 1;
  1276. }
  1277. return null;
  1278. }
  1279. function detectIE() {
  1280. var version;
  1281. var ua = window.navigator.userAgent;
  1282. var msie = ua.indexOf('MSIE ');
  1283. if (msie > 0) {
  1284. // IE 10 or older => return version number
  1285. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1286. }
  1287. var trident = ua.indexOf('Trident/');
  1288. if (!version && trident > 0) {
  1289. // IE 11 => return version number
  1290. var rv = ua.indexOf('rv:');
  1291. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1292. }
  1293. var edge = ua.indexOf('Edge/');
  1294. if (!version && edge > 0) {
  1295. // IE 12 => return version number
  1296. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1297. }
  1298. if (version) {
  1299. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1300. console.info("This appears to be IExplorer, ver: " + version);
  1301. }
  1302. return version;
  1303. }
  1304. function detectBrowser() {
  1305. var version;
  1306. var detectors = [
  1307. detectOpera,
  1308. detectChrome,
  1309. detectFirefox,
  1310. detectIE,
  1311. detectSafari
  1312. ];
  1313. // Try all browser detectors
  1314. for (var i = 0; i < detectors.length; i++) {
  1315. version = detectors[i]();
  1316. if (version)
  1317. return version;
  1318. }
  1319. console.error("Failed to detect browser type");
  1320. return undefined;
  1321. }
  1322. browserVersion = detectBrowser();
  1323. module.exports = RTCBrowserType;
  1324. },{}],11:[function(require,module,exports){
  1325. /* global config, require, attachMediaStream, getUserMedia */
  1326. var RTCBrowserType = require("./RTCBrowserType");
  1327. var Resolutions = require("../../service/RTC/Resolutions");
  1328. var AdapterJS = require("./adapter.screenshare");
  1329. var SDPUtil = require("../xmpp/SDPUtil");
  1330. var currentResolution = null;
  1331. function getPreviousResolution(resolution) {
  1332. if(!Resolutions[resolution])
  1333. return null;
  1334. var order = Resolutions[resolution].order;
  1335. var res = null;
  1336. var resName = null;
  1337. for(var i in Resolutions) {
  1338. var tmp = Resolutions[i];
  1339. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1340. resName = i;
  1341. res = tmp;
  1342. }
  1343. }
  1344. return resName;
  1345. }
  1346. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1347. if (Resolutions[resolution]) {
  1348. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1349. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1350. }
  1351. else if (isAndroid) {
  1352. // FIXME can't remember if the purpose of this was to always request
  1353. // low resolution on Android ? if yes it should be moved up front
  1354. constraints.video.mandatory.minWidth = 320;
  1355. constraints.video.mandatory.minHeight = 240;
  1356. constraints.video.mandatory.maxFrameRate = 15;
  1357. }
  1358. if (constraints.video.mandatory.minWidth)
  1359. constraints.video.mandatory.maxWidth =
  1360. constraints.video.mandatory.minWidth;
  1361. if (constraints.video.mandatory.minHeight)
  1362. constraints.video.mandatory.maxHeight =
  1363. constraints.video.mandatory.minHeight;
  1364. }
  1365. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1366. {
  1367. var constraints = {audio: false, video: false};
  1368. if (um.indexOf('video') >= 0) {
  1369. // same behaviour as true
  1370. constraints.video = { mandatory: {}, optional: [] };
  1371. constraints.video.optional.push({ googLeakyBucket: true });
  1372. setResolutionConstraints(constraints, resolution, isAndroid);
  1373. }
  1374. if (um.indexOf('audio') >= 0) {
  1375. if (!RTCBrowserType.isFirefox()) {
  1376. // same behaviour as true
  1377. constraints.audio = { mandatory: {}, optional: []};
  1378. // if it is good enough for hangouts...
  1379. constraints.audio.optional.push(
  1380. {googEchoCancellation: true},
  1381. {googAutoGainControl: true},
  1382. {googNoiseSupression: true},
  1383. {googHighpassFilter: true},
  1384. {googNoisesuppression2: true},
  1385. {googEchoCancellation2: true},
  1386. {googAutoGainControl2: true}
  1387. );
  1388. } else {
  1389. constraints.audio = true;
  1390. }
  1391. }
  1392. if (um.indexOf('screen') >= 0) {
  1393. if (RTCBrowserType.isChrome()) {
  1394. constraints.video = {
  1395. mandatory: {
  1396. chromeMediaSource: "screen",
  1397. googLeakyBucket: true,
  1398. maxWidth: window.screen.width,
  1399. maxHeight: window.screen.height,
  1400. maxFrameRate: 3
  1401. },
  1402. optional: []
  1403. };
  1404. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1405. constraints.video = {
  1406. optional: [
  1407. {
  1408. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1409. }
  1410. ]
  1411. };
  1412. } else {
  1413. console.error(
  1414. "'screen' WebRTC media source is supported only in Chrome" +
  1415. " and with Temasys plugin");
  1416. }
  1417. }
  1418. if (um.indexOf('desktop') >= 0) {
  1419. constraints.video = {
  1420. mandatory: {
  1421. chromeMediaSource: "desktop",
  1422. chromeMediaSourceId: desktopStream,
  1423. googLeakyBucket: true,
  1424. maxWidth: window.screen.width,
  1425. maxHeight: window.screen.height,
  1426. maxFrameRate: 3
  1427. },
  1428. optional: []
  1429. };
  1430. }
  1431. if (bandwidth) {
  1432. if (!constraints.video) {
  1433. //same behaviour as true
  1434. constraints.video = {mandatory: {}, optional: []};
  1435. }
  1436. constraints.video.optional.push({bandwidth: bandwidth});
  1437. }
  1438. if (fps) {
  1439. // for some cameras it might be necessary to request 30fps
  1440. // so they choose 30fps mjpg over 10fps yuy2
  1441. if (!constraints.video) {
  1442. // same behaviour as true;
  1443. constraints.video = {mandatory: {}, optional: []};
  1444. }
  1445. constraints.video.mandatory.minFrameRate = fps;
  1446. }
  1447. return constraints;
  1448. }
  1449. function RTCUtils(RTCService, onTemasysPluginReady)
  1450. {
  1451. var self = this;
  1452. this.service = RTCService;
  1453. if (RTCBrowserType.isFirefox()) {
  1454. var FFversion = RTCBrowserType.getFirefoxVersion();
  1455. if (FFversion >= 40) {
  1456. this.peerconnection = mozRTCPeerConnection;
  1457. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1458. this.pc_constraints = {};
  1459. this.attachMediaStream = function (element, stream) {
  1460. // srcObject is being standardized and FF will eventually
  1461. // support that unprefixed. FF also supports the
  1462. // "element.src = URL.createObjectURL(...)" combo, but that
  1463. // will be deprecated in favour of srcObject.
  1464. //
  1465. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1466. // https://github.com/webrtc/samples/issues/302
  1467. if(!element[0])
  1468. return;
  1469. element[0].mozSrcObject = stream;
  1470. element[0].play();
  1471. };
  1472. this.getStreamID = function (stream) {
  1473. var id = stream.id;
  1474. if (!id) {
  1475. var tracks = stream.getVideoTracks();
  1476. if (!tracks || tracks.length === 0) {
  1477. tracks = stream.getAudioTracks();
  1478. }
  1479. id = tracks[0].id;
  1480. }
  1481. return SDPUtil.filter_special_chars(id);
  1482. };
  1483. this.getVideoSrc = function (element) {
  1484. if(!element)
  1485. return null;
  1486. return element.mozSrcObject;
  1487. };
  1488. this.setVideoSrc = function (element, src) {
  1489. if(element)
  1490. element.mozSrcObject = src;
  1491. };
  1492. RTCSessionDescription = mozRTCSessionDescription;
  1493. RTCIceCandidate = mozRTCIceCandidate;
  1494. } else {
  1495. console.error(
  1496. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1497. window.location.href = 'unsupported_browser.html';
  1498. return;
  1499. }
  1500. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1501. this.peerconnection = webkitRTCPeerConnection;
  1502. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1503. this.attachMediaStream = function (element, stream) {
  1504. element.attr('src', webkitURL.createObjectURL(stream));
  1505. };
  1506. this.getStreamID = function (stream) {
  1507. // streams from FF endpoints have the characters '{' and '}'
  1508. // that make jQuery choke.
  1509. return SDPUtil.filter_special_chars(stream.id);
  1510. };
  1511. this.getVideoSrc = function (element) {
  1512. if(!element)
  1513. return null;
  1514. return element.getAttribute("src");
  1515. };
  1516. this.setVideoSrc = function (element, src) {
  1517. if(element)
  1518. element.setAttribute("src", src);
  1519. };
  1520. // DTLS should now be enabled by default but..
  1521. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1522. if (navigator.userAgent.indexOf('Android') != -1) {
  1523. this.pc_constraints = {}; // disable DTLS on Android
  1524. }
  1525. if (!webkitMediaStream.prototype.getVideoTracks) {
  1526. webkitMediaStream.prototype.getVideoTracks = function () {
  1527. return this.videoTracks;
  1528. };
  1529. }
  1530. if (!webkitMediaStream.prototype.getAudioTracks) {
  1531. webkitMediaStream.prototype.getAudioTracks = function () {
  1532. return this.audioTracks;
  1533. };
  1534. }
  1535. }
  1536. // Detect IE/Safari
  1537. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1538. //AdapterJS.WebRTCPlugin.setLogLevel(
  1539. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1540. AdapterJS.webRTCReady(function (isPlugin) {
  1541. self.peerconnection = RTCPeerConnection;
  1542. self.getUserMedia = getUserMedia;
  1543. self.attachMediaStream = function (elSel, stream) {
  1544. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1545. return;
  1546. }
  1547. attachMediaStream(elSel[0], stream);
  1548. };
  1549. self.getStreamID = function (stream) {
  1550. var id = SDPUtil.filter_special_chars(stream.label);
  1551. return id;
  1552. };
  1553. self.getVideoSrc = function (element) {
  1554. if (!element) {
  1555. console.warn("Attempt to get video SRC of null element");
  1556. return null;
  1557. }
  1558. var children = element.children;
  1559. for (var i = 0; i !== children.length; ++i) {
  1560. if (children[i].name === 'streamId') {
  1561. return children[i].value;
  1562. }
  1563. }
  1564. //console.info(element.id + " SRC: " + src);
  1565. return null;
  1566. };
  1567. self.setVideoSrc = function (element, src) {
  1568. //console.info("Set video src: ", element, src);
  1569. if (!src) {
  1570. console.warn("Not attaching video stream, 'src' is null");
  1571. return;
  1572. }
  1573. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1574. var stream = AdapterJS.WebRTCPlugin.plugin
  1575. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1576. attachMediaStream(element, stream);
  1577. };
  1578. onTemasysPluginReady(isPlugin);
  1579. });
  1580. } else {
  1581. try {
  1582. console.log('Browser does not appear to be WebRTC-capable');
  1583. } catch (e) { }
  1584. window.location.href = 'unsupported_browser.html';
  1585. }
  1586. }
  1587. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1588. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1589. desktopStream) {
  1590. currentResolution = resolution;
  1591. // Check if we are running on Android device
  1592. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1593. var constraints = getConstraints(
  1594. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1595. console.info("Get media constraints", constraints);
  1596. var self = this;
  1597. try {
  1598. this.getUserMedia(constraints,
  1599. function (stream) {
  1600. console.log('onUserMediaSuccess');
  1601. self.setAvailableDevices(um, true);
  1602. success_callback(stream);
  1603. },
  1604. function (error) {
  1605. self.setAvailableDevices(um, false);
  1606. console.warn('Failed to get access to local media. Error ',
  1607. error, constraints);
  1608. if (failure_callback) {
  1609. failure_callback(error);
  1610. }
  1611. });
  1612. } catch (e) {
  1613. console.error('GUM failed: ', e);
  1614. if(failure_callback) {
  1615. failure_callback(e);
  1616. }
  1617. }
  1618. };
  1619. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1620. var devices = {};
  1621. if(um.indexOf("video") != -1) {
  1622. devices.video = available;
  1623. }
  1624. if(um.indexOf("audio") != -1) {
  1625. devices.audio = available;
  1626. }
  1627. this.service.setDeviceAvailability(devices);
  1628. };
  1629. /**
  1630. * We ask for audio and video combined stream in order to get permissions and
  1631. * not to ask twice.
  1632. */
  1633. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1634. function(devices, callback, usageOptions)
  1635. {
  1636. var self = this;
  1637. // Get AV
  1638. var successCallback = function (stream) {
  1639. if(callback)
  1640. callback(stream, usageOptions);
  1641. else
  1642. self.successCallback(stream, usageOptions);
  1643. };
  1644. if(!devices)
  1645. devices = ['audio', 'video'];
  1646. var newDevices = [];
  1647. if(usageOptions)
  1648. for(var i = 0; i < devices.length; i++) {
  1649. var device = devices[i];
  1650. if(usageOptions[device] === true)
  1651. newDevices.push(device);
  1652. }
  1653. else
  1654. newDevices = devices;
  1655. if(newDevices.length === 0) {
  1656. successCallback();
  1657. return;
  1658. }
  1659. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1660. // With FF/IE we can't split the stream into audio and video because FF
  1661. // doesn't support media stream constructors. So, we need to get the
  1662. // audio stream separately from the video stream using two distinct GUM
  1663. // calls. Not very user friendly :-( but we don't have many other
  1664. // options neither.
  1665. //
  1666. // Note that we pack those 2 streams in a single object and pass it to
  1667. // the successCallback method.
  1668. var obtainVideo = function (audioStream) {
  1669. self.getUserMediaWithConstraints(
  1670. ['video'],
  1671. function (videoStream) {
  1672. return successCallback({
  1673. audioStream: audioStream,
  1674. videoStream: videoStream
  1675. });
  1676. },
  1677. function (error) {
  1678. console.error(
  1679. 'failed to obtain video stream - stop', error);
  1680. self.errorCallback(error);
  1681. },
  1682. config.resolution || '360');
  1683. };
  1684. var obtainAudio = function () {
  1685. self.getUserMediaWithConstraints(
  1686. ['audio'],
  1687. function (audioStream) {
  1688. if (newDevices.indexOf('video') !== -1)
  1689. obtainVideo(audioStream);
  1690. },
  1691. function (error) {
  1692. console.error(
  1693. 'failed to obtain audio stream - stop', error);
  1694. self.errorCallback(error);
  1695. }
  1696. );
  1697. };
  1698. if (newDevices.indexOf('audio') !== -1) {
  1699. obtainAudio();
  1700. } else {
  1701. obtainVideo(null);
  1702. }
  1703. } else {
  1704. this.getUserMediaWithConstraints(
  1705. newDevices,
  1706. function (stream) {
  1707. successCallback(stream);
  1708. },
  1709. function (error) {
  1710. self.errorCallback(error);
  1711. },
  1712. config.resolution || '360');
  1713. }
  1714. };
  1715. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1716. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1717. // it's an object with two properties: audioStream, videoStream.
  1718. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1719. console.log('got', stream, stream.getAudioTracks().length,
  1720. stream.getVideoTracks().length);
  1721. this.handleLocalStream(stream, usageOptions);
  1722. };
  1723. RTCUtils.prototype.errorCallback = function (error) {
  1724. var self = this;
  1725. console.error('failed to obtain audio/video stream - trying audio only', error);
  1726. var resolution = getPreviousResolution(currentResolution);
  1727. if(typeof error == "object" && error.constraintName && error.name
  1728. && (error.name == "ConstraintNotSatisfiedError" ||
  1729. error.name == "OverconstrainedError") &&
  1730. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1731. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1732. && resolution != null)
  1733. {
  1734. self.getUserMediaWithConstraints(['audio', 'video'],
  1735. function (stream) {
  1736. return self.successCallback(stream);
  1737. }, function (error) {
  1738. return self.errorCallback(error);
  1739. }, resolution);
  1740. }
  1741. else {
  1742. self.getUserMediaWithConstraints(
  1743. ['audio'],
  1744. function (stream) {
  1745. return self.successCallback(stream);
  1746. },
  1747. function (error) {
  1748. console.error('failed to obtain audio/video stream - stop',
  1749. error);
  1750. return self.successCallback(null);
  1751. }
  1752. );
  1753. }
  1754. };
  1755. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1756. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1757. // an object with two properties: audioStream, videoStream.
  1758. var audioStream, videoStream;
  1759. if(window.webkitMediaStream)
  1760. {
  1761. audioStream = new webkitMediaStream();
  1762. videoStream = new webkitMediaStream();
  1763. if(stream) {
  1764. var audioTracks = stream.getAudioTracks();
  1765. for (var i = 0; i < audioTracks.length; i++) {
  1766. audioStream.addTrack(audioTracks[i]);
  1767. }
  1768. var videoTracks = stream.getVideoTracks();
  1769. for (i = 0; i < videoTracks.length; i++) {
  1770. videoStream.addTrack(videoTracks[i]);
  1771. }
  1772. }
  1773. }
  1774. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1775. { // Firefox and Temasys plugin
  1776. if (stream && stream.audioStream)
  1777. audioStream = stream.audioStream;
  1778. else
  1779. audioStream = new DummyMediaStream("dummyAudio");
  1780. if (stream && stream.videoStream)
  1781. videoStream = stream.videoStream;
  1782. else
  1783. videoStream = new DummyMediaStream("dummyVideo");
  1784. }
  1785. var audioMuted = (usageOptions && usageOptions.audio === false),
  1786. videoMuted = (usageOptions && usageOptions.video === false);
  1787. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1788. videoGUM = (!usageOptions || usageOptions.video !== false);
  1789. this.service.createLocalStream(audioStream, "audio", null, null,
  1790. audioMuted, audioGUM);
  1791. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1792. videoMuted, videoGUM);
  1793. };
  1794. function DummyMediaStream(id) {
  1795. this.id = id;
  1796. this.label = id;
  1797. this.stop = function() { };
  1798. this.getAudioTracks = function() { return []; };
  1799. this.getVideoTracks = function() { return []; };
  1800. }
  1801. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1802. var newStream = null;
  1803. if (window.webkitMediaStream) {
  1804. newStream = new webkitMediaStream();
  1805. if (newStream) {
  1806. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1807. for (var i = 0; i < tracks.length; i++) {
  1808. newStream.addTrack(tracks[i]);
  1809. }
  1810. }
  1811. }
  1812. else {
  1813. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1814. if (stream) {
  1815. newStream = stream;
  1816. } else {
  1817. newStream =
  1818. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1819. }
  1820. }
  1821. return newStream;
  1822. };
  1823. module.exports = RTCUtils;
  1824. },{"../../service/RTC/Resolutions":112,"../xmpp/SDPUtil":60,"./RTCBrowserType":10,"./adapter.screenshare":12}],12:[function(require,module,exports){
  1825. /*! adapterjs - custom version from - 2015-08-12 */
  1826. // Adapter's interface.
  1827. var AdapterJS = AdapterJS || {};
  1828. // Browserify compatibility
  1829. if(typeof exports !== 'undefined') {
  1830. module.exports = AdapterJS;
  1831. }
  1832. AdapterJS.options = AdapterJS.options || {};
  1833. // uncomment to get virtual webcams
  1834. // AdapterJS.options.getAllCams = true;
  1835. // uncomment to prevent the install prompt when the plugin in not yet installed
  1836. // AdapterJS.options.hidePluginInstallPrompt = true;
  1837. // AdapterJS version
  1838. AdapterJS.VERSION = '0.11.1';
  1839. // This function will be called when the WebRTC API is ready to be used
  1840. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1841. // the plugin
  1842. // You may Override this function to synchronise the start of your application
  1843. // with the WebRTC API being ready.
  1844. // If you decide not to override use this synchronisation, it may result in
  1845. // an extensive CPU usage on the plugin start (once per tab loaded)
  1846. // Params:
  1847. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1848. //
  1849. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1850. // The WebRTC API is ready.
  1851. // Override me and do whatever you want here
  1852. };
  1853. // Sets a callback function to be called when the WebRTC interface is ready.
  1854. // The first argument is the function to callback.\
  1855. // Throws an error if the first argument is not a function
  1856. AdapterJS.webRTCReady = function (callback) {
  1857. if (typeof callback !== 'function') {
  1858. throw new Error('Callback provided is not a function');
  1859. }
  1860. if (true === AdapterJS.onwebrtcreadyDone) {
  1861. // All WebRTC interfaces are ready, just call the callback
  1862. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1863. } else {
  1864. // will be triggered automatically when your browser/plugin is ready.
  1865. AdapterJS.onwebrtcready = callback;
  1866. }
  1867. };
  1868. // Plugin namespace
  1869. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1870. // The object to store plugin information
  1871. AdapterJS.WebRTCPlugin.pluginInfo = {
  1872. prefix : 'Tem',
  1873. plugName : 'TemWebRTCPlugin',
  1874. pluginId : 'plugin0',
  1875. type : 'application/x-temwebrtcplugin',
  1876. onload : '__TemWebRTCReady0',
  1877. portalLink : 'http://skylink.io/plugin/',
  1878. downloadLink : null, //set below
  1879. companyName: 'Temasys'
  1880. };
  1881. if(!!navigator.platform.match(/^Mac/i)) {
  1882. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1883. }
  1884. else if(!!navigator.platform.match(/^Win/i)) {
  1885. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1886. }
  1887. // Unique identifier of each opened page
  1888. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1889. // Use this whenever you want to call the plugin.
  1890. AdapterJS.WebRTCPlugin.plugin = null;
  1891. // Set log level for the plugin once it is ready.
  1892. // The different values are
  1893. // This is an asynchronous function that will run when the plugin is ready
  1894. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1895. // Defines webrtc's JS interface according to the plugin's implementation.
  1896. // Define plugin Browsers as WebRTC Interface.
  1897. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1898. // This function detects whether or not a plugin is installed.
  1899. // Checks if Not IE (firefox, for example), else if it's IE,
  1900. // we're running IE and do something. If not it is not supported.
  1901. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1902. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1903. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1904. // Inject the HTML DOM object element into the page.
  1905. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1906. // States of readiness that the plugin goes through when
  1907. // being injected and stated
  1908. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1909. NONE : 0, // no plugin use
  1910. INITIALIZING : 1, // Detected need for plugin
  1911. INJECTING : 2, // Injecting plugin
  1912. INJECTED: 3, // Plugin element injected but not usable yet
  1913. READY: 4 // Plugin ready to be used
  1914. };
  1915. // Current state of the plugin. You cannot use the plugin before this is
  1916. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1917. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1918. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1919. // Used to make sure AdapterJS.onwebrtcready is only called once
  1920. AdapterJS.onwebrtcreadyDone = false;
  1921. // Log levels for the plugin.
  1922. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1923. /*
  1924. Log outputs are prefixed in some cases.
  1925. INFO: Information reported by the plugin.
  1926. ERROR: Errors originating from within the plugin.
  1927. WEBRTC: Error originating from within the libWebRTC library
  1928. */
  1929. // From the least verbose to the most verbose
  1930. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1931. NONE : 'NONE',
  1932. ERROR : 'ERROR',
  1933. WARNING : 'WARNING',
  1934. INFO: 'INFO',
  1935. VERBOSE: 'VERBOSE',
  1936. SENSITIVE: 'SENSITIVE'
  1937. };
  1938. // Does a waiting check before proceeding to load the plugin.
  1939. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1940. // This methid will use an interval to wait for the plugin to be ready.
  1941. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1942. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1943. // This function will be called when plugin is ready. It sends necessary
  1944. // details to the plugin.
  1945. // The function will wait for the document to be ready and the set the
  1946. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1947. // indicating that it can start being requested.
  1948. // This function is not in the IE/Safari condition brackets so that
  1949. // TemPluginLoaded function might be called on Chrome/Firefox.
  1950. // This function is the only private function that is not encapsulated to
  1951. // allow the plugin method to be called.
  1952. __TemWebRTCReady0 = function () {
  1953. if (document.readyState === 'complete') {
  1954. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1955. AdapterJS.maybeThroughWebRTCReady();
  1956. } else {
  1957. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1958. if (document.readyState === 'complete') {
  1959. // TODO: update comments, we wait for the document to be ready
  1960. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1961. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1962. AdapterJS.maybeThroughWebRTCReady();
  1963. }
  1964. }, 100);
  1965. }
  1966. };
  1967. AdapterJS.maybeThroughWebRTCReady = function() {
  1968. if (!AdapterJS.onwebrtcreadyDone) {
  1969. AdapterJS.onwebrtcreadyDone = true;
  1970. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1971. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1972. }
  1973. }
  1974. };
  1975. // Text namespace
  1976. AdapterJS.TEXT = {
  1977. PLUGIN: {
  1978. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1979. 'to work on this browser.',
  1980. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1981. BUTTON: 'Install Now'
  1982. },
  1983. REFRESH: {
  1984. REQUIRE_REFRESH: 'Please refresh page',
  1985. BUTTON: 'Refresh Page'
  1986. }
  1987. };
  1988. // The result of ice connection states.
  1989. // - starting: Ice connection is starting.
  1990. // - checking: Ice connection is checking.
  1991. // - connected Ice connection is connected.
  1992. // - completed Ice connection is connected.
  1993. // - done Ice connection has been completed.
  1994. // - disconnected Ice connection has been disconnected.
  1995. // - failed Ice connection has failed.
  1996. // - closed Ice connection is closed.
  1997. AdapterJS._iceConnectionStates = {
  1998. starting : 'starting',
  1999. checking : 'checking',
  2000. connected : 'connected',
  2001. completed : 'connected',
  2002. done : 'completed',
  2003. disconnected : 'disconnected',
  2004. failed : 'failed',
  2005. closed : 'closed'
  2006. };
  2007. //The IceConnection states that has been fired for each peer.
  2008. AdapterJS._iceConnectionFiredStates = [];
  2009. // Check if WebRTC Interface is defined.
  2010. AdapterJS.isDefined = null;
  2011. // This function helps to retrieve the webrtc detected browser information.
  2012. // This sets:
  2013. // - webrtcDetectedBrowser: The browser agent name.
  2014. // - webrtcDetectedVersion: The browser version.
  2015. // - webrtcDetectedType: The types of webRTC support.
  2016. // - 'moz': Mozilla implementation of webRTC.
  2017. // - 'webkit': WebKit implementation of webRTC.
  2018. // - 'plugin': Using the plugin implementation.
  2019. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2020. var hasMatch, checkMatch = navigator.userAgent.match(
  2021. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2022. if (/trident/i.test(checkMatch[1])) {
  2023. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2024. webrtcDetectedBrowser = 'IE';
  2025. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2026. } else if (checkMatch[1] === 'Chrome') {
  2027. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2028. if (hasMatch !== null) {
  2029. webrtcDetectedBrowser = 'opera';
  2030. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2031. }
  2032. }
  2033. if (navigator.userAgent.indexOf('Safari')) {
  2034. if (typeof InstallTrigger !== 'undefined') {
  2035. webrtcDetectedBrowser = 'firefox';
  2036. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2037. webrtcDetectedBrowser = 'IE';
  2038. } else if (
  2039. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2040. webrtcDetectedBrowser = 'safari';
  2041. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2042. webrtcDetectedBrowser = 'opera';
  2043. } else if (!!window.chrome) {
  2044. webrtcDetectedBrowser = 'chrome';
  2045. }
  2046. }
  2047. if (!webrtcDetectedBrowser) {
  2048. webrtcDetectedVersion = checkMatch[1];
  2049. }
  2050. if (!webrtcDetectedVersion) {
  2051. try {
  2052. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2053. [navigator.appName, navigator.appVersion, '-?'];
  2054. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2055. checkMatch.splice(1, 1, hasMatch[1]);
  2056. }
  2057. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2058. } catch (error) { }
  2059. }
  2060. };
  2061. // To fix configuration as some browsers does not support
  2062. // the 'urls' attribute.
  2063. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2064. if (pcConfig === null) {
  2065. return;
  2066. }
  2067. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2068. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2069. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2070. delete pcConfig.iceServers[i].urls;
  2071. }
  2072. }
  2073. };
  2074. AdapterJS.addEvent = function(elem, evnt, func) {
  2075. if (elem.addEventListener) { // W3C DOM
  2076. elem.addEventListener(evnt, func, false);
  2077. } else if (elem.attachEvent) {// OLD IE DOM
  2078. elem.attachEvent('on'+evnt, func);
  2079. } else { // No much to do
  2080. elem[evnt] = func;
  2081. }
  2082. };
  2083. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2084. // only inject once the page is ready
  2085. if (document.readyState !== 'complete') {
  2086. return;
  2087. }
  2088. var w = window;
  2089. var i = document.createElement('iframe');
  2090. i.style.position = 'fixed';
  2091. i.style.top = '-41px';
  2092. i.style.left = 0;
  2093. i.style.right = 0;
  2094. i.style.width = '100%';
  2095. i.style.height = '40px';
  2096. i.style.backgroundColor = '#ffffe1';
  2097. i.style.border = 'none';
  2098. i.style.borderBottom = '1px solid #888888';
  2099. i.style.zIndex = '9999999';
  2100. if(typeof i.style.webkitTransition === 'string') {
  2101. i.style.webkitTransition = 'all .5s ease-out';
  2102. } else if(typeof i.style.transition === 'string') {
  2103. i.style.transition = 'all .5s ease-out';
  2104. }
  2105. document.body.appendChild(i);
  2106. c = (i.contentWindow) ? i.contentWindow :
  2107. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2108. c.document.open();
  2109. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2110. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2111. 'middle; cursor: default;">' + text + '</span>');
  2112. if(buttonText && buttonLink) {
  2113. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2114. c.document.close();
  2115. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2116. if (!!displayRefreshBar) {
  2117. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2118. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2119. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2120. }
  2121. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2122. e.preventDefault();
  2123. try {
  2124. event.cancelBubble = true;
  2125. } catch(error) { }
  2126. var pluginInstallInterval = setInterval(function(){
  2127. if(! isIE) {
  2128. navigator.plugins.refresh(false);
  2129. }
  2130. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2131. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2132. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2133. function() {
  2134. clearInterval(pluginInstallInterval);
  2135. AdapterJS.WebRTCPlugin.defineWebRTCInterface()
  2136. },
  2137. function() { //Does nothing because not used here
  2138. });
  2139. } , 500);
  2140. });
  2141. }else {
  2142. c.document.close();
  2143. }
  2144. AdapterJS.addEvent(c.document, 'click', function() {
  2145. w.document.body.removeChild(i);
  2146. });
  2147. setTimeout(function() {
  2148. if(typeof i.style.webkitTransform === 'string') {
  2149. i.style.webkitTransform = 'translateY(40px)';
  2150. } else if(typeof i.style.transform === 'string') {
  2151. i.style.transform = 'translateY(40px)';
  2152. } else {
  2153. i.style.top = '0px';
  2154. }
  2155. }, 300);
  2156. };
  2157. // -----------------------------------------------------------
  2158. // Detected webrtc implementation. Types are:
  2159. // - 'moz': Mozilla implementation of webRTC.
  2160. // - 'webkit': WebKit implementation of webRTC.
  2161. // - 'plugin': Using the plugin implementation.
  2162. webrtcDetectedType = null;
  2163. // Detected webrtc datachannel support. Types are:
  2164. // - 'SCTP': SCTP datachannel support.
  2165. // - 'RTP': RTP datachannel support.
  2166. webrtcDetectedDCSupport = null;
  2167. // Set the settings for creating DataChannels, MediaStream for
  2168. // Cross-browser compability.
  2169. // - This is only for SCTP based support browsers.
  2170. // the 'urls' attribute.
  2171. checkMediaDataChannelSettings =
  2172. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2173. if (typeof callback !== 'function') {
  2174. return;
  2175. }
  2176. var beOfferer = true;
  2177. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2178. // Nightly version does not require MozDontOfferDataChannel for interop
  2179. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2180. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2181. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2182. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2183. // Resends an updated version of constraints for MozDataChannel to work
  2184. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2185. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2186. try {
  2187. delete constraints.mandatory.MozDontOfferDataChannel;
  2188. } catch (error) {
  2189. console.error('Failed deleting MozDontOfferDataChannel');
  2190. console.error(error);
  2191. }
  2192. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2193. constraints.mandatory.MozDontOfferDataChannel = true;
  2194. }
  2195. if (!isLocalFirefox) {
  2196. // temporary measure to remove Moz* constraints in non Firefox browsers
  2197. for (var prop in constraints.mandatory) {
  2198. if (constraints.mandatory.hasOwnProperty(prop)) {
  2199. if (prop.indexOf('Moz') !== -1) {
  2200. delete constraints.mandatory[prop];
  2201. }
  2202. }
  2203. }
  2204. }
  2205. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2206. // interopability of the media stream
  2207. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2208. beOfferer = false;
  2209. }
  2210. callback(beOfferer, constraints);
  2211. };
  2212. // Handles the differences for all browsers ice connection state output.
  2213. // - Tested outcomes are:
  2214. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2215. // - Chrome (answerer) : 'checking' > 'connected'
  2216. // - Firefox (offerer) : 'checking' > 'connected'
  2217. // - Firefox (answerer): 'checking' > 'connected'
  2218. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2219. if (typeof callback !== 'function') {
  2220. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2221. return;
  2222. }
  2223. peerId = (peerId) ? peerId : 'peer';
  2224. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2225. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2226. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2227. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2228. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2229. }
  2230. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2231. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2232. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2233. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2234. setTimeout(function () {
  2235. AdapterJS._iceConnectionFiredStates[peerId]
  2236. .push(AdapterJS._iceConnectionStates.done);
  2237. callback(AdapterJS._iceConnectionStates.done);
  2238. }, 1000);
  2239. }
  2240. callback(iceConnectionState);
  2241. }
  2242. return;
  2243. };
  2244. // Firefox:
  2245. // - Creates iceServer from the url for Firefox.
  2246. // - Create iceServer with stun url.
  2247. // - Create iceServer with turn url.
  2248. // - Ignore the transport parameter from TURN url for FF version <=27.
  2249. // - Return null for createIceServer if transport=tcp.
  2250. // - FF 27 and above supports transport parameters in TURN url,
  2251. // - So passing in the full url to create iceServer.
  2252. // Chrome:
  2253. // - Creates iceServer from the url for Chrome M33 and earlier.
  2254. // - Create iceServer with stun url.
  2255. // - Chrome M28 & above uses below TURN format.
  2256. // Plugin:
  2257. // - Creates Ice Server for Plugin Browsers
  2258. // - If Stun - Create iceServer with stun url.
  2259. // - Else - Create iceServer with turn url
  2260. // - This is a WebRTC Function
  2261. createIceServer = null;
  2262. // Firefox:
  2263. // - Creates IceServers for Firefox
  2264. // - Use .url for FireFox.
  2265. // - Multiple Urls support
  2266. // Chrome:
  2267. // - Creates iceServers from the urls for Chrome M34 and above.
  2268. // - .urls is supported since Chrome M34.
  2269. // - Multiple Urls support
  2270. // Plugin:
  2271. // - Creates Ice Servers for Plugin Browsers
  2272. // - Multiple Urls support
  2273. // - This is a WebRTC Function
  2274. createIceServers = null;
  2275. //------------------------------------------------------------
  2276. //The RTCPeerConnection object.
  2277. RTCPeerConnection = null;
  2278. // Creates RTCSessionDescription object for Plugin Browsers
  2279. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2280. RTCSessionDescription : null;
  2281. // Creates RTCIceCandidate object for Plugin Browsers
  2282. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2283. RTCIceCandidate : null;
  2284. // Get UserMedia (only difference is the prefix).
  2285. // Code from Adam Barth.
  2286. getUserMedia = null;
  2287. // Attach a media stream to an element.
  2288. attachMediaStream = null;
  2289. // Re-attach a media stream to an element.
  2290. reattachMediaStream = null;
  2291. // Detected browser agent name. Types are:
  2292. // - 'firefox': Firefox browser.
  2293. // - 'chrome': Chrome browser.
  2294. // - 'opera': Opera browser.
  2295. // - 'safari': Safari browser.
  2296. // - 'IE' - Internet Explorer browser.
  2297. webrtcDetectedBrowser = null;
  2298. // Detected browser version.
  2299. webrtcDetectedVersion = null;
  2300. // Check for browser types and react accordingly
  2301. if (navigator.mozGetUserMedia) {
  2302. webrtcDetectedBrowser = 'firefox';
  2303. webrtcDetectedVersion = parseInt(navigator
  2304. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2305. webrtcDetectedType = 'moz';
  2306. webrtcDetectedDCSupport = 'SCTP';
  2307. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2308. AdapterJS.maybeFixConfiguration(pcConfig);
  2309. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2310. };
  2311. // The RTCSessionDescription object.
  2312. RTCSessionDescription = mozRTCSessionDescription;
  2313. window.RTCSessionDescription = RTCSessionDescription;
  2314. // The RTCIceCandidate object.
  2315. RTCIceCandidate = mozRTCIceCandidate;
  2316. window.RTCIceCandidate = RTCIceCandidate;
  2317. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2318. navigator.getUserMedia = window.getUserMedia;
  2319. // Shim for MediaStreamTrack.getSources.
  2320. MediaStreamTrack.getSources = function(successCb) {
  2321. setTimeout(function() {
  2322. var infos = [
  2323. { kind: 'audio', id: 'default', label:'', facing:'' },
  2324. { kind: 'video', id: 'default', label:'', facing:'' }
  2325. ];
  2326. successCb(infos);
  2327. }, 0);
  2328. };
  2329. createIceServer = function (url, username, password) {
  2330. var iceServer = null;
  2331. var url_parts = url.split(':');
  2332. if (url_parts[0].indexOf('stun') === 0) {
  2333. iceServer = { url : url };
  2334. } else if (url_parts[0].indexOf('turn') === 0) {
  2335. if (webrtcDetectedVersion < 27) {
  2336. var turn_url_parts = url.split('?');
  2337. if (turn_url_parts.length === 1 ||
  2338. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2339. iceServer = {
  2340. url : turn_url_parts[0],
  2341. credential : password,
  2342. username : username
  2343. };
  2344. }
  2345. } else {
  2346. iceServer = {
  2347. url : url,
  2348. credential : password,
  2349. username : username
  2350. };
  2351. }
  2352. }
  2353. return iceServer;
  2354. };
  2355. createIceServers = function (urls, username, password) {
  2356. var iceServers = [];
  2357. for (i = 0; i < urls.length; i++) {
  2358. var iceServer = createIceServer(urls[i], username, password);
  2359. if (iceServer !== null) {
  2360. iceServers.push(iceServer);
  2361. }
  2362. }
  2363. return iceServers;
  2364. };
  2365. attachMediaStream = function (element, stream) {
  2366. element.mozSrcObject = stream;
  2367. if (stream !== null)
  2368. element.play();
  2369. return element;
  2370. };
  2371. reattachMediaStream = function (to, from) {
  2372. to.mozSrcObject = from.mozSrcObject;
  2373. to.play();
  2374. return to;
  2375. };
  2376. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2377. if (!callback) {
  2378. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2379. ': 1 argument required, but only 0 present.');
  2380. }
  2381. return callback([]);
  2382. };
  2383. // Fake get{Video,Audio}Tracks
  2384. if (!MediaStream.prototype.getVideoTracks) {
  2385. MediaStream.prototype.getVideoTracks = function () {
  2386. return [];
  2387. };
  2388. }
  2389. if (!MediaStream.prototype.getAudioTracks) {
  2390. MediaStream.prototype.getAudioTracks = function () {
  2391. return [];
  2392. };
  2393. }
  2394. AdapterJS.maybeThroughWebRTCReady();
  2395. } else if (navigator.webkitGetUserMedia) {
  2396. webrtcDetectedBrowser = 'chrome';
  2397. webrtcDetectedType = 'webkit';
  2398. webrtcDetectedVersion = parseInt(navigator
  2399. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2400. // check if browser is opera 20+
  2401. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2402. if (checkIfOpera !== null) {
  2403. webrtcDetectedBrowser = 'opera';
  2404. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2405. }
  2406. // check browser datachannel support
  2407. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2408. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2409. webrtcDetectedDCSupport = 'SCTP';
  2410. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2411. webrtcDetectedVersion > 24) {
  2412. webrtcDetectedDCSupport = 'RTP';
  2413. } else {
  2414. webrtcDetectedDCSupport = '';
  2415. }
  2416. createIceServer = function (url, username, password) {
  2417. var iceServer = null;
  2418. var url_parts = url.split(':');
  2419. if (url_parts[0].indexOf('stun') === 0) {
  2420. iceServer = { 'url' : url };
  2421. } else if (url_parts[0].indexOf('turn') === 0) {
  2422. iceServer = {
  2423. 'url' : url,
  2424. 'credential' : password,
  2425. 'username' : username
  2426. };
  2427. }
  2428. return iceServer;
  2429. };
  2430. createIceServers = function (urls, username, password) {
  2431. var iceServers = [];
  2432. if (webrtcDetectedVersion >= 34) {
  2433. iceServers = {
  2434. 'urls' : urls,
  2435. 'credential' : password,
  2436. 'username' : username
  2437. };
  2438. } else {
  2439. for (i = 0; i < urls.length; i++) {
  2440. var iceServer = createIceServer(urls[i], username, password);
  2441. if (iceServer !== null) {
  2442. iceServers.push(iceServer);
  2443. }
  2444. }
  2445. }
  2446. return iceServers;
  2447. };
  2448. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2449. if (webrtcDetectedVersion < 34) {
  2450. AdapterJS.maybeFixConfiguration(pcConfig);
  2451. }
  2452. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2453. };
  2454. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2455. navigator.getUserMedia = window.getUserMedia;
  2456. attachMediaStream = function (element, stream) {
  2457. if (typeof element.srcObject !== 'undefined') {
  2458. element.srcObject = stream;
  2459. } else if (typeof element.mozSrcObject !== 'undefined') {
  2460. element.mozSrcObject = stream;
  2461. } else if (typeof element.src !== 'undefined') {
  2462. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2463. } else {
  2464. console.log('Error attaching stream to element.');
  2465. }
  2466. return element;
  2467. };
  2468. reattachMediaStream = function (to, from) {
  2469. to.src = from.src;
  2470. return to;
  2471. };
  2472. AdapterJS.maybeThroughWebRTCReady();
  2473. } else { // TRY TO USE PLUGIN
  2474. // IE 9 is not offering an implementation of console.log until you open a console
  2475. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2476. /* jshint -W020 */
  2477. console = {} || console;
  2478. // Implemented based on console specs from MDN
  2479. // You may override these functions
  2480. console.log = function (arg) {};
  2481. console.info = function (arg) {};
  2482. console.error = function (arg) {};
  2483. console.dir = function (arg) {};
  2484. console.exception = function (arg) {};
  2485. console.trace = function (arg) {};
  2486. console.warn = function (arg) {};
  2487. console.count = function (arg) {};
  2488. console.debug = function (arg) {};
  2489. console.count = function (arg) {};
  2490. console.time = function (arg) {};
  2491. console.timeEnd = function (arg) {};
  2492. console.group = function (arg) {};
  2493. console.groupCollapsed = function (arg) {};
  2494. console.groupEnd = function (arg) {};
  2495. /* jshint +W020 */
  2496. }
  2497. webrtcDetectedType = 'plugin';
  2498. webrtcDetectedDCSupport = 'plugin';
  2499. AdapterJS.parseWebrtcDetectedBrowser();
  2500. isIE = webrtcDetectedBrowser === 'IE';
  2501. /* jshint -W035 */
  2502. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2503. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2504. /* empty because it needs to prevent the function from running. */
  2505. }
  2506. };
  2507. /* jshint +W035 */
  2508. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2509. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2510. // Call immediately if possible
  2511. // Once the plugin is set, the code will always take this path
  2512. callback();
  2513. } else {
  2514. // otherwise start a 100ms interval
  2515. var checkPluginReadyState = setInterval(function () {
  2516. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2517. clearInterval(checkPluginReadyState);
  2518. callback();
  2519. }
  2520. }, 100);
  2521. }
  2522. };
  2523. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2524. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2525. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2526. });
  2527. };
  2528. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2529. // only inject once the page is ready
  2530. if (document.readyState !== 'complete') {
  2531. return;
  2532. }
  2533. // Prevent multiple injections
  2534. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2535. return;
  2536. }
  2537. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2538. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2539. var frag = document.createDocumentFragment();
  2540. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2541. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2542. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2543. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2544. '<param name="pluginId" value="' +
  2545. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2546. '<param name="windowless" value="false" /> ' +
  2547. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2548. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2549. '" />' +
  2550. // uncomment to be able to use virtual cams
  2551. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2552. '</object>';
  2553. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2554. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2555. }
  2556. document.body.appendChild(frag);
  2557. // Need to re-fetch the plugin
  2558. AdapterJS.WebRTCPlugin.plugin =
  2559. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2560. } else {
  2561. // Load Plugin
  2562. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2563. AdapterJS.WebRTCPlugin.plugin.id =
  2564. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2565. // IE will only start the plugin if it's ACTUALLY visible
  2566. if (isIE) {
  2567. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2568. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2569. } else { // The size of the plugin on Safari should be 0x0px
  2570. // so that the autorisation prompt is at the top
  2571. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2572. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2573. }
  2574. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2575. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2576. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2577. '<param name="pluginId" value="' +
  2578. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2579. '<param name="windowless" value="false" /> ' +
  2580. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2581. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2582. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2583. }
  2584. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2585. };
  2586. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2587. function (comName, plugName, installedCb, notInstalledCb) {
  2588. if (!isIE) {
  2589. var pluginArray = navigator.plugins;
  2590. for (var i = 0; i < pluginArray.length; i++) {
  2591. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2592. installedCb();
  2593. return;
  2594. }
  2595. }
  2596. notInstalledCb();
  2597. } else {
  2598. try {
  2599. var axo = new ActiveXObject(comName + '.' + plugName);
  2600. } catch (e) {
  2601. notInstalledCb();
  2602. return;
  2603. }
  2604. installedCb();
  2605. }
  2606. };
  2607. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2608. if (AdapterJS.WebRTCPlugin.pluginState ===
  2609. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2610. console.error("WebRTC interface has been defined already");
  2611. return;
  2612. }
  2613. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2614. AdapterJS.isDefined = function (variable) {
  2615. return variable !== null && variable !== undefined;
  2616. };
  2617. createIceServer = function (url, username, password) {
  2618. var iceServer = null;
  2619. var url_parts = url.split(':');
  2620. if (url_parts[0].indexOf('stun') === 0) {
  2621. iceServer = {
  2622. 'url' : url,
  2623. 'hasCredentials' : false
  2624. };
  2625. } else if (url_parts[0].indexOf('turn') === 0) {
  2626. iceServer = {
  2627. 'url' : url,
  2628. 'hasCredentials' : true,
  2629. 'credential' : password,
  2630. 'username' : username
  2631. };
  2632. }
  2633. return iceServer;
  2634. };
  2635. createIceServers = function (urls, username, password) {
  2636. var iceServers = [];
  2637. for (var i = 0; i < urls.length; ++i) {
  2638. iceServers.push(createIceServer(urls[i], username, password));
  2639. }
  2640. return iceServers;
  2641. };
  2642. RTCSessionDescription = function (info) {
  2643. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2644. return AdapterJS.WebRTCPlugin.plugin.
  2645. ConstructSessionDescription(info.type, info.sdp);
  2646. };
  2647. RTCPeerConnection = function (servers, constraints) {
  2648. var iceServers = null;
  2649. if (servers) {
  2650. iceServers = servers.iceServers;
  2651. for (var i = 0; i < iceServers.length; i++) {
  2652. if (iceServers[i].urls && !iceServers[i].url) {
  2653. iceServers[i].url = iceServers[i].urls;
  2654. }
  2655. iceServers[i].hasCredentials = AdapterJS.
  2656. isDefined(iceServers[i].username) &&
  2657. AdapterJS.isDefined(iceServers[i].credential);
  2658. }
  2659. }
  2660. var mandatory = (constraints && constraints.mandatory) ?
  2661. constraints.mandatory : null;
  2662. var optional = (constraints && constraints.optional) ?
  2663. constraints.optional : null;
  2664. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2665. return AdapterJS.WebRTCPlugin.plugin.
  2666. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2667. iceServers, mandatory, optional);
  2668. };
  2669. MediaStreamTrack = {};
  2670. MediaStreamTrack.getSources = function (callback) {
  2671. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2672. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2673. });
  2674. };
  2675. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2676. constraints.audio = constraints.audio || false;
  2677. constraints.video = constraints.video || false;
  2678. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2679. AdapterJS.WebRTCPlugin.plugin.
  2680. getUserMedia(constraints, successCallback, failureCallback);
  2681. });
  2682. };
  2683. window.navigator.getUserMedia = window.getUserMedia;
  2684. attachMediaStream = function (element, stream) {
  2685. if (!element || !element.parentNode) {
  2686. return;
  2687. }
  2688. var streamId
  2689. if (stream === null) {
  2690. streamId = '';
  2691. }
  2692. else {
  2693. stream.enableSoundTracks(true);
  2694. streamId = stream.id;
  2695. }
  2696. if (element.nodeName.toLowerCase() !== 'audio') {
  2697. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2698. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2699. var frag = document.createDocumentFragment();
  2700. var temp = document.createElement('div');
  2701. var classHTML = '';
  2702. if (element.className) {
  2703. classHTML = 'class="' + element.className + '" ';
  2704. } else if (element.attributes && element.attributes['class']) {
  2705. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2706. }
  2707. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2708. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2709. '<param name="pluginId" value="' + elementId + '" /> ' +
  2710. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2711. '<param name="windowless" value="true" /> ' +
  2712. '<param name="streamId" value="' + streamId + '" /> ' +
  2713. '</object>';
  2714. while (temp.firstChild) {
  2715. frag.appendChild(temp.firstChild);
  2716. }
  2717. var height = '';
  2718. var width = '';
  2719. if (element.getBoundingClientRect) {
  2720. var rectObject = element.getBoundingClientRect();
  2721. width = rectObject.width + 'px';
  2722. height = rectObject.height + 'px';
  2723. }
  2724. else if (element.width) {
  2725. width = element.width;
  2726. height = element.height;
  2727. } else {
  2728. // TODO: What scenario could bring us here?
  2729. }
  2730. element.parentNode.insertBefore(frag, element);
  2731. frag = document.getElementById(elementId);
  2732. frag.width = width;
  2733. frag.height = height;
  2734. element.parentNode.removeChild(element);
  2735. } else {
  2736. var children = element.children;
  2737. for (var i = 0; i !== children.length; ++i) {
  2738. if (children[i].name === 'streamId') {
  2739. children[i].value = streamId;
  2740. break;
  2741. }
  2742. }
  2743. element.setStreamId(streamId);
  2744. }
  2745. var newElement = document.getElementById(elementId);
  2746. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2747. if (isIE) { // on IE the event needs to be plugged manually
  2748. newElement.attachEvent('onplaying', newElement.onplaying);
  2749. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2750. newElement._TemOnClick = function (id) {
  2751. var arg = {
  2752. srcElement : document.getElementById(id)
  2753. };
  2754. newElement.onclick(arg);
  2755. };
  2756. }
  2757. return newElement;
  2758. } else {
  2759. return element;
  2760. }
  2761. };
  2762. reattachMediaStream = function (to, from) {
  2763. var stream = null;
  2764. var children = from.children;
  2765. for (var i = 0; i !== children.length; ++i) {
  2766. if (children[i].name === 'streamId') {
  2767. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2768. stream = AdapterJS.WebRTCPlugin.plugin
  2769. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2770. break;
  2771. }
  2772. }
  2773. if (stream !== null) {
  2774. return attachMediaStream(to, stream);
  2775. } else {
  2776. console.log('Could not find the stream associated with this element');
  2777. }
  2778. };
  2779. RTCIceCandidate = function (candidate) {
  2780. if (!candidate.sdpMid) {
  2781. candidate.sdpMid = '';
  2782. }
  2783. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2784. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2785. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2786. );
  2787. };
  2788. // inject plugin
  2789. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2790. AdapterJS.WebRTCPlugin.injectPlugin();
  2791. };
  2792. // This function will be called if the plugin is needed (browser different
  2793. // from Chrome or Firefox), but the plugin is not installed.
  2794. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2795. function() {
  2796. AdapterJS.addEvent(document,
  2797. 'readystatechange',
  2798. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2799. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2800. };
  2801. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2802. if (AdapterJS.options.hidePluginInstallPrompt) {
  2803. return;
  2804. }
  2805. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2806. if(downloadLink) { // if download link
  2807. var popupString;
  2808. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2809. popupString = 'This website requires you to install the ' +
  2810. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2811. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2812. ' WebRTC Plugin</a>' +
  2813. ' to work on this browser.';
  2814. } else { // no portal link, just print a generic explanation
  2815. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2816. }
  2817. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2818. } else { // no download link, just print a generic explanation
  2819. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2820. }
  2821. };
  2822. // Try to detect the plugin and act accordingly
  2823. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2824. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2825. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2826. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2827. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2828. }
  2829. (function () {
  2830. 'use strict';
  2831. var baseGetUserMedia = null;
  2832. AdapterJS.TEXT.EXTENSION = {
  2833. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2834. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2835. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2836. BUTTON_FF: 'Install Now',
  2837. BUTTON_CHROME: 'Go to Chrome Web Store'
  2838. };
  2839. var clone = function(obj) {
  2840. if (null == obj || "object" != typeof obj) return obj;
  2841. var copy = obj.constructor();
  2842. for (var attr in obj) {
  2843. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2844. }
  2845. return copy;
  2846. };
  2847. if (window.navigator.mozGetUserMedia) {
  2848. baseGetUserMedia = window.navigator.getUserMedia;
  2849. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2850. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2851. // intercepting screensharing requests
  2852. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2853. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2854. }
  2855. var updatedConstraints = clone(constraints);
  2856. //constraints.video.mediaSource = constraints.video.mediaSource;
  2857. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2858. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2859. // strange but this works anyway
  2860. var checkIfReady = setInterval(function () {
  2861. if (document.readyState === 'complete') {
  2862. clearInterval(checkIfReady);
  2863. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2864. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2865. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2866. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2867. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2868. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2869. } else {
  2870. failureCb(error);
  2871. }
  2872. });
  2873. }
  2874. }, 1);
  2875. } else { // regular GetUserMediaRequest
  2876. baseGetUserMedia(constraints, successCb, failureCb);
  2877. }
  2878. };
  2879. getUserMedia = navigator.getUserMedia;
  2880. } else if (window.navigator.webkitGetUserMedia) {
  2881. baseGetUserMedia = window.navigator.getUserMedia;
  2882. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2883. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2884. if (window.webrtcDetectedBrowser !== 'chrome') {
  2885. throw new Error('Current browser does not support screensharing');
  2886. }
  2887. // would be fine since no methods
  2888. var updatedConstraints = clone(constraints);
  2889. var chromeCallback = function(error, sourceId) {
  2890. if(!error) {
  2891. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2892. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2893. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2894. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2895. if (sourceId) {
  2896. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2897. }
  2898. delete updatedConstraints.video.mediaSource;
  2899. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2900. } else {
  2901. if (error === 'permission-denied') {
  2902. throw new Error('Permission denied for screen retrieval');
  2903. } else {
  2904. throw new Error('Failed retrieving selected screen');
  2905. }
  2906. }
  2907. };
  2908. var onIFrameCallback = function (event) {
  2909. if (!event.data) {
  2910. return;
  2911. }
  2912. if (event.data.chromeMediaSourceId) {
  2913. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2914. chromeCallback('permission-denied');
  2915. } else {
  2916. chromeCallback(null, event.data.chromeMediaSourceId);
  2917. }
  2918. }
  2919. if (event.data.chromeExtensionStatus) {
  2920. if (event.data.chromeExtensionStatus === 'not-installed') {
  2921. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2922. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2923. event.data.data, true, true);
  2924. } else {
  2925. chromeCallback(event.data.chromeExtensionStatus, null);
  2926. }
  2927. }
  2928. // this event listener is no more needed
  2929. window.removeEventListener('message', onIFrameCallback);
  2930. };
  2931. window.addEventListener('message', onIFrameCallback);
  2932. postFrameMessage({
  2933. captureSourceId: true
  2934. });
  2935. } else {
  2936. baseGetUserMedia(constraints, successCb, failureCb);
  2937. }
  2938. };
  2939. getUserMedia = navigator.getUserMedia;
  2940. } else {
  2941. baseGetUserMedia = window.navigator.getUserMedia;
  2942. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2943. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2944. // would be fine since no methods
  2945. var updatedConstraints = clone(constraints);
  2946. // wait for plugin to be ready
  2947. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2948. // check if screensharing feature is available
  2949. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2950. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2951. // set the constraints
  2952. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2953. updatedConstraints.video.optional.push({
  2954. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2955. });
  2956. delete updatedConstraints.video.mediaSource;
  2957. } else {
  2958. throw new Error('Your WebRTC plugin does not support screensharing');
  2959. }
  2960. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2961. });
  2962. } else {
  2963. baseGetUserMedia(constraints, successCb, failureCb);
  2964. }
  2965. };
  2966. getUserMedia = window.navigator.getUserMedia;
  2967. }
  2968. if (window.webrtcDetectedBrowser === 'chrome') {
  2969. var iframe = document.createElement('iframe');
  2970. iframe.onload = function() {
  2971. iframe.isLoaded = true;
  2972. };
  2973. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2974. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2975. iframe.style.display = 'none';
  2976. (document.body || document.documentElement).appendChild(iframe);
  2977. var postFrameMessage = function (object) {
  2978. object = object || {};
  2979. if (!iframe.isLoaded) {
  2980. setTimeout(function () {
  2981. iframe.contentWindow.postMessage(object, '*');
  2982. }, 100);
  2983. return;
  2984. }
  2985. iframe.contentWindow.postMessage(object, '*');
  2986. };
  2987. }
  2988. })();
  2989. },{}],13:[function(require,module,exports){
  2990. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2991. var UI = {};
  2992. var VideoLayout = require("./videolayout/VideoLayout.js");
  2993. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2994. var Prezi = require("./prezi/Prezi.js");
  2995. var Etherpad = require("./etherpad/Etherpad.js");
  2996. var Chat = require("./side_pannels/chat/Chat.js");
  2997. var Toolbar = require("./toolbars/Toolbar");
  2998. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2999. var BottomToolbar = require("./toolbars/BottomToolbar");
  3000. var ContactList = require("./side_pannels/contactlist/ContactList");
  3001. var Avatar = require("./avatar/Avatar");
  3002. var EventEmitter = require("events");
  3003. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  3004. var Settings = require("./../settings/Settings");
  3005. var PanelToggler = require("./side_pannels/SidePanelToggler");
  3006. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  3007. UI.messageHandler = require("./util/MessageHandler");
  3008. var messageHandler = UI.messageHandler;
  3009. var Authentication = require("./authentication/Authentication");
  3010. var UIUtil = require("./util/UIUtil");
  3011. var NicknameHandler = require("./util/NicknameHandler");
  3012. var JitsiPopover = require("./util/JitsiPopover");
  3013. var CQEvents = require("../../service/connectionquality/CQEvents");
  3014. var DesktopSharingEventTypes
  3015. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3016. var RTCEvents = require("../../service/RTC/RTCEvents");
  3017. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3018. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  3019. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3020. var UIEvents = require("../../service/UI/UIEvents");
  3021. var MemberEvents = require("../../service/members/Events");
  3022. var eventEmitter = new EventEmitter();
  3023. var roomName = null;
  3024. function promptDisplayName() {
  3025. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  3026. message += APP.translation.translateString(
  3027. "dialog.displayNameRequired");
  3028. message += '</h2>' +
  3029. '<input name="displayName" type="text" data-i18n=' +
  3030. '"[placeholder]defaultNickname" placeholder="' +
  3031. APP.translation.translateString(
  3032. "defaultNickname", {name: "Jane Pink"}) +
  3033. '" autofocus>';
  3034. var buttonTxt
  3035. = APP.translation.generateTranslationHTML("dialog.Ok");
  3036. var buttons = [];
  3037. buttons.push({title: buttonTxt, value: "ok"});
  3038. messageHandler.openDialog(null, message,
  3039. true,
  3040. buttons,
  3041. function (e, v, m, f) {
  3042. if (v == "ok") {
  3043. var displayName = f.displayName;
  3044. if (displayName) {
  3045. VideoLayout.inputDisplayNameHandler(displayName);
  3046. return true;
  3047. }
  3048. }
  3049. e.preventDefault();
  3050. },
  3051. function () {
  3052. var form = $.prompt.getPrompt();
  3053. var input = form.find("input[name='displayName']");
  3054. input.focus();
  3055. var button = form.find("button");
  3056. button.attr("disabled", "disabled");
  3057. input.keyup(function () {
  3058. if(!input.val())
  3059. button.attr("disabled", "disabled");
  3060. else
  3061. button.removeAttr("disabled");
  3062. });
  3063. }
  3064. );
  3065. }
  3066. function notifyForInitialMute() {
  3067. messageHandler.notify(null, "notify.mutedTitle", "connected",
  3068. "notify.muted", null, {timeOut: 120000});
  3069. }
  3070. function setupPrezi() {
  3071. $("#reloadPresentationLink").click(function() {
  3072. Prezi.reloadPresentation();
  3073. });
  3074. }
  3075. function setupChat() {
  3076. Chat.init();
  3077. $("#toggle_smileys").click(function() {
  3078. Chat.toggleSmileys();
  3079. });
  3080. }
  3081. function setupToolbars() {
  3082. Toolbar.init(UI);
  3083. Toolbar.setupButtonsFromConfig();
  3084. BottomToolbar.init();
  3085. }
  3086. function streamHandler(stream, isMuted) {
  3087. switch (stream.type) {
  3088. case "audio":
  3089. VideoLayout.changeLocalAudio(stream, isMuted);
  3090. break;
  3091. case "video":
  3092. VideoLayout.changeLocalVideo(stream, isMuted);
  3093. break;
  3094. case "stream":
  3095. VideoLayout.changeLocalStream(stream, isMuted);
  3096. break;
  3097. }
  3098. }
  3099. function onXmppConnectionFailed(stropheErrorMsg) {
  3100. var title = APP.translation.generateTranslationHTML(
  3101. "dialog.error");
  3102. var message;
  3103. if (stropheErrorMsg) {
  3104. message = APP.translation.generateTranslationHTML(
  3105. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  3106. } else {
  3107. message = APP.translation.generateTranslationHTML(
  3108. "dialog.connectError");
  3109. }
  3110. messageHandler.openDialog(
  3111. title, message, true, {}, function (e, v, m, f) { return false; });
  3112. }
  3113. function onDisposeConference(unload) {
  3114. Toolbar.showAuthenticateButton(false);
  3115. }
  3116. function onDisplayNameChanged(jid, displayName) {
  3117. ContactList.onDisplayNameChange(jid, displayName);
  3118. SettingsMenu.onDisplayNameChange(jid, displayName);
  3119. VideoLayout.onDisplayNameChanged(jid, displayName);
  3120. }
  3121. function registerListeners() {
  3122. APP.RTC.addStreamListener(streamHandler,
  3123. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  3124. APP.RTC.addStreamListener(streamHandler,
  3125. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  3126. APP.RTC.addStreamListener(function (stream) {
  3127. VideoLayout.onRemoteStreamAdded(stream);
  3128. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  3129. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  3130. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  3131. function (resourceJid) {
  3132. VideoLayout.onDominantSpeakerChanged(resourceJid);
  3133. });
  3134. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  3135. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  3136. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  3137. endpointsEnteringLastN, stream);
  3138. });
  3139. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  3140. function (devices) {
  3141. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  3142. });
  3143. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  3144. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function () {
  3145. // when the data channel becomes available, tell the bridge about video
  3146. // selections so that it can do adaptive simulcast,
  3147. // we want the notification to trigger even if userJid is undefined,
  3148. // or null.
  3149. var userResource = APP.UI.getLargeVideoResource();
  3150. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userResource);
  3151. });
  3152. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  3153. var resourceJid;
  3154. if(jid === APP.statistics.LOCAL_JID) {
  3155. resourceJid = AudioLevels.LOCAL_LEVEL;
  3156. if(APP.RTC.localAudio.isMuted()) {
  3157. audioLevel = 0;
  3158. }
  3159. } else {
  3160. resourceJid = Strophe.getResourceFromJid(jid);
  3161. }
  3162. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  3163. UI.getLargeVideoResource());
  3164. });
  3165. APP.desktopsharing.addListener(function () {
  3166. ToolbarToggler.showDesktopSharingButton();
  3167. }, DesktopSharingEventTypes.INIT);
  3168. APP.desktopsharing.addListener(
  3169. Toolbar.changeDesktopSharingButtonState,
  3170. DesktopSharingEventTypes.SWITCHING_DONE);
  3171. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  3172. VideoLayout.updateLocalConnectionStats);
  3173. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  3174. VideoLayout.updateConnectionStats);
  3175. APP.connectionquality.addListener(CQEvents.STOP,
  3176. VideoLayout.onStatsStop);
  3177. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  3178. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  3179. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  3180. messageHandler.openMessageDialog(
  3181. 'dialog.serviceUnavailable',
  3182. 'dialog.gracefulShutdown'
  3183. );
  3184. });
  3185. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  3186. var title = APP.translation.generateTranslationHTML(
  3187. "dialog.reservationError");
  3188. var message = APP.translation.generateTranslationHTML(
  3189. "dialog.reservationErrorMsg", {code: code, msg: msg});
  3190. messageHandler.openDialog(
  3191. title,
  3192. message,
  3193. true, {},
  3194. function (event, value, message, formVals) {
  3195. return false;
  3196. }
  3197. );
  3198. });
  3199. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  3200. messageHandler.openMessageDialog("dialog.sessTerminated",
  3201. "dialog.kickMessage");
  3202. });
  3203. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  3204. //FIXME: use Session Terminated from translation, but
  3205. // 'reason' text comes from XMPP packet and is not translated
  3206. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  3207. messageHandler.openDialog(
  3208. title, reason, true, {},
  3209. function (event, value, message, formVals) {
  3210. return false;
  3211. }
  3212. );
  3213. });
  3214. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  3215. messageHandler.showError("dialog.error",
  3216. "dialog.bridgeUnavailable");
  3217. });
  3218. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  3219. Avatar.setUserAvatar(from, id);
  3220. });
  3221. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  3222. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  3223. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  3224. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  3225. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  3226. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  3227. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  3228. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  3229. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  3230. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  3231. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  3232. onAuthenticationRequired);
  3233. APP.xmpp.addListener(XMPPEvents.VIDEO_TYPE, onPeerVideoTypeChanged);
  3234. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  3235. function (resource, devices) {
  3236. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  3237. });
  3238. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  3239. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  3240. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function (doMuteAudio) {
  3241. UI.setAudioMuted(doMuteAudio);
  3242. });
  3243. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  3244. onDtmfSupportChanged);
  3245. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  3246. SettingsMenu.setStartMuted(audio, video);
  3247. });
  3248. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  3249. UI.setInitialMuteFromFocus(audio, video);
  3250. });
  3251. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  3252. UI.messageHandler.showError("dialog.sorry",
  3253. "dialog.internalError");
  3254. });
  3255. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function () {
  3256. messageHandler.showError("dialog.error",
  3257. "dialog.SLDFailure");
  3258. });
  3259. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function () {
  3260. messageHandler.showError("dialog.error",
  3261. "dialog.SRDFailure");
  3262. });
  3263. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function () {
  3264. messageHandler.showError();
  3265. });
  3266. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function () {
  3267. // FIXME: re-use LoginDialog which supports retries
  3268. UI.showLoginPopup(connect);
  3269. });
  3270. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focusComponent, retrySec) {
  3271. UI.messageHandler.notify(
  3272. null, "notify.focus",
  3273. 'disconnected', "notify.focusFail",
  3274. {component: focusComponent, ms: retrySec});
  3275. });
  3276. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  3277. UI.messageHandler.openReportDialog(null,
  3278. "dialog.joinError", pres);
  3279. });
  3280. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  3281. UI.messageHandler.openReportDialog(null,
  3282. "dialog.connectError", pres);
  3283. });
  3284. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function () {
  3285. var roomName = UI.generateRoomName();
  3286. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  3287. });
  3288. //NicknameHandler emits this event
  3289. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  3290. APP.xmpp.addToPresence("displayName", nickname);
  3291. });
  3292. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  3293. AudioLevels.init();
  3294. });
  3295. if (!interfaceConfig.filmStripOnly) {
  3296. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  3297. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  3298. // Listens for video interruption events.
  3299. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  3300. // Listens for video restores events.
  3301. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  3302. }
  3303. }
  3304. /**
  3305. * Mutes/unmutes the local video.
  3306. *
  3307. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  3308. * @param options an object which specifies optional arguments such as the
  3309. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  3310. * specifies whether the method was initiated in response to a user command (in
  3311. * contrast to an automatic decision taken by the application logic)
  3312. */
  3313. function setVideoMute(mute, options) {
  3314. APP.RTC.setVideoMute(mute,
  3315. UI.setVideoMuteButtonsState,
  3316. options);
  3317. }
  3318. function onResize() {
  3319. Chat.resizeChat();
  3320. VideoLayout.resizeLargeVideoContainer();
  3321. }
  3322. function bindEvents() {
  3323. /**
  3324. * Resizes and repositions videos in full screen mode.
  3325. */
  3326. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  3327. onResize);
  3328. $(window).resize(onResize);
  3329. }
  3330. UI.start = function (init) {
  3331. document.title = interfaceConfig.APP_NAME;
  3332. var setupWelcomePage = null;
  3333. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3334. (!window.localStorage.welcomePageDisabled ||
  3335. window.localStorage.welcomePageDisabled == "false")) {
  3336. $("#videoconference_page").hide();
  3337. if (!setupWelcomePage)
  3338. setupWelcomePage = require("./welcome_page/WelcomePage");
  3339. setupWelcomePage();
  3340. return;
  3341. }
  3342. $("#welcome_page").hide();
  3343. // Set the defaults for prompt dialogs.
  3344. $.prompt.setDefaults({persistent: false});
  3345. registerListeners();
  3346. VideoLayout.init(eventEmitter);
  3347. NicknameHandler.init(eventEmitter);
  3348. bindEvents();
  3349. setupPrezi();
  3350. if (!interfaceConfig.filmStripOnly) {
  3351. $("#videospace").mousemove(function () {
  3352. return ToolbarToggler.showToolbar();
  3353. });
  3354. setupToolbars();
  3355. setupChat();
  3356. // Display notice message at the top of the toolbar
  3357. if (config.noticeMessage) {
  3358. $('#noticeText').text(config.noticeMessage);
  3359. $('#notice').css({display: 'block'});
  3360. }
  3361. $("#downloadlog").click(function (event) {
  3362. dump(event.target);
  3363. });
  3364. }
  3365. else
  3366. {
  3367. $("#header").css("display", "none");
  3368. $("#bottomToolbar").css("display", "none");
  3369. $("#downloadlog").css("display", "none");
  3370. $("#remoteVideos").css("padding", "0px 0px 18px 0px");
  3371. $("#remoteVideos").css("right", "0px");
  3372. messageHandler.disableNotifications();
  3373. $('body').popover("disable");
  3374. // $("[data-toggle=popover]").popover("disable");
  3375. JitsiPopover.enabled = false;
  3376. }
  3377. document.title = interfaceConfig.APP_NAME;
  3378. if(config.requireDisplayName) {
  3379. var currentSettings = Settings.getSettings();
  3380. if (!currentSettings.displayName) {
  3381. promptDisplayName();
  3382. }
  3383. }
  3384. init();
  3385. if (!interfaceConfig.filmStripOnly) {
  3386. toastr.options = {
  3387. "closeButton": true,
  3388. "debug": false,
  3389. "positionClass": "notification-bottom-right",
  3390. "onclick": null,
  3391. "showDuration": "300",
  3392. "hideDuration": "1000",
  3393. "timeOut": "2000",
  3394. "extendedTimeOut": "1000",
  3395. "showEasing": "swing",
  3396. "hideEasing": "linear",
  3397. "showMethod": "fadeIn",
  3398. "hideMethod": "fadeOut",
  3399. "reposition": function () {
  3400. if (PanelToggler.isVisible()) {
  3401. $("#toast-container").addClass("notification-bottom-right-center");
  3402. } else {
  3403. $("#toast-container").removeClass("notification-bottom-right-center");
  3404. }
  3405. },
  3406. "newestOnTop": false
  3407. };
  3408. SettingsMenu.init();
  3409. }
  3410. };
  3411. function chatAddError(errorMessage, originalText) {
  3412. return Chat.chatAddError(errorMessage, originalText);
  3413. }
  3414. function chatSetSubject(text) {
  3415. return Chat.chatSetSubject(text);
  3416. }
  3417. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3418. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3419. }
  3420. function onMucJoined(jid, info) {
  3421. Toolbar.updateRoomUrl(window.location.href);
  3422. var meHTML = APP.translation.generateTranslationHTML("me");
  3423. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3424. var settings = Settings.getSettings();
  3425. // Make sure we configure our avatar id, before creating avatar for us
  3426. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3427. // Add myself to the contact list.
  3428. ContactList.addContact(jid);
  3429. // Once we've joined the muc show the toolbar
  3430. ToolbarToggler.showToolbar();
  3431. var displayName =
  3432. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3433. if (displayName)
  3434. onDisplayNameChanged('localVideoContainer', displayName);
  3435. VideoLayout.mucJoined();
  3436. }
  3437. function initEtherpad(name) {
  3438. Etherpad.init(name);
  3439. }
  3440. function onMucMemberLeft(jid) {
  3441. console.log('left.muc', jid);
  3442. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3443. '>.displayname').html();
  3444. messageHandler.notify(displayName,'notify.somebody',
  3445. 'disconnected',
  3446. 'notify.disconnected');
  3447. if (!config.startAudioMuted ||
  3448. config.startAudioMuted > APP.members.size()) {
  3449. UIUtil.playSoundNotification('userLeft');
  3450. }
  3451. ContactList.removeContact(jid);
  3452. VideoLayout.participantLeft(jid);
  3453. }
  3454. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3455. console.info("My role changed, new role: " + info.role);
  3456. onModeratorStatusChanged(isModerator);
  3457. VideoLayout.showModeratorIndicator();
  3458. SettingsMenu.onRoleChanged();
  3459. if (isModerator) {
  3460. Authentication.closeAuthenticationWindow();
  3461. messageHandler.notify(null, "notify.me",
  3462. 'connected', "notify.moderator");
  3463. Toolbar.checkAutoRecord();
  3464. }
  3465. }
  3466. function onModeratorStatusChanged(isModerator) {
  3467. Toolbar.showSipCallButton(isModerator);
  3468. Toolbar.showRecordingButton(
  3469. isModerator); //&&
  3470. // FIXME:
  3471. // Recording visible if
  3472. // there are at least 2(+ 1 focus) participants
  3473. //Object.keys(connection.emuc.members).length >= 3);
  3474. }
  3475. function onPasswordRequired(callback) {
  3476. // password is required
  3477. Toolbar.lockLockButton();
  3478. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3479. message += APP.translation.translateString(
  3480. "dialog.passwordRequired");
  3481. message += '</h2>' +
  3482. '<input name="lockKey" type="text" data-i18n=' +
  3483. '"[placeholder]dialog.password" placeholder="' +
  3484. APP.translation.translateString("dialog.password") +
  3485. '" autofocus>';
  3486. messageHandler.openTwoButtonDialog(null, null, null, message,
  3487. true,
  3488. "dialog.Ok",
  3489. function (e, v, m, f) {},
  3490. null,
  3491. function (e, v, m, f) {
  3492. if (v) {
  3493. var lockKey = f.lockKey;
  3494. if (lockKey) {
  3495. Toolbar.setSharedKey(lockKey);
  3496. callback(lockKey);
  3497. }
  3498. }
  3499. },
  3500. ':input:first'
  3501. );
  3502. }
  3503. /**
  3504. * The dialpad button is shown iff there is at least one member that supports
  3505. * DTMF (e.g. jigasi).
  3506. */
  3507. function onDtmfSupportChanged(dtmfSupport) {
  3508. //TODO: enable when the UI is ready
  3509. //Toolbar.showDialPadButton(dtmfSupport);
  3510. }
  3511. function onMucMemberJoined(jid, id, displayName) {
  3512. messageHandler.notify(displayName,'notify.somebody',
  3513. 'connected',
  3514. 'notify.connected');
  3515. if (!config.startAudioMuted ||
  3516. config.startAudioMuted > APP.members.size())
  3517. UIUtil.playSoundNotification('userJoined');
  3518. // Configure avatar
  3519. Avatar.setUserAvatar(jid, id);
  3520. // Add Peer's container
  3521. VideoLayout.ensurePeerContainerExists(jid);
  3522. }
  3523. function onMucPresenceStatus(jid, info) {
  3524. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3525. }
  3526. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3527. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3528. }
  3529. function onMucRoleChanged(role, displayName) {
  3530. VideoLayout.showModeratorIndicator();
  3531. if (role === 'moderator') {
  3532. var messageKey, messageOptions = {};
  3533. if (!displayName) {
  3534. messageKey = "notify.grantedToUnknown";
  3535. }
  3536. else {
  3537. messageKey = "notify.grantedTo";
  3538. messageOptions = {to: displayName};
  3539. }
  3540. messageHandler.notify(
  3541. displayName,'notify.somebody',
  3542. 'connected', messageKey,
  3543. messageOptions);
  3544. }
  3545. }
  3546. function onAuthenticationRequired(intervalCallback) {
  3547. Authentication.openAuthenticationDialog(
  3548. roomName, intervalCallback, function () {
  3549. Toolbar.authenticateClicked();
  3550. });
  3551. }
  3552. function onLastNChanged(oldValue, newValue) {
  3553. if (config.muteLocalVideoIfNotInLastN) {
  3554. setVideoMute(!newValue, { 'byUser': false });
  3555. }
  3556. }
  3557. UI.toggleSmileys = function () {
  3558. Chat.toggleSmileys();
  3559. };
  3560. UI.getSettings = function () {
  3561. return Settings.getSettings();
  3562. };
  3563. UI.toggleFilmStrip = function () {
  3564. return BottomToolbar.toggleFilmStrip();
  3565. };
  3566. UI.toggleChat = function () {
  3567. return BottomToolbar.toggleChat();
  3568. };
  3569. UI.toggleContactList = function () {
  3570. return BottomToolbar.toggleContactList();
  3571. };
  3572. UI.inputDisplayNameHandler = function (value) {
  3573. VideoLayout.inputDisplayNameHandler(value);
  3574. };
  3575. UI.getLargeVideoResource = function () {
  3576. return VideoLayout.getLargeVideoResource();
  3577. };
  3578. UI.generateRoomName = function() {
  3579. if(roomName)
  3580. return roomName;
  3581. var roomnode = null;
  3582. var path = window.location.pathname;
  3583. // determinde the room node from the url
  3584. // TODO: just the roomnode or the whole bare jid?
  3585. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3586. // custom function might be responsible for doing the pushstate
  3587. roomnode = config.getroomnode(path);
  3588. } else {
  3589. /* fall back to default strategy
  3590. * this is making assumptions about how the URL->room mapping happens.
  3591. * It currently assumes deployment at root, with a rewrite like the
  3592. * following one (for nginx):
  3593. location ~ ^/([a-zA-Z0-9]+)$ {
  3594. rewrite ^/(.*)$ / break;
  3595. }
  3596. */
  3597. if (path.length > 1) {
  3598. roomnode = path.substr(1).toLowerCase();
  3599. } else {
  3600. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3601. roomnode = word.toLowerCase();
  3602. window.history.pushState('VideoChat',
  3603. 'Room: ' + word, window.location.pathname + word);
  3604. }
  3605. }
  3606. roomName = roomnode + '@' + config.hosts.muc;
  3607. return roomName;
  3608. };
  3609. UI.connectionIndicatorShowMore = function(jid) {
  3610. return VideoLayout.showMore(jid);
  3611. };
  3612. UI.showLoginPopup = function(callback) {
  3613. console.log('password is required');
  3614. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3615. message += APP.translation.translateString(
  3616. "dialog.passwordRequired");
  3617. message += '</h2>' +
  3618. '<input name="username" type="text" ' +
  3619. 'placeholder="user@domain.net" autofocus>' +
  3620. '<input name="password" ' +
  3621. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3622. ' placeholder="user password">';
  3623. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3624. true,
  3625. "dialog.Ok",
  3626. function (e, v, m, f) {
  3627. if (v) {
  3628. if (f.username !== null && f.password != null) {
  3629. callback(f.username, f.password);
  3630. }
  3631. }
  3632. },
  3633. null, null, ':input:first'
  3634. );
  3635. };
  3636. UI.checkForNicknameAndJoin = function () {
  3637. Authentication.closeAuthenticationDialog();
  3638. Authentication.stopInterval();
  3639. var nick = null;
  3640. if (config.useNicks) {
  3641. nick = window.prompt('Your nickname (optional)');
  3642. }
  3643. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3644. };
  3645. function dump(elem, filename) {
  3646. elem = elem.parentNode;
  3647. elem.download = filename || 'meetlog.json';
  3648. elem.href = 'data:application/json;charset=utf-8,\n';
  3649. var data = APP.xmpp.getJingleLog();
  3650. var metadata = {};
  3651. metadata.time = new Date();
  3652. metadata.url = window.location.href;
  3653. metadata.ua = navigator.userAgent;
  3654. var log = APP.xmpp.getXmppLog();
  3655. if (log) {
  3656. metadata.xmpp = log;
  3657. }
  3658. data.metadata = metadata;
  3659. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3660. return false;
  3661. }
  3662. UI.getRoomName = function () {
  3663. return roomName;
  3664. };
  3665. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3666. if (muteAudio || muteVideo)
  3667. notifyForInitialMute();
  3668. if (muteAudio)
  3669. UI.setAudioMuted(true);
  3670. if (muteVideo)
  3671. UI.setVideoMute(true);
  3672. };
  3673. /**
  3674. * Mutes/unmutes the local video.
  3675. */
  3676. UI.toggleVideo = function () {
  3677. setVideoMute(!APP.RTC.localVideo.isMuted());
  3678. };
  3679. /**
  3680. * Mutes / unmutes audio for the local participant.
  3681. */
  3682. UI.toggleAudio = function() {
  3683. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3684. };
  3685. /**
  3686. * Sets muted audio state for the local participant.
  3687. */
  3688. UI.setAudioMuted = function (mute, earlyMute) {
  3689. var audioMute = null;
  3690. if (earlyMute)
  3691. audioMute = function (mute, cb) {
  3692. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3693. };
  3694. else
  3695. audioMute = function (mute, cb) {
  3696. return APP.xmpp.setAudioMute(mute, cb);
  3697. };
  3698. if (!audioMute(mute, function () {
  3699. VideoLayout.showLocalAudioIndicator(mute);
  3700. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3701. })) {
  3702. // We still click the button.
  3703. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3704. return;
  3705. }
  3706. };
  3707. UI.addListener = function (type, listener) {
  3708. eventEmitter.on(type, listener);
  3709. };
  3710. UI.clickOnVideo = function (videoNumber) {
  3711. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3712. if (remoteVideos.length > videoNumber) {
  3713. remoteVideos[videoNumber].click();
  3714. }
  3715. };
  3716. //Used by torture
  3717. UI.showToolbar = function () {
  3718. return ToolbarToggler.showToolbar();
  3719. };
  3720. //Used by torture
  3721. UI.dockToolbar = function (isDock) {
  3722. return ToolbarToggler.dockToolbar(isDock);
  3723. };
  3724. UI.setVideoMuteButtonsState = function (mute) {
  3725. var video = $('#toolbar_button_camera');
  3726. var communicativeClass = "icon-camera";
  3727. var muteClass = "icon-camera icon-camera-disabled";
  3728. if (mute) {
  3729. video.removeClass(communicativeClass);
  3730. video.addClass(muteClass);
  3731. } else {
  3732. video.removeClass(muteClass);
  3733. video.addClass(communicativeClass);
  3734. }
  3735. };
  3736. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3737. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3738. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3739. if(resourceJid === APP.xmpp.myResource())
  3740. SettingsMenu.changeAvatar(thumbUrl);
  3741. };
  3742. UI.setVideoMute = setVideoMute;
  3743. module.exports = UI;
  3744. },{"../../service/RTC/RTCEvents":111,"../../service/RTC/StreamEventTypes":113,"../../service/UI/UIEvents":114,"../../service/connectionquality/CQEvents":116,"../../service/desktopsharing/DesktopSharingEventTypes":117,"../../service/members/Events":118,"../../service/xmpp/XMPPEvents":120,"../RTC/RTCBrowserType":10,"./../settings/Settings":49,"./audio_levels/AudioLevels.js":14,"./authentication/Authentication":16,"./avatar/Avatar":18,"./etherpad/Etherpad.js":19,"./prezi/Prezi.js":20,"./side_pannels/SidePanelToggler":22,"./side_pannels/chat/Chat.js":23,"./side_pannels/contactlist/ContactList":27,"./side_pannels/settings/SettingsMenu":28,"./toolbars/BottomToolbar":29,"./toolbars/Toolbar":30,"./toolbars/ToolbarToggler":31,"./util/JitsiPopover":32,"./util/MessageHandler":33,"./util/NicknameHandler":34,"./util/UIUtil":35,"./videolayout/VideoLayout.js":41,"./welcome_page/RoomnameGenerator":42,"./welcome_page/WelcomePage":43,"events":1}],14:[function(require,module,exports){
  3745. /* global APP, interfaceConfig, $, Strophe */
  3746. var CanvasUtil = require("./CanvasUtils");
  3747. var ASDrawContext = null;
  3748. function initActiveSpeakerAudioLevels() {
  3749. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3750. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3751. // Draw a circle.
  3752. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3753. // Add a shadow around the circle
  3754. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3755. ASDrawContext.shadowOffsetX = 0;
  3756. ASDrawContext.shadowOffsetY = 0;
  3757. }
  3758. /**
  3759. * The audio Levels plugin.
  3760. */
  3761. var AudioLevels = (function(my) {
  3762. var audioLevelCanvasCache = {};
  3763. my.LOCAL_LEVEL = 'local';
  3764. my.init = function () {
  3765. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3766. initActiveSpeakerAudioLevels();
  3767. };
  3768. /**
  3769. * Updates the audio level canvas for the given peerJid. If the canvas
  3770. * didn't exist we create it.
  3771. */
  3772. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3773. var resourceJid = null;
  3774. var videoSpanId = null;
  3775. if (!peerJid)
  3776. videoSpanId = 'localVideoContainer';
  3777. else {
  3778. resourceJid = Strophe.getResourceFromJid(peerJid);
  3779. videoSpanId = 'participant_' + resourceJid;
  3780. }
  3781. var videoSpan = document.getElementById(videoSpanId);
  3782. if (!videoSpan) {
  3783. if (resourceJid)
  3784. console.error("No video element for jid", resourceJid);
  3785. else
  3786. console.error("No video element for local video.");
  3787. return;
  3788. }
  3789. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3790. var videoSpaceWidth = $('#remoteVideos').width();
  3791. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3792. var thumbnailWidth = thumbnailSize[0];
  3793. var thumbnailHeight = thumbnailSize[1];
  3794. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3795. audioLevelCanvas = document.createElement('canvas');
  3796. audioLevelCanvas.className = "audiolevel";
  3797. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3798. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3799. resizeAudioLevelCanvas( audioLevelCanvas,
  3800. thumbnailWidth,
  3801. thumbnailHeight);
  3802. videoSpan.appendChild(audioLevelCanvas);
  3803. } else {
  3804. audioLevelCanvas = audioLevelCanvas.get(0);
  3805. resizeAudioLevelCanvas( audioLevelCanvas,
  3806. thumbnailWidth,
  3807. thumbnailHeight);
  3808. }
  3809. };
  3810. /**
  3811. * Updates the audio level UI for the given resourceJid.
  3812. *
  3813. * @param resourceJid the resource jid indicating the video element for
  3814. * which we draw the audio level
  3815. * @param audioLevel the newAudio level to render
  3816. */
  3817. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3818. drawAudioLevelCanvas(resourceJid, audioLevel);
  3819. var videoSpanId = getVideoSpanId(resourceJid);
  3820. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3821. if (!audioLevelCanvas)
  3822. return;
  3823. var drawContext = audioLevelCanvas.getContext('2d');
  3824. var canvasCache = audioLevelCanvasCache[resourceJid];
  3825. drawContext.clearRect (0, 0,
  3826. audioLevelCanvas.width, audioLevelCanvas.height);
  3827. drawContext.drawImage(canvasCache, 0, 0);
  3828. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3829. if(!APP.xmpp.myJid()) {
  3830. return;
  3831. }
  3832. resourceJid = APP.xmpp.myResource();
  3833. }
  3834. if(resourceJid === largeVideoResourceJid) {
  3835. window.requestAnimationFrame(function () {
  3836. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3837. });
  3838. }
  3839. };
  3840. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3841. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3842. return;
  3843. ASDrawContext.clearRect(0, 0, 300, 300);
  3844. if(audioLevel == 0)
  3845. return;
  3846. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3847. // Fill the shape.
  3848. ASDrawContext.fill();
  3849. };
  3850. /**
  3851. * Resizes the given audio level canvas to match the given thumbnail size.
  3852. */
  3853. function resizeAudioLevelCanvas(audioLevelCanvas,
  3854. thumbnailWidth,
  3855. thumbnailHeight) {
  3856. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3857. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3858. }
  3859. /**
  3860. * Draws the audio level canvas into the cached canvas object.
  3861. *
  3862. * @param resourceJid the resource jid indicating the video element for
  3863. * which we draw the audio level
  3864. * @param audioLevel the newAudio level to render
  3865. */
  3866. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3867. if (!audioLevelCanvasCache[resourceJid]) {
  3868. var videoSpanId = getVideoSpanId(resourceJid);
  3869. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3870. /*
  3871. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3872. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3873. * error. Since audio levels are frequently updated, the errors have
  3874. * been observed to pile into the console, strain the CPU.
  3875. */
  3876. if (audioLevelCanvasOrig) {
  3877. audioLevelCanvasCache[resourceJid] =
  3878. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3879. }
  3880. }
  3881. var canvas = audioLevelCanvasCache[resourceJid];
  3882. if (!canvas)
  3883. return;
  3884. var drawContext = canvas.getContext('2d');
  3885. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3886. var shadowLevel = getShadowLevel(audioLevel);
  3887. if (shadowLevel > 0) {
  3888. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3889. CanvasUtil.drawRoundRectGlow(drawContext,
  3890. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3891. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3892. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3893. interfaceConfig.CANVAS_RADIUS,
  3894. interfaceConfig.SHADOW_COLOR,
  3895. shadowLevel);
  3896. }
  3897. }
  3898. /**
  3899. * Returns the shadow/glow level for the given audio level.
  3900. *
  3901. * @param audioLevel the audio level from which we determine the shadow
  3902. * level
  3903. */
  3904. function getShadowLevel (audioLevel) {
  3905. var shadowLevel = 0;
  3906. if (audioLevel <= 0.3) {
  3907. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3908. }
  3909. else if (audioLevel <= 0.6) {
  3910. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3911. }
  3912. else {
  3913. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3914. }
  3915. return shadowLevel;
  3916. }
  3917. /**
  3918. * Returns the video span id corresponding to the given resourceJid or local
  3919. * user.
  3920. */
  3921. function getVideoSpanId(resourceJid) {
  3922. var videoSpanId = null;
  3923. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3924. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3925. videoSpanId = 'localVideoContainer';
  3926. else
  3927. videoSpanId = 'participant_' + resourceJid;
  3928. return videoSpanId;
  3929. }
  3930. /**
  3931. * Indicates that the remote video has been resized.
  3932. */
  3933. $(document).bind('remotevideo.resized', function (event, width, height) {
  3934. var resized = false;
  3935. $('#remoteVideos>span>canvas').each(function() {
  3936. var canvas = $(this).get(0);
  3937. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3938. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3939. resized = true;
  3940. }
  3941. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3942. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3943. resized = true;
  3944. }
  3945. });
  3946. if (resized)
  3947. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3948. audioLevelCanvasCache[resourceJid].width =
  3949. width + interfaceConfig.CANVAS_EXTRA;
  3950. audioLevelCanvasCache[resourceJid].height =
  3951. height + interfaceConfig.CANVAS_EXTRA;
  3952. });
  3953. });
  3954. return my;
  3955. })(AudioLevels || {});
  3956. module.exports = AudioLevels;
  3957. },{"./CanvasUtils":15}],15:[function(require,module,exports){
  3958. /**
  3959. * Utility class for drawing canvas shapes.
  3960. */
  3961. var CanvasUtil = (function(my) {
  3962. /**
  3963. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3964. * of the glow.
  3965. *
  3966. * @param drawContext the context of the canvas to draw to
  3967. * @param x the x coordinate of the round rectangle
  3968. * @param y the y coordinate of the round rectangle
  3969. * @param w the width of the round rectangle
  3970. * @param h the height of the round rectangle
  3971. * @param glowColor the color of the glow
  3972. * @param glowWidth the width of the glow
  3973. */
  3974. my.drawRoundRectGlow
  3975. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3976. // Save the previous state of the context.
  3977. drawContext.save();
  3978. if (w < 2 * r) r = w / 2;
  3979. if (h < 2 * r) r = h / 2;
  3980. // Draw a round rectangle.
  3981. drawContext.beginPath();
  3982. drawContext.moveTo(x+r, y);
  3983. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3984. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3985. drawContext.arcTo(x, y+h, x, y, r);
  3986. drawContext.arcTo(x, y, x+w, y, r);
  3987. drawContext.closePath();
  3988. // Add a shadow around the rectangle
  3989. drawContext.shadowColor = glowColor;
  3990. drawContext.shadowBlur = glowWidth;
  3991. drawContext.shadowOffsetX = 0;
  3992. drawContext.shadowOffsetY = 0;
  3993. // Fill the shape.
  3994. drawContext.fill();
  3995. drawContext.save();
  3996. drawContext.restore();
  3997. // 1) Uncomment this line to use Composite Operation, which is doing the
  3998. // same as the clip function below and is also antialiasing the round
  3999. // border, but is said to be less fast performance wise.
  4000. // drawContext.globalCompositeOperation='destination-out';
  4001. drawContext.beginPath();
  4002. drawContext.moveTo(x+r, y);
  4003. drawContext.arcTo(x+w, y, x+w, y+h, r);
  4004. drawContext.arcTo(x+w, y+h, x, y+h, r);
  4005. drawContext.arcTo(x, y+h, x, y, r);
  4006. drawContext.arcTo(x, y, x+w, y, r);
  4007. drawContext.closePath();
  4008. // 2) Uncomment this line to use Composite Operation, which is doing the
  4009. // same as the clip function below and is also antialiasing the round
  4010. // border, but is said to be less fast performance wise.
  4011. // drawContext.fill();
  4012. // Comment these two lines if choosing to do the same with composite
  4013. // operation above 1 and 2.
  4014. drawContext.clip();
  4015. drawContext.clearRect(0, 0, 277, 200);
  4016. // Restore the previous context state.
  4017. drawContext.restore();
  4018. };
  4019. /**
  4020. * Clones the given canvas.
  4021. *
  4022. * @return the new cloned canvas.
  4023. */
  4024. my.cloneCanvas = function (oldCanvas) {
  4025. /*
  4026. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  4027. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  4028. * levels are frequently updated, the errors have been observed to pile
  4029. * into the console, strain the CPU.
  4030. */
  4031. if (!oldCanvas)
  4032. return oldCanvas;
  4033. //create a new canvas
  4034. var newCanvas = document.createElement('canvas');
  4035. var context = newCanvas.getContext('2d');
  4036. //set dimensions
  4037. newCanvas.width = oldCanvas.width;
  4038. newCanvas.height = oldCanvas.height;
  4039. //apply the old canvas to the new one
  4040. context.drawImage(oldCanvas, 0, 0);
  4041. //return the new canvas
  4042. return newCanvas;
  4043. };
  4044. return my;
  4045. })(CanvasUtil || {});
  4046. module.exports = CanvasUtil;
  4047. },{}],16:[function(require,module,exports){
  4048. /* global $, APP*/
  4049. var LoginDialog = require('./LoginDialog');
  4050. var Moderator = require('../../xmpp/moderator');
  4051. /* Initial "authentication required" dialog */
  4052. var authDialog = null;
  4053. /* Loop retry ID that wits for other user to create the room */
  4054. var authRetryId = null;
  4055. var authenticationWindow = null;
  4056. var Authentication = {
  4057. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  4058. // This is the loop that will wait for the room to be created by
  4059. // someone else. 'auth_required.moderator' will bring us back here.
  4060. authRetryId = window.setTimeout(intervalCallback, 5000);
  4061. // Show prompt only if it's not open
  4062. if (authDialog !== null) {
  4063. return;
  4064. }
  4065. // extract room name from 'room@muc.server.net'
  4066. var room = roomName.substr(0, roomName.indexOf('@'));
  4067. var title
  4068. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  4069. var msg
  4070. = APP.translation.generateTranslationHTML(
  4071. "dialog.WaitForHostMsg", {room: room});
  4072. var buttonTxt
  4073. = APP.translation.generateTranslationHTML("dialog.IamHost");
  4074. var buttons = [];
  4075. buttons.push({title: buttonTxt, value: "authNow"});
  4076. authDialog = APP.UI.messageHandler.openDialog(
  4077. title,
  4078. msg,
  4079. true,
  4080. buttons,
  4081. function (onSubmitEvent, submitValue) {
  4082. // Do not close the dialog yet
  4083. onSubmitEvent.preventDefault();
  4084. // Open login popup
  4085. if (submitValue === 'authNow') {
  4086. callback();
  4087. }
  4088. }
  4089. );
  4090. },
  4091. closeAuthenticationWindow: function () {
  4092. if (authenticationWindow) {
  4093. authenticationWindow.close();
  4094. authenticationWindow = null;
  4095. }
  4096. },
  4097. xmppAuthenticate: function () {
  4098. var loginDialog = LoginDialog.show(
  4099. function (connection, state) {
  4100. if (!state) {
  4101. // User cancelled
  4102. loginDialog.close();
  4103. return;
  4104. } else if (state == APP.xmpp.Status.CONNECTED) {
  4105. loginDialog.close();
  4106. Authentication.stopInterval();
  4107. Authentication.closeAuthenticationDialog();
  4108. // Close the connection as anonymous one will be used
  4109. // to create the conference. Session-id will authorize
  4110. // the request.
  4111. connection.disconnect();
  4112. var roomName = APP.UI.generateRoomName();
  4113. Moderator.allocateConferenceFocus(roomName, function () {
  4114. // If it's not "on the fly" authentication now join
  4115. // the conference room
  4116. if (!APP.xmpp.isMUCJoined()) {
  4117. APP.UI.checkForNicknameAndJoin();
  4118. }
  4119. });
  4120. }
  4121. }, true);
  4122. },
  4123. focusAuthenticationWindow: function () {
  4124. // If auth window exists just bring it to the front
  4125. if (authenticationWindow) {
  4126. authenticationWindow.focus();
  4127. return;
  4128. }
  4129. },
  4130. closeAuthenticationDialog: function () {
  4131. // Close authentication dialog if opened
  4132. if (authDialog) {
  4133. authDialog.close();
  4134. authDialog = null;
  4135. }
  4136. },
  4137. createAuthenticationWindow: function (callback, url) {
  4138. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  4139. url, 910, 660,
  4140. // On closed
  4141. function () {
  4142. // Close authentication dialog if opened
  4143. Authentication.closeAuthenticationDialog();
  4144. callback();
  4145. authenticationWindow = null;
  4146. });
  4147. return authenticationWindow;
  4148. },
  4149. stopInterval: function () {
  4150. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  4151. if (authRetryId) {
  4152. window.clearTimeout(authRetryId);
  4153. authRetryId = null;
  4154. }
  4155. }
  4156. };
  4157. module.exports = Authentication;
  4158. },{"../../xmpp/moderator":62,"./LoginDialog":17}],17:[function(require,module,exports){
  4159. /* global $, APP, config*/
  4160. var XMPP = require('../../xmpp/xmpp');
  4161. var Moderator = require('../../xmpp/moderator');
  4162. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  4163. // anonymous domain is not enabled
  4164. /**
  4165. * Creates new <tt>Dialog</tt> instance.
  4166. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  4167. * when we either fail to connect or succeed(check Strophe.Status).
  4168. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  4169. * in order to create session-id after the connection is established.
  4170. * @constructor
  4171. */
  4172. function Dialog(callback, obtainSession) {
  4173. var self = this;
  4174. var stop = false;
  4175. var connection = APP.xmpp.createConnection();
  4176. var message = '<h2 data-i18n="dialog.passwordRequired">';
  4177. message += APP.translation.translateString("dialog.passwordRequired");
  4178. message += '</h2>' +
  4179. '<input name="username" type="text" ' +
  4180. 'placeholder="user@domain.net" autofocus>' +
  4181. '<input name="password" ' +
  4182. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  4183. ' placeholder="user password">';
  4184. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  4185. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  4186. var states = {
  4187. login: {
  4188. html: message,
  4189. buttons: [
  4190. { title: okButton, value: true},
  4191. { title: cancelButton, value: false}
  4192. ],
  4193. focus: ':input:first',
  4194. submit: function (e, v, m, f) {
  4195. e.preventDefault();
  4196. if (v) {
  4197. var jid = f.username;
  4198. var password = f.password;
  4199. if (jid && password) {
  4200. stop = false;
  4201. connection.reset();
  4202. connDialog.goToState('connecting');
  4203. connection.connect(jid, password, stateHandler);
  4204. }
  4205. } else {
  4206. // User cancelled
  4207. stop = true;
  4208. callback();
  4209. }
  4210. }
  4211. },
  4212. connecting: {
  4213. title: APP.translation.translateString('dialog.connecting'),
  4214. html: '<div id="connectionStatus"></div>',
  4215. buttons: [],
  4216. defaultButton: 0
  4217. },
  4218. finished: {
  4219. title: APP.translation.translateString('dialog.error'),
  4220. html: '<div id="errorMessage"></div>',
  4221. buttons: [
  4222. {
  4223. title: APP.translation.translateString('dialog.retry'),
  4224. value: 'retry'
  4225. },
  4226. {
  4227. title: APP.translation.translateString('dialog.Cancel'),
  4228. value: 'cancel'
  4229. },
  4230. ],
  4231. defaultButton: 0,
  4232. submit: function (e, v, m, f) {
  4233. e.preventDefault();
  4234. if (v === 'retry')
  4235. connDialog.goToState('login');
  4236. else
  4237. callback();
  4238. }
  4239. }
  4240. };
  4241. var connDialog
  4242. = APP.UI.messageHandler.openDialogWithStates(states,
  4243. { persistent: true, closeText: '' }, null);
  4244. var stateHandler = function (status, message) {
  4245. if (stop) {
  4246. return;
  4247. }
  4248. var translateKey = "connection." + XMPP.getStatusString(status);
  4249. var statusStr = APP.translation.translateString(translateKey);
  4250. // Display current state
  4251. var connectionStatus =
  4252. connDialog.getState('connecting').find('#connectionStatus');
  4253. connectionStatus.text(statusStr);
  4254. switch (status) {
  4255. case XMPP.Status.CONNECTED:
  4256. stop = true;
  4257. if (!obtainSession) {
  4258. callback(connection, status);
  4259. return;
  4260. }
  4261. // Obtaining session-id status
  4262. connectionStatus.text(
  4263. APP.translation.translateString(
  4264. 'connection.FETCH_SESSION_ID'));
  4265. // Authenticate with Jicofo and obtain session-id
  4266. var roomName = APP.UI.generateRoomName();
  4267. // Jicofo will return new session-id when connected
  4268. // from authenticated domain
  4269. connection.sendIQ(
  4270. Moderator.createConferenceIq(roomName),
  4271. function (result) {
  4272. connectionStatus.text(
  4273. APP.translation.translateString(
  4274. 'connection.GOT_SESSION_ID'));
  4275. stop = true;
  4276. // Parse session-id
  4277. Moderator.parseSessionId(result);
  4278. callback(connection, status);
  4279. },
  4280. function (error) {
  4281. console.error("Auth on the fly failed", error);
  4282. stop = true;
  4283. var errorMsg =
  4284. APP.translation.translateString(
  4285. 'connection.GET_SESSION_ID_ERROR') +
  4286. $(error).find('>error').attr('code');
  4287. self.displayError(errorMsg);
  4288. connection.disconnect();
  4289. });
  4290. break;
  4291. case XMPP.Status.AUTHFAIL:
  4292. case XMPP.Status.CONNFAIL:
  4293. case XMPP.Status.DISCONNECTED:
  4294. stop = true;
  4295. callback(connection, status);
  4296. var errorMessage = statusStr;
  4297. if (message)
  4298. {
  4299. errorMessage += ': ' + message;
  4300. }
  4301. self.displayError(errorMessage);
  4302. break;
  4303. default:
  4304. break;
  4305. }
  4306. };
  4307. /**
  4308. * Displays error message in 'finished' state which allows either to cancel
  4309. * or retry.
  4310. * @param message the final message to be displayed.
  4311. */
  4312. this.displayError = function (message) {
  4313. var finishedState = connDialog.getState('finished');
  4314. var errorMessageElem = finishedState.find('#errorMessage');
  4315. errorMessageElem.text(message);
  4316. connDialog.goToState('finished');
  4317. };
  4318. /**
  4319. * Closes LoginDialog.
  4320. */
  4321. this.close = function () {
  4322. stop = true;
  4323. connDialog.close();
  4324. };
  4325. }
  4326. var LoginDialog = {
  4327. /**
  4328. * Displays login prompt used to establish new XMPP connection. Given
  4329. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4330. * called when we connect successfully(status === CONNECTED) or when we fail
  4331. * to do so. On connection failure program can call Dialog.close() method in
  4332. * order to cancel or do nothing to let the user retry.
  4333. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4334. * called when we either fail to connect or succeed(check
  4335. * Strophe.Status).
  4336. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4337. * Jicofo in order to create session-id after the connection is
  4338. * established.
  4339. * @returns {Dialog}
  4340. */
  4341. show: function (callback, obtainSession) {
  4342. return new Dialog(callback, obtainSession);
  4343. }
  4344. };
  4345. module.exports = LoginDialog;
  4346. },{"../../xmpp/moderator":62,"../../xmpp/xmpp":70}],18:[function(require,module,exports){
  4347. var Settings = require("../../settings/Settings");
  4348. var users = {};
  4349. var Avatar = {
  4350. /**
  4351. * Sets the user's avatar in the settings menu(if local user), contact list
  4352. * and thumbnail
  4353. * @param jid jid of the user
  4354. * @param id email or userID to be used as a hash
  4355. */
  4356. setUserAvatar: function (jid, id) {
  4357. if (id) {
  4358. if (users[jid] === id) {
  4359. return;
  4360. }
  4361. users[jid] = id;
  4362. }
  4363. var thumbUrl = this.getThumbUrl(jid);
  4364. var contactListUrl = this.getContactListUrl(jid);
  4365. var resourceJid = Strophe.getResourceFromJid(jid);
  4366. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4367. },
  4368. /**
  4369. * Returns image URL for the avatar to be displayed on large video area
  4370. * where current active speaker is presented.
  4371. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4372. */
  4373. getActiveSpeakerUrl: function (jid) {
  4374. return this.getGravatarUrl(jid, 100);
  4375. },
  4376. /**
  4377. * Returns image URL for the avatar to be displayed on small video thumbnail
  4378. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4379. */
  4380. getThumbUrl: function (jid) {
  4381. return this.getGravatarUrl(jid, 100);
  4382. },
  4383. /**
  4384. * Returns the URL for the avatar to be displayed as contactlist item
  4385. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4386. */
  4387. getContactListUrl: function (jid) {
  4388. return this.getGravatarUrl(jid, 30);
  4389. },
  4390. getGravatarUrl: function (jid, size) {
  4391. if (!jid) {
  4392. console.error("Get gravatar - jid is undefined");
  4393. return null;
  4394. }
  4395. var id = users[jid];
  4396. if (!id) {
  4397. console.warn(
  4398. "No avatar stored yet for " + jid + " - using JID as ID");
  4399. id = jid;
  4400. }
  4401. return 'https://www.gravatar.com/avatar/' +
  4402. MD5.hexdigest(id.trim().toLowerCase()) +
  4403. "?d=wavatar&size=" + (size || "30");
  4404. }
  4405. };
  4406. module.exports = Avatar;
  4407. },{"../../settings/Settings":49}],19:[function(require,module,exports){
  4408. /* global $, config,
  4409. setLargeVideoVisible, Util */
  4410. var VideoLayout = require("../videolayout/VideoLayout");
  4411. var Prezi = require("../prezi/Prezi");
  4412. var UIUtil = require("../util/UIUtil");
  4413. var etherpadName = null;
  4414. var etherpadIFrame = null;
  4415. var domain = null;
  4416. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4417. /**
  4418. * Resizes the etherpad.
  4419. */
  4420. function resize() {
  4421. if ($('#etherpad>iframe').length) {
  4422. var remoteVideos = $('#remoteVideos');
  4423. var availableHeight
  4424. = window.innerHeight - remoteVideos.outerHeight();
  4425. var availableWidth = UIUtil.getAvailableVideoWidth();
  4426. $('#etherpad>iframe').width(availableWidth);
  4427. $('#etherpad>iframe').height(availableHeight);
  4428. }
  4429. }
  4430. /**
  4431. * Creates the Etherpad button and adds it to the toolbar.
  4432. */
  4433. function enableEtherpadButton() {
  4434. if (!$('#toolbar_button_etherpad').is(":visible"))
  4435. $('#toolbar_button_etherpad').css({display: 'inline-block'});
  4436. }
  4437. /**
  4438. * Creates the IFrame for the etherpad.
  4439. */
  4440. function createIFrame() {
  4441. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4442. domain + etherpadName + options, function() {
  4443. document.domain = document.domain;
  4444. bubbleIframeMouseMove(etherpadIFrame);
  4445. setTimeout(function() {
  4446. // the iframes inside of the etherpad are
  4447. // not yet loaded when the etherpad iframe is loaded
  4448. var outer = etherpadIFrame.
  4449. contentDocument.getElementsByName("ace_outer")[0];
  4450. bubbleIframeMouseMove(outer);
  4451. var inner = outer.
  4452. contentDocument.getElementsByName("ace_inner")[0];
  4453. bubbleIframeMouseMove(inner);
  4454. }, 2000);
  4455. });
  4456. }
  4457. function bubbleIframeMouseMove(iframe){
  4458. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4459. iframe.contentWindow.onmousemove = function(e){
  4460. if(existingOnMouseMove) existingOnMouseMove(e);
  4461. var evt = document.createEvent("MouseEvents");
  4462. var boundingClientRect = iframe.getBoundingClientRect();
  4463. evt.initMouseEvent(
  4464. "mousemove",
  4465. true, // bubbles
  4466. false, // not cancelable
  4467. window,
  4468. e.detail,
  4469. e.screenX,
  4470. e.screenY,
  4471. e.clientX + boundingClientRect.left,
  4472. e.clientY + boundingClientRect.top,
  4473. e.ctrlKey,
  4474. e.altKey,
  4475. e.shiftKey,
  4476. e.metaKey,
  4477. e.button,
  4478. null // no related element
  4479. );
  4480. iframe.dispatchEvent(evt);
  4481. };
  4482. }
  4483. var Etherpad = {
  4484. /**
  4485. * Initializes the etherpad.
  4486. */
  4487. init: function (name) {
  4488. if (config.etherpad_base && !etherpadName && name) {
  4489. domain = config.etherpad_base;
  4490. etherpadName = name;
  4491. enableEtherpadButton();
  4492. /**
  4493. * Resizes the etherpad, when the window is resized.
  4494. */
  4495. $(window).resize(function () {
  4496. resize();
  4497. });
  4498. }
  4499. },
  4500. /**
  4501. * Opens/hides the Etherpad.
  4502. */
  4503. toggleEtherpad: function (isPresentation) {
  4504. if (!etherpadIFrame)
  4505. createIFrame();
  4506. if(VideoLayout.getLargeVideoState() === "etherpad")
  4507. {
  4508. VideoLayout.setLargeVideoState("video");
  4509. }
  4510. else
  4511. {
  4512. VideoLayout.setLargeVideoState("etherpad");
  4513. }
  4514. resize();
  4515. }
  4516. };
  4517. module.exports = Etherpad;
  4518. },{"../prezi/Prezi":20,"../util/UIUtil":35,"../videolayout/VideoLayout":41}],20:[function(require,module,exports){
  4519. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4520. var UIUtil = require("../util/UIUtil");
  4521. var VideoLayout = require("../videolayout/VideoLayout");
  4522. var messageHandler = require("../util/MessageHandler");
  4523. var PreziPlayer = require("./PreziPlayer");
  4524. var preziPlayer = null;
  4525. /**
  4526. * Shows/hides a presentation.
  4527. */
  4528. function setPresentationVisible(visible) {
  4529. if (visible) {
  4530. VideoLayout.setLargeVideoState("prezi");
  4531. }
  4532. else {
  4533. VideoLayout.setLargeVideoState("video");
  4534. }
  4535. }
  4536. var Prezi = {
  4537. /**
  4538. * Reloads the current presentation.
  4539. */
  4540. reloadPresentation: function() {
  4541. var iframe = document.getElementById(preziPlayer.options.preziId);
  4542. iframe.src = iframe.src;
  4543. },
  4544. /**
  4545. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4546. * otherwise.
  4547. */
  4548. isPresentationVisible: function () {
  4549. return ($('#presentation>iframe') != null
  4550. && $('#presentation>iframe').css('opacity') == 1);
  4551. },
  4552. /**
  4553. * Opens the Prezi dialog, from which the user could choose a presentation
  4554. * to load.
  4555. */
  4556. openPreziDialog: function() {
  4557. var myprezi = APP.xmpp.getPrezi();
  4558. if (myprezi) {
  4559. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4560. null,
  4561. "dialog.removePreziMsg",
  4562. null,
  4563. false,
  4564. "dialog.Remove",
  4565. function(e,v,m,f) {
  4566. if(v) {
  4567. APP.xmpp.removePreziFromPresence();
  4568. }
  4569. }
  4570. );
  4571. }
  4572. else if (preziPlayer != null) {
  4573. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4574. null, "dialog.sharePreziMsg",
  4575. null,
  4576. false,
  4577. "dialog.Ok",
  4578. function(e,v,m,f) {
  4579. $.prompt.close();
  4580. }
  4581. );
  4582. }
  4583. else {
  4584. var html = APP.translation.generateTranslationHTML(
  4585. "dialog.sharePreziTitle");
  4586. var cancelButton = APP.translation.generateTranslationHTML(
  4587. "dialog.Cancel");
  4588. var shareButton = APP.translation.generateTranslationHTML(
  4589. "dialog.Share");
  4590. var backButton = APP.translation.generateTranslationHTML(
  4591. "dialog.Back");
  4592. var buttons = [];
  4593. var buttons1 = [];
  4594. // Cancel button to both states
  4595. buttons.push({title: cancelButton, value: false});
  4596. buttons1.push({title: cancelButton, value: false});
  4597. // Share button
  4598. buttons.push({title: shareButton, value: true});
  4599. // Back button
  4600. buttons1.push({title: backButton, value: true});
  4601. var linkError = APP.translation.generateTranslationHTML(
  4602. "dialog.preziLinkError");
  4603. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4604. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4605. var openPreziState = {
  4606. state0: {
  4607. html: '<h2>' + html + '</h2>' +
  4608. '<input name="preziUrl" type="text" ' +
  4609. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4610. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4611. '\' placeholder="' + defaultUrl + '" autofocus>',
  4612. persistent: false,
  4613. buttons: buttons,
  4614. focus: ':input:first',
  4615. defaultButton: 0,
  4616. submit: function (e, v, m, f) {
  4617. e.preventDefault();
  4618. if(v)
  4619. {
  4620. var preziUrl = f.preziUrl;
  4621. if (preziUrl)
  4622. {
  4623. var urlValue
  4624. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4625. if (urlValue.indexOf('http://prezi.com/') != 0
  4626. && urlValue.indexOf('https://prezi.com/') != 0)
  4627. {
  4628. $.prompt.goToState('state1');
  4629. return false;
  4630. }
  4631. else {
  4632. var presIdTmp = urlValue.substring(
  4633. urlValue.indexOf("prezi.com/") + 10);
  4634. if (!isAlphanumeric(presIdTmp)
  4635. || presIdTmp.indexOf('/') < 2) {
  4636. $.prompt.goToState('state1');
  4637. return false;
  4638. }
  4639. else {
  4640. APP.xmpp.addToPresence("prezi", urlValue);
  4641. $.prompt.close();
  4642. }
  4643. }
  4644. }
  4645. }
  4646. else
  4647. $.prompt.close();
  4648. }
  4649. },
  4650. state1: {
  4651. html: '<h2>' + html + '</h2>' +
  4652. linkError,
  4653. persistent: false,
  4654. buttons: buttons1,
  4655. focus: ':input:first',
  4656. defaultButton: 1,
  4657. submit: function (e, v, m, f) {
  4658. e.preventDefault();
  4659. if (v === 0)
  4660. $.prompt.close();
  4661. else
  4662. $.prompt.goToState('state0');
  4663. }
  4664. }
  4665. };
  4666. messageHandler.openDialogWithStates(openPreziState);
  4667. }
  4668. }
  4669. };
  4670. /**
  4671. * A new presentation has been added.
  4672. *
  4673. * @param event the event indicating the add of a presentation
  4674. * @param jid the jid from which the presentation was added
  4675. * @param presUrl url of the presentation
  4676. * @param currentSlide the current slide to which we should move
  4677. */
  4678. function presentationAdded(event, jid, presUrl, currentSlide) {
  4679. console.log("presentation added", presUrl);
  4680. var presId = getPresentationId(presUrl);
  4681. var elementId = 'participant_'
  4682. + Strophe.getResourceFromJid(jid)
  4683. + '_' + presId;
  4684. VideoLayout.addPreziContainer(elementId);
  4685. var controlsEnabled = false;
  4686. if (jid === APP.xmpp.myJid())
  4687. controlsEnabled = true;
  4688. setPresentationVisible(true);
  4689. VideoLayout.setLargeVideoHover(
  4690. function (event) {
  4691. if (Prezi.isPresentationVisible()) {
  4692. var reloadButtonRight = window.innerWidth
  4693. - $('#presentation>iframe').offset().left
  4694. - $('#presentation>iframe').width();
  4695. $('#reloadPresentation').css({ right: reloadButtonRight,
  4696. display:'inline-block'});
  4697. }
  4698. },
  4699. function (event) {
  4700. if (!Prezi.isPresentationVisible())
  4701. $('#reloadPresentation').css({display:'none'});
  4702. else {
  4703. var e = event.toElement || event.relatedTarget;
  4704. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4705. $('#reloadPresentation').css({display:'none'});
  4706. }
  4707. });
  4708. preziPlayer = new PreziPlayer(
  4709. 'presentation',
  4710. {preziId: presId,
  4711. width: getPresentationWidth(),
  4712. height: getPresentationHeihgt(),
  4713. controls: controlsEnabled,
  4714. debug: true
  4715. });
  4716. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4717. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4718. console.log("prezi status", event.value);
  4719. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4720. if (jid != APP.xmpp.myJid())
  4721. preziPlayer.flyToStep(currentSlide);
  4722. }
  4723. });
  4724. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4725. console.log("event value", event.value);
  4726. APP.xmpp.addToPresence("preziSlide", event.value);
  4727. });
  4728. $("#" + elementId).css( 'background-image',
  4729. 'url(../images/avatarprezi.png)');
  4730. $("#" + elementId).click(
  4731. function () {
  4732. setPresentationVisible(true);
  4733. }
  4734. );
  4735. };
  4736. /**
  4737. * A presentation has been removed.
  4738. *
  4739. * @param event the event indicating the remove of a presentation
  4740. * @param jid the jid for which the presentation was removed
  4741. * @param the url of the presentation
  4742. */
  4743. function presentationRemoved(event, jid, presUrl) {
  4744. console.log('presentation removed', presUrl);
  4745. var presId = getPresentationId(presUrl);
  4746. setPresentationVisible(false);
  4747. $('#participant_'
  4748. + Strophe.getResourceFromJid(jid)
  4749. + '_' + presId).remove();
  4750. $('#presentation>iframe').remove();
  4751. if (preziPlayer != null) {
  4752. preziPlayer.destroy();
  4753. preziPlayer = null;
  4754. }
  4755. };
  4756. /**
  4757. * Indicates if the given string is an alphanumeric string.
  4758. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4759. * purpose of checking URIs.
  4760. */
  4761. function isAlphanumeric(unsafeText) {
  4762. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4763. return regex.test(unsafeText);
  4764. }
  4765. /**
  4766. * Returns the presentation id from the given url.
  4767. */
  4768. function getPresentationId (presUrl) {
  4769. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4770. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4771. }
  4772. /**
  4773. * Returns the presentation width.
  4774. */
  4775. function getPresentationWidth() {
  4776. var availableWidth = UIUtil.getAvailableVideoWidth();
  4777. var availableHeight = getPresentationHeihgt();
  4778. var aspectRatio = 16.0 / 9.0;
  4779. if (availableHeight < availableWidth / aspectRatio) {
  4780. availableWidth = Math.floor(availableHeight * aspectRatio);
  4781. }
  4782. return availableWidth;
  4783. }
  4784. /**
  4785. * Returns the presentation height.
  4786. */
  4787. function getPresentationHeihgt() {
  4788. var remoteVideos = $('#remoteVideos');
  4789. return window.innerHeight - remoteVideos.outerHeight();
  4790. }
  4791. /**
  4792. * Resizes the presentation iframe.
  4793. */
  4794. function resize() {
  4795. if ($('#presentation>iframe')) {
  4796. $('#presentation>iframe').width(getPresentationWidth());
  4797. $('#presentation>iframe').height(getPresentationHeihgt());
  4798. }
  4799. }
  4800. /**
  4801. * Presentation has been removed.
  4802. */
  4803. $(document).bind('presentationremoved.muc', presentationRemoved);
  4804. /**
  4805. * Presentation has been added.
  4806. */
  4807. $(document).bind('presentationadded.muc', presentationAdded);
  4808. /*
  4809. * Indicates presentation slide change.
  4810. */
  4811. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4812. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4813. preziPlayer.flyToStep(current);
  4814. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4815. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4816. preziPlayer.flyToStep(current, i);
  4817. }
  4818. }
  4819. });
  4820. $(window).resize(function () {
  4821. resize();
  4822. });
  4823. module.exports = Prezi;
  4824. },{"../toolbars/ToolbarToggler":31,"../util/MessageHandler":33,"../util/UIUtil":35,"../videolayout/VideoLayout":41,"./PreziPlayer":21}],21:[function(require,module,exports){
  4825. (function() {
  4826. "use strict";
  4827. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4828. window.PreziPlayer = (function() {
  4829. PreziPlayer.API_VERSION = 1;
  4830. PreziPlayer.CURRENT_STEP = 'currentStep';
  4831. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4832. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4833. PreziPlayer.STATUS_LOADING = 'loading';
  4834. PreziPlayer.STATUS_READY = 'ready';
  4835. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4836. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4837. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4838. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4839. PreziPlayer.EVENT_STATUS = "statusChange";
  4840. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4841. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4842. PreziPlayer.domain = "https://prezi.com";
  4843. PreziPlayer.path = "/player/";
  4844. PreziPlayer.players = {};
  4845. PreziPlayer.binded_methods = ['changesHandler'];
  4846. PreziPlayer.createMultiplePlayers = function(optionArray){
  4847. for(var i=0; i<optionArray.length; i++) {
  4848. var optionSet = optionArray[i];
  4849. new PreziPlayer(optionSet.id, optionSet);
  4850. };
  4851. };
  4852. PreziPlayer.messageReceived = function(event){
  4853. var message, item, player;
  4854. try {
  4855. message = JSON.parse(event.data);
  4856. if (message.id && (player = PreziPlayer.players[message.id])) {
  4857. if (player.options.debug === true) {
  4858. if (console && console.log)
  4859. console.log('received', message);
  4860. }
  4861. if (message.type === "changes") {
  4862. player.changesHandler(message);
  4863. }
  4864. for (var i = 0; i < player.callbacks.length; i++) {
  4865. item = player.callbacks[i];
  4866. if (item && message.type === item.event) {
  4867. item.callback(message);
  4868. }
  4869. }
  4870. }
  4871. } catch (e) { }
  4872. };
  4873. function PreziPlayer(id, options) {
  4874. var params, paramString = "", _this = this;
  4875. if (PreziPlayer.players[id]){
  4876. PreziPlayer.players[id].destroy();
  4877. }
  4878. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4879. var method_name = PreziPlayer.binded_methods[i];
  4880. _this[method_name] = __bind(_this[method_name], _this);
  4881. };
  4882. options = options || {};
  4883. this.options = options;
  4884. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4885. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4886. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4887. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4888. this.callbacks = [];
  4889. this.id = id;
  4890. this.embedTo = document.getElementById(id);
  4891. if (!this.embedTo) {
  4892. throw "The element id is not available.";
  4893. }
  4894. this.iframe = document.createElement('iframe');
  4895. params = [
  4896. { name: 'oid', value: options.preziId },
  4897. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4898. { name: 'controls', value: options.controls ? 1 : 0 }
  4899. ];
  4900. for(var i=0; i<params.length; i++) {
  4901. var param = params[i];
  4902. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4903. };
  4904. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4905. this.iframe.frameBorder = 0;
  4906. this.iframe.scrolling = "no";
  4907. this.iframe.width = options.width || 640;
  4908. this.iframe.height = options.height || 480;
  4909. this.embedTo.innerHTML = '';
  4910. // JITSI: IN CASE SOMETHING GOES WRONG.
  4911. try {
  4912. this.embedTo.appendChild(this.iframe);
  4913. }
  4914. catch (err) {
  4915. console.log("CATCH ERROR");
  4916. }
  4917. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4918. // crashes for us.
  4919. this.initPollInterval = setInterval(function(){
  4920. _this.sendMessage({'action': 'init'});
  4921. }, 500);
  4922. PreziPlayer.players[id] = this;
  4923. }
  4924. PreziPlayer.prototype.changesHandler = function(message) {
  4925. var key, value, j, item;
  4926. if (this.initPollInterval) {
  4927. clearInterval(this.initPollInterval);
  4928. this.initPollInterval = false;
  4929. }
  4930. for (key in message.data) {
  4931. if (message.data.hasOwnProperty(key)){
  4932. value = message.data[key];
  4933. this.values[key] = value;
  4934. for (j=0; j<this.callbacks.length; j++) {
  4935. item = this.callbacks[j];
  4936. if (item && item.event === key + "Change"){
  4937. item.callback({type: item.event, value: value});
  4938. }
  4939. }
  4940. }
  4941. }
  4942. };
  4943. PreziPlayer.prototype.destroy = function() {
  4944. if (this.initPollInterval) {
  4945. clearInterval(this.initPollInterval);
  4946. this.initPollInterval = false;
  4947. }
  4948. this.embedTo.innerHTML = '';
  4949. };
  4950. PreziPlayer.prototype.sendMessage = function(message) {
  4951. if (this.options.debug === true) {
  4952. if (console && console.log) console.log('sent', message);
  4953. }
  4954. message.version = PreziPlayer.API_VERSION;
  4955. message.id = this.id;
  4956. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4957. };
  4958. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4959. PreziPlayer.prototype.flyToNextStep = function() {
  4960. return this.sendMessage({
  4961. 'action': 'present',
  4962. 'data': ['moveToNextStep']
  4963. });
  4964. };
  4965. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4966. PreziPlayer.prototype.flyToPreviousStep = function() {
  4967. return this.sendMessage({
  4968. 'action': 'present',
  4969. 'data': ['moveToPrevStep']
  4970. });
  4971. };
  4972. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4973. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4974. var obj = this;
  4975. // check animation_step
  4976. if (animation_step > 0 &&
  4977. obj.values.animationCountOnSteps &&
  4978. obj.values.animationCountOnSteps[step] <= animation_step) {
  4979. animation_step = obj.values.animationCountOnSteps[step];
  4980. }
  4981. // jump to animation steps by calling flyToNextStep()
  4982. function doAnimationSteps() {
  4983. if (obj.values.isMoving == true) {
  4984. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4985. return;
  4986. }
  4987. while (animation_step-- > 0) {
  4988. obj.flyToNextStep(); // do the animation steps
  4989. }
  4990. }
  4991. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4992. // jump to the step
  4993. return this.sendMessage({
  4994. 'action': 'present',
  4995. 'data': ['moveToStep', step]
  4996. });
  4997. };
  4998. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4999. PreziPlayer.prototype.flyToObject = function(objectId) {
  5000. return this.sendMessage({
  5001. 'action': 'present',
  5002. 'data': ['moveToObject', objectId]
  5003. });
  5004. };
  5005. PreziPlayer.prototype.play = function(defaultDelay) {
  5006. return this.sendMessage({
  5007. 'action': 'present',
  5008. 'data': ['startAutoPlay', defaultDelay]
  5009. });
  5010. };
  5011. PreziPlayer.prototype.stop = function() {
  5012. return this.sendMessage({
  5013. 'action': 'present',
  5014. 'data': ['stopAutoPlay']
  5015. });
  5016. };
  5017. PreziPlayer.prototype.pause = function(defaultDelay) {
  5018. return this.sendMessage({
  5019. 'action': 'present',
  5020. 'data': ['pauseAutoPlay', defaultDelay]
  5021. });
  5022. };
  5023. PreziPlayer.prototype.getCurrentStep = function() {
  5024. return this.values.currentStep;
  5025. };
  5026. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  5027. return this.values.currentAnimationStep;
  5028. };
  5029. PreziPlayer.prototype.getCurrentObject = function() {
  5030. return this.values.currentObject;
  5031. };
  5032. PreziPlayer.prototype.getStatus = function() {
  5033. return this.values.status;
  5034. };
  5035. PreziPlayer.prototype.isPlaying = function() {
  5036. return this.values.isAutoPlaying;
  5037. };
  5038. PreziPlayer.prototype.getStepCount = function() {
  5039. return this.values.stepCount;
  5040. };
  5041. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  5042. return this.values.animationCountOnSteps;
  5043. };
  5044. PreziPlayer.prototype.getTitle = function() {
  5045. return this.values.title;
  5046. };
  5047. PreziPlayer.prototype.setDimensions = function(dims) {
  5048. for (var parameter in dims) {
  5049. this.iframe[parameter] = dims[parameter];
  5050. }
  5051. }
  5052. PreziPlayer.prototype.getDimensions = function() {
  5053. return {
  5054. width: parseInt(this.iframe.width, 10),
  5055. height: parseInt(this.iframe.height, 10)
  5056. }
  5057. }
  5058. PreziPlayer.prototype.on = function(event, callback) {
  5059. this.callbacks.push({
  5060. event: event,
  5061. callback: callback
  5062. });
  5063. };
  5064. PreziPlayer.prototype.off = function(event, callback) {
  5065. var j, item;
  5066. if (event === undefined) {
  5067. this.callbacks = [];
  5068. }
  5069. j = this.callbacks.length;
  5070. while (j--) {
  5071. item = this.callbacks[j];
  5072. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  5073. this.callbacks.splice(j, 1);
  5074. }
  5075. }
  5076. };
  5077. if (window.addEventListener) {
  5078. window.addEventListener('message', PreziPlayer.messageReceived, false);
  5079. } else {
  5080. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  5081. }
  5082. return PreziPlayer;
  5083. })();
  5084. })();
  5085. module.exports = PreziPlayer;
  5086. },{}],22:[function(require,module,exports){
  5087. /* global require, $ */
  5088. var Chat = require("./chat/Chat");
  5089. var ContactList = require("./contactlist/ContactList");
  5090. var Settings = require("./../../settings/Settings");
  5091. var SettingsMenu = require("./settings/SettingsMenu");
  5092. var VideoLayout = require("../videolayout/VideoLayout");
  5093. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  5094. var UIUtil = require("../util/UIUtil");
  5095. var LargeVideo = require("../videolayout/LargeVideo");
  5096. /**
  5097. * Toggler for the chat, contact list, settings menu, etc..
  5098. */
  5099. var PanelToggler = (function(my) {
  5100. var currentlyOpen = null;
  5101. var buttons = {
  5102. '#chatspace': '#chatBottomButton',
  5103. '#contactlist': '#contactListButton',
  5104. '#settingsmenu': '#toolbar_button_settings'
  5105. };
  5106. /**
  5107. * Toggles the windows in the side panel
  5108. * @param object the window that should be shown
  5109. * @param selector the selector for the element containing the panel
  5110. * @param onOpenComplete function to be called when the panel is opened
  5111. * @param onOpen function to be called if the window is going to be opened
  5112. * @param onClose function to be called if the window is going to be closed
  5113. */
  5114. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  5115. UIUtil.buttonClick(buttons[selector], "active");
  5116. if (object.isVisible()) {
  5117. $("#toast-container").animate({
  5118. right: '5px'
  5119. },
  5120. {
  5121. queue: false,
  5122. duration: 500
  5123. });
  5124. $(selector).hide("slide", {
  5125. direction: "right",
  5126. queue: false,
  5127. duration: 500
  5128. });
  5129. if(typeof onClose === "function") {
  5130. onClose();
  5131. }
  5132. currentlyOpen = null;
  5133. }
  5134. else {
  5135. // Undock the toolbar when the chat is shown and if we're in a
  5136. // video mode.
  5137. if (LargeVideo.isLargeVideoVisible()) {
  5138. ToolbarToggler.dockToolbar(false);
  5139. }
  5140. if(currentlyOpen) {
  5141. var current = $(currentlyOpen);
  5142. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  5143. current.css('z-index', 4);
  5144. setTimeout(function () {
  5145. current.css('display', 'none');
  5146. current.css('z-index', 5);
  5147. }, 500);
  5148. }
  5149. $("#toast-container").animate({
  5150. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  5151. },
  5152. {
  5153. queue: false,
  5154. duration: 500
  5155. });
  5156. $(selector).show("slide", {
  5157. direction: "right",
  5158. queue: false,
  5159. duration: 500,
  5160. complete: onOpenComplete
  5161. });
  5162. if(typeof onOpen === "function") {
  5163. onOpen();
  5164. }
  5165. currentlyOpen = selector;
  5166. }
  5167. };
  5168. /**
  5169. * Opens / closes the chat area.
  5170. */
  5171. my.toggleChat = function() {
  5172. var chatCompleteFunction = Chat.isVisible() ?
  5173. function() {} : function () {
  5174. Chat.scrollChatToBottom();
  5175. $('#chatspace').trigger('shown');
  5176. };
  5177. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  5178. toggle(Chat,
  5179. '#chatspace',
  5180. function () {
  5181. // Request the focus in the nickname field or the chat input field.
  5182. if ($('#nickname').css('visibility') === 'visible') {
  5183. $('#nickinput').focus();
  5184. } else {
  5185. $('#usermsg').focus();
  5186. }
  5187. },
  5188. null,
  5189. Chat.resizeChat,
  5190. null);
  5191. };
  5192. /**
  5193. * Opens / closes the contact list area.
  5194. */
  5195. my.toggleContactList = function () {
  5196. var completeFunction = ContactList.isVisible() ?
  5197. function() {} : function () { $('#contactlist').trigger('shown');};
  5198. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  5199. toggle(ContactList,
  5200. '#contactlist',
  5201. null,
  5202. function() {
  5203. ContactList.setVisualNotification(false);
  5204. },
  5205. null);
  5206. };
  5207. /**
  5208. * Opens / closes the settings menu
  5209. */
  5210. my.toggleSettingsMenu = function() {
  5211. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  5212. toggle(SettingsMenu,
  5213. '#settingsmenu',
  5214. null,
  5215. function() {
  5216. var settings = Settings.getSettings();
  5217. $('#setDisplayName').get(0).value = settings.displayName;
  5218. $('#setEmail').get(0).value = settings.email;
  5219. },
  5220. null);
  5221. };
  5222. /**
  5223. * Returns the size of the side panel.
  5224. */
  5225. my.getPanelSize = function () {
  5226. var availableHeight = window.innerHeight;
  5227. var availableWidth = window.innerWidth;
  5228. var panelWidth = 200;
  5229. if (availableWidth * 0.2 < 200) {
  5230. panelWidth = availableWidth * 0.2;
  5231. }
  5232. return [panelWidth, availableHeight];
  5233. };
  5234. my.isVisible = function() {
  5235. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  5236. };
  5237. return my;
  5238. }(PanelToggler || {}));
  5239. module.exports = PanelToggler;
  5240. },{"../toolbars/ToolbarToggler":31,"../util/UIUtil":35,"../videolayout/LargeVideo":37,"../videolayout/VideoLayout":41,"./../../settings/Settings":49,"./chat/Chat":23,"./contactlist/ContactList":27,"./settings/SettingsMenu":28}],23:[function(require,module,exports){
  5241. /* global APP, $, Util, nickname:true */
  5242. var Replacement = require("./Replacement");
  5243. var CommandsProcessor = require("./Commands");
  5244. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  5245. var smileys = require("./smileys.json").smileys;
  5246. var NicknameHandler = require("../../util/NicknameHandler");
  5247. var UIUtil = require("../../util/UIUtil");
  5248. var UIEvents = require("../../../../service/UI/UIEvents");
  5249. var notificationInterval = false;
  5250. var unreadMessages = 0;
  5251. /**
  5252. * Shows/hides a visual notification, indicating that a message has arrived.
  5253. */
  5254. function setVisualNotification(show) {
  5255. var unreadMsgElement = document.getElementById('unreadMessages');
  5256. var unreadMsgBottomElement
  5257. = document.getElementById('bottomUnreadMessages');
  5258. var glower = $('#toolbar_button_chat');
  5259. var bottomGlower = $('#chatBottomButton');
  5260. if (unreadMessages) {
  5261. unreadMsgElement.innerHTML = unreadMessages.toString();
  5262. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  5263. ToolbarToggler.dockToolbar(true);
  5264. var chatButtonElement
  5265. = document.getElementById('toolbar_button_chat');
  5266. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  5267. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  5268. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  5269. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  5270. unreadMsgElement.setAttribute(
  5271. 'style',
  5272. 'top:' + topIndent +
  5273. '; left:' + leftIndent + ';');
  5274. var chatBottomButtonElement
  5275. = document.getElementById('chatBottomButton').parentNode;
  5276. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  5277. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  5278. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  5279. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5280. unreadMsgBottomElement.setAttribute(
  5281. 'style',
  5282. 'top:' + bottomTopIndent +
  5283. '; left:' + bottomLeftIndent + ';');
  5284. if (!glower.hasClass('icon-chat-simple')) {
  5285. glower.removeClass('icon-chat');
  5286. glower.addClass('icon-chat-simple');
  5287. }
  5288. }
  5289. else {
  5290. unreadMsgElement.innerHTML = '';
  5291. unreadMsgBottomElement.innerHTML = '';
  5292. glower.removeClass('icon-chat-simple');
  5293. glower.addClass('icon-chat');
  5294. }
  5295. if (show && !notificationInterval) {
  5296. notificationInterval = window.setInterval(function () {
  5297. glower.toggleClass('active');
  5298. bottomGlower.toggleClass('active glowing');
  5299. }, 800);
  5300. }
  5301. else if (!show && notificationInterval) {
  5302. window.clearInterval(notificationInterval);
  5303. notificationInterval = false;
  5304. glower.removeClass('active');
  5305. bottomGlower.removeClass('glowing');
  5306. bottomGlower.addClass('active');
  5307. }
  5308. }
  5309. /**
  5310. * Returns the current time in the format it is shown to the user
  5311. * @returns {string}
  5312. */
  5313. function getCurrentTime(stamp) {
  5314. var now = (stamp? new Date(stamp): new Date());
  5315. var hour = now.getHours();
  5316. var minute = now.getMinutes();
  5317. var second = now.getSeconds();
  5318. if(hour.toString().length === 1) {
  5319. hour = '0'+hour;
  5320. }
  5321. if(minute.toString().length === 1) {
  5322. minute = '0'+minute;
  5323. }
  5324. if(second.toString().length === 1) {
  5325. second = '0'+second;
  5326. }
  5327. return hour+':'+minute+':'+second;
  5328. }
  5329. function toggleSmileys() {
  5330. var smileys = $('#smileysContainer');
  5331. if(!smileys.is(':visible')) {
  5332. smileys.show("slide", { direction: "down", duration: 300});
  5333. } else {
  5334. smileys.hide("slide", { direction: "down", duration: 300});
  5335. }
  5336. $('#usermsg').focus();
  5337. }
  5338. function addClickFunction(smiley, number) {
  5339. smiley.onclick = function addSmileyToMessage() {
  5340. var usermsg = $('#usermsg');
  5341. var message = usermsg.val();
  5342. message += smileys['smiley' + number];
  5343. usermsg.val(message);
  5344. usermsg.get(0).setSelectionRange(message.length, message.length);
  5345. toggleSmileys();
  5346. usermsg.focus();
  5347. };
  5348. }
  5349. /**
  5350. * Adds the smileys container to the chat
  5351. */
  5352. function addSmileys() {
  5353. var smileysContainer = document.createElement('div');
  5354. smileysContainer.id = 'smileysContainer';
  5355. for(var i = 1; i <= 21; i++) {
  5356. var smileyContainer = document.createElement('div');
  5357. smileyContainer.id = 'smiley' + i;
  5358. smileyContainer.className = 'smileyContainer';
  5359. var smiley = document.createElement('img');
  5360. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5361. smiley.className = 'smiley';
  5362. addClickFunction(smiley, i);
  5363. smileyContainer.appendChild(smiley);
  5364. smileysContainer.appendChild(smileyContainer);
  5365. }
  5366. $("#chatspace").append(smileysContainer);
  5367. }
  5368. /**
  5369. * Resizes the chat conversation.
  5370. */
  5371. function resizeChatConversation() {
  5372. var msgareaHeight = $('#usermsg').outerHeight();
  5373. var chatspace = $('#chatspace');
  5374. var width = chatspace.width();
  5375. var chat = $('#chatconversation');
  5376. var smileys = $('#smileysarea');
  5377. smileys.height(msgareaHeight);
  5378. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5379. $('#smileysContainer').css('bottom', msgareaHeight);
  5380. chat.width(width - 10);
  5381. chat.height(window.innerHeight - 15 - msgareaHeight);
  5382. }
  5383. /**
  5384. * Chat related user interface.
  5385. */
  5386. var Chat = (function (my) {
  5387. /**
  5388. * Initializes chat related interface.
  5389. */
  5390. my.init = function () {
  5391. if(NicknameHandler.getNickname())
  5392. Chat.setChatConversationMode(true);
  5393. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5394. function (nickname) {
  5395. Chat.setChatConversationMode(true);
  5396. });
  5397. $('#nickinput').keydown(function (event) {
  5398. if (event.keyCode === 13) {
  5399. event.preventDefault();
  5400. var val = UIUtil.escapeHtml(this.value);
  5401. this.value = '';
  5402. if (!NicknameHandler.getNickname()) {
  5403. NicknameHandler.setNickname(val);
  5404. return;
  5405. }
  5406. }
  5407. });
  5408. var usermsg = $('#usermsg');
  5409. usermsg.keydown(function (event) {
  5410. if (event.keyCode === 13) {
  5411. event.preventDefault();
  5412. var value = this.value;
  5413. usermsg.val('').trigger('autosize.resize');
  5414. this.focus();
  5415. var command = new CommandsProcessor(value);
  5416. if(command.isCommand()) {
  5417. command.processCommand();
  5418. }
  5419. else {
  5420. var message = UIUtil.escapeHtml(value);
  5421. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5422. }
  5423. }
  5424. });
  5425. var onTextAreaResize = function () {
  5426. resizeChatConversation();
  5427. Chat.scrollChatToBottom();
  5428. };
  5429. usermsg.autosize({callback: onTextAreaResize});
  5430. $("#chatspace").bind("shown",
  5431. function () {
  5432. unreadMessages = 0;
  5433. setVisualNotification(false);
  5434. });
  5435. addSmileys();
  5436. };
  5437. /**
  5438. * Appends the given message to the chat conversation.
  5439. */
  5440. my.updateChatConversation =
  5441. function (from, displayName, message, myjid, stamp) {
  5442. var divClassName = '';
  5443. if (APP.xmpp.myJid() === from) {
  5444. divClassName = "localuser";
  5445. }
  5446. else {
  5447. divClassName = "remoteuser";
  5448. if (!Chat.isVisible()) {
  5449. unreadMessages++;
  5450. UIUtil.playSoundNotification('chatNotification');
  5451. setVisualNotification(true);
  5452. }
  5453. }
  5454. // replace links and smileys
  5455. // Strophe already escapes special symbols on sending,
  5456. // so we escape here only tags to avoid double &amp;
  5457. var escMessage = message.replace(/</g, '&lt;').
  5458. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5459. var escDisplayName = UIUtil.escapeHtml(displayName);
  5460. message = Replacement.processReplacements(escMessage);
  5461. var messageContainer =
  5462. '<div class="chatmessage">'+
  5463. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5464. '<div class="username ' + divClassName +'">' + escDisplayName +
  5465. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5466. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5467. '</div>';
  5468. $('#chatconversation').append(messageContainer);
  5469. $('#chatconversation').animate(
  5470. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5471. };
  5472. /**
  5473. * Appends error message to the conversation
  5474. * @param errorMessage the received error message.
  5475. * @param originalText the original message.
  5476. */
  5477. my.chatAddError = function(errorMessage, originalText) {
  5478. errorMessage = UIUtil.escapeHtml(errorMessage);
  5479. originalText = UIUtil.escapeHtml(originalText);
  5480. $('#chatconversation').append(
  5481. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5482. (originalText? (' \"'+ originalText + '\"') : "") +
  5483. ' was not sent.' +
  5484. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5485. $('#chatconversation').animate(
  5486. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5487. };
  5488. /**
  5489. * Sets the subject to the UI
  5490. * @param subject the subject
  5491. */
  5492. my.chatSetSubject = function(subject) {
  5493. if (subject)
  5494. subject = subject.trim();
  5495. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5496. if(subject === "") {
  5497. $("#subject").css({display: "none"});
  5498. }
  5499. else {
  5500. $("#subject").css({display: "block"});
  5501. }
  5502. };
  5503. /**
  5504. * Sets the chat conversation mode.
  5505. */
  5506. my.setChatConversationMode = function (isConversationMode) {
  5507. if (isConversationMode) {
  5508. $('#nickname').css({visibility: 'hidden'});
  5509. $('#chatconversation').css({visibility: 'visible'});
  5510. $('#usermsg').css({visibility: 'visible'});
  5511. $('#smileysarea').css({visibility: 'visible'});
  5512. $('#usermsg').focus();
  5513. }
  5514. };
  5515. /**
  5516. * Resizes the chat area.
  5517. */
  5518. my.resizeChat = function () {
  5519. var chatSize = require("../SidePanelToggler").getPanelSize();
  5520. $('#chatspace').width(chatSize[0]);
  5521. $('#chatspace').height(chatSize[1]);
  5522. resizeChatConversation();
  5523. };
  5524. /**
  5525. * Indicates if the chat is currently visible.
  5526. */
  5527. my.isVisible = function () {
  5528. return $('#chatspace').is(":visible");
  5529. };
  5530. /**
  5531. * Shows and hides the window with the smileys
  5532. */
  5533. my.toggleSmileys = toggleSmileys;
  5534. /**
  5535. * Scrolls chat to the bottom.
  5536. */
  5537. my.scrollChatToBottom = function() {
  5538. setTimeout(function () {
  5539. $('#chatconversation').scrollTop(
  5540. $('#chatconversation')[0].scrollHeight);
  5541. }, 5);
  5542. };
  5543. return my;
  5544. }(Chat || {}));
  5545. module.exports = Chat;
  5546. },{"../../../../service/UI/UIEvents":114,"../../toolbars/ToolbarToggler":31,"../../util/NicknameHandler":34,"../../util/UIUtil":35,"../SidePanelToggler":22,"./Commands":24,"./Replacement":25,"./smileys.json":26}],24:[function(require,module,exports){
  5547. /* global APP, require */
  5548. var UIUtil = require("../../util/UIUtil");
  5549. /**
  5550. * List with supported commands. The keys are the names of the commands and
  5551. * the value is the function that processes the message.
  5552. * @type {{String: function}}
  5553. */
  5554. var commands = {
  5555. "topic" : processTopic
  5556. };
  5557. /**
  5558. * Extracts the command from the message.
  5559. * @param message the received message
  5560. * @returns {string} the command
  5561. */
  5562. function getCommand(message) {
  5563. if(message) {
  5564. for(var command in commands) {
  5565. if(message.indexOf("/" + command) == 0)
  5566. return command;
  5567. }
  5568. }
  5569. return "";
  5570. }
  5571. /**
  5572. * Processes the data for topic command.
  5573. * @param commandArguments the arguments of the topic command.
  5574. */
  5575. function processTopic(commandArguments) {
  5576. var topic = UIUtil.escapeHtml(commandArguments);
  5577. APP.xmpp.setSubject(topic);
  5578. }
  5579. /**
  5580. * Constructs a new CommandProccessor instance from a message that
  5581. * handles commands received via chat messages.
  5582. * @param message the message
  5583. * @constructor
  5584. */
  5585. function CommandsProcessor(message) {
  5586. var command = getCommand(message);
  5587. /**
  5588. * Returns the name of the command.
  5589. * @returns {String} the command
  5590. */
  5591. this.getCommand = function() {
  5592. return command;
  5593. };
  5594. var messageArgument = message.substr(command.length + 2);
  5595. /**
  5596. * Returns the arguments of the command.
  5597. * @returns {string}
  5598. */
  5599. this.getArgument = function() {
  5600. return messageArgument;
  5601. };
  5602. }
  5603. /**
  5604. * Checks whether this instance is valid command or not.
  5605. * @returns {boolean}
  5606. */
  5607. CommandsProcessor.prototype.isCommand = function() {
  5608. if (this.getCommand())
  5609. return true;
  5610. return false;
  5611. };
  5612. /**
  5613. * Processes the command.
  5614. */
  5615. CommandsProcessor.prototype.processCommand = function() {
  5616. if(!this.isCommand())
  5617. return;
  5618. commands[this.getCommand()](this.getArgument());
  5619. };
  5620. module.exports = CommandsProcessor;
  5621. },{"../../util/UIUtil":35}],25:[function(require,module,exports){
  5622. var Smileys = require("./smileys.json");
  5623. /**
  5624. * Processes links and smileys in "body"
  5625. */
  5626. function processReplacements(body)
  5627. {
  5628. //make links clickable
  5629. body = linkify(body);
  5630. //add smileys
  5631. body = smilify(body);
  5632. return body;
  5633. }
  5634. /**
  5635. * Finds and replaces all links in the links in "body"
  5636. * with their <a href=""></a>
  5637. */
  5638. function linkify(inputText)
  5639. {
  5640. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5641. //URLs starting with http://, https://, or ftp://
  5642. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5643. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5644. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5645. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5646. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5647. //Change email addresses to mailto:: links.
  5648. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5649. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5650. return replacedText;
  5651. }
  5652. /**
  5653. * Replaces common smiley strings with images
  5654. */
  5655. function smilify(body)
  5656. {
  5657. if(!body) {
  5658. return body;
  5659. }
  5660. var regexs = Smileys["regexs"];
  5661. for(var smiley in regexs) {
  5662. if(regexs.hasOwnProperty(smiley)) {
  5663. body = body.replace(regexs[smiley],
  5664. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5665. }
  5666. }
  5667. return body;
  5668. }
  5669. module.exports = {
  5670. processReplacements: processReplacements,
  5671. linkify: linkify
  5672. };
  5673. },{"./smileys.json":26}],26:[function(require,module,exports){
  5674. module.exports={
  5675. "smileys": {
  5676. "smiley1": ":)",
  5677. "smiley2": ":(",
  5678. "smiley3": ":D",
  5679. "smiley4": "(y)",
  5680. "smiley5": " :P",
  5681. "smiley6": "(wave)",
  5682. "smiley7": "(blush)",
  5683. "smiley8": "(chuckle)",
  5684. "smiley9": "(shocked)",
  5685. "smiley10": ":*",
  5686. "smiley11": "(n)",
  5687. "smiley12": "(search)",
  5688. "smiley13": " <3",
  5689. "smiley14": "(oops)",
  5690. "smiley15": "(angry)",
  5691. "smiley16": "(angel)",
  5692. "smiley17": "(sick)",
  5693. "smiley18": ";(",
  5694. "smiley19": "(bomb)",
  5695. "smiley20": "(clap)",
  5696. "smiley21": " ;)"
  5697. },
  5698. "regexs": {
  5699. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5700. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5701. "smiley1": /(:-\)|:\))/gi,
  5702. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5703. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5704. "smiley6": /(\(wave\))/gi,
  5705. "smiley7": /(\(blush\))/gi,
  5706. "smiley8": /(\(chuckle\))/gi,
  5707. "smiley9": /(:-0|\(shocked\))/gi,
  5708. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5709. "smiley11": /(\(n\))/gi,
  5710. "smiley12": /(\(search\))/g,
  5711. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5712. "smiley14": /(\(oops\))/gi,
  5713. "smiley15": /(\(angry\))/gi,
  5714. "smiley16": /(\(angel\))/gi,
  5715. "smiley17": /(\(sick\))/gi,
  5716. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5717. "smiley19": /(\(bomb\))/gi,
  5718. "smiley20": /(\(clap\))/gi,
  5719. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5720. }
  5721. }
  5722. },{}],27:[function(require,module,exports){
  5723. /* global $, APP, Strophe */
  5724. var Avatar = require('../../avatar/Avatar');
  5725. var numberOfContacts = 0;
  5726. var notificationInterval;
  5727. /**
  5728. * Updates the number of participants in the contact list button and sets
  5729. * the glow
  5730. * @param delta indicates whether a new user has joined (1) or someone has
  5731. * left(-1)
  5732. */
  5733. function updateNumberOfParticipants(delta) {
  5734. numberOfContacts += delta;
  5735. if (numberOfContacts === 1) {
  5736. // when the user is alone we don't show the number of participants
  5737. $("#numberOfParticipants").text('');
  5738. ContactList.setVisualNotification(false);
  5739. } else if (numberOfContacts > 1) {
  5740. ContactList.setVisualNotification(!ContactList.isVisible());
  5741. $("#numberOfParticipants").text(numberOfContacts);
  5742. } else {
  5743. console.error("Invalid number of participants: " + numberOfContacts);
  5744. }
  5745. }
  5746. /**
  5747. * Creates the avatar element.
  5748. *
  5749. * @return {object} the newly created avatar element
  5750. */
  5751. function createAvatar(jid) {
  5752. var avatar = document.createElement('img');
  5753. avatar.className = "icon-avatar avatar";
  5754. avatar.src = Avatar.getContactListUrl(jid);
  5755. return avatar;
  5756. }
  5757. /**
  5758. * Creates the display name paragraph.
  5759. *
  5760. * @param displayName the display name to set
  5761. */
  5762. function createDisplayNameParagraph(key, displayName) {
  5763. var p = document.createElement('p');
  5764. if(displayName)
  5765. p.innerText = displayName;
  5766. else if(key) {
  5767. p.setAttribute("data-i18n",key);
  5768. p.innerText = APP.translation.translateString(key);
  5769. }
  5770. return p;
  5771. }
  5772. function stopGlowing(glower) {
  5773. window.clearInterval(notificationInterval);
  5774. notificationInterval = false;
  5775. glower.removeClass('glowing');
  5776. if (!ContactList.isVisible()) {
  5777. glower.removeClass('active');
  5778. }
  5779. }
  5780. /**
  5781. * Contact list.
  5782. */
  5783. var ContactList = {
  5784. /**
  5785. * Indicates if the chat is currently visible.
  5786. *
  5787. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5788. * otherwise
  5789. */
  5790. isVisible: function () {
  5791. return $('#contactlist').is(":visible");
  5792. },
  5793. /**
  5794. * Adds a contact for the given peerJid if such doesn't yet exist.
  5795. *
  5796. * @param peerJid the peerJid corresponding to the contact
  5797. */
  5798. ensureAddContact: function (peerJid) {
  5799. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5800. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5801. if (!contact || contact.length <= 0)
  5802. ContactList.addContact(peerJid);
  5803. },
  5804. /**
  5805. * Adds a contact for the given peer jid.
  5806. *
  5807. * @param peerJid the jid of the contact to add
  5808. */
  5809. addContact: function (peerJid) {
  5810. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5811. var contactlist = $('#contacts');
  5812. var newContact = document.createElement('li');
  5813. newContact.id = resourceJid;
  5814. newContact.className = "clickable";
  5815. newContact.onclick = function (event) {
  5816. if (event.currentTarget.className === "clickable") {
  5817. $(ContactList).trigger('contactclicked', [peerJid]);
  5818. }
  5819. };
  5820. newContact.appendChild(createAvatar(peerJid));
  5821. newContact.appendChild(createDisplayNameParagraph("participant"));
  5822. if (resourceJid === APP.xmpp.myResource()) {
  5823. contactlist.prepend(newContact);
  5824. }
  5825. else {
  5826. contactlist.append(newContact);
  5827. }
  5828. updateNumberOfParticipants(1);
  5829. },
  5830. /**
  5831. * Removes a contact for the given peer jid.
  5832. *
  5833. * @param peerJid the peerJid corresponding to the contact to remove
  5834. */
  5835. removeContact: function (peerJid) {
  5836. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5837. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5838. if (contact && contact.length > 0) {
  5839. var contactlist = $('#contactlist>ul');
  5840. contactlist.get(0).removeChild(contact.get(0));
  5841. updateNumberOfParticipants(-1);
  5842. }
  5843. },
  5844. setVisualNotification: function (show, stopGlowingIn) {
  5845. var glower = $('#contactListButton');
  5846. if (show && !notificationInterval) {
  5847. notificationInterval = window.setInterval(function () {
  5848. glower.toggleClass('active glowing');
  5849. }, 800);
  5850. }
  5851. else if (!show && notificationInterval) {
  5852. stopGlowing(glower);
  5853. }
  5854. if (stopGlowingIn) {
  5855. setTimeout(function () {
  5856. stopGlowing(glower);
  5857. }, stopGlowingIn);
  5858. }
  5859. },
  5860. setClickable: function (resourceJid, isClickable) {
  5861. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5862. if (isClickable) {
  5863. contact.addClass('clickable');
  5864. } else {
  5865. contact.removeClass('clickable');
  5866. }
  5867. },
  5868. onDisplayNameChange: function (peerJid, displayName) {
  5869. if (peerJid === 'localVideoContainer')
  5870. peerJid = APP.xmpp.myJid();
  5871. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5872. var contactName = $('#contacts #' + resourceJid + '>p');
  5873. if (contactName && displayName && displayName.length > 0)
  5874. contactName.html(displayName);
  5875. },
  5876. userAvatarChanged: function (resourceJid, contactListUrl) {
  5877. // set the avatar in the contact list
  5878. var contact = $('#' + resourceJid + '>img');
  5879. if (contact && contact.length > 0) {
  5880. contact.get(0).src = contactListUrl;
  5881. }
  5882. }
  5883. };
  5884. module.exports = ContactList;
  5885. },{"../../avatar/Avatar":18}],28:[function(require,module,exports){
  5886. /* global APP, $ */
  5887. var Avatar = require("../../avatar/Avatar");
  5888. var Settings = require("./../../../settings/Settings");
  5889. var UIUtil = require("../../util/UIUtil");
  5890. var languages = require("../../../../service/translation/languages");
  5891. function generateLanguagesSelectBox() {
  5892. var currentLang = APP.translation.getCurrentLanguage();
  5893. var html = "<select id=\"languages_selectbox\">";
  5894. var langArray = languages.getLanguages();
  5895. for(var i = 0; i < langArray.length; i++) {
  5896. var lang = langArray[i];
  5897. html += "<option ";
  5898. if(lang === currentLang)
  5899. html += "selected ";
  5900. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5901. html += "</option>";
  5902. }
  5903. return html + "</select>";
  5904. }
  5905. var SettingsMenu = {
  5906. init: function () {
  5907. var startMutedSelector = $("#startMutedOptions");
  5908. startMutedSelector.before(generateLanguagesSelectBox());
  5909. APP.translation.translateElement($("#languages_selectbox"));
  5910. $('#settingsmenu>input').keyup(function(event){
  5911. if(event.keyCode === 13) {//enter
  5912. SettingsMenu.update();
  5913. }
  5914. });
  5915. if (APP.xmpp.isModerator()) {
  5916. startMutedSelector.css("display", "block");
  5917. }
  5918. else {
  5919. startMutedSelector.css("display", "none");
  5920. }
  5921. $("#updateSettings").click(function () {
  5922. SettingsMenu.update();
  5923. });
  5924. },
  5925. onRoleChanged: function () {
  5926. if(APP.xmpp.isModerator()) {
  5927. $("#startMutedOptions").css("display", "block");
  5928. }
  5929. else {
  5930. $("#startMutedOptions").css("display", "none");
  5931. }
  5932. },
  5933. setStartMuted: function (audio, video) {
  5934. $("#startAudioMuted").attr("checked", audio);
  5935. $("#startVideoMuted").attr("checked", video);
  5936. },
  5937. update: function() {
  5938. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5939. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5940. if(newDisplayName) {
  5941. var displayName = Settings.setDisplayName(newDisplayName);
  5942. APP.xmpp.addToPresence("displayName", displayName, true);
  5943. }
  5944. var language = $("#languages_selectbox").val();
  5945. APP.translation.setLanguage(language);
  5946. Settings.setLanguage(language);
  5947. APP.xmpp.addToPresence("email", newEmail);
  5948. var email = Settings.setEmail(newEmail);
  5949. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5950. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5951. APP.xmpp.addToPresence("startMuted",
  5952. [startAudioMuted, startVideoMuted]);
  5953. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5954. },
  5955. isVisible: function() {
  5956. return $('#settingsmenu').is(':visible');
  5957. },
  5958. setDisplayName: function(newDisplayName) {
  5959. var displayName = Settings.setDisplayName(newDisplayName);
  5960. $('#setDisplayName').get(0).value = displayName;
  5961. },
  5962. onDisplayNameChange: function(peerJid, newDisplayName) {
  5963. if(peerJid === 'localVideoContainer' ||
  5964. peerJid === APP.xmpp.myJid()) {
  5965. this.setDisplayName(newDisplayName);
  5966. }
  5967. },
  5968. changeAvatar: function (thumbUrl) {
  5969. $('#avatar').get(0).src = thumbUrl;
  5970. }
  5971. };
  5972. module.exports = SettingsMenu;
  5973. },{"../../../../service/translation/languages":119,"../../avatar/Avatar":18,"../../util/UIUtil":35,"./../../../settings/Settings":49}],29:[function(require,module,exports){
  5974. /* global $ */
  5975. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5976. var buttonHandlers = {
  5977. "bottom_toolbar_contact_list": function () {
  5978. BottomToolbar.toggleContactList();
  5979. },
  5980. "bottom_toolbar_film_strip": function () {
  5981. BottomToolbar.toggleFilmStrip();
  5982. },
  5983. "bottom_toolbar_chat": function () {
  5984. BottomToolbar.toggleChat();
  5985. }
  5986. };
  5987. var BottomToolbar = (function (my) {
  5988. my.init = function () {
  5989. for(var k in buttonHandlers)
  5990. $("#" + k).click(buttonHandlers[k]);
  5991. };
  5992. my.toggleChat = function() {
  5993. PanelToggler.toggleChat();
  5994. };
  5995. my.toggleContactList = function() {
  5996. PanelToggler.toggleContactList();
  5997. };
  5998. my.toggleFilmStrip = function() {
  5999. var filmstrip = $("#remoteVideos");
  6000. filmstrip.toggleClass("hidden");
  6001. };
  6002. $(document).bind("remotevideo.resized", function (event, width, height) {
  6003. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  6004. $('#bottomToolbar').css({bottom: bottom + 'px'});
  6005. });
  6006. return my;
  6007. }(BottomToolbar || {}));
  6008. module.exports = BottomToolbar;
  6009. },{"../side_pannels/SidePanelToggler":22}],30:[function(require,module,exports){
  6010. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  6011. Util */
  6012. var messageHandler = require("../util/MessageHandler");
  6013. var BottomToolbar = require("./BottomToolbar");
  6014. var Prezi = require("../prezi/Prezi");
  6015. var Etherpad = require("../etherpad/Etherpad");
  6016. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6017. var Authentication = require("../authentication/Authentication");
  6018. var UIUtil = require("../util/UIUtil");
  6019. var AuthenticationEvents
  6020. = require("../../../service/authentication/AuthenticationEvents");
  6021. var roomUrl = null;
  6022. var sharedKey = '';
  6023. var UI = null;
  6024. var recordingToaster = null;
  6025. var buttonHandlers = {
  6026. "toolbar_button_mute": function () {
  6027. return APP.UI.toggleAudio();
  6028. },
  6029. "toolbar_button_camera": function () {
  6030. return APP.UI.toggleVideo();
  6031. },
  6032. /*"toolbar_button_authentication": function () {
  6033. return Toolbar.authenticateClicked();
  6034. },*/
  6035. "toolbar_button_record": function () {
  6036. return toggleRecording();
  6037. },
  6038. "toolbar_button_security": function () {
  6039. return Toolbar.openLockDialog();
  6040. },
  6041. "toolbar_button_link": function () {
  6042. return Toolbar.openLinkDialog();
  6043. },
  6044. "toolbar_button_chat": function () {
  6045. return BottomToolbar.toggleChat();
  6046. },
  6047. "toolbar_button_prezi": function () {
  6048. return Prezi.openPreziDialog();
  6049. },
  6050. "toolbar_button_etherpad": function () {
  6051. return Etherpad.toggleEtherpad(0);
  6052. },
  6053. "toolbar_button_desktopsharing": function () {
  6054. return APP.desktopsharing.toggleScreenSharing();
  6055. },
  6056. "toolbar_button_fullScreen": function() {
  6057. UIUtil.buttonClick("#toolbar_button_fullScreen", "icon-full-screen icon-exit-full-screen");
  6058. return Toolbar.toggleFullScreen();
  6059. },
  6060. "toolbar_button_sip": function () {
  6061. return callSipButtonClicked();
  6062. },
  6063. "toolbar_button_dialpad": function () {
  6064. return dialpadButtonClicked();
  6065. },
  6066. "toolbar_button_settings": function () {
  6067. PanelToggler.toggleSettingsMenu();
  6068. },
  6069. "toolbar_button_hangup": function () {
  6070. return hangup();
  6071. },
  6072. "toolbar_button_login": function () {
  6073. Toolbar.authenticateClicked();
  6074. },
  6075. "toolbar_button_logout": function () {
  6076. // Ask for confirmation
  6077. messageHandler.openTwoButtonDialog(
  6078. "dialog.logoutTitle",
  6079. null,
  6080. "dialog.logoutQuestion",
  6081. null,
  6082. false,
  6083. "dialog.Yes",
  6084. function (evt, yes) {
  6085. if (yes) {
  6086. APP.xmpp.logout(function (url) {
  6087. if (url) {
  6088. window.location.href = url;
  6089. } else {
  6090. hangup();
  6091. }
  6092. });
  6093. }
  6094. });
  6095. }
  6096. };
  6097. function hangup() {
  6098. APP.xmpp.disposeConference();
  6099. if(config.enableWelcomePage) {
  6100. setTimeout(function() {
  6101. window.localStorage.welcomePageDisabled = false;
  6102. window.location.pathname = "/";
  6103. }, 10000);
  6104. }
  6105. var title = APP.translation.generateTranslationHTML(
  6106. "dialog.sessTerminated");
  6107. var msg = APP.translation.generateTranslationHTML(
  6108. "dialog.hungUp");
  6109. var button = APP.translation.generateTranslationHTML(
  6110. "dialog.joinAgain");
  6111. var buttons = [];
  6112. buttons.push({title: button, value: true});
  6113. UI.messageHandler.openDialog(
  6114. title,
  6115. msg,
  6116. true,
  6117. buttons,
  6118. function(event, value, message, formVals) {
  6119. window.location.reload();
  6120. return false;
  6121. }
  6122. );
  6123. }
  6124. /**
  6125. * Starts or stops the recording for the conference.
  6126. */
  6127. function toggleRecording(predefinedToken) {
  6128. APP.xmpp.toggleRecording(function (callback) {
  6129. if (predefinedToken) {
  6130. callback(UIUtil.escapeHtml(predefinedToken));
  6131. return;
  6132. }
  6133. var msg = APP.translation.generateTranslationHTML(
  6134. "dialog.recordingToken");
  6135. var token = APP.translation.translateString("dialog.token");
  6136. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  6137. '<h2>' + msg + '</h2>' +
  6138. '<input name="recordingToken" type="text" ' +
  6139. ' data-i18n="[placeholder]dialog.token" ' +
  6140. 'placeholder="' + token + '" autofocus>',
  6141. false,
  6142. "dialog.Save",
  6143. function (e, v, m, f) {
  6144. if (v) {
  6145. var token = f.recordingToken;
  6146. if (token) {
  6147. callback(UIUtil.escapeHtml(token));
  6148. }
  6149. }
  6150. },
  6151. null,
  6152. function () { },
  6153. ':input:first'
  6154. );
  6155. }, Toolbar.setRecordingButtonState);
  6156. }
  6157. /**
  6158. * Locks / unlocks the room.
  6159. */
  6160. function lockRoom(lock) {
  6161. var currentSharedKey = '';
  6162. if (lock)
  6163. currentSharedKey = sharedKey;
  6164. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  6165. // password is required
  6166. if (sharedKey) {
  6167. console.log('set room password');
  6168. Toolbar.lockLockButton();
  6169. }
  6170. else {
  6171. console.log('removed room password');
  6172. Toolbar.unlockLockButton();
  6173. }
  6174. }, function (err) {
  6175. console.warn('setting password failed', err);
  6176. messageHandler.showError("dialog.lockTitle",
  6177. "dialog.lockMessage");
  6178. Toolbar.setSharedKey('');
  6179. }, function () {
  6180. console.warn('room passwords not supported');
  6181. messageHandler.showError("dialog.warning",
  6182. "dialog.passwordNotSupported");
  6183. Toolbar.setSharedKey('');
  6184. });
  6185. }
  6186. /**
  6187. * Invite participants to conference.
  6188. */
  6189. function inviteParticipants() {
  6190. if (roomUrl === null)
  6191. return;
  6192. var sharedKeyText = "";
  6193. if (sharedKey && sharedKey.length > 0) {
  6194. sharedKeyText =
  6195. APP.translation.translateString("email.sharedKey",
  6196. {sharedKey: sharedKey});
  6197. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  6198. }
  6199. var supportedBrowsers = "Chromium, Google Chrome " +
  6200. APP.translation.translateString("email.and") + " Opera";
  6201. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  6202. var subject = APP.translation.translateString("email.subject",
  6203. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  6204. var body = APP.translation.translateString("email.body",
  6205. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  6206. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  6207. body = body.replace(/\n/g, "%0D%0A");
  6208. if (window.localStorage.displayname) {
  6209. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  6210. }
  6211. if (interfaceConfig.INVITATION_POWERED_BY) {
  6212. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  6213. }
  6214. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  6215. }
  6216. function dialpadButtonClicked() {
  6217. //TODO show the dialpad box
  6218. }
  6219. function callSipButtonClicked() {
  6220. var defaultNumber
  6221. = config.defaultSipNumber ? config.defaultSipNumber : '';
  6222. var sipMsg = APP.translation.generateTranslationHTML(
  6223. "dialog.sipMsg");
  6224. messageHandler.openTwoButtonDialog(null, null, null,
  6225. '<h2>' + sipMsg + '</h2>' +
  6226. '<input name="sipNumber" type="text"' +
  6227. ' value="' + defaultNumber + '" autofocus>',
  6228. false,
  6229. "dialog.Dial",
  6230. function (e, v, m, f) {
  6231. if (v) {
  6232. var numberInput = f.sipNumber;
  6233. if (numberInput) {
  6234. APP.xmpp.dial(
  6235. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  6236. }
  6237. }
  6238. },
  6239. null, null, ':input:first'
  6240. );
  6241. }
  6242. var Toolbar = (function (my) {
  6243. my.init = function (ui) {
  6244. for(var k in buttonHandlers)
  6245. $("#" + k).click(buttonHandlers[k]);
  6246. UI = ui;
  6247. // Update login info
  6248. APP.xmpp.addListener(
  6249. AuthenticationEvents.IDENTITY_UPDATED,
  6250. function (authenticationEnabled, userIdentity) {
  6251. var loggedIn = false;
  6252. if (userIdentity) {
  6253. loggedIn = true;
  6254. }
  6255. Toolbar.showAuthenticateButton(authenticationEnabled);
  6256. if (authenticationEnabled) {
  6257. Toolbar.setAuthenticatedIdentity(userIdentity);
  6258. Toolbar.showLoginButton(!loggedIn);
  6259. Toolbar.showLogoutButton(loggedIn);
  6260. }
  6261. }
  6262. );
  6263. };
  6264. /**
  6265. * Sets shared key
  6266. * @param sKey the shared key
  6267. */
  6268. my.setSharedKey = function (sKey) {
  6269. sharedKey = sKey;
  6270. };
  6271. my.authenticateClicked = function () {
  6272. Authentication.focusAuthenticationWindow();
  6273. if (!APP.xmpp.isExternalAuthEnabled()) {
  6274. Authentication.xmppAuthenticate();
  6275. return;
  6276. }
  6277. // Get authentication URL
  6278. if (!APP.xmpp.isMUCJoined()) {
  6279. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6280. // If conference has not been started yet - redirect to login page
  6281. window.location.href = url;
  6282. });
  6283. } else {
  6284. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6285. // Otherwise - open popup with authentication URL
  6286. var authenticationWindow = Authentication.createAuthenticationWindow(
  6287. function () {
  6288. // On popup closed - retry room allocation
  6289. APP.xmpp.allocateConferenceFocus(
  6290. APP.UI.getRoomName(),
  6291. function () { console.info("AUTH DONE"); }
  6292. );
  6293. }, url);
  6294. if (!authenticationWindow) {
  6295. messageHandler.openMessageDialog(
  6296. null, "dialog.popupError");
  6297. }
  6298. });
  6299. }
  6300. };
  6301. /**
  6302. * Updates the room invite url.
  6303. */
  6304. my.updateRoomUrl = function (newRoomUrl) {
  6305. roomUrl = newRoomUrl;
  6306. // If the invite dialog has been already opened we update the information.
  6307. var inviteLink = document.getElementById('inviteLinkRef');
  6308. if (inviteLink) {
  6309. inviteLink.value = roomUrl;
  6310. inviteLink.select();
  6311. $('#inviteLinkRef').parent()
  6312. .find('button[value=true]').prop('disabled', false);
  6313. }
  6314. };
  6315. /**
  6316. * Disables and enables some of the buttons.
  6317. */
  6318. my.setupButtonsFromConfig = function () {
  6319. if (config.disablePrezi) {
  6320. $("#toolbar_button_prezi").css({display: "none"});
  6321. }
  6322. };
  6323. /**
  6324. * Opens the lock room dialog.
  6325. */
  6326. my.openLockDialog = function () {
  6327. // Only the focus is able to set a shared key.
  6328. if (!APP.xmpp.isModerator()) {
  6329. if (sharedKey) {
  6330. messageHandler.openMessageDialog(null,
  6331. "dialog.passwordError");
  6332. } else {
  6333. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6334. }
  6335. } else {
  6336. if (sharedKey) {
  6337. messageHandler.openTwoButtonDialog(null, null,
  6338. "dialog.passwordCheck",
  6339. null,
  6340. false,
  6341. "dialog.Remove",
  6342. function (e, v) {
  6343. if (v) {
  6344. Toolbar.setSharedKey('');
  6345. lockRoom(false);
  6346. }
  6347. });
  6348. } else {
  6349. var msg = APP.translation.generateTranslationHTML(
  6350. "dialog.passwordMsg");
  6351. var yourPassword = APP.translation.translateString(
  6352. "dialog.yourPassword");
  6353. messageHandler.openTwoButtonDialog(null, null, null,
  6354. '<h2>' + msg + '</h2>' +
  6355. '<input name="lockKey" type="text"' +
  6356. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6357. 'placeholder="' + yourPassword + '" autofocus>',
  6358. false,
  6359. "dialog.Save",
  6360. function (e, v, m, f) {
  6361. if (v) {
  6362. var lockKey = f.lockKey;
  6363. if (lockKey) {
  6364. Toolbar.setSharedKey(
  6365. UIUtil.escapeHtml(lockKey));
  6366. lockRoom(true);
  6367. }
  6368. }
  6369. },
  6370. null, null, 'input:first'
  6371. );
  6372. }
  6373. }
  6374. };
  6375. /**
  6376. * Opens the invite link dialog.
  6377. */
  6378. my.openLinkDialog = function () {
  6379. var inviteAttreibutes;
  6380. if (roomUrl === null) {
  6381. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6382. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6383. } else {
  6384. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6385. }
  6386. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6387. null, null,
  6388. '<input id="inviteLinkRef" type="text" ' +
  6389. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6390. false,
  6391. "dialog.Invite",
  6392. function (e, v) {
  6393. if (v) {
  6394. if (roomUrl) {
  6395. inviteParticipants();
  6396. }
  6397. }
  6398. },
  6399. function (event) {
  6400. if (roomUrl) {
  6401. document.getElementById('inviteLinkRef').select();
  6402. } else {
  6403. if (event && event.target)
  6404. $(event.target)
  6405. .find('button[value=true]').prop('disabled', true);
  6406. }
  6407. }
  6408. );
  6409. };
  6410. /**
  6411. * Opens the settings dialog.
  6412. * FIXME: not used ?
  6413. */
  6414. my.openSettingsDialog = function () {
  6415. var settings1 = APP.translation.generateTranslationHTML(
  6416. "dialog.settings1");
  6417. var settings2 = APP.translation.generateTranslationHTML(
  6418. "dialog.settings2");
  6419. var settings3 = APP.translation.generateTranslationHTML(
  6420. "dialog.settings3");
  6421. var yourPassword = APP.translation.translateString(
  6422. "dialog.yourPassword");
  6423. messageHandler.openTwoButtonDialog(null,
  6424. '<h2>' + settings1 + '</h2>' +
  6425. '<input type="checkbox" id="initMuted">' +
  6426. settings2 + '<br/>' +
  6427. '<input type="checkbox" id="requireNicknames">' +
  6428. settings3 +
  6429. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6430. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6431. null,
  6432. null,
  6433. false,
  6434. "dialog.Save",
  6435. function () {
  6436. document.getElementById('lockKey').focus();
  6437. },
  6438. function (e, v) {
  6439. if (v) {
  6440. if ($('#initMuted').is(":checked")) {
  6441. // it is checked
  6442. }
  6443. if ($('#requireNicknames').is(":checked")) {
  6444. // it is checked
  6445. }
  6446. /*
  6447. var lockKey = document.getElementById('lockKey');
  6448. if (lockKey.value) {
  6449. setSharedKey(lockKey.value);
  6450. lockRoom(true);
  6451. }
  6452. */
  6453. }
  6454. }
  6455. );
  6456. };
  6457. /**
  6458. * Toggles the application in and out of full screen mode
  6459. * (a.k.a. presentation mode in Chrome).
  6460. */
  6461. my.toggleFullScreen = function () {
  6462. var fsElement = document.documentElement;
  6463. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6464. //Enter Full Screen
  6465. if (fsElement.mozRequestFullScreen) {
  6466. fsElement.mozRequestFullScreen();
  6467. }
  6468. else {
  6469. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6470. }
  6471. } else {
  6472. //Exit Full Screen
  6473. if (document.mozCancelFullScreen) {
  6474. document.mozCancelFullScreen();
  6475. } else {
  6476. document.webkitCancelFullScreen();
  6477. }
  6478. }
  6479. };
  6480. /**
  6481. * Unlocks the lock button state.
  6482. */
  6483. my.unlockLockButton = function () {
  6484. if ($("#toolbar_button_security").hasClass("icon-security-locked"))
  6485. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6486. };
  6487. /**
  6488. * Updates the lock button state to locked.
  6489. */
  6490. my.lockLockButton = function () {
  6491. if ($("#toolbar_button_security").hasClass("icon-security"))
  6492. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6493. };
  6494. /**
  6495. * Shows or hides authentication button
  6496. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6497. */
  6498. my.showAuthenticateButton = function (show) {
  6499. if (show) {
  6500. $('#authentication').css({display: "inline"});
  6501. }
  6502. else {
  6503. $('#authentication').css({display: "none"});
  6504. }
  6505. };
  6506. // Shows or hides the 'recording' button.
  6507. my.showRecordingButton = function (show) {
  6508. if (!config.enableRecording) {
  6509. return;
  6510. }
  6511. if (show) {
  6512. $('#toolbar_button_record').css({display: "inline-block"});
  6513. }
  6514. else {
  6515. $('#toolbar_button_record').css({display: "none"});
  6516. }
  6517. };
  6518. // Sets the state of the recording button
  6519. my.setRecordingButtonState = function (recordingState) {
  6520. var selector = $('#toolbar_button_record');
  6521. if (recordingState === 'on') {
  6522. selector.removeClass("icon-recEnable");
  6523. selector.addClass("icon-recEnable active");
  6524. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6525. var recordOnKey = "recording.on";
  6526. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6527. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6528. setTimeout(function(){
  6529. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6530. $('#videoConnectionMessage').css({display: "none"});
  6531. }, 1500);
  6532. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6533. null, null, {timeOut: 0, closeButton: null, tapToDismiss: false});
  6534. } else if (recordingState === 'off') {
  6535. selector.removeClass("icon-recEnable active");
  6536. selector.addClass("icon-recEnable");
  6537. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6538. $('#videoConnectionMessage').css({display: "none"});
  6539. if (recordingToaster)
  6540. messageHandler.remove(recordingToaster);
  6541. } else if (recordingState === 'pending') {
  6542. selector.removeClass("icon-recEnable active");
  6543. selector.addClass("icon-recEnable");
  6544. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6545. var recordPendingKey = "recording.pending";
  6546. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6547. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6548. $('#videoConnectionMessage').css({display: "block"});
  6549. }
  6550. };
  6551. // checks whether recording is enabled and whether we have params to start automatically recording
  6552. my.checkAutoRecord = function () {
  6553. if (config.enableRecording && config.autoRecord) {
  6554. toggleRecording(config.autoRecordToken);
  6555. }
  6556. }
  6557. // Shows or hides SIP calls button
  6558. my.showSipCallButton = function (show) {
  6559. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6560. $('#toolbar_button_sip').css({display: "inline-block"});
  6561. } else {
  6562. $('#toolbar_button_sip').css({display: "none"});
  6563. }
  6564. };
  6565. // Shows or hides the dialpad button
  6566. my.showDialPadButton = function (show) {
  6567. if (show) {
  6568. $('#toolbar_button_dialpad').css({display: "inline-block"});
  6569. } else {
  6570. $('#toolbar_button_dialpad').css({display: "none"});
  6571. }
  6572. };
  6573. /**
  6574. * Displays user authenticated identity name(login).
  6575. * @param authIdentity identity name to be displayed.
  6576. */
  6577. my.setAuthenticatedIdentity = function (authIdentity) {
  6578. if (authIdentity) {
  6579. var selector = $('#toolbar_auth_identity');
  6580. selector.css({display: "list-item"});
  6581. selector.text(authIdentity);
  6582. } else {
  6583. $('#toolbar_auth_identity').css({display: "none"});
  6584. }
  6585. };
  6586. /**
  6587. * Shows/hides login button.
  6588. * @param show <tt>true</tt> to show
  6589. */
  6590. my.showLoginButton = function (show) {
  6591. if (show) {
  6592. $('#toolbar_button_login').css({display: "list-item"});
  6593. } else {
  6594. $('#toolbar_button_login').css({display: "none"});
  6595. }
  6596. };
  6597. /**
  6598. * Shows/hides logout button.
  6599. * @param show <tt>true</tt> to show
  6600. */
  6601. my.showLogoutButton = function (show) {
  6602. if (show) {
  6603. $('#toolbar_button_logout').css({display: "list-item"});
  6604. } else {
  6605. $('#toolbar_button_logout').css({display: "none"});
  6606. }
  6607. };
  6608. /**
  6609. * Sets the state of the button. The button has blue glow if desktop
  6610. * streaming is active.
  6611. * @param active the state of the desktop streaming.
  6612. */
  6613. my.changeDesktopSharingButtonState = function (active) {
  6614. var button = $("#toolbar_button_desktopsharing");
  6615. if (active) {
  6616. button.addClass("glow");
  6617. } else {
  6618. button.removeClass("glow");
  6619. }
  6620. };
  6621. return my;
  6622. }(Toolbar || {}));
  6623. module.exports = Toolbar;
  6624. },{"../../../service/authentication/AuthenticationEvents":115,"../authentication/Authentication":16,"../etherpad/Etherpad":19,"../prezi/Prezi":20,"../side_pannels/SidePanelToggler":22,"../util/MessageHandler":33,"../util/UIUtil":35,"./BottomToolbar":29}],31:[function(require,module,exports){
  6625. /* global APP, config, $, interfaceConfig, Moderator,
  6626. DesktopStreaming.showDesktopSharingButton */
  6627. var toolbarTimeoutObject,
  6628. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6629. function showDesktopSharingButton() {
  6630. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6631. $('#toolbar_button_desktopsharing').css({display: "inline-block"});
  6632. } else {
  6633. $('#toolbar_button_desktopsharing').css({display: "none"});
  6634. }
  6635. }
  6636. /**
  6637. * Hides the toolbar.
  6638. */
  6639. function hideToolbar() {
  6640. if(config.alwaysVisibleToolbar)
  6641. return;
  6642. var header = $("#header"),
  6643. bottomToolbar = $("#bottomToolbar");
  6644. var isToolbarHover = false;
  6645. header.find('*').each(function () {
  6646. var id = $(this).attr('id');
  6647. if ($("#" + id + ":hover").length > 0) {
  6648. isToolbarHover = true;
  6649. }
  6650. });
  6651. if ($("#bottomToolbar:hover").length > 0) {
  6652. isToolbarHover = true;
  6653. }
  6654. clearTimeout(toolbarTimeoutObject);
  6655. toolbarTimeoutObject = null;
  6656. if (!isToolbarHover) {
  6657. header.hide("slide", { direction: "up", duration: 300});
  6658. $('#subject').animate({top: "-=40"}, 300);
  6659. if ($("#remoteVideos").hasClass("hidden")) {
  6660. bottomToolbar.hide(
  6661. "slide", {direction: "right", duration: 300});
  6662. }
  6663. }
  6664. else {
  6665. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6666. }
  6667. }
  6668. var ToolbarToggler = {
  6669. /**
  6670. * Shows the main toolbar.
  6671. */
  6672. showToolbar: function () {
  6673. if (interfaceConfig.filmStripOnly)
  6674. return;
  6675. var header = $("#header"),
  6676. bottomToolbar = $("#bottomToolbar");
  6677. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6678. header.show("slide", { direction: "up", duration: 300});
  6679. $('#subject').animate({top: "+=40"}, 300);
  6680. if (!bottomToolbar.is(":visible")) {
  6681. bottomToolbar.show(
  6682. "slide", {direction: "right", duration: 300});
  6683. }
  6684. if (toolbarTimeoutObject) {
  6685. clearTimeout(toolbarTimeoutObject);
  6686. toolbarTimeoutObject = null;
  6687. }
  6688. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6689. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6690. }
  6691. if (APP.xmpp.isModerator())
  6692. {
  6693. // TODO: Enable settings functionality.
  6694. // Need to uncomment the settings button in index.html.
  6695. // $('#settingsButton').css({visibility:"visible"});
  6696. }
  6697. // Show/hide desktop sharing button
  6698. showDesktopSharingButton();
  6699. },
  6700. /**
  6701. * Docks/undocks the toolbar.
  6702. *
  6703. * @param isDock indicates what operation to perform
  6704. */
  6705. dockToolbar: function (isDock) {
  6706. if (interfaceConfig.filmStripOnly)
  6707. return;
  6708. if (isDock) {
  6709. // First make sure the toolbar is shown.
  6710. if (!$('#header').is(':visible')) {
  6711. this.showToolbar();
  6712. }
  6713. // Then clear the time out, to dock the toolbar.
  6714. if (toolbarTimeoutObject) {
  6715. clearTimeout(toolbarTimeoutObject);
  6716. toolbarTimeoutObject = null;
  6717. }
  6718. }
  6719. else {
  6720. if (!$('#header').is(':visible')) {
  6721. this.showToolbar();
  6722. }
  6723. else {
  6724. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6725. }
  6726. }
  6727. },
  6728. showDesktopSharingButton: showDesktopSharingButton
  6729. };
  6730. module.exports = ToolbarToggler;
  6731. },{}],32:[function(require,module,exports){
  6732. /* global $ */
  6733. var JitsiPopover = (function () {
  6734. /**
  6735. * Constructs new JitsiPopover and attaches it to the element
  6736. * @param element jquery selector
  6737. * @param options the options for the popover.
  6738. * @constructor
  6739. */
  6740. function JitsiPopover(element, options)
  6741. {
  6742. this.options = {
  6743. skin: "white",
  6744. content: ""
  6745. };
  6746. if(options)
  6747. {
  6748. if(options.skin)
  6749. this.options.skin = options.skin;
  6750. if(options.content)
  6751. this.options.content = options.content;
  6752. }
  6753. this.elementIsHovered = false;
  6754. this.popoverIsHovered = false;
  6755. this.popoverShown = false;
  6756. element.data("jitsi_popover", this);
  6757. this.element = element;
  6758. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6759. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6760. '<div class="jitsiPopupmenuPadding"></div></div>';
  6761. var self = this;
  6762. this.element.on("mouseenter", function () {
  6763. self.elementIsHovered = true;
  6764. self.show();
  6765. }).on("mouseleave", function () {
  6766. self.elementIsHovered = false;
  6767. setTimeout(function () {
  6768. self.hide();
  6769. }, 10);
  6770. });
  6771. }
  6772. /**
  6773. * Shows the popover
  6774. */
  6775. JitsiPopover.prototype.show = function () {
  6776. if(!JitsiPopover.enabled)
  6777. return;
  6778. this.createPopover();
  6779. this.popoverShown = true;
  6780. };
  6781. /**
  6782. * Hides the popover
  6783. */
  6784. JitsiPopover.prototype.hide = function () {
  6785. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6786. this.popoverShown) {
  6787. this.forceHide();
  6788. }
  6789. };
  6790. /**
  6791. * Hides the popover.
  6792. */
  6793. JitsiPopover.prototype.forceHide = function () {
  6794. $(".jitsipopover").remove();
  6795. this.popoverShown = false;
  6796. };
  6797. /**
  6798. * Creates the popover html.
  6799. */
  6800. JitsiPopover.prototype.createPopover = function () {
  6801. $("body").append(this.template);
  6802. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6803. var self = this;
  6804. $(".jitsipopover").on("mouseenter", function () {
  6805. self.popoverIsHovered = true;
  6806. }).on("mouseleave", function () {
  6807. self.popoverIsHovered = false;
  6808. self.hide();
  6809. });
  6810. this.refreshPosition();
  6811. };
  6812. /**
  6813. * Refreshes the position of the popover.
  6814. */
  6815. JitsiPopover.prototype.refreshPosition = function () {
  6816. $(".jitsipopover").position({
  6817. my: "bottom",
  6818. at: "top",
  6819. collision: "fit",
  6820. of: this.element,
  6821. using: function (position, elements) {
  6822. var calcLeft = elements.target.left - elements.element.left +
  6823. elements.target.width/2;
  6824. $(".jitsipopover").css(
  6825. {top: position.top, left: position.left, display: "table"});
  6826. $(".jitsipopover > .arrow").css({left: calcLeft});
  6827. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6828. {left: calcLeft - 50});
  6829. }
  6830. });
  6831. };
  6832. /**
  6833. * Updates the content of popover.
  6834. * @param content new content
  6835. */
  6836. JitsiPopover.prototype.updateContent = function (content) {
  6837. this.options.content = content;
  6838. if(!this.popoverShown)
  6839. return;
  6840. $(".jitsipopover").remove();
  6841. this.createPopover();
  6842. };
  6843. JitsiPopover.enabled = true;
  6844. return JitsiPopover;
  6845. })();
  6846. module.exports = JitsiPopover;
  6847. },{}],33:[function(require,module,exports){
  6848. /* global $, APP, jQuery, toastr */
  6849. /**
  6850. * Flag for enable/disable of the notifications.
  6851. * @type {boolean}
  6852. */
  6853. var notificationsEnabled = true;
  6854. var messageHandler = (function(my) {
  6855. /**
  6856. * Shows a message to the user.
  6857. *
  6858. * @param titleKey the title of the message
  6859. * @param messageKey the text of the message
  6860. */
  6861. my.openMessageDialog = function(titleKey, messageKey) {
  6862. var title = null;
  6863. if(titleKey) {
  6864. title = APP.translation.generateTranslationHTML(titleKey);
  6865. }
  6866. var message = APP.translation.generateTranslationHTML(messageKey);
  6867. $.prompt(message,
  6868. {title: title, persistent: false}
  6869. );
  6870. };
  6871. /**
  6872. * Shows a message to the user with two buttons: first is given as a
  6873. * parameter and the second is Cancel.
  6874. *
  6875. * @param titleString the title of the message
  6876. * @param msgString the text of the message
  6877. * @param persistent boolean value which determines whether the message is
  6878. * persistent or not
  6879. * @param leftButton the fist button's text
  6880. * @param submitFunction function to be called on submit
  6881. * @param loadedFunction function to be called after the prompt is fully
  6882. * loaded
  6883. * @param closeFunction function to be called after the prompt is closed
  6884. * @param focus optional focus selector or button index to be focused after
  6885. * the dialog is opened
  6886. * @param defaultButton index of default button which will be activated when
  6887. * the user press 'enter'. Indexed from 0.
  6888. */
  6889. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6890. persistent, leftButtonKey, submitFunction, loadedFunction,
  6891. closeFunction, focus, defaultButton) {
  6892. var buttons = [];
  6893. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6894. buttons.push({ title: leftButton, value: true});
  6895. var cancelButton
  6896. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6897. buttons.push({title: cancelButton, value: false});
  6898. var message = msgString, title = titleString;
  6899. if (titleKey) {
  6900. title = APP.translation.generateTranslationHTML(titleKey);
  6901. }
  6902. if (msgKey) {
  6903. message = APP.translation.generateTranslationHTML(msgKey);
  6904. }
  6905. $.prompt(message, {
  6906. title: title,
  6907. persistent: false,
  6908. buttons: buttons,
  6909. defaultButton: defaultButton,
  6910. focus: focus,
  6911. loaded: loadedFunction,
  6912. submit: submitFunction,
  6913. close: closeFunction
  6914. });
  6915. };
  6916. /**
  6917. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6918. *
  6919. * @param titleString the title of the message
  6920. * @param msgString the text of the message
  6921. * @param persistent boolean value which determines whether the message is
  6922. * persistent or not
  6923. * @param buttons object with the buttons. The keys must be the name of the
  6924. * button and value is the value that will be passed to
  6925. * submitFunction
  6926. * @param submitFunction function to be called on submit
  6927. * @param loadedFunction function to be called after the prompt is fully
  6928. * loaded
  6929. */
  6930. my.openDialog = function (titleString, msgString, persistent, buttons,
  6931. submitFunction, loadedFunction) {
  6932. var args = {
  6933. title: titleString,
  6934. persistent: persistent,
  6935. buttons: buttons,
  6936. defaultButton: 1,
  6937. loaded: loadedFunction,
  6938. submit: submitFunction
  6939. };
  6940. if (persistent) {
  6941. args.closeText = '';
  6942. }
  6943. return new Impromptu(msgString, args);
  6944. };
  6945. /**
  6946. * Closes currently opened dialog.
  6947. */
  6948. my.closeDialog = function () {
  6949. $.prompt.close();
  6950. };
  6951. /**
  6952. * Shows a dialog with different states to the user.
  6953. *
  6954. * @param statesObject object containing all the states of the dialog.
  6955. */
  6956. my.openDialogWithStates = function (statesObject, options) {
  6957. return new Impromptu(statesObject, options);
  6958. };
  6959. /**
  6960. * Opens new popup window for given <tt>url</tt> centered over current
  6961. * window.
  6962. *
  6963. * @param url the URL to be displayed in the popup window
  6964. * @param w the width of the popup window
  6965. * @param h the height of the popup window
  6966. * @param onPopupClosed optional callback function called when popup window
  6967. * has been closed.
  6968. *
  6969. * @returns {object} popup window object if opened successfully or undefined
  6970. * in case we failed to open it(popup blocked)
  6971. */
  6972. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6973. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6974. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6975. var popup = window.open(
  6976. url, '_blank',
  6977. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6978. if (popup && onPopupClosed) {
  6979. var pollTimer = window.setInterval(function () {
  6980. if (popup.closed !== false) {
  6981. window.clearInterval(pollTimer);
  6982. onPopupClosed();
  6983. }
  6984. }, 200);
  6985. }
  6986. return popup;
  6987. };
  6988. /**
  6989. * Shows a dialog prompting the user to send an error report.
  6990. *
  6991. * @param titleKey the title of the message
  6992. * @param msgKey the text of the message
  6993. * @param error the error that is being reported
  6994. */
  6995. my.openReportDialog = function(titleKey, msgKey, error) {
  6996. my.openMessageDialog(titleKey, msgKey);
  6997. console.log(error);
  6998. //FIXME send the error to the server
  6999. };
  7000. /**
  7001. * Shows an error dialog to the user.
  7002. * @param titleKey the title of the message.
  7003. * @param msgKey the text of the message.
  7004. */
  7005. my.showError = function(titleKey, msgKey) {
  7006. if (!titleKey) {
  7007. titleKey = "dialog.oops";
  7008. }
  7009. if (!msgKey) {
  7010. msgKey = "dialog.defaultError";
  7011. }
  7012. messageHandler.openMessageDialog(titleKey, msgKey);
  7013. };
  7014. /**
  7015. * Displayes notification.
  7016. * @param displayName display name of the participant that is associated with the notification.
  7017. * @param displayNameKey the key from the language file for the display name.
  7018. * @param cls css class for the notification
  7019. * @param messageKey the key from the language file for the text of the message.
  7020. * @param messageArguments object with the arguments for the message.
  7021. * @param options object with language options.
  7022. */
  7023. my.notify = function(displayName, displayNameKey,
  7024. cls, messageKey, messageArguments, options) {
  7025. if(!notificationsEnabled)
  7026. return;
  7027. var displayNameSpan = '<span class="nickname" ';
  7028. if (displayName) {
  7029. displayNameSpan += ">" + displayName;
  7030. } else {
  7031. displayNameSpan += "data-i18n='" + displayNameKey +
  7032. "'>" + APP.translation.translateString(displayNameKey);
  7033. }
  7034. displayNameSpan += "</span>";
  7035. return toastr.info(
  7036. displayNameSpan + '<br>' +
  7037. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  7038. (messageArguments?
  7039. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  7040. : "") + ">" +
  7041. APP.translation.translateString(messageKey,
  7042. messageArguments) +
  7043. '</span>', null, options);
  7044. };
  7045. /**
  7046. * Removes the toaster.
  7047. * @param toasterElement
  7048. */
  7049. my.remove = function(toasterElement) {
  7050. toasterElement.remove();
  7051. };
  7052. /**
  7053. * Disables notifications.
  7054. */
  7055. my.disableNotifications = function () {
  7056. notificationsEnabled = false;
  7057. };
  7058. /**
  7059. * Enables notifications.
  7060. */
  7061. my.enableNotifications = function () {
  7062. notificationsEnabled = true;
  7063. };
  7064. return my;
  7065. }(messageHandler || {}));
  7066. module.exports = messageHandler;
  7067. },{}],34:[function(require,module,exports){
  7068. var UIEvents = require("../../../service/UI/UIEvents");
  7069. var nickname = null;
  7070. var eventEmitter = null;
  7071. var NicknameHandler = {
  7072. init: function (emitter) {
  7073. eventEmitter = emitter;
  7074. var storedDisplayName = window.localStorage.displayname;
  7075. if (storedDisplayName) {
  7076. nickname = storedDisplayName;
  7077. }
  7078. },
  7079. setNickname: function (newNickname) {
  7080. if (!newNickname || nickname === newNickname)
  7081. return;
  7082. nickname = newNickname;
  7083. window.localStorage.displayname = nickname;
  7084. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  7085. },
  7086. getNickname: function () {
  7087. return nickname;
  7088. },
  7089. addListener: function (type, listener) {
  7090. eventEmitter.on(type, listener);
  7091. }
  7092. };
  7093. module.exports = NicknameHandler;
  7094. },{"../../../service/UI/UIEvents":114}],35:[function(require,module,exports){
  7095. /* global $ */
  7096. /**
  7097. * Created by hristo on 12/22/14.
  7098. */
  7099. module.exports = {
  7100. /**
  7101. * Returns the available video width.
  7102. */
  7103. getAvailableVideoWidth: function (isVisible) {
  7104. var PanelToggler = require("../side_pannels/SidePanelToggler");
  7105. if(typeof isVisible === "undefined" || isVisible === null)
  7106. isVisible = PanelToggler.isVisible();
  7107. var rightPanelWidth
  7108. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  7109. return window.innerWidth - rightPanelWidth;
  7110. },
  7111. /**
  7112. * Changes the style class of the element given by id.
  7113. */
  7114. buttonClick: function(id, classname) {
  7115. $(id).toggleClass(classname); // add the class to the clicked element
  7116. },
  7117. /**
  7118. * Returns the text width for the given element.
  7119. *
  7120. * @param el the element
  7121. */
  7122. getTextWidth: function (el) {
  7123. return (el.clientWidth + 1);
  7124. },
  7125. /**
  7126. * Returns the text height for the given element.
  7127. *
  7128. * @param el the element
  7129. */
  7130. getTextHeight: function (el) {
  7131. return (el.clientHeight + 1);
  7132. },
  7133. /**
  7134. * Plays the sound given by id.
  7135. *
  7136. * @param id the identifier of the audio element.
  7137. */
  7138. playSoundNotification: function (id) {
  7139. document.getElementById(id).play();
  7140. },
  7141. /**
  7142. * Escapes the given text.
  7143. */
  7144. escapeHtml: function (unsafeText) {
  7145. return $('<div/>').text(unsafeText).html();
  7146. },
  7147. imageToGrayScale: function (canvas) {
  7148. var context = canvas.getContext('2d');
  7149. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  7150. var pixels = imgData.data;
  7151. for (var i = 0, n = pixels.length; i < n; i += 4) {
  7152. var grayscale
  7153. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  7154. pixels[i ] = grayscale; // red
  7155. pixels[i+1] = grayscale; // green
  7156. pixels[i+2] = grayscale; // blue
  7157. // pixels[i+3] is alpha
  7158. }
  7159. // redraw the image in black & white
  7160. context.putImageData(imgData, 0, 0);
  7161. },
  7162. setTooltip: function (element, key, position) {
  7163. element.setAttribute("data-i18n", "[data-content]" + key);
  7164. element.setAttribute("data-toggle", "popover");
  7165. element.setAttribute("data-placement", position);
  7166. element.setAttribute("data-html", true);
  7167. element.setAttribute("data-container", "body");
  7168. },
  7169. /**
  7170. * Inserts given child element as the first one into the container.
  7171. * @param container the container to which new child element will be added
  7172. * @param newChild the new element that will be inserted into the container
  7173. */
  7174. prependChild: function (container, newChild) {
  7175. var firstChild = container.childNodes[0];
  7176. if (firstChild) {
  7177. container.insertBefore(newChild, firstChild);
  7178. } else {
  7179. container.appendChild(newChild);
  7180. }
  7181. }
  7182. };
  7183. },{"../side_pannels/SidePanelToggler":22}],36:[function(require,module,exports){
  7184. /* global APP, $ */
  7185. var JitsiPopover = require("../util/JitsiPopover");
  7186. /**
  7187. * Constructs new connection indicator.
  7188. * @param videoContainer the video container associated with the indicator.
  7189. * @constructor
  7190. */
  7191. function ConnectionIndicator(videoContainer, jid) {
  7192. this.videoContainer = videoContainer;
  7193. this.bandwidth = null;
  7194. this.packetLoss = null;
  7195. this.bitrate = null;
  7196. this.showMoreValue = false;
  7197. this.resolution = null;
  7198. this.transport = [];
  7199. this.popover = null;
  7200. this.jid = jid;
  7201. this.create();
  7202. }
  7203. /**
  7204. * Values for the connection quality
  7205. * @type {{98: string,
  7206. * 81: string,
  7207. * 64: string,
  7208. * 47: string,
  7209. * 30: string,
  7210. * 0: string}}
  7211. */
  7212. ConnectionIndicator.connectionQualityValues = {
  7213. 98: "18px", //full
  7214. 81: "15px",//4 bars
  7215. 64: "11px",//3 bars
  7216. 47: "7px",//2 bars
  7217. 30: "3px",//1 bar
  7218. 0: "0px"//empty
  7219. };
  7220. ConnectionIndicator.getIP = function(value) {
  7221. return value.substring(0, value.lastIndexOf(":"));
  7222. };
  7223. ConnectionIndicator.getPort = function(value) {
  7224. return value.substring(value.lastIndexOf(":") + 1, value.length);
  7225. };
  7226. ConnectionIndicator.getStringFromArray = function (array) {
  7227. var res = "";
  7228. for(var i = 0; i < array.length; i++) {
  7229. res += (i === 0? "" : ", ") + array[i];
  7230. }
  7231. return res;
  7232. };
  7233. /**
  7234. * Generates the html content.
  7235. * @returns {string} the html content.
  7236. */
  7237. ConnectionIndicator.prototype.generateText = function () {
  7238. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  7239. var translate = APP.translation.translateString;
  7240. if(this.bitrate === null) {
  7241. downloadBitrate = "N/A";
  7242. uploadBitrate = "N/A";
  7243. }
  7244. else {
  7245. downloadBitrate =
  7246. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  7247. uploadBitrate =
  7248. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  7249. }
  7250. if(this.packetLoss === null) {
  7251. packetLoss = "N/A";
  7252. } else {
  7253. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  7254. (this.packetLoss.download !== null ?
  7255. this.packetLoss.download : "N/A") +
  7256. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  7257. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  7258. "%";
  7259. }
  7260. var resolutionValue = null;
  7261. if(this.resolution && this.jid != null) {
  7262. var keys = Object.keys(this.resolution);
  7263. for(var ssrc in this.resolution) {
  7264. resolutionValue = this.resolution[ssrc];
  7265. }
  7266. }
  7267. if(this.jid === null) {
  7268. resolution = "";
  7269. if(this.resolution === null || !Object.keys(this.resolution) ||
  7270. Object.keys(this.resolution).length === 0) {
  7271. resolution = "N/A";
  7272. } else {
  7273. for (i in this.resolution) {
  7274. resolutionValue = this.resolution[i];
  7275. if (resolutionValue) {
  7276. if (resolutionValue.height &&
  7277. resolutionValue.width) {
  7278. resolution += (resolution === "" ? "" : ", ") +
  7279. resolutionValue.width + "x" +
  7280. resolutionValue.height;
  7281. }
  7282. }
  7283. }
  7284. }
  7285. } else if(!resolutionValue ||
  7286. !resolutionValue.height ||
  7287. !resolutionValue.width) {
  7288. resolution = "N/A";
  7289. } else {
  7290. resolution = resolutionValue.width + "x" + resolutionValue.height;
  7291. }
  7292. var result = "<table style='width:100%'>" +
  7293. "<tr>" +
  7294. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  7295. translate("connectionindicator.bitrate") + "</span></td>" +
  7296. "<td><span class='jitsipopover_green'>&darr;</span>" +
  7297. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  7298. uploadBitrate + "</td>" +
  7299. "</tr><tr>" +
  7300. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  7301. translate("connectionindicator.packetloss") + "</span></td>" +
  7302. "<td>" + packetLoss + "</td>" +
  7303. "</tr><tr>" +
  7304. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  7305. translate("connectionindicator.resolution") + "</span></td>" +
  7306. "<td>" + resolution + "</td></tr></table>";
  7307. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  7308. result += "<div class=\"jitsipopover_showmore\" " +
  7309. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  7310. // FIXME: we do not know local jid when this text is generated
  7311. //this.jid + "')\" data-i18n='connectionindicator." +
  7312. "local')\" data-i18n='connectionindicator." +
  7313. (this.showMoreValue ? "less" : "more") + "'>" +
  7314. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  7315. "</div><br />";
  7316. }
  7317. if (this.showMoreValue) {
  7318. var downloadBandwidth, uploadBandwidth, transport;
  7319. if (this.bandwidth === null) {
  7320. downloadBandwidth = "N/A";
  7321. uploadBandwidth = "N/A";
  7322. } else {
  7323. downloadBandwidth = this.bandwidth.download?
  7324. this.bandwidth.download + " Kbps" :
  7325. "N/A";
  7326. uploadBandwidth = this.bandwidth.upload?
  7327. this.bandwidth.upload + " Kbps" :
  7328. "N/A";
  7329. }
  7330. if (!this.transport || this.transport.length === 0) {
  7331. transport = "<tr>" +
  7332. "<td><span class='jitsipopover_blue' " +
  7333. "data-i18n='connectionindicator.address'>" +
  7334. translate("connectionindicator.address") + "</span></td>" +
  7335. "<td> N/A</td></tr>";
  7336. } else {
  7337. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7338. for(i = 0; i < this.transport.length; i++) {
  7339. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7340. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7341. var localIP =
  7342. ConnectionIndicator.getIP(this.transport[i].localip);
  7343. var localPort =
  7344. ConnectionIndicator.getPort(this.transport[i].localip);
  7345. if(data.remoteIP.indexOf(ip) == -1) {
  7346. data.remoteIP.push(ip);
  7347. }
  7348. if(data.remotePort.indexOf(port) == -1) {
  7349. data.remotePort.push(port);
  7350. }
  7351. if(data.localIP.indexOf(localIP) == -1) {
  7352. data.localIP.push(localIP);
  7353. }
  7354. if(data.localPort.indexOf(localPort) == -1) {
  7355. data.localPort.push(localPort);
  7356. }
  7357. }
  7358. var local_address_key = "connectionindicator.localaddress";
  7359. var remote_address_key = "connectionindicator.remoteaddress";
  7360. var localTransport =
  7361. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7362. local_address_key +"' data-i18n-options='" +
  7363. JSON.stringify({count: data.localIP.length}) + "'>" +
  7364. translate(local_address_key, {count: data.localIP.length}) +
  7365. "</span></td><td> " +
  7366. ConnectionIndicator.getStringFromArray(data.localIP) +
  7367. "</td></tr>";
  7368. transport =
  7369. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7370. remote_address_key + "' data-i18n-options='" +
  7371. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7372. translate(remote_address_key,
  7373. {count: data.remoteIP.length}) +
  7374. "</span></td><td> " +
  7375. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7376. "</td></tr>";
  7377. var key_remote = "connectionindicator.remoteport",
  7378. key_local = "connectionindicator.localport";
  7379. transport += "<tr>" +
  7380. "<td>" +
  7381. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7382. "' data-i18n-options='" +
  7383. JSON.stringify({count: this.transport.length}) + "'>" +
  7384. translate(key_remote, {count: this.transport.length}) +
  7385. "</span></td><td>";
  7386. localTransport += "<tr>" +
  7387. "<td>" +
  7388. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7389. "' data-i18n-options='" +
  7390. JSON.stringify({count: this.transport.length}) + "'>" +
  7391. translate(key_local, {count: this.transport.length}) +
  7392. "</span></td><td>";
  7393. transport +=
  7394. ConnectionIndicator.getStringFromArray(data.remotePort);
  7395. localTransport +=
  7396. ConnectionIndicator.getStringFromArray(data.localPort);
  7397. transport += "</td></tr>";
  7398. transport += localTransport + "</td></tr>";
  7399. transport +="<tr>" +
  7400. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7401. translate("connectionindicator.transport") + "</span></td>" +
  7402. "<td>" + this.transport[0].type + "</td></tr>";
  7403. }
  7404. result += "<table style='width:100%'>" +
  7405. "<tr>" +
  7406. "<td>" +
  7407. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7408. translate("connectionindicator.bandwidth") + "</span>" +
  7409. "</td><td>" +
  7410. "<span class='jitsipopover_green'>&darr;</span>" +
  7411. downloadBandwidth +
  7412. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7413. uploadBandwidth + "</td></tr>";
  7414. result += transport + "</table>";
  7415. }
  7416. return result;
  7417. };
  7418. /**
  7419. * Shows or hide the additional information.
  7420. */
  7421. ConnectionIndicator.prototype.showMore = function () {
  7422. this.showMoreValue = !this.showMoreValue;
  7423. this.updatePopoverData();
  7424. };
  7425. function createIcon(classes) {
  7426. var icon = document.createElement("span");
  7427. for(var i in classes) {
  7428. icon.classList.add(classes[i]);
  7429. }
  7430. icon.appendChild(
  7431. document.createElement("i")).classList.add("icon-connection");
  7432. return icon;
  7433. }
  7434. /**
  7435. * Creates the indicator
  7436. */
  7437. ConnectionIndicator.prototype.create = function () {
  7438. this.connectionIndicatorContainer = document.createElement("div");
  7439. this.connectionIndicatorContainer.className = "connectionindicator";
  7440. this.connectionIndicatorContainer.style.display = "none";
  7441. this.videoContainer.container.appendChild(
  7442. this.connectionIndicatorContainer);
  7443. this.popover = new JitsiPopover(
  7444. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7445. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7446. APP.translation.translateString("connectionindicator.na") + "</div>",
  7447. skin: "black"});
  7448. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7449. createIcon(["connection", "connection_empty"]));
  7450. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7451. createIcon(["connection", "connection_full"]));
  7452. };
  7453. /**
  7454. * Removes the indicator
  7455. */
  7456. ConnectionIndicator.prototype.remove = function() {
  7457. if (this.connectionIndicatorContainer.parentNode) {
  7458. this.connectionIndicatorContainer.parentNode.removeChild(
  7459. this.connectionIndicatorContainer);
  7460. }
  7461. this.popover.forceHide();
  7462. };
  7463. /**
  7464. * Updates the data of the indicator
  7465. * @param percent the percent of connection quality
  7466. * @param object the statistics data.
  7467. */
  7468. ConnectionIndicator.prototype.updateConnectionQuality =
  7469. function (percent, object) {
  7470. if (percent === null) {
  7471. this.connectionIndicatorContainer.style.display = "none";
  7472. this.popover.forceHide();
  7473. return;
  7474. } else {
  7475. if(this.connectionIndicatorContainer.style.display == "none") {
  7476. this.connectionIndicatorContainer.style.display = "block";
  7477. this.videoContainer.updateIconPositions();
  7478. }
  7479. }
  7480. this.bandwidth = object.bandwidth;
  7481. this.bitrate = object.bitrate;
  7482. this.packetLoss = object.packetLoss;
  7483. this.transport = object.transport;
  7484. if (object.resolution) {
  7485. this.resolution = object.resolution;
  7486. }
  7487. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7488. if (percent >= quality) {
  7489. this.fullIcon.style.width =
  7490. ConnectionIndicator.connectionQualityValues[quality];
  7491. }
  7492. }
  7493. this.updatePopoverData();
  7494. };
  7495. /**
  7496. * Updates the resolution
  7497. * @param resolution the new resolution
  7498. */
  7499. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7500. this.resolution = resolution;
  7501. this.updatePopoverData();
  7502. };
  7503. /**
  7504. * Updates the content of the popover
  7505. */
  7506. ConnectionIndicator.prototype.updatePopoverData = function () {
  7507. this.popover.updateContent(
  7508. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7509. APP.translation.translateElement($(".connection_info"));
  7510. };
  7511. /**
  7512. * Hides the popover
  7513. */
  7514. ConnectionIndicator.prototype.hide = function () {
  7515. this.popover.forceHide();
  7516. };
  7517. /**
  7518. * Hides the indicator
  7519. */
  7520. ConnectionIndicator.prototype.hideIndicator = function () {
  7521. this.connectionIndicatorContainer.style.display = "none";
  7522. if(this.popover)
  7523. this.popover.forceHide();
  7524. };
  7525. module.exports = ConnectionIndicator;
  7526. },{"../util/JitsiPopover":32}],37:[function(require,module,exports){
  7527. /* global $, APP, Strophe, interfaceConfig */
  7528. var Avatar = require("../avatar/Avatar");
  7529. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7530. var UIUtil = require("../util/UIUtil");
  7531. var UIEvents = require("../../../service/UI/UIEvents");
  7532. var xmpp = require("../../xmpp/xmpp");
  7533. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7534. // FIXME: With Temasys we have to re-select everytime
  7535. //var video = $('#largeVideo');
  7536. var currentVideoWidth = null;
  7537. var currentVideoHeight = null;
  7538. // By default we use camera
  7539. var getVideoSize = getCameraVideoSize;
  7540. var getVideoPosition = getCameraVideoPosition;
  7541. /**
  7542. * The small video instance that is displayed in the large video
  7543. * @type {SmallVideo}
  7544. */
  7545. var currentSmallVideo = null;
  7546. /**
  7547. * Indicates whether the large video is enabled.
  7548. * @type {boolean}
  7549. */
  7550. var isEnabled = true;
  7551. /**
  7552. * Current large video state.
  7553. * Possible values - video, prezi or etherpad.
  7554. * @type {string}
  7555. */
  7556. var state = "video";
  7557. /**
  7558. * Returns the html element associated with the passed state of large video
  7559. * @param state the state.
  7560. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7561. */
  7562. function getContainerByState(state)
  7563. {
  7564. var selector = null;
  7565. switch (state)
  7566. {
  7567. case "video":
  7568. selector = "#largeVideo";
  7569. break;
  7570. case "etherpad":
  7571. selector = "#etherpad>iframe";
  7572. break;
  7573. case "prezi":
  7574. selector = "#presentation>iframe";
  7575. break;
  7576. }
  7577. return (selector !== null)? $(selector) : null;
  7578. }
  7579. /**
  7580. * Sets the size and position of the given video element.
  7581. *
  7582. * @param video the video element to position
  7583. * @param width the desired video width
  7584. * @param height the desired video height
  7585. * @param horizontalIndent the left and right indent
  7586. * @param verticalIndent the top and bottom indent
  7587. */
  7588. function positionVideo(video,
  7589. width,
  7590. height,
  7591. horizontalIndent,
  7592. verticalIndent,
  7593. animate) {
  7594. if (animate) {
  7595. video.animate({
  7596. width: width,
  7597. height: height,
  7598. top: verticalIndent,
  7599. bottom: verticalIndent,
  7600. left: horizontalIndent,
  7601. right: horizontalIndent
  7602. },
  7603. {
  7604. queue: false,
  7605. duration: 500
  7606. });
  7607. } else {
  7608. video.width(width);
  7609. video.height(height);
  7610. video.css({ top: verticalIndent + 'px',
  7611. bottom: verticalIndent + 'px',
  7612. left: horizontalIndent + 'px',
  7613. right: horizontalIndent + 'px'});
  7614. }
  7615. }
  7616. /**
  7617. * Returns an array of the video dimensions, so that it keeps it's aspect
  7618. * ratio and fits available area with it's larger dimension. This method
  7619. * ensures that whole video will be visible and can leave empty areas.
  7620. *
  7621. * @return an array with 2 elements, the video width and the video height
  7622. */
  7623. function getDesktopVideoSize(videoWidth,
  7624. videoHeight,
  7625. videoSpaceWidth,
  7626. videoSpaceHeight) {
  7627. if (!videoWidth)
  7628. videoWidth = currentVideoWidth;
  7629. if (!videoHeight)
  7630. videoHeight = currentVideoHeight;
  7631. var aspectRatio = videoWidth / videoHeight;
  7632. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7633. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7634. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7635. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7636. {
  7637. availableHeight = videoSpaceHeight;
  7638. availableWidth = availableHeight * aspectRatio;
  7639. }
  7640. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7641. {
  7642. availableWidth = videoSpaceWidth;
  7643. availableHeight = availableWidth / aspectRatio;
  7644. }
  7645. return [availableWidth, availableHeight];
  7646. }
  7647. /**
  7648. * Returns an array of the video horizontal and vertical indents,
  7649. * so that if fits its parent.
  7650. *
  7651. * @return an array with 2 elements, the horizontal indent and the vertical
  7652. * indent
  7653. */
  7654. function getCameraVideoPosition(videoWidth,
  7655. videoHeight,
  7656. videoSpaceWidth,
  7657. videoSpaceHeight) {
  7658. // Parent height isn't completely calculated when we position the video in
  7659. // full screen mode and this is why we use the screen height in this case.
  7660. // Need to think it further at some point and implement it properly.
  7661. var isFullScreen = document.fullScreen ||
  7662. document.mozFullScreen ||
  7663. document.webkitIsFullScreen;
  7664. if (isFullScreen)
  7665. videoSpaceHeight = window.innerHeight;
  7666. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7667. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7668. return [horizontalIndent, verticalIndent];
  7669. }
  7670. /**
  7671. * Returns an array of the video horizontal and vertical indents.
  7672. * Centers horizontally and top aligns vertically.
  7673. *
  7674. * @return an array with 2 elements, the horizontal indent and the vertical
  7675. * indent
  7676. */
  7677. function getDesktopVideoPosition(videoWidth,
  7678. videoHeight,
  7679. videoSpaceWidth,
  7680. videoSpaceHeight) {
  7681. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7682. var verticalIndent = 0;// Top aligned
  7683. return [horizontalIndent, verticalIndent];
  7684. }
  7685. /**
  7686. * Returns an array of the video dimensions, so that it covers the screen.
  7687. * It leaves no empty areas, but some parts of the video might not be visible.
  7688. *
  7689. * @return an array with 2 elements, the video width and the video height
  7690. */
  7691. function getCameraVideoSize(videoWidth,
  7692. videoHeight,
  7693. videoSpaceWidth,
  7694. videoSpaceHeight) {
  7695. if (!videoWidth)
  7696. videoWidth = currentVideoWidth;
  7697. if (!videoHeight)
  7698. videoHeight = currentVideoHeight;
  7699. var aspectRatio = videoWidth / videoHeight;
  7700. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7701. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7702. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7703. availableHeight = videoSpaceHeight;
  7704. availableWidth = availableHeight * aspectRatio;
  7705. }
  7706. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7707. availableWidth = videoSpaceWidth;
  7708. availableHeight = availableWidth / aspectRatio;
  7709. }
  7710. return [availableWidth, availableHeight];
  7711. }
  7712. /**
  7713. * Updates the src of the active speaker avatar
  7714. * @param jid of the current active speaker
  7715. */
  7716. function updateActiveSpeakerAvatarSrc() {
  7717. var avatar = $("#activeSpeakerAvatar")[0];
  7718. var jid = currentSmallVideo.peerJid;
  7719. var url = Avatar.getActiveSpeakerUrl(jid);
  7720. if (avatar.src === url)
  7721. return;
  7722. if (jid) {
  7723. avatar.src = url;
  7724. currentSmallVideo.showAvatar();
  7725. }
  7726. }
  7727. /**
  7728. * Change the video source of the large video.
  7729. * @param isVisible
  7730. */
  7731. function changeVideo(isVisible) {
  7732. if (!currentSmallVideo) {
  7733. console.error("Unable to change large video - no 'currentSmallVideo'");
  7734. return;
  7735. }
  7736. updateActiveSpeakerAvatarSrc();
  7737. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7738. var videoTransform = document.getElementById('largeVideo')
  7739. .style.webkitTransform;
  7740. var flipX = currentSmallVideo.flipX;
  7741. if (flipX && videoTransform !== 'scaleX(-1)') {
  7742. document.getElementById('largeVideo').style.webkitTransform =
  7743. "scaleX(-1)";
  7744. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7745. document.getElementById('largeVideo').style.webkitTransform =
  7746. "none";
  7747. }
  7748. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7749. // Change the way we'll be measuring and positioning large video
  7750. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7751. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7752. getCameraVideoPosition;
  7753. // Only if the large video is currently visible.
  7754. if (isVisible) {
  7755. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7756. $('#largeVideo').fadeIn(300);
  7757. }
  7758. }
  7759. /**
  7760. * Creates the html elements for the large video.
  7761. */
  7762. function createLargeVideoHTML()
  7763. {
  7764. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7765. html += '<div id="presentation"></div>' +
  7766. '<div id="etherpad"></div>' +
  7767. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7768. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7769. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7770. '<span data-i18n="poweredby"></span> jitsi.org' +
  7771. '</a>'+
  7772. '<div id="activeSpeaker">' +
  7773. '<img id="activeSpeakerAvatar" src=""/>' +
  7774. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7775. '</div>' +
  7776. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7777. '<span id="videoConnectionMessage"></span>';
  7778. html += '</div>';
  7779. $(html).prependTo("#videospace");
  7780. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7781. var leftWatermarkDiv
  7782. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7783. leftWatermarkDiv.css({display: 'block'});
  7784. leftWatermarkDiv.parent().get(0).href
  7785. = interfaceConfig.JITSI_WATERMARK_LINK;
  7786. }
  7787. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7788. var rightWatermarkDiv
  7789. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7790. rightWatermarkDiv.css({display: 'block'});
  7791. rightWatermarkDiv.parent().get(0).href
  7792. = interfaceConfig.BRAND_WATERMARK_LINK;
  7793. rightWatermarkDiv.get(0).style.backgroundImage
  7794. = "url(images/rightwatermark.png)";
  7795. }
  7796. if (interfaceConfig.SHOW_POWERED_BY) {
  7797. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7798. }
  7799. if (!RTCBrowserType.isIExplorer()) {
  7800. $('#largeVideo').volume = 0;
  7801. }
  7802. }
  7803. var LargeVideo = {
  7804. init: function (VideoLayout, emitter) {
  7805. if(!isEnabled)
  7806. return;
  7807. createLargeVideoHTML();
  7808. this.VideoLayout = VideoLayout;
  7809. this.eventEmitter = emitter;
  7810. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7811. var self = this;
  7812. // Listen for large video size updates
  7813. var largeVideo = $('#largeVideo')[0];
  7814. var onplaying = function (arg1, arg2, arg3) {
  7815. // re-select
  7816. if (RTCBrowserType.isTemasysPluginUsed())
  7817. largeVideo = $('#largeVideo')[0];
  7818. currentVideoWidth = largeVideo.videoWidth;
  7819. currentVideoHeight = largeVideo.videoHeight;
  7820. self.position(currentVideoWidth, currentVideoHeight);
  7821. };
  7822. largeVideo.onplaying = onplaying;
  7823. },
  7824. /**
  7825. * Indicates if the large video is currently visible.
  7826. *
  7827. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7828. */
  7829. isLargeVideoVisible: function() {
  7830. return $('#largeVideo').is(':visible');
  7831. },
  7832. /**
  7833. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7834. */
  7835. isCurrentlyOnLarge: function (resourceJid) {
  7836. return currentSmallVideo && resourceJid &&
  7837. currentSmallVideo.getResourceJid() === resourceJid;
  7838. },
  7839. /**
  7840. * Updates the large video with the given new video source.
  7841. */
  7842. updateLargeVideo: function (resourceJid, forceUpdate) {
  7843. if(!isEnabled)
  7844. return;
  7845. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7846. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7847. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7848. $('#activeSpeaker').css('visibility', 'hidden');
  7849. var oldSmallVideo = null;
  7850. if (currentSmallVideo) {
  7851. oldSmallVideo = currentSmallVideo;
  7852. }
  7853. currentSmallVideo = newSmallVideo;
  7854. var oldJid = null;
  7855. if (oldSmallVideo)
  7856. oldJid = oldSmallVideo.peerJid;
  7857. if (oldJid !== resourceJid) {
  7858. // we want the notification to trigger even if userJid is undefined,
  7859. // or null.
  7860. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7861. }
  7862. if (RTCBrowserType.isSafari()) {
  7863. // FIXME In Safari fadeOut works only for the first time
  7864. changeVideo(this.isLargeVideoVisible());
  7865. } else {
  7866. $('#largeVideo').fadeOut(300,
  7867. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7868. }
  7869. } else {
  7870. if (currentSmallVideo) {
  7871. currentSmallVideo.showAvatar();
  7872. }
  7873. }
  7874. },
  7875. /**
  7876. * Shows/hides the large video.
  7877. */
  7878. setLargeVideoVisible: function(isVisible) {
  7879. if(!isEnabled)
  7880. return;
  7881. if (isVisible) {
  7882. $('#largeVideo').css({visibility: 'visible'});
  7883. $('.watermark').css({visibility: 'visible'});
  7884. if(currentSmallVideo)
  7885. currentSmallVideo.enableDominantSpeaker(true);
  7886. }
  7887. else {
  7888. $('#largeVideo').css({visibility: 'hidden'});
  7889. $('#activeSpeaker').css('visibility', 'hidden');
  7890. $('.watermark').css({visibility: 'hidden'});
  7891. if(currentSmallVideo)
  7892. currentSmallVideo.enableDominantSpeaker(false);
  7893. }
  7894. },
  7895. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7896. if (!isEnabled)
  7897. return;
  7898. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7899. {
  7900. var isDesktop = newVideoType === 'screen';
  7901. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7902. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7903. : getCameraVideoPosition;
  7904. this.position(null, null);
  7905. }
  7906. },
  7907. /**
  7908. * Positions the large video.
  7909. *
  7910. * @param videoWidth the stream video width
  7911. * @param videoHeight the stream video height
  7912. */
  7913. position: function (videoWidth, videoHeight,
  7914. videoSpaceWidth, videoSpaceHeight, animate) {
  7915. if(!isEnabled)
  7916. return;
  7917. if(!videoSpaceWidth)
  7918. videoSpaceWidth = $('#videospace').width();
  7919. if(!videoSpaceHeight)
  7920. videoSpaceHeight = window.innerHeight;
  7921. var videoSize = getVideoSize(videoWidth,
  7922. videoHeight,
  7923. videoSpaceWidth,
  7924. videoSpaceHeight);
  7925. var largeVideoWidth = videoSize[0];
  7926. var largeVideoHeight = videoSize[1];
  7927. var videoPosition = getVideoPosition(largeVideoWidth,
  7928. largeVideoHeight,
  7929. videoSpaceWidth,
  7930. videoSpaceHeight);
  7931. var horizontalIndent = videoPosition[0];
  7932. var verticalIndent = videoPosition[1];
  7933. positionVideo($('#largeVideo'),
  7934. largeVideoWidth,
  7935. largeVideoHeight,
  7936. horizontalIndent, verticalIndent, animate);
  7937. },
  7938. /**
  7939. * Resizes the large html elements.
  7940. * @param animate boolean property that indicates whether the resize should be animated or not.
  7941. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  7942. * If that parameter is null the method will check the chat pannel visibility.
  7943. * @param completeFunction a function to be called when the video space is resized
  7944. * @returns {*[]} array with the current width and height values of the largeVideo html element.
  7945. */
  7946. resize: function (animate, isVisible, completeFunction) {
  7947. if(!isEnabled)
  7948. return;
  7949. var availableHeight = window.innerHeight;
  7950. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7951. if (availableWidth < 0 || availableHeight < 0) return;
  7952. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7953. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7954. $('#activeSpeaker').css('top', top);
  7955. this.VideoLayout.resizeVideoSpace(animate, isVisible, completeFunction);
  7956. if(animate) {
  7957. $('#largeVideoContainer').animate({
  7958. width: availableWidth,
  7959. height: availableHeight
  7960. },
  7961. {
  7962. queue: false,
  7963. duration: 500
  7964. });
  7965. } else {
  7966. $('#largeVideoContainer').width(availableWidth);
  7967. $('#largeVideoContainer').height(availableHeight);
  7968. }
  7969. return [availableWidth, availableHeight];
  7970. },
  7971. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7972. if(!isEnabled)
  7973. return;
  7974. var size = this.resize(true, isVisible, completeFunction);
  7975. this.position(null, null, size[0], size[1], true);
  7976. },
  7977. getResourceJid: function () {
  7978. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7979. },
  7980. updateAvatar: function (resourceJid) {
  7981. if(!isEnabled)
  7982. return;
  7983. if (resourceJid === this.getResourceJid()) {
  7984. updateActiveSpeakerAvatarSrc();
  7985. }
  7986. },
  7987. showAvatar: function (resourceJid, show) {
  7988. if(!isEnabled)
  7989. return;
  7990. if(this.getResourceJid() === resourceJid && state === "video") {
  7991. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7992. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7993. return true;
  7994. }
  7995. return false;
  7996. },
  7997. /**
  7998. * Disables the large video
  7999. */
  8000. disable: function () {
  8001. isEnabled = false;
  8002. },
  8003. /**
  8004. * Enables the large video
  8005. */
  8006. enable: function () {
  8007. isEnabled = true;
  8008. },
  8009. /**
  8010. * Returns true if the video is enabled.
  8011. */
  8012. isEnabled: function () {
  8013. return isEnabled;
  8014. },
  8015. /**
  8016. * Creates the iframe used by the etherpad
  8017. * @param src the value for src attribute
  8018. * @param onloadHandler handler executed when the iframe loads it content
  8019. * @returns {HTMLElement} the iframe
  8020. */
  8021. createEtherpadIframe: function (src, onloadHandler) {
  8022. if(!isEnabled)
  8023. return;
  8024. var etherpadIFrame = document.createElement('iframe');
  8025. etherpadIFrame.src = src;
  8026. etherpadIFrame.frameBorder = 0;
  8027. etherpadIFrame.scrolling = "no";
  8028. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  8029. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  8030. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  8031. document.getElementById('etherpad').appendChild(etherpadIFrame);
  8032. etherpadIFrame.onload = onloadHandler;
  8033. return etherpadIFrame;
  8034. },
  8035. /**
  8036. * Changes the state of the large video.
  8037. * Possible values - video, prezi, etherpad.
  8038. * @param newState - the new state
  8039. */
  8040. setState: function (newState) {
  8041. if(state === newState)
  8042. return;
  8043. var currentContainer = getContainerByState(state);
  8044. if(!currentContainer)
  8045. return;
  8046. var self = this;
  8047. var oldState = state;
  8048. switch (newState)
  8049. {
  8050. case "etherpad":
  8051. $('#activeSpeaker').css('visibility', 'hidden');
  8052. currentContainer.fadeOut(300, function () {
  8053. if (oldState === "prezi") {
  8054. currentContainer.css({opacity: '0'});
  8055. $('#reloadPresentation').css({display: 'none'});
  8056. }
  8057. else {
  8058. self.setLargeVideoVisible(false);
  8059. }
  8060. });
  8061. $('#etherpad>iframe').fadeIn(300, function () {
  8062. document.body.style.background = '#eeeeee';
  8063. $('#etherpad>iframe').css({visibility: 'visible'});
  8064. $('#etherpad').css({zIndex: 2});
  8065. });
  8066. break;
  8067. case "prezi":
  8068. var prezi = $('#presentation>iframe');
  8069. currentContainer.fadeOut(300, function() {
  8070. document.body.style.background = 'black';
  8071. });
  8072. prezi.fadeIn(300, function() {
  8073. prezi.css({opacity:'1'});
  8074. ToolbarToggler.dockToolbar(true);//fix that
  8075. self.setLargeVideoVisible(false);
  8076. $('#etherpad>iframe').css({visibility: 'hidden'});
  8077. $('#etherpad').css({zIndex: 0});
  8078. });
  8079. $('#activeSpeaker').css('visibility', 'hidden');
  8080. break;
  8081. case "video":
  8082. currentContainer.fadeOut(300, function () {
  8083. $('#presentation>iframe').css({opacity:'0'});
  8084. $('#reloadPresentation').css({display:'none'});
  8085. $('#etherpad>iframe').css({visibility: 'hidden'});
  8086. $('#etherpad').css({zIndex: 0});
  8087. document.body.style.background = 'black';
  8088. ToolbarToggler.dockToolbar(false);//fix that
  8089. });
  8090. $('#largeVideo').fadeIn(300, function () {
  8091. self.setLargeVideoVisible(true);
  8092. });
  8093. break;
  8094. }
  8095. state = newState;
  8096. },
  8097. /**
  8098. * Returns the current state of the large video.
  8099. * @returns {string} the current state - video, prezi or etherpad.
  8100. */
  8101. getState: function () {
  8102. return state;
  8103. },
  8104. /**
  8105. * Sets hover handlers for the large video container div.
  8106. *
  8107. * @param inHandler
  8108. * @param outHandler
  8109. */
  8110. setHover: function(inHandler, outHandler)
  8111. {
  8112. $('#largeVideoContainer').hover(inHandler, outHandler);
  8113. },
  8114. /**
  8115. * Enables/disables the filter indicating a video problem to the user.
  8116. *
  8117. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  8118. */
  8119. enableVideoProblemFilter: function (enable) {
  8120. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  8121. }
  8122. };
  8123. module.exports = LargeVideo;
  8124. },{"../../../service/UI/UIEvents":114,"../../RTC/RTCBrowserType":10,"../../xmpp/xmpp":70,"../avatar/Avatar":18,"../toolbars/ToolbarToggler":31,"../util/UIUtil":35}],38:[function(require,module,exports){
  8125. /* global $, interfaceConfig, APP */
  8126. var SmallVideo = require("./SmallVideo");
  8127. var ConnectionIndicator = require("./ConnectionIndicator");
  8128. var NicknameHandler = require("../util/NicknameHandler");
  8129. var UIUtil = require("../util/UIUtil");
  8130. var LargeVideo = require("./LargeVideo");
  8131. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8132. function LocalVideo(VideoLayout) {
  8133. this.videoSpanId = "localVideoContainer";
  8134. this.container = $("#localVideoContainer").get(0);
  8135. this.VideoLayout = VideoLayout;
  8136. this.flipX = true;
  8137. this.isLocal = true;
  8138. this.peerJid = null;
  8139. }
  8140. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  8141. LocalVideo.prototype.constructor = LocalVideo;
  8142. /**
  8143. * Creates the edit display name button.
  8144. *
  8145. * @returns {object} the edit button
  8146. */
  8147. function createEditDisplayNameButton() {
  8148. var editButton = document.createElement('a');
  8149. editButton.className = 'displayname';
  8150. UIUtil.setTooltip(editButton,
  8151. "videothumbnail.editnickname",
  8152. "top");
  8153. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  8154. return editButton;
  8155. }
  8156. /**
  8157. * Sets the display name for the given video span id.
  8158. */
  8159. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  8160. if (!this.container) {
  8161. console.warn(
  8162. "Unable to set displayName - " + this.videoSpanId +
  8163. " does not exist");
  8164. return;
  8165. }
  8166. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8167. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  8168. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8169. var meHTML;
  8170. // If we already have a display name for this video.
  8171. if (nameSpan.length > 0) {
  8172. if (nameSpan.text() !== displayName) {
  8173. if (displayName && displayName.length > 0) {
  8174. meHTML = APP.translation.generateTranslationHTML("me");
  8175. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  8176. } else {
  8177. $('#localDisplayName').html(defaultLocalDisplayName);
  8178. }
  8179. }
  8180. } else {
  8181. var editButton = createEditDisplayNameButton();
  8182. nameSpan = document.createElement('span');
  8183. nameSpan.className = 'displayname';
  8184. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8185. if (displayName && displayName.length > 0) {
  8186. meHTML = APP.translation.generateTranslationHTML("me");
  8187. nameSpan.innerHTML = displayName + meHTML;
  8188. }
  8189. else {
  8190. nameSpan.innerHTML = defaultLocalDisplayName;
  8191. }
  8192. nameSpan.id = 'localDisplayName';
  8193. this.container.appendChild(editButton);
  8194. //translates popover of edit button
  8195. APP.translation.translateElement($("a.displayname"));
  8196. var editableText = document.createElement('input');
  8197. editableText.className = 'displayname';
  8198. editableText.type = 'text';
  8199. editableText.id = 'editDisplayName';
  8200. if (displayName && displayName.length) {
  8201. editableText.value = displayName;
  8202. }
  8203. var defaultNickname = APP.translation.translateString(
  8204. "defaultNickname", {name: "Jane Pink"});
  8205. editableText.setAttribute('style', 'display:none;');
  8206. editableText.setAttribute('data-18n',
  8207. '[placeholder]defaultNickname');
  8208. editableText.setAttribute("data-i18n-options",
  8209. JSON.stringify({name: "Jane Pink"}));
  8210. editableText.setAttribute("placeholder", defaultNickname);
  8211. this.container.appendChild(editableText);
  8212. var self = this;
  8213. $('#localVideoContainer .displayname')
  8214. .bind("click", function (e) {
  8215. var editDisplayName = $('#editDisplayName');
  8216. e.preventDefault();
  8217. e.stopPropagation();
  8218. $('#localDisplayName').hide();
  8219. editDisplayName.show();
  8220. editDisplayName.focus();
  8221. editDisplayName.select();
  8222. editDisplayName.one("focusout", function (e) {
  8223. self.VideoLayout.inputDisplayNameHandler(this.value);
  8224. });
  8225. editDisplayName.on('keydown', function (e) {
  8226. if (e.keyCode === 13) {
  8227. e.preventDefault();
  8228. self.VideoLayout.inputDisplayNameHandler(this.value);
  8229. }
  8230. });
  8231. });
  8232. }
  8233. };
  8234. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  8235. NicknameHandler.setNickname(name);
  8236. var localDisplayName = $('#localDisplayName');
  8237. if (!localDisplayName.is(":visible")) {
  8238. if (NicknameHandler.getNickname()) {
  8239. var meHTML = APP.translation.generateTranslationHTML("me");
  8240. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  8241. meHTML + ")");
  8242. } else {
  8243. var defaultHTML = APP.translation.generateTranslationHTML(
  8244. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8245. localDisplayName .html(defaultHTML);
  8246. }
  8247. localDisplayName.show();
  8248. }
  8249. $('#editDisplayName').hide();
  8250. };
  8251. LocalVideo.prototype.createConnectionIndicator = function() {
  8252. if(this.connectionIndicator)
  8253. return;
  8254. this.connectionIndicator = new ConnectionIndicator(this, null);
  8255. };
  8256. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  8257. var self = this;
  8258. function localVideoClick(event) {
  8259. // FIXME: with Temasys plugin event arg is not an event, but
  8260. // the clicked object itself, so we have to skip this call
  8261. if (event.stopPropagation) {
  8262. event.stopPropagation();
  8263. }
  8264. self.VideoLayout.handleVideoThumbClicked(
  8265. false,
  8266. APP.xmpp.myResource());
  8267. }
  8268. var localVideoContainerSelector = $('#localVideoContainer');
  8269. localVideoContainerSelector.off('click');
  8270. localVideoContainerSelector.on('click', localVideoClick);
  8271. // Add hover handler
  8272. localVideoContainerSelector.hover(
  8273. function() {
  8274. self.showDisplayName(true);
  8275. },
  8276. function() {
  8277. if (!LargeVideo.isLargeVideoVisible() ||
  8278. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  8279. self.showDisplayName(false);
  8280. }
  8281. }
  8282. );
  8283. if(isMuted) {
  8284. APP.UI.setVideoMute(true);
  8285. return;
  8286. }
  8287. this.flipX = stream.videoType != "screen";
  8288. var localVideo = document.createElement('video');
  8289. localVideo.id = 'localVideo_' +
  8290. APP.RTC.getStreamID(stream.getOriginalStream());
  8291. if (!RTCBrowserType.isIExplorer()) {
  8292. localVideo.autoplay = true;
  8293. localVideo.volume = 0; // is it required if audio is separated ?
  8294. }
  8295. localVideo.oncontextmenu = function () { return false; };
  8296. var localVideoContainer = document.getElementById('localVideoWrapper');
  8297. // Put the new video always in front
  8298. UIUtil.prependChild(localVideoContainer, localVideo);
  8299. var localVideoSelector = $('#' + localVideo.id);
  8300. // Add click handler to both video and video wrapper elements in case
  8301. // there's no video.
  8302. // onclick has to be used with Temasys plugin
  8303. localVideo.onclick = localVideoClick;
  8304. if (this.flipX) {
  8305. localVideoSelector.addClass("flipVideoX");
  8306. }
  8307. // Attach WebRTC stream
  8308. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  8309. // Add stream ended handler
  8310. stream.getOriginalStream().onended = function () {
  8311. // We have to re-select after attach when Temasys plugin is used,
  8312. // because <video> element is replaced with <object>
  8313. localVideo = $('#' + localVideo.id)[0];
  8314. localVideoContainer.removeChild(localVideo);
  8315. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  8316. };
  8317. };
  8318. LocalVideo.prototype.joined = function (jid) {
  8319. this.peerJid = jid;
  8320. };
  8321. LocalVideo.prototype.getResourceJid = function () {
  8322. var myResource = APP.xmpp.myResource();
  8323. if (!myResource) {
  8324. console.error("Requested local resource before we're in the MUC");
  8325. }
  8326. return myResource;
  8327. };
  8328. module.exports = LocalVideo;
  8329. },{"../../RTC/RTCBrowserType":10,"../util/NicknameHandler":34,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],39:[function(require,module,exports){
  8330. /* global $, APP, require, Strophe, interfaceConfig */
  8331. var ConnectionIndicator = require("./ConnectionIndicator");
  8332. var SmallVideo = require("./SmallVideo");
  8333. var AudioLevels = require("../audio_levels/AudioLevels");
  8334. var LargeVideo = require("./LargeVideo");
  8335. var Avatar = require("../avatar/Avatar");
  8336. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8337. var UIUtils = require("../util/UIUtil");
  8338. function RemoteVideo(peerJid, VideoLayout) {
  8339. this.peerJid = peerJid;
  8340. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  8341. this.videoSpanId = 'participant_' + this.resourceJid;
  8342. this.VideoLayout = VideoLayout;
  8343. this.addRemoteVideoContainer();
  8344. this.connectionIndicator = new ConnectionIndicator(
  8345. this, this.peerJid);
  8346. this.setDisplayName();
  8347. var nickfield = document.createElement('span');
  8348. nickfield.className = "nick";
  8349. nickfield.appendChild(document.createTextNode(this.resourceJid));
  8350. this.container.appendChild(nickfield);
  8351. this.flipX = false;
  8352. this.isLocal = false;
  8353. }
  8354. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  8355. RemoteVideo.prototype.constructor = RemoteVideo;
  8356. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  8357. this.container = RemoteVideo.createContainer(this.videoSpanId);
  8358. if (APP.xmpp.isModerator())
  8359. this.addRemoteVideoMenu();
  8360. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  8361. return this.container;
  8362. };
  8363. /**
  8364. * Adds the remote video menu element for the given <tt>jid</tt> in the
  8365. * given <tt>parentElement</tt>.
  8366. *
  8367. * @param jid the jid indicating the video for which we're adding a menu.
  8368. * @param parentElement the parent element where this menu will be added
  8369. */
  8370. if (!interfaceConfig.filmStripOnly) {
  8371. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  8372. var spanElement = document.createElement('span');
  8373. spanElement.className = 'remotevideomenu';
  8374. this.container.appendChild(spanElement);
  8375. var menuElement = document.createElement('i');
  8376. menuElement.className = 'fa fa-angle-down';
  8377. menuElement.title = 'Remote user controls';
  8378. spanElement.appendChild(menuElement);
  8379. var popupmenuElement = document.createElement('ul');
  8380. popupmenuElement.className = 'popupmenu';
  8381. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  8382. spanElement.appendChild(popupmenuElement);
  8383. var muteMenuItem = document.createElement('li');
  8384. var muteLinkItem = document.createElement('a');
  8385. var mutedIndicator = "<i style='float:left;' " +
  8386. "class='icon-mic-disabled'></i>";
  8387. if (!this.isMuted) {
  8388. muteLinkItem.innerHTML = mutedIndicator +
  8389. " <div style='width: 90px;margin-left: 20px;' " +
  8390. "data-i18n='videothumbnail.domute'></div>";
  8391. muteLinkItem.className = 'mutelink';
  8392. }
  8393. else {
  8394. muteLinkItem.innerHTML = mutedIndicator +
  8395. " <div style='width: 90px;margin-left: 20px;' " +
  8396. "data-i18n='videothumbnail.muted'></div>";
  8397. muteLinkItem.className = 'mutelink disabled';
  8398. }
  8399. var self = this;
  8400. muteLinkItem.onclick = function(){
  8401. if ($(this).attr('disabled') != undefined) {
  8402. event.preventDefault();
  8403. }
  8404. var isMute = self.isMuted == true;
  8405. APP.xmpp.setMute(self.peerJid, !isMute);
  8406. popupmenuElement.setAttribute('style', 'display:none;');
  8407. if (isMute) {
  8408. this.innerHTML = mutedIndicator +
  8409. " <div style='width: 90px;margin-left: 20px;' " +
  8410. "data-i18n='videothumbnail.muted'></div>";
  8411. this.className = 'mutelink disabled';
  8412. }
  8413. else {
  8414. this.innerHTML = mutedIndicator +
  8415. " <div style='width: 90px;margin-left: 20px;' " +
  8416. "data-i18n='videothumbnail.domute'></div>";
  8417. this.className = 'mutelink';
  8418. }
  8419. };
  8420. muteMenuItem.appendChild(muteLinkItem);
  8421. popupmenuElement.appendChild(muteMenuItem);
  8422. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8423. var ejectMenuItem = document.createElement('li');
  8424. var ejectLinkItem = document.createElement('a');
  8425. var ejectText = "<div style='width: 90px;margin-left: 20px;' " +
  8426. "data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8427. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8428. ejectLinkItem.onclick = function(){
  8429. APP.xmpp.eject(self.peerJid);
  8430. popupmenuElement.setAttribute('style', 'display:none;');
  8431. };
  8432. ejectMenuItem.appendChild(ejectLinkItem);
  8433. popupmenuElement.appendChild(ejectMenuItem);
  8434. var paddingSpan = document.createElement('span');
  8435. paddingSpan.className = 'popupmenuPadding';
  8436. popupmenuElement.appendChild(paddingSpan);
  8437. APP.translation.translateElement(
  8438. $("#" + popupmenuElement.id + " > li > a > div"));
  8439. };
  8440. } else {
  8441. RemoteVideo.prototype.addRemoteVideoMenu = function() {}
  8442. }
  8443. /**
  8444. * Removes the remote stream element corresponding to the given stream and
  8445. * parent container.
  8446. *
  8447. * @param stream the stream
  8448. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8449. */
  8450. RemoteVideo.prototype.removeRemoteStreamElement =
  8451. function (stream, isVideo, id) {
  8452. if (!this.container)
  8453. return false;
  8454. var select = null;
  8455. if (isVideo) {
  8456. select = $('#' + id);
  8457. }
  8458. else
  8459. select = $('#' + this.videoSpanId + '>audio');
  8460. select.remove();
  8461. console.info((isVideo ? "Video" : "Audio") +
  8462. " removed " + this.getResourceJid(), select);
  8463. if (isVideo)
  8464. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8465. };
  8466. /**
  8467. * Removes RemoteVideo from the page.
  8468. */
  8469. RemoteVideo.prototype.remove = function () {
  8470. console.log("Remove thumbnail", this.peerJid);
  8471. this.removeConnectionIndicator();
  8472. // Remove whole container
  8473. if (this.container.parentNode)
  8474. this.container.parentNode.removeChild(this.container);
  8475. };
  8476. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8477. var isVideo = stream.getVideoTracks().length > 0;
  8478. if (!isVideo || stream.id === 'mixedmslabel') {
  8479. return;
  8480. }
  8481. var self = this;
  8482. var resourceJid = this.getResourceJid();
  8483. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8484. // when video playback starts
  8485. var onPlayingHandler = function () {
  8486. // FIXME: why do i have to do this for FF?
  8487. if (RTCBrowserType.isFirefox()) {
  8488. APP.RTC.attachMediaStream(sel, stream);
  8489. }
  8490. if (RTCBrowserType.isTemasysPluginUsed()) {
  8491. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8492. }
  8493. self.VideoLayout.videoactive(sel, resourceJid);
  8494. sel[0].onplaying = null;
  8495. if (RTCBrowserType.isTemasysPluginUsed()) {
  8496. // 'currentTime' is used to check if the video has started
  8497. // and the value is not set by the plugin, so we do it
  8498. sel[0].currentTime = 1;
  8499. }
  8500. };
  8501. sel[0].onplaying = onPlayingHandler;
  8502. };
  8503. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8504. if (!this.container)
  8505. return;
  8506. var self = this;
  8507. var isVideo = stream.getVideoTracks().length > 0;
  8508. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8509. var newElementId = streamElement.id;
  8510. // Put new stream element always in front
  8511. UIUtils.prependChild(this.container, streamElement);
  8512. var sel = $('#' + newElementId);
  8513. sel.hide();
  8514. // If the container is currently visible we attach the stream.
  8515. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8516. this.waitForPlayback(sel, stream);
  8517. APP.RTC.attachMediaStream(sel, stream);
  8518. }
  8519. stream.onended = function () {
  8520. console.log('stream ended', this);
  8521. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8522. };
  8523. // Name of video element name is different for IE/Safari
  8524. var videoElem = APP.RTC.getVideoElementName();
  8525. // Add click handler.
  8526. var onClickHandler = function (event) {
  8527. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8528. // On IE we need to populate this handler on video <object>
  8529. // and it does not give event instance as an argument,
  8530. // so we check here for methods.
  8531. if (event.stopPropagation && event.preventDefault) {
  8532. event.stopPropagation();
  8533. event.preventDefault();
  8534. }
  8535. return false;
  8536. };
  8537. this.container.onclick = onClickHandler;
  8538. // reselect
  8539. if (RTCBrowserType.isTemasysPluginUsed())
  8540. sel = $('#' + newElementId);
  8541. sel[0].onclick = onClickHandler;
  8542. //FIXME
  8543. // Add hover handler
  8544. $(this.container).hover(
  8545. function() {
  8546. self.showDisplayName(true);
  8547. },
  8548. function() {
  8549. // If the video has been "pinned" by the user we want to
  8550. // keep the display name on place.
  8551. if (!LargeVideo.isLargeVideoVisible() ||
  8552. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8553. self.showDisplayName(false);
  8554. }
  8555. );
  8556. },
  8557. /**
  8558. * Show/hide peer container for the given resourceJid.
  8559. */
  8560. RemoteVideo.prototype.showPeerContainer = function (state) {
  8561. if (!this.container)
  8562. return;
  8563. var isHide = state === 'hide';
  8564. var resizeThumbnails = false;
  8565. if (!isHide) {
  8566. if (!$(this.container).is(':visible')) {
  8567. resizeThumbnails = true;
  8568. $(this.container).show();
  8569. }
  8570. this.showAvatar(state !== 'show');
  8571. }
  8572. else if ($(this.container).is(':visible') && isHide)
  8573. {
  8574. resizeThumbnails = true;
  8575. $(this.container).hide();
  8576. if(this.connectionIndicator)
  8577. this.connectionIndicator.hide();
  8578. }
  8579. if (resizeThumbnails) {
  8580. this.VideoLayout.resizeThumbnails();
  8581. }
  8582. // We want to be able to pin a participant from the contact list, even
  8583. // if he's not in the lastN set!
  8584. // ContactList.setClickable(resourceJid, !isHide);
  8585. };
  8586. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8587. if (this.connectionIndicator)
  8588. this.connectionIndicator.remove();
  8589. };
  8590. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8591. if (this.connectionIndicator)
  8592. this.connectionIndicator.hide();
  8593. };
  8594. /**
  8595. * Updates the remote video menu.
  8596. *
  8597. * @param jid the jid indicating the video for which we're adding a menu.
  8598. * @param isMuted indicates the current mute state
  8599. */
  8600. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8601. var muteMenuItem
  8602. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8603. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8604. if (muteMenuItem.length) {
  8605. var muteLink = muteMenuItem.get(0);
  8606. if (isMuted === 'true') {
  8607. muteLink.innerHTML = mutedIndicator + ' Muted';
  8608. muteLink.className = 'mutelink disabled';
  8609. }
  8610. else {
  8611. muteLink.innerHTML = mutedIndicator + ' Mute';
  8612. muteLink.className = 'mutelink';
  8613. }
  8614. }
  8615. };
  8616. /**
  8617. * Sets the display name for the given video span id.
  8618. */
  8619. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8620. if (!this.container) {
  8621. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8622. " does not exist");
  8623. return;
  8624. }
  8625. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8626. // If we already have a display name for this video.
  8627. if (nameSpan.length > 0) {
  8628. if (displayName && displayName.length > 0) {
  8629. $('#' + this.videoSpanId + '_name').html(displayName);
  8630. }
  8631. else if (key && key.length > 0) {
  8632. var nameHtml = APP.translation.generateTranslationHTML(key);
  8633. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8634. }
  8635. else
  8636. $('#' + this.videoSpanId + '_name').text(
  8637. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8638. } else {
  8639. nameSpan = document.createElement('span');
  8640. nameSpan.className = 'displayname';
  8641. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8642. if (displayName && displayName.length > 0) {
  8643. nameSpan.innerText = displayName;
  8644. }
  8645. else
  8646. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8647. nameSpan.id = this.videoSpanId + '_name';
  8648. }
  8649. };
  8650. /**
  8651. * Removes remote video menu element from video element identified by
  8652. * given <tt>videoElementId</tt>.
  8653. *
  8654. * @param videoElementId the id of local or remote video element.
  8655. */
  8656. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8657. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8658. if (menuSpan.length) {
  8659. menuSpan.remove();
  8660. }
  8661. };
  8662. RemoteVideo.prototype.getResourceJid = function () {
  8663. if (!this.resourceJid) {
  8664. console.error("Undefined resource jid");
  8665. }
  8666. return this.resourceJid;
  8667. };
  8668. RemoteVideo.createContainer = function (spanId) {
  8669. var container = document.createElement('span');
  8670. container.id = spanId;
  8671. container.className = 'videocontainer';
  8672. var remotes = document.getElementById('remoteVideos');
  8673. return remotes.appendChild(container);
  8674. };
  8675. module.exports = RemoteVideo;
  8676. },{"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../avatar/Avatar":18,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],40:[function(require,module,exports){
  8677. /* global $, APP, require */
  8678. var Avatar = require("../avatar/Avatar");
  8679. var UIUtil = require("../util/UIUtil");
  8680. var LargeVideo = require("./LargeVideo");
  8681. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8682. function SmallVideo() {
  8683. this.isMuted = false;
  8684. this.hasAvatar = false;
  8685. }
  8686. function setVisibility(selector, show) {
  8687. if (selector && selector.length > 0) {
  8688. selector.css("visibility", show ? "visible" : "hidden");
  8689. }
  8690. }
  8691. SmallVideo.prototype.showDisplayName = function(isShow) {
  8692. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8693. if (isShow) {
  8694. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8695. nameSpan.setAttribute("style", "display:inline-block;");
  8696. }
  8697. else {
  8698. if (nameSpan)
  8699. nameSpan.setAttribute("style", "display:none;");
  8700. }
  8701. };
  8702. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8703. if(!this.container)
  8704. return;
  8705. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8706. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8707. noMic.remove();
  8708. noVideo.remove();
  8709. if (!devices.audio) {
  8710. this.container.appendChild(
  8711. document.createElement("div")).setAttribute("class", "noMic");
  8712. }
  8713. if (!devices.video) {
  8714. this.container.appendChild(
  8715. document.createElement("div")).setAttribute("class", "noVideo");
  8716. }
  8717. if (!devices.audio && !devices.video) {
  8718. noMic.css("background-position", "75%");
  8719. noVideo.css("background-position", "25%");
  8720. noVideo.css("background-color", "transparent");
  8721. }
  8722. };
  8723. /**
  8724. * Sets the type of the video displayed by this instance.
  8725. * @param videoType 'camera' or 'screen'
  8726. */
  8727. SmallVideo.prototype.setVideoType = function (videoType) {
  8728. this.videoType = videoType;
  8729. };
  8730. /**
  8731. * Returns the type of the video displayed by this instance.
  8732. * @returns {String} 'camera', 'screen' or undefined.
  8733. */
  8734. SmallVideo.prototype.getVideoType = function () {
  8735. return this.videoType;
  8736. };
  8737. /**
  8738. * Shows the presence status message for the given video.
  8739. */
  8740. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8741. if (!this.container) {
  8742. // No container
  8743. return;
  8744. }
  8745. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8746. if (!statusSpan.length) {
  8747. //Add status span
  8748. statusSpan = document.createElement('span');
  8749. statusSpan.className = 'status';
  8750. statusSpan.id = this.videoSpanId + '_status';
  8751. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8752. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8753. }
  8754. // Display status
  8755. if (statusMsg && statusMsg.length) {
  8756. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8757. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8758. }
  8759. else {
  8760. // Hide
  8761. statusSpan.get(0).setAttribute("style", "display:none;");
  8762. }
  8763. };
  8764. /**
  8765. * Creates an audio or video stream element.
  8766. */
  8767. SmallVideo.createStreamElement = function (sid, stream) {
  8768. var isVideo = stream.getVideoTracks().length > 0;
  8769. var element = isVideo ? document.createElement('video')
  8770. : document.createElement('audio');
  8771. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8772. APP.RTC.getStreamID(stream);
  8773. element.id = id;
  8774. if (!RTCBrowserType.isIExplorer()) {
  8775. element.autoplay = true;
  8776. }
  8777. element.oncontextmenu = function () { return false; };
  8778. return element;
  8779. };
  8780. /**
  8781. * Updates the data for the indicator
  8782. * @param id the id of the indicator
  8783. * @param percent the percent for connection quality
  8784. * @param object the data
  8785. */
  8786. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8787. if(this.connectionIndicator)
  8788. this.connectionIndicator.updateConnectionQuality(percent, object);
  8789. };
  8790. SmallVideo.prototype.hideIndicator = function () {
  8791. if(this.connectionIndicator)
  8792. this.connectionIndicator.hideIndicator();
  8793. };
  8794. /**
  8795. * Shows audio muted indicator over small videos.
  8796. * @param {string} isMuted
  8797. */
  8798. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8799. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8800. if (!isMuted) {
  8801. if (audioMutedSpan.length > 0) {
  8802. audioMutedSpan.popover('hide');
  8803. audioMutedSpan.remove();
  8804. }
  8805. }
  8806. else {
  8807. if(audioMutedSpan.length == 0 ) {
  8808. audioMutedSpan = document.createElement('span');
  8809. audioMutedSpan.className = 'audioMuted';
  8810. UIUtil.setTooltip(audioMutedSpan,
  8811. "videothumbnail.mute",
  8812. "top");
  8813. this.container.appendChild(audioMutedSpan);
  8814. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8815. var mutedIndicator = document.createElement('i');
  8816. mutedIndicator.className = 'icon-mic-disabled';
  8817. audioMutedSpan.appendChild(mutedIndicator);
  8818. }
  8819. this.updateIconPositions();
  8820. }
  8821. this.isMuted = isMuted;
  8822. };
  8823. /**
  8824. * Shows video muted indicator over small videos.
  8825. */
  8826. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8827. this.showAvatar(isMuted);
  8828. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8829. if (isMuted === false) {
  8830. if (videoMutedSpan.length > 0) {
  8831. videoMutedSpan.remove();
  8832. }
  8833. }
  8834. else {
  8835. if(videoMutedSpan.length == 0) {
  8836. videoMutedSpan = document.createElement('span');
  8837. videoMutedSpan.className = 'videoMuted';
  8838. this.container.appendChild(videoMutedSpan);
  8839. var mutedIndicator = document.createElement('i');
  8840. mutedIndicator.className = 'icon-camera-disabled';
  8841. UIUtil.setTooltip(mutedIndicator,
  8842. "videothumbnail.videomute",
  8843. "top");
  8844. videoMutedSpan.appendChild(mutedIndicator);
  8845. //translate texts for muted indicator
  8846. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8847. }
  8848. this.updateIconPositions();
  8849. }
  8850. };
  8851. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8852. var resourceJid = this.getResourceJid();
  8853. var displayName = resourceJid;
  8854. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8855. if (nameSpan.length > 0)
  8856. displayName = nameSpan.html();
  8857. console.log("UI enable dominant speaker",
  8858. displayName,
  8859. resourceJid,
  8860. isEnable);
  8861. if (!this.container) {
  8862. return;
  8863. }
  8864. if (isEnable) {
  8865. this.showDisplayName(LargeVideo.getState() === "video");
  8866. if (!this.container.classList.contains("dominantspeaker"))
  8867. this.container.classList.add("dominantspeaker");
  8868. }
  8869. else {
  8870. this.showDisplayName(false);
  8871. if (this.container.classList.contains("dominantspeaker"))
  8872. this.container.classList.remove("dominantspeaker");
  8873. }
  8874. this.showAvatar();
  8875. };
  8876. SmallVideo.prototype.updateIconPositions = function () {
  8877. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8878. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8879. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8880. if(connectionIndicator.length > 0 &&
  8881. connectionIndicator[0].style.display != "none") {
  8882. audioMutedSpan.css({right: "23px"});
  8883. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8884. } else {
  8885. audioMutedSpan.css({right: "0px"});
  8886. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8887. }
  8888. };
  8889. /**
  8890. * Creates the element indicating the moderator(owner) of the conference.
  8891. *
  8892. * @param parentElement the parent element where the owner indicator will
  8893. * be added
  8894. */
  8895. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8896. // Show moderator indicator
  8897. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8898. if (!indicatorSpan || indicatorSpan.length === 0) {
  8899. indicatorSpan = document.createElement('span');
  8900. indicatorSpan.className = 'focusindicator';
  8901. this.container.appendChild(indicatorSpan);
  8902. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8903. }
  8904. if (indicatorSpan.children().length !== 0)
  8905. return;
  8906. var moderatorIndicator = document.createElement('i');
  8907. moderatorIndicator.className = 'fa fa-star';
  8908. indicatorSpan[0].appendChild(moderatorIndicator);
  8909. UIUtil.setTooltip(indicatorSpan[0],
  8910. "videothumbnail.moderator",
  8911. "top");
  8912. //translates text in focus indicators
  8913. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8914. };
  8915. SmallVideo.prototype.getSrc = function () {
  8916. var videoElement = APP.RTC.getVideoElementName();
  8917. return APP.RTC.getVideoSrc(
  8918. $('#' + this.videoSpanId).find(videoElement).get(0));
  8919. };
  8920. SmallVideo.prototype.focus = function(isFocused) {
  8921. if(!isFocused) {
  8922. this.container.classList.remove("videoContainerFocused");
  8923. } else {
  8924. this.container.classList.add("videoContainerFocused");
  8925. }
  8926. };
  8927. SmallVideo.prototype.hasVideo = function () {
  8928. return $("#" + this.videoSpanId).find(
  8929. APP.RTC.getVideoElementName()).length !== 0;
  8930. };
  8931. /**
  8932. * Hides or shows the user's avatar
  8933. * @param show whether we should show the avatar or not
  8934. * video because there is no dominant speaker and no focused speaker
  8935. */
  8936. SmallVideo.prototype.showAvatar = function (show) {
  8937. if (!this.hasAvatar) {
  8938. if (this.peerJid) {
  8939. // Init avatar
  8940. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8941. } else {
  8942. console.error("Unable to init avatar - no peerjid", this);
  8943. return;
  8944. }
  8945. }
  8946. var resourceJid = this.getResourceJid();
  8947. var videoElem = APP.RTC.getVideoElementName();
  8948. var video = $('#' + this.videoSpanId).find(videoElem);
  8949. var avatar = $('#avatar_' + resourceJid);
  8950. if (show === undefined || show === null) {
  8951. if (!this.isLocal &&
  8952. !this.VideoLayout.isInLastN(resourceJid)) {
  8953. show = true;
  8954. } else {
  8955. // We want to show the avatar when the video is muted or not exists
  8956. // that is when 'true' or 'null' is returned
  8957. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8958. }
  8959. }
  8960. if (LargeVideo.showAvatar(resourceJid, show)) {
  8961. setVisibility(avatar, false);
  8962. setVisibility(video, false);
  8963. } else {
  8964. if (video && video.length > 0) {
  8965. setVisibility(video, !show);
  8966. }
  8967. setVisibility(avatar, show);
  8968. }
  8969. };
  8970. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8971. var thumbnail = $('#' + this.videoSpanId);
  8972. var resourceJid = this.getResourceJid();
  8973. var avatar = $('#avatar_' + resourceJid);
  8974. this.hasAvatar = true;
  8975. // set the avatar in the thumbnail
  8976. if (avatar && avatar.length > 0) {
  8977. avatar[0].src = thumbUrl;
  8978. } else {
  8979. if (thumbnail && thumbnail.length > 0) {
  8980. avatar = document.createElement('img');
  8981. avatar.id = 'avatar_' + resourceJid;
  8982. avatar.className = 'userAvatar';
  8983. avatar.src = thumbUrl;
  8984. thumbnail.append(avatar);
  8985. }
  8986. }
  8987. };
  8988. module.exports = SmallVideo;
  8989. },{"../../RTC/RTCBrowserType":10,"../avatar/Avatar":18,"../util/UIUtil":35,"./LargeVideo":37}],41:[function(require,module,exports){
  8990. /* global config, APP, $, Strophe, require, interfaceConfig */
  8991. var AudioLevels = require("../audio_levels/AudioLevels");
  8992. var ContactList = require("../side_pannels/contactlist/ContactList");
  8993. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8994. var UIEvents = require("../../../service/UI/UIEvents");
  8995. var UIUtil = require("../util/UIUtil");
  8996. var RTC = require("../../RTC/RTC");
  8997. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8998. var RemoteVideo = require("./RemoteVideo");
  8999. var LargeVideo = require("./LargeVideo");
  9000. var LocalVideo = require("./LocalVideo");
  9001. var remoteVideos = {};
  9002. var remoteVideoTypes = {};
  9003. var localVideoThumbnail = null;
  9004. var currentDominantSpeaker = null;
  9005. var lastNCount = config.channelLastN;
  9006. var localLastNCount = config.channelLastN;
  9007. var localLastNSet = [];
  9008. var lastNEndpointsCache = [];
  9009. var lastNPickupJid = null;
  9010. var eventEmitter = null;
  9011. /**
  9012. * Currently focused video jid
  9013. * @type {String}
  9014. */
  9015. var focusedVideoResourceJid = null;
  9016. var VideoLayout = (function (my) {
  9017. my.init = function (emitter) {
  9018. eventEmitter = emitter;
  9019. localVideoThumbnail = new LocalVideo(VideoLayout);
  9020. if (interfaceConfig.filmStripOnly) {
  9021. LargeVideo.disable();
  9022. } else {
  9023. LargeVideo.init(VideoLayout, emitter);
  9024. }
  9025. VideoLayout.resizeLargeVideoContainer();
  9026. };
  9027. my.isInLastN = function(resource) {
  9028. return lastNCount < 0 || // lastN is disabled
  9029. // lastNEndpoints cache not built yet
  9030. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  9031. (lastNEndpointsCache &&
  9032. lastNEndpointsCache.indexOf(resource) !== -1);
  9033. };
  9034. my.changeLocalStream = function (stream, isMuted) {
  9035. VideoLayout.changeLocalVideo(stream, isMuted);
  9036. };
  9037. my.changeLocalAudio = function(stream, isMuted) {
  9038. if (isMuted)
  9039. APP.UI.setAudioMuted(true, true);
  9040. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  9041. var localAudio = document.getElementById('localAudio');
  9042. // Writing volume not allowed in IE
  9043. if (!RTCBrowserType.isIExplorer()) {
  9044. localAudio.autoplay = true;
  9045. localAudio.volume = 0;
  9046. }
  9047. };
  9048. my.changeLocalVideo = function(stream, isMuted) {
  9049. // Set default display name.
  9050. localVideoThumbnail.setDisplayName();
  9051. localVideoThumbnail.createConnectionIndicator();
  9052. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  9053. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  9054. localVideoThumbnail.changeVideo(stream, isMuted);
  9055. /* force update if we're currently being displayed */
  9056. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  9057. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  9058. }
  9059. };
  9060. my.mucJoined = function () {
  9061. var myResourceJid = APP.xmpp.myResource();
  9062. localVideoThumbnail.joined(APP.xmpp.myJid());
  9063. if (!LargeVideo.getResourceJid())
  9064. LargeVideo.updateLargeVideo(myResourceJid, true);
  9065. };
  9066. /**
  9067. * Adds or removes icons for not available camera and microphone.
  9068. * @param resourceJid the jid of user
  9069. * @param devices available devices
  9070. */
  9071. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  9072. if(!devices)
  9073. return;
  9074. if(!resourceJid) {
  9075. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  9076. } else {
  9077. if(remoteVideos[resourceJid])
  9078. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  9079. }
  9080. };
  9081. /**
  9082. * Checks if removed video is currently displayed and tries to display
  9083. * another one instead.
  9084. * @param removedVideoSrc src stream identifier of the video.
  9085. */
  9086. my.updateRemovedVideo = function(resourceJid) {
  9087. if (resourceJid === LargeVideo.getResourceJid()) {
  9088. var newResourceJid;
  9089. // We'll show user's avatar if he is the dominant speaker or if
  9090. // his video thumbnail is pinned
  9091. if (remoteVideos[resourceJid] &&
  9092. resourceJid === focusedVideoResourceJid ||
  9093. resourceJid === currentDominantSpeaker) {
  9094. newResourceJid = resourceJid;
  9095. } else {
  9096. // Otherwise select last visible video
  9097. newResourceJid = this.electLastVisibleVideo();
  9098. }
  9099. LargeVideo.updateLargeVideo(newResourceJid);
  9100. }
  9101. };
  9102. my.electLastVisibleVideo = function() {
  9103. // pick the last visible video in the row
  9104. // if nobody else is left, this picks the local video
  9105. var jid;
  9106. var videoElem = RTC.getVideoElementName();
  9107. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  9108. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  9109. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  9110. } else {
  9111. console.info("Last visible video no longer exists");
  9112. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  9113. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  9114. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  9115. } else {
  9116. // Try local video
  9117. console.info("Fallback to local video...");
  9118. jid = APP.xmpp.myResource();
  9119. }
  9120. }
  9121. console.info("electLastVisibleVideo: " + jid);
  9122. return jid;
  9123. };
  9124. my.onRemoteStreamAdded = function (stream) {
  9125. if (stream.peerjid) {
  9126. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  9127. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  9128. remoteVideos[resourceJid].addRemoteStreamElement(
  9129. stream.sid,
  9130. stream.getOriginalStream(),
  9131. stream.ssrc);
  9132. }
  9133. };
  9134. my.getLargeVideoResource = function () {
  9135. return LargeVideo.getResourceJid();
  9136. };
  9137. /**
  9138. * Called when large video update is finished
  9139. * @param currentSmallVideo small video currently displayed on large video
  9140. */
  9141. my.largeVideoUpdated = function (currentSmallVideo) {
  9142. // Makes sure that dominant speaker UI
  9143. // is enabled only on current small video
  9144. localVideoThumbnail.enableDominantSpeaker(
  9145. localVideoThumbnail === currentSmallVideo);
  9146. Object.keys(remoteVideos).forEach(
  9147. function (resourceJid) {
  9148. var remoteVideo = remoteVideos[resourceJid];
  9149. if (remoteVideo) {
  9150. remoteVideo.enableDominantSpeaker(
  9151. remoteVideo === currentSmallVideo);
  9152. }
  9153. }
  9154. );
  9155. };
  9156. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  9157. resourceJid) {
  9158. if(focusedVideoResourceJid) {
  9159. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9160. if (oldSmallVideo && !interfaceConfig.filmStripOnly)
  9161. oldSmallVideo.focus(false);
  9162. }
  9163. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9164. // Unlock current focused.
  9165. if (focusedVideoResourceJid === resourceJid)
  9166. {
  9167. focusedVideoResourceJid = null;
  9168. // Enable the currently set dominant speaker.
  9169. if (currentDominantSpeaker) {
  9170. if(smallVideo && smallVideo.hasVideo()) {
  9171. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  9172. }
  9173. }
  9174. if (!noPinnedEndpointChangedEvent) {
  9175. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  9176. }
  9177. return;
  9178. }
  9179. // Lock new video
  9180. focusedVideoResourceJid = resourceJid;
  9181. // Update focused/pinned interface.
  9182. if (resourceJid) {
  9183. if (smallVideo && !interfaceConfig.filmStripOnly)
  9184. smallVideo.focus(true);
  9185. if (!noPinnedEndpointChangedEvent) {
  9186. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  9187. }
  9188. }
  9189. LargeVideo.setState("video");
  9190. LargeVideo.updateLargeVideo(resourceJid);
  9191. // Writing volume not allowed in IE
  9192. if (!RTCBrowserType.isIExplorer()) {
  9193. $('audio').each(function (idx, el) {
  9194. el.volume = 0;
  9195. el.volume = 1;
  9196. });
  9197. }
  9198. };
  9199. /**
  9200. * Checks if container for participant identified by given peerJid exists
  9201. * in the document and creates it eventually.
  9202. *
  9203. * @param peerJid peer Jid to check.
  9204. *
  9205. * @return Returns <tt>true</tt> if the peer container exists,
  9206. * <tt>false</tt> - otherwise
  9207. */
  9208. my.ensurePeerContainerExists = function(peerJid) {
  9209. ContactList.ensureAddContact(peerJid);
  9210. var resourceJid = Strophe.getResourceFromJid(peerJid);
  9211. if (!remoteVideos[resourceJid]) {
  9212. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  9213. remoteVideos[resourceJid] = remoteVideo;
  9214. var videoType = remoteVideoTypes[resourceJid];
  9215. if (videoType) {
  9216. remoteVideo.setVideoType(videoType);
  9217. }
  9218. // In case this is not currently in the last n we don't show it.
  9219. if (localLastNCount &&
  9220. localLastNCount > 0 &&
  9221. $('#remoteVideos>span').length >= localLastNCount + 2) {
  9222. remoteVideo.showPeerContainer('hide');
  9223. }
  9224. else
  9225. VideoLayout.resizeThumbnails();
  9226. }
  9227. };
  9228. my.inputDisplayNameHandler = function (name) {
  9229. localVideoThumbnail.inputDisplayNameHandler(name);
  9230. };
  9231. my.videoactive = function (videoelem, resourceJid) {
  9232. console.info(resourceJid + " video is now active");
  9233. videoelem.show();
  9234. VideoLayout.resizeThumbnails();
  9235. // Update the large video to the last added video only if there's no
  9236. // current dominant, focused speaker or prezi playing or update it to
  9237. // the current dominant speaker.
  9238. if ((!focusedVideoResourceJid &&
  9239. !currentDominantSpeaker &&
  9240. !require("../prezi/Prezi").isPresentationVisible()) ||
  9241. focusedVideoResourceJid === resourceJid ||
  9242. (resourceJid &&
  9243. currentDominantSpeaker === resourceJid)) {
  9244. LargeVideo.updateLargeVideo(resourceJid, true);
  9245. }
  9246. };
  9247. /**
  9248. * Shows the presence status message for the given video.
  9249. */
  9250. my.setPresenceStatus = function (resourceJid, statusMsg) {
  9251. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  9252. };
  9253. /**
  9254. * Shows a visual indicator for the moderator of the conference.
  9255. */
  9256. my.showModeratorIndicator = function () {
  9257. var isModerator = APP.xmpp.isModerator();
  9258. if (isModerator) {
  9259. localVideoThumbnail.createModeratorIndicatorElement();
  9260. }
  9261. var members = APP.xmpp.getMembers();
  9262. Object.keys(members).forEach(function (jid) {
  9263. if (Strophe.getResourceFromJid(jid) === 'focus') {
  9264. // Skip server side focus
  9265. return;
  9266. }
  9267. var resourceJid = Strophe.getResourceFromJid(jid);
  9268. var member = members[jid];
  9269. if (member.role === 'moderator') {
  9270. remoteVideos[resourceJid].removeRemoteVideoMenu();
  9271. remoteVideos[resourceJid].createModeratorIndicatorElement();
  9272. } else if (isModerator) {
  9273. // We are moderator, but user is not - add menu
  9274. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  9275. remoteVideos[resourceJid].addRemoteVideoMenu();
  9276. }
  9277. }
  9278. });
  9279. };
  9280. /*
  9281. * Shows or hides the audio muted indicator over the local thumbnail video.
  9282. * @param {boolean} isMuted
  9283. */
  9284. my.showLocalAudioIndicator = function(isMuted) {
  9285. localVideoThumbnail.showAudioIndicator(isMuted);
  9286. };
  9287. /**
  9288. * Resizes the large video container.
  9289. */
  9290. my.resizeLargeVideoContainer = function () {
  9291. if(LargeVideo.isEnabled()) {
  9292. LargeVideo.resize();
  9293. } else {
  9294. VideoLayout.resizeVideoSpace();
  9295. }
  9296. VideoLayout.resizeThumbnails();
  9297. LargeVideo.position();
  9298. };
  9299. /**
  9300. * Resizes thumbnails.
  9301. */
  9302. my.resizeThumbnails = function(animate) {
  9303. var videoSpaceWidth = $('#remoteVideos').width();
  9304. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  9305. var width = thumbnailSize[0];
  9306. var height = thumbnailSize[1];
  9307. $('.userAvatar').css('left', (width - height) / 2);
  9308. if(animate) {
  9309. $('#remoteVideos').animate({
  9310. height: height + 2 // adds 2 px because of small video 1px border
  9311. },
  9312. {
  9313. queue: false,
  9314. duration: 500
  9315. });
  9316. $('#remoteVideos>span').animate({
  9317. height: height,
  9318. width: width
  9319. },
  9320. {
  9321. queue: false,
  9322. duration: 500,
  9323. complete: function () {
  9324. $(document).trigger(
  9325. "remotevideo.resized",
  9326. [width,
  9327. height]);
  9328. }
  9329. });
  9330. } else {
  9331. // size videos so that while keeping AR and max height, we have a
  9332. // nice fit
  9333. $('#remoteVideos').height(height + 2);// adds 2 px because of small video 1px border
  9334. $('#remoteVideos>span').width(width);
  9335. $('#remoteVideos>span').height(height);
  9336. $(document).trigger("remotevideo.resized", [width, height]);
  9337. }
  9338. };
  9339. /**
  9340. * Calculates the thumbnail size.
  9341. *
  9342. * @param videoSpaceWidth the width of the video space
  9343. */
  9344. my.calculateThumbnailSize = function (videoSpaceWidth) {
  9345. // Calculate the available height, which is the inner window height minus
  9346. // 39px for the header minus 2px for the delimiter lines on the top and
  9347. // bottom of the large video, minus the 36px space inside the remoteVideos
  9348. // container used for highlighting shadow.
  9349. var availableHeight = 100;
  9350. var numvids = $('#remoteVideos>span:visible').length;
  9351. if (localLastNCount && localLastNCount > 0) {
  9352. numvids = Math.min(localLastNCount + 1, numvids);
  9353. }
  9354. // Remove the 3px borders arround videos and border around the remote
  9355. // videos area and the 4 pixels between the local video and the others
  9356. //TODO: Find out where the 4 pixels come from and remove them
  9357. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  9358. var availableWidth = availableWinWidth / numvids;
  9359. var aspectRatio = 16.0 / 9.0;
  9360. var maxHeight = Math.min(160, availableHeight);
  9361. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio, window.innerHeight - 18);
  9362. if (availableHeight < availableWidth / aspectRatio) {
  9363. availableWidth = Math.floor(availableHeight * aspectRatio);
  9364. }
  9365. return [availableWidth, availableHeight];
  9366. };
  9367. /**
  9368. * Returns the corresponding resource jid to the given peer container
  9369. * DOM element.
  9370. *
  9371. * @return the corresponding resource jid to the given peer container
  9372. * DOM element
  9373. */
  9374. my.getPeerContainerResourceJid = function (containerElement) {
  9375. var i = containerElement.id.indexOf('participant_');
  9376. if (i >= 0)
  9377. return containerElement.id.substring(i + 12);
  9378. };
  9379. my.getPeerVideoSel = function (peerResourceJid) {
  9380. return $('#participant_' + peerResourceJid +
  9381. '>' + APP.RTC.getVideoElementName());
  9382. };
  9383. /**
  9384. * On contact list item clicked.
  9385. */
  9386. $(ContactList).bind('contactclicked', function(event, jid) {
  9387. if (!jid) {
  9388. return;
  9389. }
  9390. if (jid === APP.xmpp.myJid()) {
  9391. $("#localVideoContainer").click();
  9392. return;
  9393. }
  9394. var resource = Strophe.getResourceFromJid(jid);
  9395. var videoSel = VideoLayout.getPeerVideoSel(resource);
  9396. if (videoSel.length > 0) {
  9397. var videoThumb = videoSel[0];
  9398. // It is not always the case that a videoThumb exists (if there is
  9399. // no actual video).
  9400. if (RTC.getVideoSrc(videoThumb)) {
  9401. // We have a video src, great! Let's update the large video
  9402. // now.
  9403. VideoLayout.handleVideoThumbClicked(
  9404. false,
  9405. Strophe.getResourceFromJid(jid));
  9406. } else {
  9407. // If we don't have a video src for jid, there's absolutely
  9408. // no point in calling handleVideoThumbClicked; Quite
  9409. // simply, it won't work because it needs an src to attach
  9410. // to the large video.
  9411. //
  9412. // Instead, we trigger the pinned endpoint changed event to
  9413. // let the bridge adjust its lastN set for myjid and store
  9414. // the pinned user in the lastNPickupJid variable to be
  9415. // picked up later by the lastN changed event handler.
  9416. lastNPickupJid = jid;
  9417. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9418. Strophe.getResourceFromJid(jid));
  9419. }
  9420. }
  9421. });
  9422. /**
  9423. * On audio muted event.
  9424. */
  9425. my.onAudioMute = function (jid, isMuted) {
  9426. var resourceJid = Strophe.getResourceFromJid(jid);
  9427. if (resourceJid === APP.xmpp.myResource()) {
  9428. localVideoThumbnail.showAudioIndicator(isMuted);
  9429. } else {
  9430. VideoLayout.ensurePeerContainerExists(jid);
  9431. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9432. if (APP.xmpp.isModerator()) {
  9433. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9434. }
  9435. }
  9436. };
  9437. /**
  9438. * On video muted event.
  9439. */
  9440. my.onVideoMute = function (jid, value) {
  9441. if (jid !== APP.xmpp.myJid() &&
  9442. !APP.RTC.muteRemoteVideoStream(jid, value))
  9443. return;
  9444. if (jid === APP.xmpp.myJid()) {
  9445. localVideoThumbnail.showVideoIndicator(value);
  9446. } else {
  9447. var resource = Strophe.getResourceFromJid(jid);
  9448. VideoLayout.ensurePeerContainerExists(jid);
  9449. remoteVideos[resource].showVideoIndicator(value);
  9450. var el = VideoLayout.getPeerVideoSel(resource);
  9451. if (!value)
  9452. el.show();
  9453. else
  9454. el.hide();
  9455. }
  9456. };
  9457. /**
  9458. * Display name changed.
  9459. */
  9460. my.onDisplayNameChanged =
  9461. function (jid, displayName, status) {
  9462. if (jid === 'localVideoContainer' ||
  9463. jid === APP.xmpp.myJid()) {
  9464. localVideoThumbnail.setDisplayName(displayName);
  9465. } else {
  9466. VideoLayout.ensurePeerContainerExists(jid);
  9467. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9468. displayName,
  9469. status);
  9470. }
  9471. };
  9472. /**
  9473. * On dominant speaker changed event.
  9474. */
  9475. my.onDominantSpeakerChanged = function (resourceJid) {
  9476. // We ignore local user events.
  9477. if (resourceJid === APP.xmpp.myResource())
  9478. return;
  9479. var members = APP.xmpp.getMembers();
  9480. // Update the current dominant speaker.
  9481. if (resourceJid !== currentDominantSpeaker) {
  9482. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9483. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9484. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9485. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9486. remoteVideos[resourceJid].setDisplayName(null);
  9487. }
  9488. if(resourceJid && (!members || !members[newJID] ||
  9489. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9490. remoteVideos[resourceJid].setDisplayName(null,
  9491. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9492. }
  9493. currentDominantSpeaker = resourceJid;
  9494. } else {
  9495. return;
  9496. }
  9497. // Obtain container for new dominant speaker.
  9498. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9499. // Local video will not have container found, but that's ok
  9500. // since we don't want to switch to local video.
  9501. if (!focusedVideoResourceJid && videoSel.length) {
  9502. // Update the large video if the video source is already available,
  9503. // otherwise wait for the "videoactive.jingle" event.
  9504. if (videoSel[0].currentTime > 0) {
  9505. LargeVideo.updateLargeVideo(resourceJid);
  9506. }
  9507. }
  9508. };
  9509. /**
  9510. * On last N change event.
  9511. *
  9512. * @param lastNEndpoints the list of last N endpoints
  9513. * @param endpointsEnteringLastN the list currently entering last N
  9514. * endpoints
  9515. */
  9516. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9517. endpointsEnteringLastN,
  9518. stream) {
  9519. if (lastNCount !== lastNEndpoints.length)
  9520. lastNCount = lastNEndpoints.length;
  9521. lastNEndpointsCache = lastNEndpoints;
  9522. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9523. //
  9524. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9525. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9526. // so E sees them. C is only in E's local LastN set.
  9527. //
  9528. // If F starts talking and LastN = 3, then E should see thumbnails for
  9529. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9530. // enters E's local LastN ejecting C.
  9531. // Increase the local LastN set size, if necessary.
  9532. if (lastNCount > localLastNCount) {
  9533. localLastNCount = lastNCount;
  9534. }
  9535. // Update the local LastN set preserving the order in which the
  9536. // endpoints appeared in the LastN/local LastN set.
  9537. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9538. for (var i = 0; i < localLastNSet.length; i++) {
  9539. if (nextLocalLastNSet.length >= localLastNCount) {
  9540. break;
  9541. }
  9542. var resourceJid = localLastNSet[i];
  9543. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9544. nextLocalLastNSet.push(resourceJid);
  9545. }
  9546. }
  9547. localLastNSet = nextLocalLastNSet;
  9548. var updateLargeVideo = false;
  9549. // Handle LastN/local LastN changes.
  9550. $('#remoteVideos>span').each(function( index, element ) {
  9551. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9552. var isReceived = true;
  9553. if (resourceJid &&
  9554. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9555. localLastNSet.indexOf(resourceJid) < 0) {
  9556. console.log("Remove from last N", resourceJid);
  9557. remoteVideos[resourceJid].showPeerContainer('hide');
  9558. isReceived = false;
  9559. } else if (resourceJid &&
  9560. $('#participant_' + resourceJid).is(':visible') &&
  9561. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9562. localLastNSet.indexOf(resourceJid) >= 0) {
  9563. remoteVideos[resourceJid].showPeerContainer('avatar');
  9564. isReceived = false;
  9565. }
  9566. if (!isReceived) {
  9567. // resourceJid has dropped out of the server side lastN set, so
  9568. // it is no longer being received. If resourceJid was being
  9569. // displayed in the large video we have to switch to another
  9570. // user.
  9571. if (!updateLargeVideo &&
  9572. resourceJid === LargeVideo.getResourceJid()) {
  9573. updateLargeVideo = true;
  9574. }
  9575. }
  9576. });
  9577. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9578. endpointsEnteringLastN = lastNEndpoints;
  9579. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9580. endpointsEnteringLastN.forEach(function (resourceJid) {
  9581. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9582. remoteVideos[resourceJid].showPeerContainer('show');
  9583. if (!isVisible) {
  9584. console.log("Add to last N", resourceJid);
  9585. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9586. var mediaStream =
  9587. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9588. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9589. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9590. if (lastNPickupJid == mediaStream.peerjid) {
  9591. // Clean up the lastN pickup jid.
  9592. lastNPickupJid = null;
  9593. // Don't fire the events again, they've already
  9594. // been fired in the contact list click handler.
  9595. VideoLayout.handleVideoThumbClicked(
  9596. false,
  9597. Strophe.getResourceFromJid(mediaStream.peerjid));
  9598. updateLargeVideo = false;
  9599. }
  9600. remoteVideos[resourceJid].
  9601. waitForPlayback(sel, mediaStream.stream);
  9602. }
  9603. });
  9604. }
  9605. // The endpoint that was being shown in the large video has dropped out
  9606. // of the lastN set and there was no lastN pickup jid. We need to update
  9607. // the large video now.
  9608. if (updateLargeVideo) {
  9609. var resource;
  9610. var myResource
  9611. = APP.xmpp.myResource();
  9612. // Find out which endpoint to show in the large video.
  9613. for (i = 0; i < lastNEndpoints.length; i++) {
  9614. resource = lastNEndpoints[i];
  9615. if (!resource || resource === myResource)
  9616. continue;
  9617. // videoSrcToSsrc needs to be update for this call to succeed.
  9618. LargeVideo.updateLargeVideo(resource);
  9619. break;
  9620. }
  9621. }
  9622. };
  9623. /**
  9624. * Updates local stats
  9625. * @param percent
  9626. * @param object
  9627. */
  9628. my.updateLocalConnectionStats = function (percent, object) {
  9629. var resolution = null;
  9630. if (object.resolution !== null) {
  9631. resolution = object.resolution;
  9632. object.resolution = resolution[APP.xmpp.myJid()];
  9633. delete resolution[APP.xmpp.myJid()];
  9634. }
  9635. localVideoThumbnail.updateStatsIndicator(percent, object);
  9636. for (var jid in resolution) {
  9637. if (resolution[jid] === null)
  9638. continue;
  9639. var resourceJid = Strophe.getResourceFromJid(jid);
  9640. if (remoteVideos[resourceJid] &&
  9641. remoteVideos[resourceJid].connectionIndicator) {
  9642. remoteVideos[resourceJid].connectionIndicator.
  9643. updateResolution(resolution[jid]);
  9644. }
  9645. }
  9646. };
  9647. /**
  9648. * Updates remote stats.
  9649. * @param jid the jid associated with the stats
  9650. * @param percent the connection quality percent
  9651. * @param object the stats data
  9652. */
  9653. my.updateConnectionStats = function (jid, percent, object) {
  9654. var resourceJid = Strophe.getResourceFromJid(jid);
  9655. if (remoteVideos[resourceJid])
  9656. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9657. };
  9658. /**
  9659. * Hides the connection indicator
  9660. * @param jid
  9661. */
  9662. my.hideConnectionIndicator = function (jid) {
  9663. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9664. };
  9665. /**
  9666. * Hides all the indicators
  9667. */
  9668. my.onStatsStop = function () {
  9669. for(var video in remoteVideos) {
  9670. remoteVideos[video].hideIndicator();
  9671. }
  9672. localVideoThumbnail.hideIndicator();
  9673. };
  9674. my.participantLeft = function (jid) {
  9675. // Unlock large video
  9676. var resourceJid = Strophe.getResourceFromJid(jid);
  9677. if (focusedVideoResourceJid === resourceJid) {
  9678. console.info("Focused video owner has left the conference");
  9679. focusedVideoResourceJid = null;
  9680. }
  9681. if (currentDominantSpeaker === resourceJid)
  9682. {
  9683. console.info("Dominant speaker has left the conference");
  9684. currentDominantSpeaker = null;
  9685. }
  9686. var remoteVideo = remoteVideos[resourceJid];
  9687. if (remoteVideo) {
  9688. // Remove remote video
  9689. console.info("Removing remote video: " + resourceJid);
  9690. remoteVideo.remove();
  9691. delete remoteVideos[resourceJid];
  9692. } else {
  9693. console.warn("No remote video for " + resourceJid);
  9694. }
  9695. VideoLayout.resizeThumbnails();
  9696. };
  9697. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9698. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9699. return;
  9700. }
  9701. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9702. remoteVideoTypes[resourceJid] = newVideoType;
  9703. var smallVideo;
  9704. if (resourceJid === APP.xmpp.myResource()) {
  9705. if (!localVideoThumbnail) {
  9706. console.warn("Local video not ready yet");
  9707. return;
  9708. }
  9709. smallVideo = localVideoThumbnail;
  9710. } else if (remoteVideos[resourceJid]) {
  9711. smallVideo = remoteVideos[resourceJid];
  9712. } else {
  9713. return;
  9714. }
  9715. smallVideo.setVideoType(newVideoType);
  9716. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9717. };
  9718. my.showMore = function (jid) {
  9719. if (jid === 'local') {
  9720. localVideoThumbnail.connectionIndicator.showMore();
  9721. } else {
  9722. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9723. if (remoteVideo) {
  9724. remoteVideo.connectionIndicator.showMore();
  9725. } else {
  9726. console.info("Error - no remote video for jid: " + jid);
  9727. }
  9728. }
  9729. };
  9730. my.addPreziContainer = function (id) {
  9731. var container = RemoteVideo.createContainer(id);
  9732. VideoLayout.resizeThumbnails();
  9733. return container;
  9734. };
  9735. my.setLargeVideoVisible = function (isVisible) {
  9736. LargeVideo.setLargeVideoVisible(isVisible);
  9737. if(!isVisible && focusedVideoResourceJid) {
  9738. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9739. if(smallVideo) {
  9740. smallVideo.focus(false);
  9741. smallVideo.showAvatar();
  9742. }
  9743. focusedVideoResourceJid = null;
  9744. }
  9745. };
  9746. /**
  9747. * Resizes the video area
  9748. * @param callback a function to be called when the video space is
  9749. * resized.
  9750. */
  9751. my.resizeVideoArea = function(isVisible, callback) {
  9752. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9753. VideoLayout.resizeThumbnails(true);
  9754. };
  9755. /**
  9756. * Resizes the #videospace html element
  9757. * @param animate boolean property that indicates whether the resize should be animated or not.
  9758. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  9759. * If that parameter is null the method will check the chat pannel visibility.
  9760. * @param completeFunction a function to be called when the video space is resized
  9761. */
  9762. my.resizeVideoSpace = function (animate, isChatVisible, completeFunction) {
  9763. var availableHeight = window.innerHeight;
  9764. var availableWidth = UIUtil.getAvailableVideoWidth(isChatVisible);
  9765. if (availableWidth < 0 || availableHeight < 0) return;
  9766. if(animate) {
  9767. $('#videospace').animate({
  9768. right: window.innerWidth - availableWidth,
  9769. width: availableWidth,
  9770. height: availableHeight
  9771. },
  9772. {
  9773. queue: false,
  9774. duration: 500,
  9775. complete: completeFunction
  9776. });
  9777. } else {
  9778. $('#videospace').width(availableWidth);
  9779. $('#videospace').height(availableHeight);
  9780. }
  9781. };
  9782. my.getSmallVideo = function (resourceJid) {
  9783. if(resourceJid == APP.xmpp.myResource()) {
  9784. return localVideoThumbnail;
  9785. } else {
  9786. if(!remoteVideos[resourceJid])
  9787. return null;
  9788. return remoteVideos[resourceJid];
  9789. }
  9790. };
  9791. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9792. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9793. if(smallVideo)
  9794. smallVideo.avatarChanged(thumbUrl);
  9795. else
  9796. console.warn(
  9797. "Missed avatar update - no small video yet for " + resourceJid);
  9798. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9799. };
  9800. my.createEtherpadIframe = function(src, onloadHandler)
  9801. {
  9802. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9803. };
  9804. my.setLargeVideoState = function (state) {
  9805. LargeVideo.setState(state);
  9806. };
  9807. my.getLargeVideoState = function () {
  9808. return LargeVideo.getState();
  9809. };
  9810. my.setLargeVideoHover = function (inHandler, outHandler) {
  9811. LargeVideo.setHover(inHandler, outHandler);
  9812. };
  9813. /**
  9814. * Indicates that the video has been interrupted.
  9815. */
  9816. my.onVideoInterrupted = function () {
  9817. LargeVideo.enableVideoProblemFilter(true);
  9818. var reconnectingKey = "connection.RECONNECTING";
  9819. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9820. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9821. $('#videoConnectionMessage').css({display: "block"});
  9822. };
  9823. /**
  9824. * Indicates that the video has been restored.
  9825. */
  9826. my.onVideoRestored = function () {
  9827. LargeVideo.enableVideoProblemFilter(false);
  9828. $('#videoConnectionMessage').css({display: "none"});
  9829. };
  9830. return my;
  9831. }(VideoLayout || {}));
  9832. module.exports = VideoLayout;
  9833. },{"../../../service/RTC/MediaStreamTypes":110,"../../../service/UI/UIEvents":114,"../../RTC/RTC":9,"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../prezi/Prezi":20,"../side_pannels/contactlist/ContactList":27,"../util/UIUtil":35,"./LargeVideo":37,"./LocalVideo":38,"./RemoteVideo":39}],42:[function(require,module,exports){
  9834. //var nouns = [
  9835. //];
  9836. var pluralNouns = [
  9837. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9838. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9839. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9840. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9841. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9842. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9843. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9844. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9845. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9846. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9847. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9848. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9849. ];
  9850. //var places = [
  9851. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9852. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9853. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9854. // "Bridge"
  9855. //];
  9856. var verbs = [
  9857. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9858. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9859. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9860. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9861. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9862. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9863. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9864. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9865. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9866. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9867. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9868. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9869. ];
  9870. var adverbs = [
  9871. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9872. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9873. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9874. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9875. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9876. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9877. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9878. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9879. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9880. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9881. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9882. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9883. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9884. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9885. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9886. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9887. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9888. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9889. ];
  9890. var adjectives = [
  9891. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9892. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9893. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9894. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9895. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9896. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9897. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9898. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9899. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9900. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9901. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9902. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9903. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9904. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9905. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9906. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9907. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9908. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9909. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9910. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9911. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9912. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9913. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9914. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9915. "Zealous"
  9916. ];
  9917. //var pronouns = [
  9918. //];
  9919. //var conjunctions = [
  9920. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9921. //];
  9922. /*
  9923. * Maps a string (category name) to the array of words from that category.
  9924. */
  9925. var CATEGORIES =
  9926. {
  9927. //"_NOUN_": nouns,
  9928. "_PLURALNOUN_": pluralNouns,
  9929. //"_PLACE_": places,
  9930. "_VERB_": verbs,
  9931. "_ADVERB_": adverbs,
  9932. "_ADJECTIVE_": adjectives
  9933. //"_PRONOUN_": pronouns,
  9934. //"_CONJUNCTION_": conjunctions,
  9935. };
  9936. var PATTERNS = [
  9937. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9938. // BeautifulFungiOrSpaghetti
  9939. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9940. // AmazinglyScaryToy
  9941. //"_ADVERB__ADJECTIVE__NOUN_",
  9942. // NeitherTrashNorRifle
  9943. //"Neither_NOUN_Nor_NOUN_",
  9944. //"Either_NOUN_Or_NOUN_",
  9945. // EitherCopulateOrInvestigate
  9946. //"Either_VERB_Or_VERB_",
  9947. //"Neither_VERB_Nor_VERB_",
  9948. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9949. //"The_ADVERB__ADJECTIVE__NOUN_",
  9950. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9951. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9952. // WolvesComputeBadly
  9953. //"_PLURALNOUN__VERB__ADVERB_",
  9954. // UniteFacilitateAndMerge
  9955. //"_VERB__VERB_And_VERB_",
  9956. //NastyWitchesAtThePub
  9957. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9958. ];
  9959. /*
  9960. * Returns a random element from the array 'arr'
  9961. */
  9962. function randomElement(arr) {
  9963. return arr[Math.floor(Math.random() * arr.length)];
  9964. }
  9965. /*
  9966. * Returns true if the string 's' contains one of the
  9967. * template strings.
  9968. */
  9969. function hasTemplate(s) {
  9970. for (var template in CATEGORIES){
  9971. if (s.indexOf(template) >= 0){
  9972. return true;
  9973. }
  9974. }
  9975. }
  9976. /**
  9977. * Generates new room name.
  9978. */
  9979. var RoomNameGenerator = {
  9980. generateRoomWithoutSeparator: function() {
  9981. // Note that if more than one pattern is available, the choice of
  9982. // 'name' won't have a uniform distribution amongst all patterns (names
  9983. // from patterns with fewer options will have higher probability of
  9984. // being chosen that names from patterns with more options).
  9985. var name = randomElement(PATTERNS);
  9986. var word;
  9987. while (hasTemplate(name)) {
  9988. for (var template in CATEGORIES) {
  9989. word = randomElement(CATEGORIES[template]);
  9990. name = name.replace(template, word);
  9991. }
  9992. }
  9993. return name;
  9994. }
  9995. };
  9996. module.exports = RoomNameGenerator;
  9997. },{}],43:[function(require,module,exports){
  9998. /* global $, interfaceConfig */
  9999. var animateTimeout, updateTimeout;
  10000. var RoomNameGenerator = require("./RoomnameGenerator");
  10001. function enter_room() {
  10002. var val = $("#enter_room_field").val();
  10003. if(!val) {
  10004. val = $("#enter_room_field").attr("room_name");
  10005. }
  10006. if (val) {
  10007. window.location.pathname = "/" + val;
  10008. }
  10009. }
  10010. function animate(word) {
  10011. var currentVal = $("#enter_room_field").attr("placeholder");
  10012. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  10013. animateTimeout = setTimeout(function() {
  10014. animate(word.substring(1, word.length))
  10015. }, 70);
  10016. }
  10017. function update_roomname() {
  10018. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  10019. $("#enter_room_field").attr("room_name", word);
  10020. $("#enter_room_field").attr("placeholder", "");
  10021. clearTimeout(animateTimeout);
  10022. animate(word);
  10023. updateTimeout = setTimeout(update_roomname, 10000);
  10024. }
  10025. function setupWelcomePage() {
  10026. $("#videoconference_page").hide();
  10027. $("#domain_name").text(
  10028. window.location.protocol + "//" + window.location.host + "/");
  10029. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  10030. var leftWatermarkDiv =
  10031. $("#welcome_page_header div[class='watermark leftwatermark']");
  10032. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  10033. leftWatermarkDiv.css({display: 'block'});
  10034. leftWatermarkDiv.parent().get(0).href =
  10035. interfaceConfig.JITSI_WATERMARK_LINK;
  10036. }
  10037. }
  10038. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  10039. var rightWatermarkDiv =
  10040. $("#welcome_page_header div[class='watermark rightwatermark']");
  10041. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  10042. rightWatermarkDiv.css({display: 'block'});
  10043. rightWatermarkDiv.parent().get(0).href =
  10044. interfaceConfig.BRAND_WATERMARK_LINK;
  10045. rightWatermarkDiv.get(0).style.backgroundImage =
  10046. "url(images/rightwatermark.png)";
  10047. }
  10048. }
  10049. if (interfaceConfig.SHOW_POWERED_BY) {
  10050. $("#welcome_page_header>a[class='poweredby']")
  10051. .css({display: 'block'});
  10052. }
  10053. $("#enter_room_button").click(function() {
  10054. enter_room();
  10055. });
  10056. $("#enter_room_field").keydown(function (event) {
  10057. if (event.keyCode === 13 /* enter */) {
  10058. enter_room();
  10059. }
  10060. });
  10061. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  10062. var updateTimeout;
  10063. var animateTimeout;
  10064. var selector = $("#reload_roomname");
  10065. selector.click(function () {
  10066. clearTimeout(updateTimeout);
  10067. clearTimeout(animateTimeout);
  10068. update_roomname();
  10069. });
  10070. selector.show();
  10071. update_roomname();
  10072. }
  10073. $("#disable_welcome").click(function () {
  10074. window.localStorage.welcomePageDisabled =
  10075. $("#disable_welcome").is(":checked");
  10076. });
  10077. }
  10078. module.exports = setupWelcomePage;
  10079. },{"./RoomnameGenerator":42}],44:[function(require,module,exports){
  10080. /* global $, $iq, config, interfaceConfig */
  10081. var params = {};
  10082. function getConfigParamsFromUrl() {
  10083. if(!location.hash)
  10084. return {};
  10085. var hash = location.hash.substr(1);
  10086. var result = {};
  10087. hash.split("&").forEach(function(part) {
  10088. var item = part.split("=");
  10089. result[item[0]] = JSON.parse(
  10090. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  10091. });
  10092. return result;
  10093. }
  10094. params = getConfigParamsFromUrl();
  10095. var URLProcessor = {
  10096. setConfigParametersFromUrl: function () {
  10097. for(var key in params) {
  10098. if(typeof key !== "string")
  10099. continue;
  10100. var confObj = null, confKey;
  10101. if (key.indexOf("config.") === 0) {
  10102. confObj = config;
  10103. confKey = key.substr("config.".length);
  10104. } else if (key.indexOf("interfaceConfig.") === 0) {
  10105. confObj = interfaceConfig;
  10106. confKey = key.substr("interfaceConfig.".length);
  10107. }
  10108. if (!confObj)
  10109. continue;
  10110. var value = params[key];
  10111. if (confObj[confKey] && typeof confObj[confKey] !== typeof value)
  10112. {
  10113. console.warn("The type of " + key +
  10114. " is wrong. That parameter won't be updated in config.js.");
  10115. continue;
  10116. }
  10117. confObj[confKey] = value;
  10118. }
  10119. }
  10120. };
  10121. module.exports = URLProcessor;
  10122. },{}],45:[function(require,module,exports){
  10123. /* global APP, require */
  10124. var EventEmitter = require("events");
  10125. var eventEmitter = new EventEmitter();
  10126. var CQEvents = require("../../service/connectionquality/CQEvents");
  10127. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10128. /**
  10129. * local stats
  10130. * @type {{}}
  10131. */
  10132. var stats = {};
  10133. /**
  10134. * remote stats
  10135. * @type {{}}
  10136. */
  10137. var remoteStats = {};
  10138. /**
  10139. * Interval for sending statistics to other participants
  10140. * @type {null}
  10141. */
  10142. var sendIntervalId = null;
  10143. /**
  10144. * Start statistics sending.
  10145. */
  10146. function startSendingStats() {
  10147. sendStats();
  10148. sendIntervalId = setInterval(sendStats, 10000);
  10149. }
  10150. /**
  10151. * Sends statistics to other participants
  10152. */
  10153. function sendStats() {
  10154. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  10155. }
  10156. /**
  10157. * Converts statistics to format for sending through XMPP
  10158. * @param stats the statistics
  10159. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  10160. */
  10161. function convertToMUCStats(stats) {
  10162. return {
  10163. "bitrate_download": stats.bitrate.download,
  10164. "bitrate_upload": stats.bitrate.upload,
  10165. "packetLoss_total": stats.packetLoss.total,
  10166. "packetLoss_download": stats.packetLoss.download,
  10167. "packetLoss_upload": stats.packetLoss.upload
  10168. };
  10169. }
  10170. /**
  10171. * Converts statistics to format used by VideoLayout
  10172. * @param stats
  10173. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  10174. */
  10175. function parseMUCStats(stats) {
  10176. return {
  10177. bitrate: {
  10178. download: stats.bitrate_download,
  10179. upload: stats.bitrate_upload
  10180. },
  10181. packetLoss: {
  10182. total: stats.packetLoss_total,
  10183. download: stats.packetLoss_download,
  10184. upload: stats.packetLoss_upload
  10185. }
  10186. };
  10187. }
  10188. var ConnectionQuality = {
  10189. init: function () {
  10190. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  10191. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  10192. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  10193. },
  10194. /**
  10195. * Updates the local statistics
  10196. * @param data new statistics
  10197. */
  10198. updateLocalStats: function (data) {
  10199. stats = data;
  10200. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  10201. if (sendIntervalId == null) {
  10202. startSendingStats();
  10203. }
  10204. },
  10205. /**
  10206. * Updates remote statistics
  10207. * @param jid the jid associated with the statistics
  10208. * @param data the statistics
  10209. */
  10210. updateRemoteStats: function (jid, data) {
  10211. if (data == null || data.packetLoss_total == null) {
  10212. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  10213. return;
  10214. }
  10215. remoteStats[jid] = parseMUCStats(data);
  10216. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  10217. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  10218. },
  10219. /**
  10220. * Stops statistics sending.
  10221. */
  10222. stopSendingStats: function () {
  10223. clearInterval(sendIntervalId);
  10224. sendIntervalId = null;
  10225. //notify UI about stopping statistics gathering
  10226. eventEmitter.emit(CQEvents.STOP);
  10227. },
  10228. /**
  10229. * Returns the local statistics.
  10230. */
  10231. getStats: function () {
  10232. return stats;
  10233. },
  10234. addListener: function (type, listener) {
  10235. eventEmitter.on(type, listener);
  10236. }
  10237. };
  10238. module.exports = ConnectionQuality;
  10239. },{"../../service/connectionquality/CQEvents":116,"../../service/xmpp/XMPPEvents":120,"events":1}],46:[function(require,module,exports){
  10240. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  10241. getUserMediaWithConstraints */
  10242. /**
  10243. * Indicates that desktop stream is currently in use(for toggle purpose).
  10244. * @type {boolean}
  10245. */
  10246. var isUsingScreenStream = false;
  10247. /**
  10248. * Indicates that switch stream operation is in progress and prevent from
  10249. * triggering new events.
  10250. * @type {boolean}
  10251. */
  10252. var switchInProgress = false;
  10253. /**
  10254. * Method used to get screen sharing stream.
  10255. *
  10256. * @type {function (stream_callback, failure_callback}
  10257. */
  10258. var obtainDesktopStream = null;
  10259. /**
  10260. * Indicates whether desktop sharing extension is installed.
  10261. * @type {boolean}
  10262. */
  10263. var extInstalled = false;
  10264. /**
  10265. * Indicates whether update of desktop sharing extension is required.
  10266. * @type {boolean}
  10267. */
  10268. var extUpdateRequired = false;
  10269. var AdapterJS = require("../RTC/adapter.screenshare");
  10270. var EventEmitter = require("events");
  10271. var eventEmitter = new EventEmitter();
  10272. var DesktopSharingEventTypes
  10273. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  10274. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10275. var RTCEvents = require("../../service/RTC/RTCEvents");
  10276. /**
  10277. * Method obtains desktop stream from WebRTC 'screen' source.
  10278. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  10279. */
  10280. function obtainWebRTCScreen(streamCallback, failCallback) {
  10281. APP.RTC.getUserMediaWithConstraints(
  10282. ['screen'],
  10283. streamCallback,
  10284. failCallback
  10285. );
  10286. }
  10287. /**
  10288. * Constructs inline install URL for Chrome desktop streaming extension.
  10289. * The 'chromeExtensionId' must be defined in config.js.
  10290. * @returns {string}
  10291. */
  10292. function getWebStoreInstallUrl()
  10293. {
  10294. return "https://chrome.google.com/webstore/detail/" +
  10295. config.chromeExtensionId;
  10296. }
  10297. /**
  10298. * Checks whether extension update is required.
  10299. * @param minVersion minimal required version
  10300. * @param extVersion current extension version
  10301. * @returns {boolean}
  10302. */
  10303. function isUpdateRequired(minVersion, extVersion)
  10304. {
  10305. try
  10306. {
  10307. var s1 = minVersion.split('.');
  10308. var s2 = extVersion.split('.');
  10309. var len = Math.max(s1.length, s2.length);
  10310. for (var i = 0; i < len; i++)
  10311. {
  10312. var n1 = 0,
  10313. n2 = 0;
  10314. if (i < s1.length)
  10315. n1 = parseInt(s1[i]);
  10316. if (i < s2.length)
  10317. n2 = parseInt(s2[i]);
  10318. if (isNaN(n1) || isNaN(n2))
  10319. {
  10320. return true;
  10321. }
  10322. else if (n1 !== n2)
  10323. {
  10324. return n1 > n2;
  10325. }
  10326. }
  10327. // will happen if boths version has identical numbers in
  10328. // their components (even if one of them is longer, has more components)
  10329. return false;
  10330. }
  10331. catch (e)
  10332. {
  10333. console.error("Failed to parse extension version", e);
  10334. APP.UI.messageHandler.showError("dialog.error",
  10335. "dialog.detectext");
  10336. return true;
  10337. }
  10338. }
  10339. function checkChromeExtInstalled(callback) {
  10340. if (!chrome.runtime) {
  10341. // No API, so no extension for sure
  10342. callback(false, false);
  10343. return;
  10344. }
  10345. chrome.runtime.sendMessage(
  10346. config.chromeExtensionId,
  10347. { getVersion: true },
  10348. function (response) {
  10349. if (!response || !response.version) {
  10350. // Communication failure - assume that no endpoint exists
  10351. console.warn(
  10352. "Extension not installed?: ", chrome.runtime.lastError);
  10353. callback(false, false);
  10354. return;
  10355. }
  10356. // Check installed extension version
  10357. var extVersion = response.version;
  10358. console.log('Extension version is: ' + extVersion);
  10359. var updateRequired
  10360. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  10361. callback(!updateRequired, updateRequired);
  10362. }
  10363. );
  10364. }
  10365. function doGetStreamFromExtension(streamCallback, failCallback) {
  10366. // Sends 'getStream' msg to the extension.
  10367. // Extension id must be defined in the config.
  10368. chrome.runtime.sendMessage(
  10369. config.chromeExtensionId,
  10370. { getStream: true, sources: config.desktopSharingSources },
  10371. function (response) {
  10372. if (!response) {
  10373. failCallback(chrome.runtime.lastError);
  10374. return;
  10375. }
  10376. console.log("Response from extension: " + response);
  10377. if (response.streamId) {
  10378. APP.RTC.getUserMediaWithConstraints(
  10379. ['desktop'],
  10380. function (stream) {
  10381. streamCallback(stream);
  10382. },
  10383. failCallback,
  10384. null, null, null,
  10385. response.streamId);
  10386. } else {
  10387. failCallback("Extension failed to get the stream");
  10388. }
  10389. }
  10390. );
  10391. }
  10392. /**
  10393. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10394. * stream for returned stream token.
  10395. */
  10396. function obtainScreenFromExtension(streamCallback, failCallback) {
  10397. if (extInstalled) {
  10398. doGetStreamFromExtension(streamCallback, failCallback);
  10399. } else {
  10400. if (extUpdateRequired) {
  10401. alert(
  10402. 'Jitsi Desktop Streamer requires update. ' +
  10403. 'Changes will take effect after next Chrome restart.');
  10404. }
  10405. chrome.webstore.install(
  10406. getWebStoreInstallUrl(),
  10407. function (arg) {
  10408. console.log("Extension installed successfully", arg);
  10409. extInstalled = true;
  10410. // We need to give a moment for the endpoint to become available
  10411. window.setTimeout(function () {
  10412. doGetStreamFromExtension(streamCallback, failCallback);
  10413. }, 500);
  10414. },
  10415. function (arg) {
  10416. console.log("Failed to install the extension", arg);
  10417. failCallback(arg);
  10418. APP.UI.messageHandler.showError("dialog.error",
  10419. "dialog.failtoinstall");
  10420. }
  10421. );
  10422. }
  10423. }
  10424. /**
  10425. * Call this method to toggle desktop sharing feature.
  10426. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10427. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10428. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10429. * enabled), pass any other string or nothing in order to disable this
  10430. * feature completely.
  10431. */
  10432. function setDesktopSharing(method) {
  10433. obtainDesktopStream = null;
  10434. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10435. // care about 'method' parameter
  10436. if (RTCBrowserType.isTemasysPluginUsed()) {
  10437. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10438. console.info("Screensharing not supported by this plugin version");
  10439. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10440. console.info(
  10441. "Screensharing not available with Temasys plugin on this site");
  10442. } else {
  10443. obtainDesktopStream = obtainWebRTCScreen;
  10444. console.info("Using Temasys plugin for desktop sharing");
  10445. }
  10446. } else if (RTCBrowserType.isChrome()) {
  10447. if (method == "ext") {
  10448. if (RTCBrowserType.getChromeVersion() >= 34) {
  10449. obtainDesktopStream = obtainScreenFromExtension;
  10450. console.info("Using Chrome extension for desktop sharing");
  10451. initChromeExtension();
  10452. } else {
  10453. console.info("Chrome extension not supported until ver 34");
  10454. }
  10455. } else if (method == "webrtc") {
  10456. obtainDesktopStream = obtainWebRTCScreen;
  10457. console.info("Using Chrome WebRTC for desktop sharing");
  10458. }
  10459. }
  10460. if (!obtainDesktopStream) {
  10461. console.info("Desktop sharing disabled");
  10462. }
  10463. }
  10464. /**
  10465. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10466. * config.js to support inline installs. Host site must be selected as main
  10467. * website of published extension.
  10468. */
  10469. function initInlineInstalls()
  10470. {
  10471. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10472. }
  10473. function initChromeExtension() {
  10474. // Initialize Chrome extension inline installs
  10475. initInlineInstalls();
  10476. // Check if extension is installed
  10477. checkChromeExtInstalled(function (installed, updateRequired) {
  10478. extInstalled = installed;
  10479. extUpdateRequired = updateRequired;
  10480. console.info(
  10481. "Chrome extension installed: " + extInstalled +
  10482. " updateRequired: " + extUpdateRequired);
  10483. });
  10484. }
  10485. function getVideoStreamFailed(error) {
  10486. console.error("Failed to obtain the stream to switch to", error);
  10487. switchInProgress = false;
  10488. isUsingScreenStream = false;
  10489. newStreamCreated(null);
  10490. }
  10491. function getDesktopStreamFailed(error) {
  10492. console.error("Failed to obtain the stream to switch to", error);
  10493. switchInProgress = false;
  10494. }
  10495. function streamSwitchDone() {
  10496. switchInProgress = false;
  10497. eventEmitter.emit(
  10498. DesktopSharingEventTypes.SWITCHING_DONE,
  10499. isUsingScreenStream);
  10500. }
  10501. function newStreamCreated(stream)
  10502. {
  10503. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10504. stream, isUsingScreenStream, streamSwitchDone);
  10505. }
  10506. function onEndedHandler(stream) {
  10507. if (!switchInProgress && isUsingScreenStream) {
  10508. APP.desktopsharing.toggleScreenSharing();
  10509. }
  10510. //FIXME: to be verified
  10511. if (stream.removeEventListener) {
  10512. stream.removeEventListener('ended', onEndedHandler);
  10513. } else {
  10514. stream.detachEvent('ended', onEndedHandler);
  10515. }
  10516. }
  10517. // Called when RTC finishes initialization
  10518. function onWebRtcReady() {
  10519. setDesktopSharing(config.desktopSharing);
  10520. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10521. }
  10522. module.exports = {
  10523. isUsingScreenStream: function () {
  10524. return isUsingScreenStream;
  10525. },
  10526. /**
  10527. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10528. * and enabled.
  10529. */
  10530. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10531. init: function () {
  10532. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10533. },
  10534. addListener: function (listener, type)
  10535. {
  10536. eventEmitter.on(type, listener);
  10537. },
  10538. removeListener: function (listener, type) {
  10539. eventEmitter.removeListener(type, listener);
  10540. },
  10541. /*
  10542. * Toggles screen sharing.
  10543. */
  10544. toggleScreenSharing: function () {
  10545. if (switchInProgress || !obtainDesktopStream) {
  10546. console.warn("Switch in progress or no method defined");
  10547. return;
  10548. }
  10549. switchInProgress = true;
  10550. if (!isUsingScreenStream)
  10551. {
  10552. // Switch to desktop stream
  10553. obtainDesktopStream(
  10554. function (stream) {
  10555. // We now use screen stream
  10556. isUsingScreenStream = true;
  10557. // Hook 'ended' event to restore camera
  10558. // when screen stream stops
  10559. //FIXME: to be verified
  10560. if (stream.addEventListener) {
  10561. stream.addEventListener('ended', function () {
  10562. onEndedHandler(stream);
  10563. });
  10564. } else {
  10565. stream.attachEvent('ended', function () {
  10566. onEndedHandler(stream);
  10567. });
  10568. }
  10569. newStreamCreated(stream);
  10570. },
  10571. getDesktopStreamFailed);
  10572. } else {
  10573. // Disable screen stream
  10574. APP.RTC.getUserMediaWithConstraints(
  10575. ['video'],
  10576. function (stream) {
  10577. // We are now using camera stream
  10578. isUsingScreenStream = false;
  10579. newStreamCreated(stream);
  10580. },
  10581. getVideoStreamFailed, config.resolution || '360'
  10582. );
  10583. }
  10584. }
  10585. };
  10586. },{"../../service/RTC/RTCEvents":111,"../../service/desktopsharing/DesktopSharingEventTypes":117,"../RTC/RTCBrowserType":10,"../RTC/adapter.screenshare":12,"events":1}],47:[function(require,module,exports){
  10587. /* global APP, $ */
  10588. //maps keycode to character, id of popover for given function and function
  10589. var shortcuts = {};
  10590. function initShortcutHandlers() {
  10591. shortcuts = {
  10592. 67: {
  10593. character: "C",
  10594. id: "toggleChatPopover",
  10595. function: APP.UI.toggleChat
  10596. },
  10597. 70: {
  10598. character: "F",
  10599. id: "filmstripPopover",
  10600. function: APP.UI.toggleFilmStrip
  10601. },
  10602. 77: {
  10603. character: "M",
  10604. id: "mutePopover",
  10605. function: APP.UI.toggleAudio
  10606. },
  10607. 84: {
  10608. character: "T",
  10609. function: function() {
  10610. if(!APP.RTC.localAudio.isMuted()) {
  10611. APP.UI.toggleAudio();
  10612. }
  10613. }
  10614. },
  10615. 86: {
  10616. character: "V",
  10617. id: "toggleVideoPopover",
  10618. function: APP.UI.toggleVideo
  10619. }
  10620. };
  10621. }
  10622. var KeyboardShortcut = {
  10623. init: function () {
  10624. initShortcutHandlers();
  10625. window.onkeyup = function(e) {
  10626. var keycode = e.which;
  10627. if(!($(":focus").is("input[type=text]") ||
  10628. $(":focus").is("input[type=password]") ||
  10629. $(":focus").is("textarea"))) {
  10630. if (typeof shortcuts[keycode] === "object") {
  10631. shortcuts[keycode].function();
  10632. }
  10633. else if (keycode >= "0".charCodeAt(0) &&
  10634. keycode <= "9".charCodeAt(0)) {
  10635. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10636. }
  10637. //esc while the smileys are visible hides them
  10638. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10639. APP.UI.toggleSmileys();
  10640. }
  10641. };
  10642. window.onkeydown = function(e) {
  10643. if(!($(":focus").is("input[type=text]") ||
  10644. $(":focus").is("input[type=password]") ||
  10645. $(":focus").is("textarea"))) {
  10646. if(e.which === "T".charCodeAt(0)) {
  10647. if(APP.RTC.localAudio.isMuted()) {
  10648. APP.UI.toggleAudio();
  10649. }
  10650. }
  10651. }
  10652. };
  10653. var self = this;
  10654. $('body').popover({ selector: '[data-toggle=popover]',
  10655. trigger: 'click hover',
  10656. content: function() {
  10657. return this.getAttribute("content") +
  10658. self.getShortcut(this.getAttribute("shortcut"));
  10659. }
  10660. });
  10661. },
  10662. /**
  10663. *
  10664. * @param id indicates the popover associated with the shortcut
  10665. * @returns {string} the keyboard shortcut used for the id given
  10666. */
  10667. getShortcut: function (id) {
  10668. for (var keycode in shortcuts) {
  10669. if (shortcuts.hasOwnProperty(keycode)) {
  10670. if (shortcuts[keycode].id === id) {
  10671. return " (" + shortcuts[keycode].character + ")";
  10672. }
  10673. }
  10674. }
  10675. return "";
  10676. }
  10677. };
  10678. module.exports = KeyboardShortcut;
  10679. },{}],48:[function(require,module,exports){
  10680. /* global APP, require, $ */
  10681. /**
  10682. * This module is meant to (eventually) contain and manage all information
  10683. * about members/participants of the conference, so that other modules don't
  10684. * have to do it on their own, and so that other modules can access members'
  10685. * information from a single place.
  10686. *
  10687. * Currently this module only manages information about the support of jingle
  10688. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10689. * be added as needed.
  10690. */
  10691. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10692. var Events = require("../../service/members/Events");
  10693. var EventEmitter = require("events");
  10694. var eventEmitter = new EventEmitter();
  10695. /**
  10696. * The actual container.
  10697. */
  10698. var members = {};
  10699. /**
  10700. * There is at least one member that supports DTMF (i.e. is jigasi).
  10701. */
  10702. var atLeastOneDtmf = false;
  10703. function registerListeners() {
  10704. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10705. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10706. }
  10707. /**
  10708. * Handles a new member joining the MUC.
  10709. */
  10710. function onMucMemberJoined(jid, id, displayName) {
  10711. var member = {
  10712. displayName: displayName
  10713. };
  10714. APP.xmpp.getConnection().disco.info(
  10715. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10716. members[jid] = member;
  10717. }
  10718. /**
  10719. * Handles a member leaving the MUC.
  10720. */
  10721. function onMucMemberLeft(jid) {
  10722. delete members[jid];
  10723. updateAtLeastOneDtmf();
  10724. }
  10725. /**
  10726. * Handles the reception of a disco#info packet from a particular JID.
  10727. * @param jid the JID sending the packet.
  10728. * @param iq the packet.
  10729. */
  10730. function onDiscoInfoReceived(jid, iq) {
  10731. if (!members[jid])
  10732. return;
  10733. var supportsDtmf
  10734. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10735. updateDtmf(jid, supportsDtmf);
  10736. }
  10737. /**
  10738. * Updates the 'supportsDtmf' field for a member.
  10739. * @param jid the jid of the member.
  10740. * @param newValue the new value for the 'supportsDtmf' field.
  10741. */
  10742. function updateDtmf(jid, newValue) {
  10743. var oldValue = members[jid].supportsDtmf;
  10744. members[jid].supportsDtmf = newValue;
  10745. if (newValue != oldValue) {
  10746. updateAtLeastOneDtmf();
  10747. }
  10748. }
  10749. /**
  10750. * Checks each member's 'supportsDtmf' field and updates
  10751. * 'atLastOneSupportsDtmf'.
  10752. */
  10753. function updateAtLeastOneDtmf() {
  10754. var newAtLeastOneDtmf = false;
  10755. for (var key in members) {
  10756. if (typeof members[key].supportsDtmf !== 'undefined'
  10757. && members[key].supportsDtmf) {
  10758. newAtLeastOneDtmf= true;
  10759. break;
  10760. }
  10761. }
  10762. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10763. atLeastOneDtmf = newAtLeastOneDtmf;
  10764. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10765. }
  10766. }
  10767. /**
  10768. * Exported interface.
  10769. */
  10770. var Members = {
  10771. start: function() {
  10772. registerListeners();
  10773. },
  10774. addListener: function(type, listener) {
  10775. eventEmitter.on(type, listener);
  10776. },
  10777. removeListener: function (type, listener) {
  10778. eventEmitter.removeListener(type, listener);
  10779. },
  10780. size: function () {
  10781. return Object.keys(members).length;
  10782. },
  10783. getMembers: function () {
  10784. return members;
  10785. }
  10786. };
  10787. module.exports = Members;
  10788. },{"../../service/members/Events":118,"../../service/xmpp/XMPPEvents":120,"events":1}],49:[function(require,module,exports){
  10789. var email = '';
  10790. var displayName = '';
  10791. var userId;
  10792. var language = null;
  10793. function supportsLocalStorage() {
  10794. try {
  10795. return 'localStorage' in window && window.localStorage !== null;
  10796. } catch (e) {
  10797. console.log("localstorage is not supported");
  10798. return false;
  10799. }
  10800. }
  10801. function generateUniqueId() {
  10802. function _p8() {
  10803. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10804. }
  10805. return _p8() + _p8() + _p8() + _p8();
  10806. }
  10807. if (supportsLocalStorage()) {
  10808. if (!window.localStorage.jitsiMeetId) {
  10809. window.localStorage.jitsiMeetId = generateUniqueId();
  10810. console.log("generated id", window.localStorage.jitsiMeetId);
  10811. }
  10812. userId = window.localStorage.jitsiMeetId || '';
  10813. email = window.localStorage.email || '';
  10814. displayName = window.localStorage.displayname || '';
  10815. language = window.localStorage.language;
  10816. } else {
  10817. console.log("local storage is not supported");
  10818. userId = generateUniqueId();
  10819. }
  10820. var Settings = {
  10821. setDisplayName: function (newDisplayName) {
  10822. displayName = newDisplayName;
  10823. window.localStorage.displayname = displayName;
  10824. return displayName;
  10825. },
  10826. setEmail: function (newEmail) {
  10827. email = newEmail;
  10828. window.localStorage.email = newEmail;
  10829. return email;
  10830. },
  10831. getSettings: function () {
  10832. return {
  10833. email: email,
  10834. displayName: displayName,
  10835. uid: userId,
  10836. language: language
  10837. };
  10838. },
  10839. setLanguage: function (lang) {
  10840. language = lang;
  10841. window.localStorage.language = lang;
  10842. }
  10843. };
  10844. module.exports = Settings;
  10845. },{}],50:[function(require,module,exports){
  10846. /* global config, $, APP, Strophe, callstats */
  10847. var callStats = null;
  10848. function initCallback (err, msg) {
  10849. console.log("Initializing Status: err="+err+" msg="+msg);
  10850. }
  10851. var CallStats = {
  10852. init: function (jingleSession) {
  10853. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10854. return;
  10855. callStats = new callstats($,io,jsSHA);
  10856. this.session = jingleSession;
  10857. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10858. this.userID = APP.xmpp.myResource();
  10859. var location = window.location;
  10860. this.confID = location.protocol + "//" +
  10861. location.hostname + location.pathname;
  10862. //userID is generated or given by the origin server
  10863. callStats.initialize(config.callStatsID,
  10864. config.callStatsSecret,
  10865. this.userID,
  10866. initCallback);
  10867. var usage = callStats.fabricUsage.multiplex;
  10868. callStats.addNewFabric(this.peerconnection,
  10869. Strophe.getResourceFromJid(jingleSession.peerjid),
  10870. usage,
  10871. this.confID,
  10872. this.pcCallback.bind(this));
  10873. },
  10874. pcCallback: function (err, msg) {
  10875. if (!callStats)
  10876. return;
  10877. console.log("Monitoring status: "+ err + " msg: " + msg);
  10878. callStats.sendFabricEvent(this.peerconnection,
  10879. callStats.fabricEvent.fabricSetup, this.confID);
  10880. },
  10881. sendMuteEvent: function (mute, type) {
  10882. if (!callStats)
  10883. return;
  10884. var event = null;
  10885. if (type === "video") {
  10886. event = (mute? callStats.fabricEvent.videoPause :
  10887. callStats.fabricEvent.videoResume);
  10888. }
  10889. else {
  10890. event = (mute? callStats.fabricEvent.audioMute :
  10891. callStats.fabricEvent.audioUnmute);
  10892. }
  10893. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10894. },
  10895. sendTerminateEvent: function () {
  10896. if(!callStats) {
  10897. return;
  10898. }
  10899. callStats.sendFabricEvent(this.peerconnection,
  10900. callStats.fabricEvent.fabricTerminated, this.confID);
  10901. },
  10902. sendSetupFailedEvent: function () {
  10903. if(!callStats) {
  10904. return;
  10905. }
  10906. callStats.sendFabricEvent(this.peerconnection,
  10907. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10908. }
  10909. };
  10910. module.exports = CallStats;
  10911. },{}],51:[function(require,module,exports){
  10912. /* global config */
  10913. /**
  10914. * Provides statistics for the local stream.
  10915. */
  10916. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10917. /**
  10918. * Size of the webaudio analyzer buffer.
  10919. * @type {number}
  10920. */
  10921. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10922. /**
  10923. * Value of the webaudio analyzer smoothing time parameter.
  10924. * @type {number}
  10925. */
  10926. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10927. /**
  10928. * Converts time domain data array to audio level.
  10929. * @param samples the time domain data array.
  10930. * @returns {number} the audio level
  10931. */
  10932. function timeDomainDataToAudioLevel(samples) {
  10933. var maxVolume = 0;
  10934. var length = samples.length;
  10935. for (var i = 0; i < length; i++) {
  10936. if (maxVolume < samples[i])
  10937. maxVolume = samples[i];
  10938. }
  10939. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10940. }
  10941. /**
  10942. * Animates audio level change
  10943. * @param newLevel the new audio level
  10944. * @param lastLevel the last audio level
  10945. * @returns {Number} the audio level to be set
  10946. */
  10947. function animateLevel(newLevel, lastLevel) {
  10948. var value = 0;
  10949. var diff = lastLevel - newLevel;
  10950. if(diff > 0.2) {
  10951. value = lastLevel - 0.2;
  10952. }
  10953. else if(diff < -0.4) {
  10954. value = lastLevel + 0.4;
  10955. }
  10956. else {
  10957. value = newLevel;
  10958. }
  10959. return parseFloat(value.toFixed(3));
  10960. }
  10961. /**
  10962. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10963. *
  10964. * @param stream the local stream
  10965. * @param interval stats refresh interval given in ms.
  10966. * @constructor
  10967. */
  10968. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10969. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10970. this.stream = stream;
  10971. this.intervalId = null;
  10972. this.intervalMilis = interval;
  10973. this.eventEmitter = eventEmitter;
  10974. this.audioLevel = 0;
  10975. this.statisticsService = statisticsService;
  10976. }
  10977. /**
  10978. * Starts the collecting the statistics.
  10979. */
  10980. LocalStatsCollector.prototype.start = function () {
  10981. if (config.disableAudioLevels || !window.AudioContext ||
  10982. RTCBrowserType.isTemasysPluginUsed())
  10983. return;
  10984. var context = new AudioContext();
  10985. var analyser = context.createAnalyser();
  10986. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10987. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10988. var source = context.createMediaStreamSource(this.stream);
  10989. source.connect(analyser);
  10990. var self = this;
  10991. this.intervalId = setInterval(
  10992. function () {
  10993. var array = new Uint8Array(analyser.frequencyBinCount);
  10994. analyser.getByteTimeDomainData(array);
  10995. var audioLevel = timeDomainDataToAudioLevel(array);
  10996. if (audioLevel != self.audioLevel) {
  10997. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10998. self.eventEmitter.emit(
  10999. "statistics.audioLevel",
  11000. self.statisticsService.LOCAL_JID,
  11001. self.audioLevel);
  11002. }
  11003. },
  11004. this.intervalMilis
  11005. );
  11006. };
  11007. /**
  11008. * Stops collecting the statistics.
  11009. */
  11010. LocalStatsCollector.prototype.stop = function () {
  11011. if (this.intervalId) {
  11012. clearInterval(this.intervalId);
  11013. this.intervalId = null;
  11014. }
  11015. };
  11016. module.exports = LocalStatsCollector;
  11017. },{"../RTC/RTCBrowserType":10}],52:[function(require,module,exports){
  11018. /* global require, ssrc2jid */
  11019. /* jshint -W117 */
  11020. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11021. /* Whether we support the browser we are running into for logging statistics */
  11022. var browserSupported = RTCBrowserType.isChrome() ||
  11023. RTCBrowserType.isOpera();
  11024. /**
  11025. * Calculates packet lost percent using the number of lost packets and the
  11026. * number of all packet.
  11027. * @param lostPackets the number of lost packets
  11028. * @param totalPackets the number of all packets.
  11029. * @returns {number} packet loss percent
  11030. */
  11031. function calculatePacketLoss(lostPackets, totalPackets) {
  11032. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  11033. return 0;
  11034. return Math.round((lostPackets/totalPackets)*100);
  11035. }
  11036. function getStatValue(item, name) {
  11037. var browserType = RTCBrowserType.getBrowserType();
  11038. if (!keyMap[browserType][name])
  11039. throw "The property isn't supported!";
  11040. var key = keyMap[browserType][name];
  11041. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  11042. item.stat(key) : item[key];
  11043. }
  11044. /**
  11045. * Peer statistics data holder.
  11046. * @constructor
  11047. */
  11048. function PeerStats()
  11049. {
  11050. this.ssrc2Loss = {};
  11051. this.ssrc2AudioLevel = {};
  11052. this.ssrc2bitrate = {};
  11053. this.ssrc2resolution = {};
  11054. }
  11055. /**
  11056. * The bandwidth
  11057. * @type {{}}
  11058. */
  11059. PeerStats.bandwidth = {};
  11060. /**
  11061. * The bit rate
  11062. * @type {{}}
  11063. */
  11064. PeerStats.bitrate = {};
  11065. /**
  11066. * The packet loss rate
  11067. * @type {{}}
  11068. */
  11069. PeerStats.packetLoss = null;
  11070. /**
  11071. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  11072. * represented by this instance.
  11073. * @param ssrc audio or video RTP stream SSRC.
  11074. * @param lossRate new packet loss rate value to be set.
  11075. */
  11076. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  11077. {
  11078. this.ssrc2Loss[ssrc] = lossRate;
  11079. };
  11080. /**
  11081. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  11082. * represented by this instance.
  11083. * @param ssrc audio or video RTP stream SSRC.
  11084. * @param resolution new resolution value to be set.
  11085. */
  11086. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  11087. {
  11088. if(resolution === null && this.ssrc2resolution[ssrc])
  11089. {
  11090. delete this.ssrc2resolution[ssrc];
  11091. }
  11092. else if(resolution !== null)
  11093. this.ssrc2resolution[ssrc] = resolution;
  11094. };
  11095. /**
  11096. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  11097. * represented by this instance.
  11098. * @param ssrc audio or video RTP stream SSRC.
  11099. * @param bitrate new bitrate value to be set.
  11100. */
  11101. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  11102. {
  11103. if(this.ssrc2bitrate[ssrc])
  11104. {
  11105. this.ssrc2bitrate[ssrc].download += bitrate.download;
  11106. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  11107. }
  11108. else {
  11109. this.ssrc2bitrate[ssrc] = bitrate;
  11110. }
  11111. };
  11112. /**
  11113. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  11114. * the stream which belongs to the peer represented by this instance.
  11115. * @param ssrc RTP stream SSRC for which current audio level value will be
  11116. * updated.
  11117. * @param audioLevel the new audio level value to be set. Value is truncated to
  11118. * fit the range from 0 to 1.
  11119. */
  11120. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  11121. {
  11122. // Range limit 0 - 1
  11123. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  11124. };
  11125. function formatAudioLevel(audioLevel) {
  11126. return Math.min(Math.max(audioLevel, 0), 1);
  11127. }
  11128. /**
  11129. * Array with the transport information.
  11130. * @type {Array}
  11131. */
  11132. PeerStats.transport = [];
  11133. /**
  11134. * <tt>StatsCollector</tt> registers for stats updates of given
  11135. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  11136. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  11137. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  11138. * instance as an event source.
  11139. *
  11140. * @param peerconnection webRTC peer connection object.
  11141. * @param interval stats refresh interval given in ms.
  11142. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  11143. * called on stats update.
  11144. * @constructor
  11145. */
  11146. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  11147. {
  11148. this.peerconnection = peerconnection;
  11149. this.baselineAudioLevelsReport = null;
  11150. this.currentAudioLevelsReport = null;
  11151. this.currentStatsReport = null;
  11152. this.baselineStatsReport = null;
  11153. this.audioLevelsIntervalId = null;
  11154. this.eventEmitter = eventEmitter;
  11155. /**
  11156. * Gather PeerConnection stats once every this many milliseconds.
  11157. */
  11158. this.GATHER_INTERVAL = 15000;
  11159. /**
  11160. * Log stats via the focus once every this many milliseconds.
  11161. */
  11162. this.LOG_INTERVAL = 60000;
  11163. /**
  11164. * Gather stats and store them in this.statsToBeLogged.
  11165. */
  11166. this.gatherStatsIntervalId = null;
  11167. /**
  11168. * Send the stats already saved in this.statsToBeLogged to be logged via
  11169. * the focus.
  11170. */
  11171. this.logStatsIntervalId = null;
  11172. /**
  11173. * Stores the statistics which will be send to the focus to be logged.
  11174. */
  11175. this.statsToBeLogged =
  11176. {
  11177. timestamps: [],
  11178. stats: {}
  11179. };
  11180. // Updates stats interval
  11181. this.audioLevelsIntervalMilis = audioLevelsInterval;
  11182. this.statsIntervalId = null;
  11183. this.statsIntervalMilis = statsInterval;
  11184. // Map of jids to PeerStats
  11185. this.jid2stats = {};
  11186. }
  11187. module.exports = StatsCollector;
  11188. /**
  11189. * Stops stats updates.
  11190. */
  11191. StatsCollector.prototype.stop = function () {
  11192. if (this.audioLevelsIntervalId) {
  11193. clearInterval(this.audioLevelsIntervalId);
  11194. this.audioLevelsIntervalId = null;
  11195. }
  11196. if (this.statsIntervalId)
  11197. {
  11198. clearInterval(this.statsIntervalId);
  11199. this.statsIntervalId = null;
  11200. }
  11201. if(this.logStatsIntervalId)
  11202. {
  11203. clearInterval(this.logStatsIntervalId);
  11204. this.logStatsIntervalId = null;
  11205. }
  11206. if(this.gatherStatsIntervalId)
  11207. {
  11208. clearInterval(this.gatherStatsIntervalId);
  11209. this.gatherStatsIntervalId = null;
  11210. }
  11211. };
  11212. /**
  11213. * Callback passed to <tt>getStats</tt> method.
  11214. * @param error an error that occurred on <tt>getStats</tt> call.
  11215. */
  11216. StatsCollector.prototype.errorCallback = function (error)
  11217. {
  11218. console.error("Get stats error", error);
  11219. this.stop();
  11220. };
  11221. /**
  11222. * Starts stats updates.
  11223. */
  11224. StatsCollector.prototype.start = function ()
  11225. {
  11226. var self = this;
  11227. if (!config.disableAudioLevels) {
  11228. this.audioLevelsIntervalId = setInterval(
  11229. function () {
  11230. // Interval updates
  11231. self.peerconnection.getStats(
  11232. function (report) {
  11233. var results = null;
  11234. if (!report || !report.result ||
  11235. typeof report.result != 'function') {
  11236. results = report;
  11237. }
  11238. else {
  11239. results = report.result();
  11240. }
  11241. //console.error("Got interval report", results);
  11242. self.currentAudioLevelsReport = results;
  11243. self.processAudioLevelReport();
  11244. self.baselineAudioLevelsReport =
  11245. self.currentAudioLevelsReport;
  11246. },
  11247. self.errorCallback
  11248. );
  11249. },
  11250. self.audioLevelsIntervalMilis
  11251. );
  11252. }
  11253. if (!config.disableStats && browserSupported) {
  11254. this.statsIntervalId = setInterval(
  11255. function () {
  11256. // Interval updates
  11257. self.peerconnection.getStats(
  11258. function (report) {
  11259. var results = null;
  11260. if (!report || !report.result ||
  11261. typeof report.result != 'function') {
  11262. //firefox
  11263. results = report;
  11264. }
  11265. else {
  11266. //chrome
  11267. results = report.result();
  11268. }
  11269. //console.error("Got interval report", results);
  11270. self.currentStatsReport = results;
  11271. try {
  11272. self.processStatsReport();
  11273. }
  11274. catch (e) {
  11275. console.error("Unsupported key:" + e, e);
  11276. }
  11277. self.baselineStatsReport = self.currentStatsReport;
  11278. },
  11279. self.errorCallback
  11280. );
  11281. },
  11282. self.statsIntervalMilis
  11283. );
  11284. }
  11285. if (config.logStats && browserSupported) {
  11286. this.gatherStatsIntervalId = setInterval(
  11287. function () {
  11288. self.peerconnection.getStats(
  11289. function (report) {
  11290. self.addStatsToBeLogged(report.result());
  11291. },
  11292. function () {
  11293. }
  11294. );
  11295. },
  11296. this.GATHER_INTERVAL
  11297. );
  11298. this.logStatsIntervalId = setInterval(
  11299. function() { self.logStats(); },
  11300. this.LOG_INTERVAL);
  11301. }
  11302. };
  11303. /**
  11304. * Checks whether a certain record should be included in the logged statistics.
  11305. */
  11306. function acceptStat(reportId, reportType, statName) {
  11307. if (reportType == "googCandidatePair" && statName == "googChannelId")
  11308. return false;
  11309. if (reportType == "ssrc") {
  11310. if (statName == "googTrackId" ||
  11311. statName == "transportId" ||
  11312. statName == "ssrc")
  11313. return false;
  11314. }
  11315. return true;
  11316. }
  11317. /**
  11318. * Checks whether a certain record should be included in the logged statistics.
  11319. */
  11320. function acceptReport(id, type) {
  11321. if (id.substring(0, 15) == "googCertificate" ||
  11322. id.substring(0, 9) == "googTrack" ||
  11323. id.substring(0, 20) == "googLibjingleSession")
  11324. return false;
  11325. if (type == "googComponent")
  11326. return false;
  11327. return true;
  11328. }
  11329. /**
  11330. * Converts the stats to the format used for logging, and saves the data in
  11331. * this.statsToBeLogged.
  11332. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  11333. */
  11334. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  11335. var self = this;
  11336. var num_records = this.statsToBeLogged.timestamps.length;
  11337. this.statsToBeLogged.timestamps.push(new Date().getTime());
  11338. reports.map(function (report) {
  11339. if (!acceptReport(report.id, report.type))
  11340. return;
  11341. var stat = self.statsToBeLogged.stats[report.id];
  11342. if (!stat) {
  11343. stat = self.statsToBeLogged.stats[report.id] = {};
  11344. }
  11345. stat.type = report.type;
  11346. report.names().map(function (name) {
  11347. if (!acceptStat(report.id, report.type, name))
  11348. return;
  11349. var values = stat[name];
  11350. if (!values) {
  11351. values = stat[name] = [];
  11352. }
  11353. while (values.length < num_records) {
  11354. values.push(null);
  11355. }
  11356. values.push(report.stat(name));
  11357. });
  11358. });
  11359. };
  11360. StatsCollector.prototype.logStats = function () {
  11361. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  11362. return;
  11363. // Reset the stats
  11364. this.statsToBeLogged.stats = {};
  11365. this.statsToBeLogged.timestamps = [];
  11366. };
  11367. var keyMap = {};
  11368. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11369. "ssrc": "ssrc",
  11370. "packetsReceived": "packetsReceived",
  11371. "packetsLost": "packetsLost",
  11372. "packetsSent": "packetsSent",
  11373. "bytesReceived": "bytesReceived",
  11374. "bytesSent": "bytesSent"
  11375. };
  11376. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11377. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11378. "sendBandwidth": "googAvailableSendBandwidth",
  11379. "remoteAddress": "googRemoteAddress",
  11380. "transportType": "googTransportType",
  11381. "localAddress": "googLocalAddress",
  11382. "activeConnection": "googActiveConnection",
  11383. "ssrc": "ssrc",
  11384. "packetsReceived": "packetsReceived",
  11385. "packetsSent": "packetsSent",
  11386. "packetsLost": "packetsLost",
  11387. "bytesReceived": "bytesReceived",
  11388. "bytesSent": "bytesSent",
  11389. "googFrameHeightReceived": "googFrameHeightReceived",
  11390. "googFrameWidthReceived": "googFrameWidthReceived",
  11391. "googFrameHeightSent": "googFrameHeightSent",
  11392. "googFrameWidthSent": "googFrameWidthSent",
  11393. "audioInputLevel": "audioInputLevel",
  11394. "audioOutputLevel": "audioOutputLevel"
  11395. };
  11396. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11397. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11398. /**
  11399. * Stats processing logic.
  11400. */
  11401. StatsCollector.prototype.processStatsReport = function () {
  11402. if (!this.baselineStatsReport) {
  11403. return;
  11404. }
  11405. for (var idx in this.currentStatsReport) {
  11406. var now = this.currentStatsReport[idx];
  11407. try {
  11408. if (getStatValue(now, 'receiveBandwidth') ||
  11409. getStatValue(now, 'sendBandwidth')) {
  11410. PeerStats.bandwidth = {
  11411. "download": Math.round(
  11412. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11413. "upload": Math.round(
  11414. (getStatValue(now, 'sendBandwidth')) / 1000)
  11415. };
  11416. }
  11417. }
  11418. catch(e){/*not supported*/}
  11419. if(now.type == 'googCandidatePair')
  11420. {
  11421. var ip, type, localIP, active;
  11422. try {
  11423. ip = getStatValue(now, 'remoteAddress');
  11424. type = getStatValue(now, "transportType");
  11425. localIP = getStatValue(now, "localAddress");
  11426. active = getStatValue(now, "activeConnection");
  11427. }
  11428. catch(e){/*not supported*/}
  11429. if(!ip || !type || !localIP || active != "true")
  11430. continue;
  11431. var addressSaved = false;
  11432. for(var i = 0; i < PeerStats.transport.length; i++)
  11433. {
  11434. if(PeerStats.transport[i].ip == ip &&
  11435. PeerStats.transport[i].type == type &&
  11436. PeerStats.transport[i].localip == localIP)
  11437. {
  11438. addressSaved = true;
  11439. }
  11440. }
  11441. if(addressSaved)
  11442. continue;
  11443. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11444. continue;
  11445. }
  11446. if(now.type == "candidatepair")
  11447. {
  11448. if(now.state == "succeeded")
  11449. continue;
  11450. var local = this.currentStatsReport[now.localCandidateId];
  11451. var remote = this.currentStatsReport[now.remoteCandidateId];
  11452. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11453. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11454. }
  11455. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11456. now.type != "inboundrtp") {
  11457. continue;
  11458. }
  11459. var before = this.baselineStatsReport[idx];
  11460. if (!before) {
  11461. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11462. continue;
  11463. }
  11464. var ssrc = getStatValue(now, 'ssrc');
  11465. if(!ssrc)
  11466. continue;
  11467. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11468. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11469. console.warn("No jid for ssrc: " + ssrc);
  11470. continue;
  11471. }
  11472. var jidStats = this.jid2stats[jid];
  11473. if (!jidStats) {
  11474. jidStats = new PeerStats();
  11475. this.jid2stats[jid] = jidStats;
  11476. }
  11477. var isDownloadStream = true;
  11478. var key = 'packetsReceived';
  11479. if (!getStatValue(now, key))
  11480. {
  11481. isDownloadStream = false;
  11482. key = 'packetsSent';
  11483. if (!getStatValue(now, key))
  11484. {
  11485. console.warn("No packetsReceived nor packetSent stat found");
  11486. continue;
  11487. }
  11488. }
  11489. var packetsNow = getStatValue(now, key);
  11490. if(!packetsNow || packetsNow < 0)
  11491. packetsNow = 0;
  11492. var packetsBefore = getStatValue(before, key);
  11493. if(!packetsBefore || packetsBefore < 0)
  11494. packetsBefore = 0;
  11495. var packetRate = packetsNow - packetsBefore;
  11496. if(!packetRate || packetRate < 0)
  11497. packetRate = 0;
  11498. var currentLoss = getStatValue(now, 'packetsLost');
  11499. if(!currentLoss || currentLoss < 0)
  11500. currentLoss = 0;
  11501. var previousLoss = getStatValue(before, 'packetsLost');
  11502. if(!previousLoss || previousLoss < 0)
  11503. previousLoss = 0;
  11504. var lossRate = currentLoss - previousLoss;
  11505. if(!lossRate || lossRate < 0)
  11506. lossRate = 0;
  11507. var packetsTotal = (packetRate + lossRate);
  11508. jidStats.setSsrcLoss(ssrc,
  11509. {"packetsTotal": packetsTotal,
  11510. "packetsLost": lossRate,
  11511. "isDownloadStream": isDownloadStream});
  11512. var bytesReceived = 0, bytesSent = 0;
  11513. if(getStatValue(now, "bytesReceived"))
  11514. {
  11515. bytesReceived = getStatValue(now, "bytesReceived") -
  11516. getStatValue(before, "bytesReceived");
  11517. }
  11518. if(getStatValue(now, "bytesSent"))
  11519. {
  11520. bytesSent = getStatValue(now, "bytesSent") -
  11521. getStatValue(before, "bytesSent");
  11522. }
  11523. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11524. if(bytesReceived <= 0 || time <= 0)
  11525. {
  11526. bytesReceived = 0;
  11527. }
  11528. else
  11529. {
  11530. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11531. }
  11532. if(bytesSent <= 0 || time <= 0)
  11533. {
  11534. bytesSent = 0;
  11535. }
  11536. else
  11537. {
  11538. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11539. }
  11540. jidStats.setSsrcBitrate(ssrc, {
  11541. "download": bytesReceived,
  11542. "upload": bytesSent});
  11543. var resolution = {height: null, width: null};
  11544. try {
  11545. if (getStatValue(now, "googFrameHeightReceived") &&
  11546. getStatValue(now, "googFrameWidthReceived")) {
  11547. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11548. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11549. }
  11550. else if (getStatValue(now, "googFrameHeightSent") &&
  11551. getStatValue(now, "googFrameWidthSent")) {
  11552. resolution.height = getStatValue(now, "googFrameHeightSent");
  11553. resolution.width = getStatValue(now, "googFrameWidthSent");
  11554. }
  11555. }
  11556. catch(e){/*not supported*/}
  11557. if(resolution.height && resolution.width)
  11558. {
  11559. jidStats.setSsrcResolution(ssrc, resolution);
  11560. }
  11561. else
  11562. {
  11563. jidStats.setSsrcResolution(ssrc, null);
  11564. }
  11565. }
  11566. var self = this;
  11567. // Jid stats
  11568. var totalPackets = {download: 0, upload: 0};
  11569. var lostPackets = {download: 0, upload: 0};
  11570. var bitrateDownload = 0;
  11571. var bitrateUpload = 0;
  11572. var resolutions = {};
  11573. Object.keys(this.jid2stats).forEach(
  11574. function (jid)
  11575. {
  11576. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11577. function (ssrc)
  11578. {
  11579. var type = "upload";
  11580. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11581. type = "download";
  11582. totalPackets[type] +=
  11583. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11584. lostPackets[type] +=
  11585. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11586. }
  11587. );
  11588. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11589. function (ssrc) {
  11590. bitrateDownload +=
  11591. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11592. bitrateUpload +=
  11593. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11594. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11595. }
  11596. );
  11597. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11598. }
  11599. );
  11600. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11601. PeerStats.packetLoss = {
  11602. total:
  11603. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11604. totalPackets.download + totalPackets.upload),
  11605. download:
  11606. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11607. upload:
  11608. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11609. };
  11610. this.eventEmitter.emit("statistics.connectionstats",
  11611. {
  11612. "bitrate": PeerStats.bitrate,
  11613. "packetLoss": PeerStats.packetLoss,
  11614. "bandwidth": PeerStats.bandwidth,
  11615. "resolution": resolutions,
  11616. "transport": PeerStats.transport
  11617. });
  11618. PeerStats.transport = [];
  11619. };
  11620. /**
  11621. * Stats processing logic.
  11622. */
  11623. StatsCollector.prototype.processAudioLevelReport = function () {
  11624. if (!this.baselineAudioLevelsReport) {
  11625. return;
  11626. }
  11627. for (var idx in this.currentAudioLevelsReport) {
  11628. var now = this.currentAudioLevelsReport[idx];
  11629. if (now.type != 'ssrc') {
  11630. continue;
  11631. }
  11632. var before = this.baselineAudioLevelsReport[idx];
  11633. if (!before) {
  11634. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11635. continue;
  11636. }
  11637. var ssrc = getStatValue(now, 'ssrc');
  11638. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11639. if (!jid) {
  11640. if((Date.now() - now.timestamp) < 3000)
  11641. console.warn("No jid for ssrc: " + ssrc);
  11642. continue;
  11643. }
  11644. var jidStats = this.jid2stats[jid];
  11645. if (!jidStats) {
  11646. jidStats = new PeerStats();
  11647. this.jid2stats[jid] = jidStats;
  11648. }
  11649. // Audio level
  11650. var audioLevel = null;
  11651. try {
  11652. audioLevel = getStatValue(now, 'audioInputLevel');
  11653. if (!audioLevel)
  11654. audioLevel = getStatValue(now, 'audioOutputLevel');
  11655. }
  11656. catch(e) {/*not supported*/
  11657. console.warn("Audio Levels are not available in the statistics.");
  11658. clearInterval(this.audioLevelsIntervalId);
  11659. return;
  11660. }
  11661. if (audioLevel) {
  11662. // TODO: can't find specs about what this value really is,
  11663. // but it seems to vary between 0 and around 32k.
  11664. audioLevel = audioLevel / 32767;
  11665. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11666. if(jid != APP.xmpp.myJid())
  11667. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11668. }
  11669. }
  11670. };
  11671. },{"../RTC/RTCBrowserType":10}],53:[function(require,module,exports){
  11672. /* global require, APP */
  11673. /**
  11674. * Created by hristo on 8/4/14.
  11675. */
  11676. var LocalStats = require("./LocalStatsCollector.js");
  11677. var RTPStats = require("./RTPStatsCollector.js");
  11678. var EventEmitter = require("events");
  11679. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11680. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11681. var CallStats = require("./CallStats");
  11682. var RTCEvents = require("../../service/RTC/RTCEvents");
  11683. var eventEmitter = new EventEmitter();
  11684. var localStats = null;
  11685. var rtpStats = null;
  11686. function stopLocal() {
  11687. if (localStats) {
  11688. localStats.stop();
  11689. localStats = null;
  11690. }
  11691. }
  11692. function stopRemote() {
  11693. if (rtpStats) {
  11694. rtpStats.stop();
  11695. eventEmitter.emit("statistics.stop");
  11696. rtpStats = null;
  11697. }
  11698. }
  11699. function startRemoteStats (peerconnection) {
  11700. if (rtpStats) {
  11701. rtpStats.stop();
  11702. }
  11703. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11704. rtpStats.start();
  11705. }
  11706. function onStreamCreated(stream) {
  11707. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11708. return;
  11709. }
  11710. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11711. eventEmitter);
  11712. localStats.start();
  11713. }
  11714. function onDisposeConference(onUnload) {
  11715. CallStats.sendTerminateEvent();
  11716. stopRemote();
  11717. if(onUnload) {
  11718. stopLocal();
  11719. eventEmitter.removeAllListeners();
  11720. }
  11721. }
  11722. var statistics = {
  11723. /**
  11724. * Indicates that this audio level is for local jid.
  11725. * @type {string}
  11726. */
  11727. LOCAL_JID: 'local',
  11728. addAudioLevelListener: function(listener)
  11729. {
  11730. eventEmitter.on("statistics.audioLevel", listener);
  11731. },
  11732. removeAudioLevelListener: function(listener)
  11733. {
  11734. eventEmitter.removeListener("statistics.audioLevel", listener);
  11735. },
  11736. addConnectionStatsListener: function(listener)
  11737. {
  11738. eventEmitter.on("statistics.connectionstats", listener);
  11739. },
  11740. removeConnectionStatsListener: function(listener)
  11741. {
  11742. eventEmitter.removeListener("statistics.connectionstats", listener);
  11743. },
  11744. addRemoteStatsStopListener: function(listener)
  11745. {
  11746. eventEmitter.on("statistics.stop", listener);
  11747. },
  11748. removeRemoteStatsStopListener: function(listener)
  11749. {
  11750. eventEmitter.removeListener("statistics.stop", listener);
  11751. },
  11752. stop: function () {
  11753. stopLocal();
  11754. stopRemote();
  11755. if(eventEmitter)
  11756. {
  11757. eventEmitter.removeAllListeners();
  11758. }
  11759. },
  11760. stopRemoteStatistics: function()
  11761. {
  11762. stopRemote();
  11763. },
  11764. start: function () {
  11765. APP.RTC.addStreamListener(onStreamCreated,
  11766. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11767. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11768. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11769. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11770. startRemoteStats(event.peerconnection);
  11771. // CallStats.init(event);
  11772. });
  11773. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11774. CallStats.init(session);
  11775. });
  11776. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11777. CallStats.sendMuteEvent(mute, "audio");
  11778. });
  11779. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11780. CallStats.sendSetupFailedEvent();
  11781. });
  11782. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11783. CallStats.sendMuteEvent(mute, "video");
  11784. });
  11785. }
  11786. };
  11787. module.exports = statistics;
  11788. },{"../../service/RTC/RTCEvents":111,"../../service/RTC/StreamEventTypes.js":113,"../../service/xmpp/XMPPEvents":120,"./CallStats":50,"./LocalStatsCollector.js":51,"./RTPStatsCollector.js":52,"events":1}],54:[function(require,module,exports){
  11789. /* global $, require, config, interfaceConfig */
  11790. var i18n = require("i18next-client");
  11791. var languages = require("../../service/translation/languages");
  11792. var Settings = require("../settings/Settings");
  11793. var DEFAULT_LANG = languages.EN;
  11794. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11795. return value.replace("__app__", interfaceConfig.APP_NAME);
  11796. });
  11797. var defaultOptions = {
  11798. detectLngQS: "lang",
  11799. useCookie: false,
  11800. fallbackLng: DEFAULT_LANG,
  11801. load: "unspecific",
  11802. resGetPath: 'lang/__ns__-__lng__.json',
  11803. ns: {
  11804. namespaces: ['main', 'languages'],
  11805. defaultNs: 'main'
  11806. },
  11807. lngWhitelist : languages.getLanguages(),
  11808. fallbackOnNull: true,
  11809. fallbackOnEmpty: true,
  11810. useDataAttrOptions: true,
  11811. app: interfaceConfig.APP_NAME,
  11812. getAsync: false,
  11813. defaultValueFromContent: false,
  11814. customLoad: function(lng, ns, options, done) {
  11815. var resPath = "lang/__ns__-__lng__.json";
  11816. if(lng === languages.EN)
  11817. resPath = "lang/__ns__.json";
  11818. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11819. i18n.functions.ajax({
  11820. url: url,
  11821. success: function(data, status, xhr) {
  11822. i18n.functions.log('loaded: ' + url);
  11823. done(null, data);
  11824. },
  11825. error : function(xhr, status, error) {
  11826. if ((status && status == 200) ||
  11827. (xhr && xhr.status && xhr.status == 200)) {
  11828. // file loaded but invalid json, stop waste time !
  11829. i18n.functions.error('There is a typo in: ' + url);
  11830. } else if ((status && status == 404) ||
  11831. (xhr && xhr.status && xhr.status == 404)) {
  11832. i18n.functions.log('Does not exist: ' + url);
  11833. } else {
  11834. var theStatus = status ? status :
  11835. ((xhr && xhr.status) ? xhr.status : null);
  11836. i18n.functions.log(theStatus + ' when loading ' + url);
  11837. }
  11838. done(error, {});
  11839. },
  11840. dataType: "json",
  11841. async : options.getAsync
  11842. });
  11843. }
  11844. // options for caching
  11845. // useLocalStorage: true,
  11846. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11847. };
  11848. function initCompleted(t) {
  11849. $("[data-i18n]").i18n();
  11850. }
  11851. function checkForParameter() {
  11852. var query = window.location.search.substring(1);
  11853. var vars = query.split("&");
  11854. for (var i=0;i<vars.length;i++) {
  11855. var pair = vars[i].split("=");
  11856. if(pair[0] == "lang")
  11857. {
  11858. return pair[1];
  11859. }
  11860. }
  11861. return null;
  11862. }
  11863. module.exports = {
  11864. init: function (lang) {
  11865. var options = defaultOptions;
  11866. if(!lang)
  11867. {
  11868. lang = checkForParameter();
  11869. if(!lang)
  11870. {
  11871. var settings = Settings.getSettings();
  11872. if(settings)
  11873. lang = settings.language;
  11874. if(!lang && config.defaultLanguage)
  11875. {
  11876. lang = config.defaultLanguage;
  11877. }
  11878. }
  11879. }
  11880. if(lang) {
  11881. options.lng = lang;
  11882. }
  11883. i18n.init(options, initCompleted);
  11884. },
  11885. translateString: function (key, options) {
  11886. return i18n.t(key, options);
  11887. },
  11888. setLanguage: function (lang) {
  11889. if(!lang)
  11890. lang = DEFAULT_LANG;
  11891. i18n.setLng(lang, defaultOptions, initCompleted);
  11892. },
  11893. getCurrentLanguage: function () {
  11894. return i18n.lng();
  11895. },
  11896. translateElement: function (selector) {
  11897. selector.i18n();
  11898. },
  11899. generateTranslationHTML: function (key, options) {
  11900. var str = "<span data-i18n=\"" + key + "\"";
  11901. if(options)
  11902. {
  11903. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11904. }
  11905. str += ">";
  11906. str += this.translateString(key, options);
  11907. str += "</span>";
  11908. return str;
  11909. }
  11910. };
  11911. },{"../../service/translation/languages":119,"../settings/Settings":49,"i18next-client":72}],55:[function(require,module,exports){
  11912. /*
  11913. * JingleSession provides an API to manage a single Jingle session. We will
  11914. * have different implementations depending on the underlying interface used
  11915. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  11916. */
  11917. function JingleSession(me, sid, connection, service, eventEmitter) {
  11918. /**
  11919. * Our JID.
  11920. */
  11921. this.me = me;
  11922. /**
  11923. * The Jingle session identifier.
  11924. */
  11925. this.sid = sid;
  11926. /**
  11927. * The XMPP connection.
  11928. */
  11929. this.connection = connection;
  11930. /**
  11931. * The XMPP service.
  11932. */
  11933. this.service = service;
  11934. /**
  11935. * The event emitter.
  11936. */
  11937. this.eventEmitter = eventEmitter;
  11938. /**
  11939. * Whether to use dripping or not. Dripping is sending trickle candidates
  11940. * not one-by-one.
  11941. * Note: currently we do not support 'false'.
  11942. */
  11943. this.usedrip = true;
  11944. /**
  11945. * When dripping is used, stores ICE candidates which are to be sent.
  11946. */
  11947. this.drip_container = [];
  11948. // Media constraints. Is this WebRTC only?
  11949. this.media_constraints = null;
  11950. // ICE servers config (RTCConfiguration?).
  11951. this.ice_config = {};
  11952. }
  11953. /**
  11954. * Prepares this object to initiate a session.
  11955. * @param peerjid the JID of the remote peer.
  11956. * @param isInitiator whether we will be the Jingle initiator.
  11957. * @param media_constraints
  11958. * @param ice_config
  11959. */
  11960. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  11961. media_constraints, ice_config) {
  11962. this.media_constraints = media_constraints;
  11963. this.ice_config = ice_config;
  11964. if (this.state !== null) {
  11965. console.error('attempt to initiate on session ' + this.sid +
  11966. 'in state ' + this.state);
  11967. return;
  11968. }
  11969. this.state = 'pending';
  11970. this.initiator = isInitiator ? this.me : peerjid;
  11971. this.responder = !isInitiator ? this.me : peerjid;
  11972. this.peerjid = peerjid;
  11973. this.doInitialize();
  11974. };
  11975. /**
  11976. * Finishes initialization.
  11977. */
  11978. JingleSession.prototype.doInitialize = function() {};
  11979. /**
  11980. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  11981. * Note: currently only used on transport-info
  11982. */
  11983. JingleSession.prototype.addIceCandidates = function(contents) {};
  11984. /**
  11985. * Handles an 'add-source' event.
  11986. *
  11987. * @param contents an array of Jingle 'content' elements.
  11988. */
  11989. JingleSession.prototype.addSources = function(contents) {};
  11990. /**
  11991. * Handles a 'remove-source' event.
  11992. *
  11993. * @param contents an array of Jingle 'content' elements.
  11994. */
  11995. JingleSession.prototype.removeSources = function(contents) {};
  11996. /**
  11997. * Terminates this Jingle session (stops sending media and closes the streams?)
  11998. */
  11999. JingleSession.prototype.terminate = function() {};
  12000. /**
  12001. * Sends a Jingle session-terminate message to the peer and terminates the
  12002. * session.
  12003. * @param reason
  12004. * @param text
  12005. */
  12006. JingleSession.prototype.sendTerminate = function(reason, text) {};
  12007. /**
  12008. * Handles an offer from the remote peer (prepares to accept a session).
  12009. * @param jingle the 'jingle' XML element.
  12010. */
  12011. JingleSession.prototype.setOffer = function(jingle) {};
  12012. /**
  12013. * Handles an answer from the remote peer (prepares to accept a session).
  12014. * @param jingle the 'jingle' XML element.
  12015. */
  12016. JingleSession.prototype.setAnswer = function(jingle) {};
  12017. module.exports = JingleSession;
  12018. },{}],56:[function(require,module,exports){
  12019. /* jshint -W117 */
  12020. var JingleSession = require("./JingleSession");
  12021. var TraceablePeerConnection = require("./TraceablePeerConnection");
  12022. var SDPDiffer = require("./SDPDiffer");
  12023. var SDPUtil = require("./SDPUtil");
  12024. var SDP = require("./SDP");
  12025. var async = require("async");
  12026. var transform = require("sdp-transform");
  12027. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12028. var RTCBrowserType = require("../RTC/RTCBrowserType");
  12029. var SSRCReplacement = require("./LocalSSRCReplacement");
  12030. // Jingle stuff
  12031. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  12032. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  12033. this.initiator = null;
  12034. this.responder = null;
  12035. this.peerjid = null;
  12036. this.state = null;
  12037. this.localSDP = null;
  12038. this.remoteSDP = null;
  12039. this.relayedStreams = [];
  12040. this.pc_constraints = null;
  12041. this.usetrickle = true;
  12042. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  12043. this.hadstuncandidate = false;
  12044. this.hadturncandidate = false;
  12045. this.lasticecandidate = false;
  12046. this.statsinterval = null;
  12047. this.reason = null;
  12048. this.addssrc = [];
  12049. this.removessrc = [];
  12050. this.pendingop = null;
  12051. this.switchstreams = false;
  12052. this.wait = true;
  12053. this.localStreamsSSRC = null;
  12054. this.ssrcOwners = {};
  12055. this.ssrcVideoTypes = {};
  12056. this.eventEmitter = eventEmitter;
  12057. /**
  12058. * The indicator which determines whether the (local) video has been muted
  12059. * in response to a user command in contrast to an automatic decision made
  12060. * by the application logic.
  12061. */
  12062. this.videoMuteByUser = false;
  12063. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  12064. // We start with the queue paused. We resume it when the signaling state is
  12065. // stable and the ice connection state is connected.
  12066. this.modifySourcesQueue.pause();
  12067. }
  12068. JingleSessionPC.prototype = JingleSession.prototype;
  12069. JingleSessionPC.prototype.constructor = JingleSessionPC;
  12070. JingleSessionPC.prototype.setOffer = function(offer) {
  12071. this.setRemoteDescription(offer, 'offer');
  12072. };
  12073. JingleSessionPC.prototype.setAnswer = function(answer) {
  12074. this.setRemoteDescription(answer, 'answer');
  12075. };
  12076. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  12077. var signalingState = this.peerconnection.signalingState;
  12078. var iceConnectionState = this.peerconnection.iceConnectionState;
  12079. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  12080. this.modifySourcesQueue.resume();
  12081. } else {
  12082. this.modifySourcesQueue.pause();
  12083. }
  12084. };
  12085. JingleSessionPC.prototype.doInitialize = function () {
  12086. var self = this;
  12087. this.hadstuncandidate = false;
  12088. this.hadturncandidate = false;
  12089. this.lasticecandidate = false;
  12090. this.isreconnect = false;
  12091. this.peerconnection = new TraceablePeerConnection(
  12092. this.connection.jingle.ice_config,
  12093. this.connection.jingle.pc_constraints,
  12094. this);
  12095. this.peerconnection.onicecandidate = function (event) {
  12096. self.sendIceCandidate(event.candidate);
  12097. };
  12098. this.peerconnection.onaddstream = function (event) {
  12099. if (event.stream.id !== 'default') {
  12100. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  12101. self.remoteStreamAdded(event);
  12102. } else {
  12103. // This is a recvonly stream. Clients that implement Unified Plan,
  12104. // such as Firefox use recvonly "streams/channels/tracks" for
  12105. // receiving remote stream/tracks, as opposed to Plan B where there
  12106. // are only 3 channels: audio, video and data.
  12107. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  12108. }
  12109. };
  12110. this.peerconnection.onremovestream = function (event) {
  12111. // Remove the stream from remoteStreams
  12112. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  12113. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  12114. };
  12115. this.peerconnection.onsignalingstatechange = function (event) {
  12116. if (!(self && self.peerconnection)) return;
  12117. self.updateModifySourcesQueue();
  12118. };
  12119. /**
  12120. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  12121. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  12122. * RTCPeerConnection.iceConnectionState changes.
  12123. *
  12124. * @param event the event containing information about the change
  12125. */
  12126. this.peerconnection.oniceconnectionstatechange = function (event) {
  12127. if (!(self && self.peerconnection)) return;
  12128. self.updateModifySourcesQueue();
  12129. switch (self.peerconnection.iceConnectionState) {
  12130. case 'connected':
  12131. // Informs interested parties that the connection has been restored.
  12132. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  12133. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  12134. self.isreconnect = false;
  12135. break;
  12136. case 'disconnected':
  12137. self.isreconnect = true;
  12138. // Informs interested parties that the connection has been interrupted.
  12139. if (self.peerconnection.signalingState === 'stable')
  12140. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  12141. break;
  12142. case 'failed':
  12143. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12144. break;
  12145. }
  12146. onIceConnectionStateChange(self.sid, self);
  12147. };
  12148. this.peerconnection.onnegotiationneeded = function (event) {
  12149. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  12150. };
  12151. // add any local and relayed stream
  12152. APP.RTC.localStreams.forEach(function(stream) {
  12153. self.peerconnection.addStream(stream.getOriginalStream());
  12154. });
  12155. this.relayedStreams.forEach(function(stream) {
  12156. self.peerconnection.addStream(stream);
  12157. });
  12158. };
  12159. function onIceConnectionStateChange(sid, session) {
  12160. switch (session.peerconnection.iceConnectionState) {
  12161. case 'checking':
  12162. session.timeChecking = (new Date()).getTime();
  12163. session.firstconnect = true;
  12164. break;
  12165. case 'completed': // on caller side
  12166. case 'connected':
  12167. if (session.firstconnect) {
  12168. session.firstconnect = false;
  12169. var metadata = {};
  12170. metadata.setupTime
  12171. = (new Date()).getTime() - session.timeChecking;
  12172. session.peerconnection.getStats(function (res) {
  12173. if(res && res.result) {
  12174. res.result().forEach(function (report) {
  12175. if (report.type == 'googCandidatePair' &&
  12176. report.stat('googActiveConnection') == 'true') {
  12177. metadata.localCandidateType
  12178. = report.stat('googLocalCandidateType');
  12179. metadata.remoteCandidateType
  12180. = report.stat('googRemoteCandidateType');
  12181. // log pair as well so we can get nice pie
  12182. // charts
  12183. metadata.candidatePair
  12184. = report.stat('googLocalCandidateType') +
  12185. ';' +
  12186. report.stat('googRemoteCandidateType');
  12187. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  12188. {
  12189. metadata.ipv6 = true;
  12190. }
  12191. }
  12192. });
  12193. }
  12194. });
  12195. }
  12196. break;
  12197. }
  12198. }
  12199. JingleSessionPC.prototype.accept = function () {
  12200. this.state = 'active';
  12201. var pranswer = this.peerconnection.localDescription;
  12202. if (!pranswer || pranswer.type != 'pranswer') {
  12203. return;
  12204. }
  12205. console.log('going from pranswer to answer');
  12206. if (this.usetrickle) {
  12207. // remove candidates already sent from session-accept
  12208. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  12209. for (var i = 0; i < lines.length; i++) {
  12210. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  12211. }
  12212. }
  12213. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  12214. // FIXME: change any inactive to sendrecv or whatever they were originally
  12215. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  12216. }
  12217. var prsdp = new SDP(pranswer.sdp);
  12218. var accept = $iq({to: this.peerjid,
  12219. type: 'set'})
  12220. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12221. action: 'session-accept',
  12222. initiator: this.initiator,
  12223. responder: this.responder,
  12224. sid: this.sid });
  12225. // FIXME why do we generate session-accept in 3 different places ?
  12226. prsdp.toJingle(
  12227. accept,
  12228. this.initiator == this.me ? 'initiator' : 'responder',
  12229. this.localStreamsSSRC);
  12230. var sdp = this.peerconnection.localDescription.sdp;
  12231. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  12232. // FIXME: change any inactive to sendrecv or whatever they were originally
  12233. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  12234. }
  12235. var self = this;
  12236. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  12237. function () {
  12238. //console.log('setLocalDescription success');
  12239. self.setLocalDescription();
  12240. SSRCReplacement.processSessionInit(accept);
  12241. self.connection.sendIQ(accept,
  12242. function () {
  12243. var ack = {};
  12244. ack.source = 'answer';
  12245. $(document).trigger('ack.jingle', [self.sid, ack]);
  12246. },
  12247. function (stanza) {
  12248. var error = ($(stanza).find('error').length) ? {
  12249. code: $(stanza).find('error').attr('code'),
  12250. reason: $(stanza).find('error :first')[0].tagName
  12251. }:{};
  12252. error.source = 'answer';
  12253. JingleSessionPC.onJingleError(self.sid, error);
  12254. },
  12255. 10000);
  12256. },
  12257. function (e) {
  12258. console.error('setLocalDescription failed', e);
  12259. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12260. }
  12261. );
  12262. };
  12263. JingleSessionPC.prototype.terminate = function (reason) {
  12264. this.state = 'ended';
  12265. this.reason = reason;
  12266. this.peerconnection.close();
  12267. if (this.statsinterval !== null) {
  12268. window.clearInterval(this.statsinterval);
  12269. this.statsinterval = null;
  12270. }
  12271. };
  12272. JingleSessionPC.prototype.active = function () {
  12273. return this.state == 'active';
  12274. };
  12275. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  12276. var self = this;
  12277. if (candidate && !this.lasticecandidate) {
  12278. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  12279. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  12280. if (!(ice && jcand)) {
  12281. console.error('failed to get ice && jcand');
  12282. return;
  12283. }
  12284. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12285. if (jcand.type === 'srflx') {
  12286. this.hadstuncandidate = true;
  12287. } else if (jcand.type === 'relay') {
  12288. this.hadturncandidate = true;
  12289. }
  12290. if (this.usetrickle) {
  12291. if (this.usedrip) {
  12292. if (this.drip_container.length === 0) {
  12293. // start 20ms callout
  12294. window.setTimeout(function () {
  12295. if (self.drip_container.length === 0) return;
  12296. self.sendIceCandidates(self.drip_container);
  12297. self.drip_container = [];
  12298. }, 20);
  12299. }
  12300. this.drip_container.push(candidate);
  12301. return;
  12302. } else {
  12303. self.sendIceCandidate([candidate]);
  12304. }
  12305. }
  12306. } else {
  12307. //console.log('sendIceCandidate: last candidate.');
  12308. if (!this.usetrickle) {
  12309. //console.log('should send full offer now...');
  12310. //FIXME why do we generate session-accept in 3 different places ?
  12311. var init = $iq({to: this.peerjid,
  12312. type: 'set'})
  12313. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12314. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  12315. initiator: this.initiator,
  12316. sid: this.sid});
  12317. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  12318. var sendJingle = function (ssrc) {
  12319. if(!ssrc)
  12320. ssrc = {};
  12321. self.localSDP.toJingle(
  12322. init,
  12323. self.initiator == self.me ? 'initiator' : 'responder',
  12324. ssrc);
  12325. SSRCReplacement.processSessionInit(init);
  12326. self.connection.sendIQ(init,
  12327. function () {
  12328. //console.log('session initiate ack');
  12329. var ack = {};
  12330. ack.source = 'offer';
  12331. $(document).trigger('ack.jingle', [self.sid, ack]);
  12332. },
  12333. function (stanza) {
  12334. self.state = 'error';
  12335. self.peerconnection.close();
  12336. var error = ($(stanza).find('error').length) ? {
  12337. code: $(stanza).find('error').attr('code'),
  12338. reason: $(stanza).find('error :first')[0].tagName,
  12339. }:{};
  12340. error.source = 'offer';
  12341. JingleSessionPC.onJingleError(self.sid, error);
  12342. },
  12343. 10000);
  12344. };
  12345. sendJingle();
  12346. }
  12347. this.lasticecandidate = true;
  12348. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  12349. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  12350. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  12351. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  12352. }
  12353. }
  12354. };
  12355. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  12356. console.log('sendIceCandidates', candidates);
  12357. var cand = $iq({to: this.peerjid, type: 'set'})
  12358. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12359. action: 'transport-info',
  12360. initiator: this.initiator,
  12361. sid: this.sid});
  12362. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  12363. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  12364. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  12365. if (cands.length > 0) {
  12366. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  12367. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12368. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  12369. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  12370. }).c('transport', ice);
  12371. for (var i = 0; i < cands.length; i++) {
  12372. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  12373. }
  12374. // add fingerprint
  12375. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  12376. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  12377. tmp.required = true;
  12378. cand.c(
  12379. 'fingerprint',
  12380. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  12381. .t(tmp.fingerprint);
  12382. delete tmp.fingerprint;
  12383. cand.attrs(tmp);
  12384. cand.up();
  12385. }
  12386. cand.up(); // transport
  12387. cand.up(); // content
  12388. }
  12389. }
  12390. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  12391. //console.log('was this the last candidate', this.lasticecandidate);
  12392. this.connection.sendIQ(cand,
  12393. function () {
  12394. var ack = {};
  12395. ack.source = 'transportinfo';
  12396. $(document).trigger('ack.jingle', [this.sid, ack]);
  12397. },
  12398. function (stanza) {
  12399. var error = ($(stanza).find('error').length) ? {
  12400. code: $(stanza).find('error').attr('code'),
  12401. reason: $(stanza).find('error :first')[0].tagName,
  12402. }:{};
  12403. error.source = 'transportinfo';
  12404. JingleSessionPC.onJingleError(this.sid, error);
  12405. },
  12406. 10000);
  12407. };
  12408. JingleSessionPC.prototype.sendOffer = function () {
  12409. //console.log('sendOffer...');
  12410. var self = this;
  12411. this.peerconnection.createOffer(function (sdp) {
  12412. self.createdOffer(sdp);
  12413. },
  12414. function (e) {
  12415. console.error('createOffer failed', e);
  12416. },
  12417. this.media_constraints
  12418. );
  12419. };
  12420. // FIXME createdOffer is never used in jitsi-meet
  12421. JingleSessionPC.prototype.createdOffer = function (sdp) {
  12422. //console.log('createdOffer', sdp);
  12423. var self = this;
  12424. this.localSDP = new SDP(sdp.sdp);
  12425. //this.localSDP.mangle();
  12426. var sendJingle = function () {
  12427. var init = $iq({to: this.peerjid,
  12428. type: 'set'})
  12429. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12430. action: 'session-initiate',
  12431. initiator: this.initiator,
  12432. sid: this.sid});
  12433. self.localSDP.toJingle(
  12434. init,
  12435. this.initiator == this.me ? 'initiator' : 'responder',
  12436. this.localStreamsSSRC);
  12437. SSRCReplacement.processSessionInit(init);
  12438. self.connection.sendIQ(init,
  12439. function () {
  12440. var ack = {};
  12441. ack.source = 'offer';
  12442. $(document).trigger('ack.jingle', [self.sid, ack]);
  12443. },
  12444. function (stanza) {
  12445. self.state = 'error';
  12446. self.peerconnection.close();
  12447. var error = ($(stanza).find('error').length) ? {
  12448. code: $(stanza).find('error').attr('code'),
  12449. reason: $(stanza).find('error :first')[0].tagName,
  12450. }:{};
  12451. error.source = 'offer';
  12452. JingleSessionPC.onJingleError(self.sid, error);
  12453. },
  12454. 10000);
  12455. }
  12456. sdp.sdp = this.localSDP.raw;
  12457. this.peerconnection.setLocalDescription(sdp,
  12458. function () {
  12459. if(self.usetrickle)
  12460. {
  12461. sendJingle();
  12462. }
  12463. self.setLocalDescription();
  12464. //console.log('setLocalDescription success');
  12465. },
  12466. function (e) {
  12467. console.error('setLocalDescription failed', e);
  12468. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12469. }
  12470. );
  12471. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12472. for (var i = 0; i < cands.length; i++) {
  12473. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12474. if (cand.type == 'srflx') {
  12475. this.hadstuncandidate = true;
  12476. } else if (cand.type == 'relay') {
  12477. this.hadturncandidate = true;
  12478. }
  12479. }
  12480. };
  12481. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  12482. var self = this;
  12483. $(contents).each(function (idx, content) {
  12484. var name = $(content).attr('name');
  12485. var mediaType = this.getAttribute('name');
  12486. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12487. ssrcs.each(function () {
  12488. var ssrc = this.getAttribute('ssrc');
  12489. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12490. function () {
  12491. var owner = this.getAttribute('owner');
  12492. self.ssrcOwners[ssrc] = owner;
  12493. }
  12494. );
  12495. });
  12496. });
  12497. };
  12498. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  12499. return this.ssrcOwners[ssrc];
  12500. };
  12501. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  12502. //console.log('setting remote description... ', desctype);
  12503. this.remoteSDP = new SDP('');
  12504. this.remoteSDP.fromJingle(elem);
  12505. this.readSsrcInfo($(elem).find(">content"));
  12506. if (this.peerconnection.remoteDescription !== null) {
  12507. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12508. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12509. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12510. for (var i = 0; i < pranswer.media.length; i++) {
  12511. // make sure we have ice ufrag and pwd
  12512. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12513. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12514. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12515. } else {
  12516. console.warn('no ice ufrag?');
  12517. }
  12518. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12519. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12520. } else {
  12521. console.warn('no ice pwd?');
  12522. }
  12523. }
  12524. // copy over candidates
  12525. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12526. for (var j = 0; j < lines.length; j++) {
  12527. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12528. }
  12529. }
  12530. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12531. }
  12532. }
  12533. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12534. this.peerconnection.setRemoteDescription(remotedesc,
  12535. function () {
  12536. //console.log('setRemoteDescription success');
  12537. },
  12538. function (e) {
  12539. console.error('setRemoteDescription error', e);
  12540. JingleSessionPC.onJingleFatalError(self, e);
  12541. }
  12542. );
  12543. };
  12544. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  12545. var self = this;
  12546. if (this.peerconnection.signalingState == 'closed') {
  12547. return;
  12548. }
  12549. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12550. console.log('trickle ice candidate arriving before session accept...');
  12551. // create a PRANSWER for setRemoteDescription
  12552. if (!this.remoteSDP) {
  12553. var cobbled = 'v=0\r\n' +
  12554. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12555. 's=-\r\n' +
  12556. 't=0 0\r\n';
  12557. // first, take some things from the local description
  12558. for (var i = 0; i < this.localSDP.media.length; i++) {
  12559. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12560. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12561. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12562. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12563. }
  12564. cobbled += 'a=inactive\r\n';
  12565. }
  12566. this.remoteSDP = new SDP(cobbled);
  12567. }
  12568. // then add things like ice and dtls from remote candidate
  12569. elem.each(function () {
  12570. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12571. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12572. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12573. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12574. var tmp = $(this).find('transport');
  12575. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12576. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12577. tmp = $(this).find('transport>fingerprint');
  12578. if (tmp.length) {
  12579. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12580. } else {
  12581. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12582. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12583. }
  12584. break;
  12585. }
  12586. }
  12587. }
  12588. });
  12589. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12590. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12591. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12592. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12593. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12594. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12595. }).length == this.remoteSDP.media.length;
  12596. if (iscomplete) {
  12597. console.log('setting pranswer');
  12598. try {
  12599. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12600. function() {
  12601. },
  12602. function(e) {
  12603. console.log('setRemoteDescription pranswer failed', e.toString());
  12604. });
  12605. } catch (e) {
  12606. console.error('setting pranswer failed', e);
  12607. }
  12608. } else {
  12609. //console.log('not yet setting pranswer');
  12610. }
  12611. }
  12612. // operate on each content element
  12613. elem.each(function () {
  12614. // would love to deactivate this, but firefox still requires it
  12615. var idx = -1;
  12616. var i;
  12617. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12618. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12619. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12620. idx = i;
  12621. break;
  12622. }
  12623. }
  12624. if (idx == -1) { // fall back to localdescription
  12625. for (i = 0; i < self.localSDP.media.length; i++) {
  12626. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12627. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12628. idx = i;
  12629. break;
  12630. }
  12631. }
  12632. }
  12633. var name = $(this).attr('name');
  12634. // TODO: check ice-pwd and ice-ufrag?
  12635. $(this).find('transport>candidate').each(function () {
  12636. var line, candidate;
  12637. line = SDPUtil.candidateFromJingle(this);
  12638. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12639. sdpMid: name,
  12640. candidate: line});
  12641. try {
  12642. self.peerconnection.addIceCandidate(candidate);
  12643. } catch (e) {
  12644. console.error('addIceCandidate failed', e.toString(), line);
  12645. }
  12646. });
  12647. });
  12648. };
  12649. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  12650. //console.log('createAnswer', provisional);
  12651. var self = this;
  12652. this.peerconnection.createAnswer(
  12653. function (sdp) {
  12654. self.createdAnswer(sdp, provisional);
  12655. },
  12656. function (e) {
  12657. console.error('createAnswer failed', e);
  12658. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12659. },
  12660. this.media_constraints
  12661. );
  12662. };
  12663. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  12664. //console.log('createAnswer callback');
  12665. var self = this;
  12666. this.localSDP = new SDP(sdp.sdp);
  12667. //this.localSDP.mangle();
  12668. this.usepranswer = provisional === true;
  12669. if (this.usetrickle) {
  12670. if (this.usepranswer) {
  12671. sdp.type = 'pranswer';
  12672. for (var i = 0; i < this.localSDP.media.length; i++) {
  12673. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12674. }
  12675. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12676. }
  12677. }
  12678. var self = this;
  12679. var sendJingle = function (ssrcs) {
  12680. // FIXME why do we generate session-accept in 3 different places ?
  12681. var accept = $iq({to: self.peerjid,
  12682. type: 'set'})
  12683. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12684. action: 'session-accept',
  12685. initiator: self.initiator,
  12686. responder: self.responder,
  12687. sid: self.sid });
  12688. self.localSDP.toJingle(
  12689. accept,
  12690. self.initiator == self.me ? 'initiator' : 'responder',
  12691. ssrcs);
  12692. SSRCReplacement.processSessionInit(accept);
  12693. self.connection.sendIQ(accept,
  12694. function () {
  12695. var ack = {};
  12696. ack.source = 'answer';
  12697. $(document).trigger('ack.jingle', [self.sid, ack]);
  12698. },
  12699. function (stanza) {
  12700. var error = ($(stanza).find('error').length) ? {
  12701. code: $(stanza).find('error').attr('code'),
  12702. reason: $(stanza).find('error :first')[0].tagName,
  12703. }:{};
  12704. error.source = 'answer';
  12705. JingleSessionPC.onJingleError(self.sid, error);
  12706. },
  12707. 10000);
  12708. }
  12709. sdp.sdp = this.localSDP.raw;
  12710. this.peerconnection.setLocalDescription(sdp,
  12711. function () {
  12712. //console.log('setLocalDescription success');
  12713. if (self.usetrickle && !self.usepranswer) {
  12714. sendJingle();
  12715. }
  12716. self.setLocalDescription();
  12717. },
  12718. function (e) {
  12719. console.error('setLocalDescription failed', e);
  12720. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12721. }
  12722. );
  12723. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12724. for (var j = 0; j < cands.length; j++) {
  12725. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12726. if (cand.type == 'srflx') {
  12727. this.hadstuncandidate = true;
  12728. } else if (cand.type == 'relay') {
  12729. this.hadturncandidate = true;
  12730. }
  12731. }
  12732. };
  12733. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  12734. var self = this,
  12735. term = $iq({to: this.peerjid,
  12736. type: 'set'})
  12737. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12738. action: 'session-terminate',
  12739. initiator: this.initiator,
  12740. sid: this.sid})
  12741. .c('reason')
  12742. .c(reason || 'success');
  12743. if (text) {
  12744. term.up().c('text').t(text);
  12745. }
  12746. this.connection.sendIQ(term,
  12747. function () {
  12748. self.peerconnection.close();
  12749. self.peerconnection = null;
  12750. self.terminate();
  12751. var ack = {};
  12752. ack.source = 'terminate';
  12753. $(document).trigger('ack.jingle', [self.sid, ack]);
  12754. },
  12755. function (stanza) {
  12756. var error = ($(stanza).find('error').length) ? {
  12757. code: $(stanza).find('error').attr('code'),
  12758. reason: $(stanza).find('error :first')[0].tagName,
  12759. }:{};
  12760. $(document).trigger('ack.jingle', [self.sid, error]);
  12761. },
  12762. 10000);
  12763. if (this.statsinterval !== null) {
  12764. window.clearInterval(this.statsinterval);
  12765. this.statsinterval = null;
  12766. }
  12767. };
  12768. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  12769. var self = this;
  12770. // FIXME: dirty waiting
  12771. if (!this.peerconnection.localDescription)
  12772. {
  12773. console.warn("addSource - localDescription not ready yet")
  12774. setTimeout(function()
  12775. {
  12776. self.addSource(elem, fromJid);
  12777. },
  12778. 200
  12779. );
  12780. return;
  12781. }
  12782. console.log('addssrc', new Date().getTime());
  12783. console.log('ice', this.peerconnection.iceConnectionState);
  12784. this.readSsrcInfo(elem);
  12785. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12786. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12787. $(elem).each(function (idx, content) {
  12788. var name = $(content).attr('name');
  12789. var lines = '';
  12790. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12791. var semantics = this.getAttribute('semantics');
  12792. var ssrcs = $(this).find('>source').map(function () {
  12793. return this.getAttribute('ssrc');
  12794. }).get();
  12795. if (ssrcs.length != 0) {
  12796. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12797. }
  12798. });
  12799. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12800. tmp.each(function () {
  12801. var ssrc = $(this).attr('ssrc');
  12802. if(mySdp.containsSSRC(ssrc)){
  12803. /**
  12804. * This happens when multiple participants change their streams at the same time and
  12805. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12806. * addssrc are scheduled for update IQ. See
  12807. */
  12808. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12809. return;
  12810. }
  12811. if (sdp.containsSSRC(ssrc)) {
  12812. console.warn("Source-add request for existing SSRC: " + ssrc);
  12813. return;
  12814. }
  12815. $(this).find('>parameter').each(function () {
  12816. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12817. if ($(this).attr('value') && $(this).attr('value').length)
  12818. lines += ':' + $(this).attr('value');
  12819. lines += '\r\n';
  12820. });
  12821. });
  12822. sdp.media.forEach(function(media, idx) {
  12823. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12824. return;
  12825. sdp.media[idx] += lines;
  12826. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12827. self.addssrc[idx] += lines;
  12828. });
  12829. sdp.raw = sdp.session + sdp.media.join('');
  12830. });
  12831. this.modifySourcesQueue.push(function() {
  12832. // When a source is added and if this is FF, a new channel is allocated
  12833. // for receiving the added source. We need to diffuse the SSRC of this
  12834. // new recvonly channel to the rest of the peers.
  12835. console.log('modify sources done');
  12836. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12837. console.log("SDPs", mySdp, newSdp);
  12838. self.notifyMySSRCUpdate(mySdp, newSdp);
  12839. });
  12840. };
  12841. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  12842. var self = this;
  12843. // FIXME: dirty waiting
  12844. if (!this.peerconnection.localDescription)
  12845. {
  12846. console.warn("removeSource - localDescription not ready yet")
  12847. setTimeout(function()
  12848. {
  12849. self.removeSource(elem, fromJid);
  12850. },
  12851. 200
  12852. );
  12853. return;
  12854. }
  12855. console.log('removessrc', new Date().getTime());
  12856. console.log('ice', this.peerconnection.iceConnectionState);
  12857. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12858. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12859. $(elem).each(function (idx, content) {
  12860. var name = $(content).attr('name');
  12861. var lines = '';
  12862. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12863. var semantics = this.getAttribute('semantics');
  12864. var ssrcs = $(this).find('>source').map(function () {
  12865. return this.getAttribute('ssrc');
  12866. }).get();
  12867. if (ssrcs.length != 0) {
  12868. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12869. }
  12870. });
  12871. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12872. tmp.each(function () {
  12873. var ssrc = $(this).attr('ssrc');
  12874. // This should never happen, but can be useful for bug detection
  12875. if(mySdp.containsSSRC(ssrc)){
  12876. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12877. return;
  12878. }
  12879. $(this).find('>parameter').each(function () {
  12880. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12881. if ($(this).attr('value') && $(this).attr('value').length)
  12882. lines += ':' + $(this).attr('value');
  12883. lines += '\r\n';
  12884. });
  12885. });
  12886. sdp.media.forEach(function(media, idx) {
  12887. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12888. return;
  12889. sdp.media[idx] += lines;
  12890. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12891. self.removessrc[idx] += lines;
  12892. });
  12893. sdp.raw = sdp.session + sdp.media.join('');
  12894. });
  12895. this.modifySourcesQueue.push(function() {
  12896. // When a source is removed and if this is FF, the recvonly channel that
  12897. // receives the remote stream is deactivated . We need to diffuse the
  12898. // recvonly SSRC removal to the rest of the peers.
  12899. console.log('modify sources done');
  12900. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12901. console.log("SDPs", mySdp, newSdp);
  12902. self.notifyMySSRCUpdate(mySdp, newSdp);
  12903. });
  12904. };
  12905. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  12906. var self = this;
  12907. if (this.peerconnection.signalingState == 'closed') return;
  12908. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12909. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12910. this.setLocalDescription();
  12911. if(successCallback){
  12912. successCallback();
  12913. }
  12914. queueCallback();
  12915. return;
  12916. }
  12917. // Reset switch streams flag
  12918. this.switchstreams = false;
  12919. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12920. // add sources
  12921. this.addssrc.forEach(function(lines, idx) {
  12922. sdp.media[idx] += lines;
  12923. });
  12924. this.addssrc = [];
  12925. // remove sources
  12926. this.removessrc.forEach(function(lines, idx) {
  12927. lines = lines.split('\r\n');
  12928. lines.pop(); // remove empty last element;
  12929. lines.forEach(function(line) {
  12930. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12931. });
  12932. });
  12933. this.removessrc = [];
  12934. sdp.raw = sdp.session + sdp.media.join('');
  12935. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12936. function() {
  12937. if(self.signalingState == 'closed') {
  12938. console.error("createAnswer attempt on closed state");
  12939. queueCallback("createAnswer attempt on closed state");
  12940. return;
  12941. }
  12942. self.peerconnection.createAnswer(
  12943. function(modifiedAnswer) {
  12944. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12945. if (self.pendingop !== null) {
  12946. var sdp = new SDP(modifiedAnswer.sdp);
  12947. if (sdp.media.length > 1) {
  12948. switch(self.pendingop) {
  12949. case 'mute':
  12950. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12951. break;
  12952. case 'unmute':
  12953. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12954. break;
  12955. }
  12956. sdp.raw = sdp.session + sdp.media.join('');
  12957. modifiedAnswer.sdp = sdp.raw;
  12958. }
  12959. self.pendingop = null;
  12960. }
  12961. // FIXME: pushing down an answer while ice connection state
  12962. // is still checking is bad...
  12963. //console.log(self.peerconnection.iceConnectionState);
  12964. // trying to work around another chrome bug
  12965. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12966. self.peerconnection.setLocalDescription(modifiedAnswer,
  12967. function() {
  12968. //console.log('modified setLocalDescription ok');
  12969. self.setLocalDescription();
  12970. if(successCallback){
  12971. successCallback();
  12972. }
  12973. queueCallback();
  12974. },
  12975. function(error) {
  12976. console.error('modified setLocalDescription failed', error);
  12977. queueCallback(error);
  12978. }
  12979. );
  12980. },
  12981. function(error) {
  12982. console.error('modified answer failed', error);
  12983. queueCallback(error);
  12984. }
  12985. );
  12986. },
  12987. function(error) {
  12988. console.error('modify failed', error);
  12989. queueCallback(error);
  12990. }
  12991. );
  12992. };
  12993. /**
  12994. * Switches video streams.
  12995. * @param new_stream new stream that will be used as video of this session.
  12996. * @param oldStream old video stream of this session.
  12997. * @param success_callback callback executed after successful stream switch.
  12998. */
  12999. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  13000. var self = this;
  13001. // Remember SDP to figure out added/removed SSRCs
  13002. var oldSdp = null;
  13003. if(self.peerconnection) {
  13004. if(self.peerconnection.localDescription) {
  13005. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  13006. }
  13007. self.peerconnection.removeStream(oldStream, true);
  13008. if(new_stream)
  13009. self.peerconnection.addStream(new_stream);
  13010. }
  13011. // Conference is not active
  13012. if(!oldSdp || !self.peerconnection) {
  13013. success_callback();
  13014. return;
  13015. }
  13016. self.switchstreams = true;
  13017. self.modifySourcesQueue.push(function() {
  13018. console.log('modify sources done');
  13019. success_callback();
  13020. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  13021. console.log("SDPs", oldSdp, newSdp);
  13022. self.notifyMySSRCUpdate(oldSdp, newSdp);
  13023. });
  13024. };
  13025. /**
  13026. * Figures out added/removed ssrcs and send update IQs.
  13027. * @param old_sdp SDP object for old description.
  13028. * @param new_sdp SDP object for new description.
  13029. */
  13030. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  13031. if (!(this.peerconnection.signalingState == 'stable' &&
  13032. this.peerconnection.iceConnectionState == 'connected')){
  13033. console.log("Too early to send updates");
  13034. return;
  13035. }
  13036. // send source-remove IQ.
  13037. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  13038. var remove = $iq({to: this.peerjid, type: 'set'})
  13039. .c('jingle', {
  13040. xmlns: 'urn:xmpp:jingle:1',
  13041. action: 'source-remove',
  13042. initiator: this.initiator,
  13043. sid: this.sid
  13044. }
  13045. );
  13046. var removed = sdpDiffer.toJingle(remove);
  13047. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  13048. // it in the current form
  13049. if (removed)
  13050. remove = SSRCReplacement.processSourceRemove(remove);
  13051. if (removed && remove) {
  13052. console.info("Sending source-remove", remove);
  13053. this.connection.sendIQ(remove,
  13054. function (res) {
  13055. console.info('got remove result', res);
  13056. },
  13057. function (err) {
  13058. console.error('got remove error', err);
  13059. }
  13060. );
  13061. } else {
  13062. console.log('removal not necessary');
  13063. }
  13064. // send source-add IQ.
  13065. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  13066. var add = $iq({to: this.peerjid, type: 'set'})
  13067. .c('jingle', {
  13068. xmlns: 'urn:xmpp:jingle:1',
  13069. action: 'source-add',
  13070. initiator: this.initiator,
  13071. sid: this.sid
  13072. }
  13073. );
  13074. var added = sdpDiffer.toJingle(add);
  13075. // Let 'source-add' IQ through the hack and see if we're allowed to send
  13076. // it in the current form
  13077. if (added)
  13078. add = SSRCReplacement.processSourceAdd(add);
  13079. if (added && add) {
  13080. console.info("Sending source-add", add);
  13081. this.connection.sendIQ(add,
  13082. function (res) {
  13083. console.info('got add result', res);
  13084. },
  13085. function (err) {
  13086. console.error('got add error', err);
  13087. }
  13088. );
  13089. } else {
  13090. console.log('addition not necessary');
  13091. }
  13092. };
  13093. /**
  13094. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  13095. *
  13096. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  13097. * tracks; otherwise, <tt>false</tt>
  13098. * @param callback a function to be invoked with <tt>mute</tt> after all video
  13099. * tracks have been enabled/disabled. The function may, optionally, return
  13100. * another function which is to be invoked after the whole mute/unmute operation
  13101. * has completed successfully.
  13102. * @param options an object which specifies optional arguments such as the
  13103. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  13104. * specifies whether the method was initiated in response to a user command (in
  13105. * contrast to an automatic decision made by the application logic)
  13106. */
  13107. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  13108. var byUser;
  13109. if (options) {
  13110. byUser = options.byUser;
  13111. if (typeof byUser === 'undefined') {
  13112. byUser = true;
  13113. }
  13114. } else {
  13115. byUser = true;
  13116. }
  13117. // The user's command to mute the (local) video takes precedence over any
  13118. // automatic decision made by the application logic.
  13119. if (byUser) {
  13120. this.videoMuteByUser = mute;
  13121. } else if (this.videoMuteByUser) {
  13122. return;
  13123. }
  13124. this.hardMuteVideo(mute);
  13125. var self = this;
  13126. var oldSdp = null;
  13127. if(self.peerconnection) {
  13128. if(self.peerconnection.localDescription) {
  13129. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  13130. }
  13131. }
  13132. this.modifySourcesQueue.push(function() {
  13133. console.log('modify sources done');
  13134. callback(mute);
  13135. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  13136. console.log("SDPs", oldSdp, newSdp);
  13137. self.notifyMySSRCUpdate(oldSdp, newSdp);
  13138. });
  13139. };
  13140. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  13141. this.pendingop = muted ? 'mute' : 'unmute';
  13142. };
  13143. JingleSessionPC.prototype.sendMute = function (muted, content) {
  13144. var info = $iq({to: this.peerjid,
  13145. type: 'set'})
  13146. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  13147. action: 'session-info',
  13148. initiator: this.initiator,
  13149. sid: this.sid });
  13150. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  13151. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  13152. if (content) {
  13153. info.attrs({'name': content});
  13154. }
  13155. this.connection.send(info);
  13156. };
  13157. JingleSessionPC.prototype.sendRinging = function () {
  13158. var info = $iq({to: this.peerjid,
  13159. type: 'set'})
  13160. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  13161. action: 'session-info',
  13162. initiator: this.initiator,
  13163. sid: this.sid });
  13164. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  13165. this.connection.send(info);
  13166. };
  13167. JingleSessionPC.prototype.getStats = function (interval) {
  13168. var self = this;
  13169. var recv = {audio: 0, video: 0};
  13170. var lost = {audio: 0, video: 0};
  13171. var lastrecv = {audio: 0, video: 0};
  13172. var lastlost = {audio: 0, video: 0};
  13173. var loss = {audio: 0, video: 0};
  13174. var delta = {audio: 0, video: 0};
  13175. this.statsinterval = window.setInterval(function () {
  13176. if (self && self.peerconnection && self.peerconnection.getStats) {
  13177. self.peerconnection.getStats(function (stats) {
  13178. var results = stats.result();
  13179. // TODO: there are so much statistics you can get from this..
  13180. for (var i = 0; i < results.length; ++i) {
  13181. if (results[i].type == 'ssrc') {
  13182. var packetsrecv = results[i].stat('packetsReceived');
  13183. var packetslost = results[i].stat('packetsLost');
  13184. if (packetsrecv && packetslost) {
  13185. packetsrecv = parseInt(packetsrecv, 10);
  13186. packetslost = parseInt(packetslost, 10);
  13187. if (results[i].stat('googFrameRateReceived')) {
  13188. lastlost.video = lost.video;
  13189. lastrecv.video = recv.video;
  13190. recv.video = packetsrecv;
  13191. lost.video = packetslost;
  13192. } else {
  13193. lastlost.audio = lost.audio;
  13194. lastrecv.audio = recv.audio;
  13195. recv.audio = packetsrecv;
  13196. lost.audio = packetslost;
  13197. }
  13198. }
  13199. }
  13200. }
  13201. delta.audio = recv.audio - lastrecv.audio;
  13202. delta.video = recv.video - lastrecv.video;
  13203. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  13204. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  13205. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  13206. });
  13207. }
  13208. }, interval || 3000);
  13209. return this.statsinterval;
  13210. };
  13211. JingleSessionPC.onJingleError = function (session, error)
  13212. {
  13213. console.error("Jingle error", error);
  13214. }
  13215. JingleSessionPC.onJingleFatalError = function (session, error)
  13216. {
  13217. this.service.sessionTerminated = true;
  13218. this.connection.emuc.doLeave();
  13219. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  13220. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  13221. }
  13222. JingleSessionPC.prototype.setLocalDescription = function () {
  13223. var self = this;
  13224. var newssrcs = [];
  13225. var session = transform.parse(this.peerconnection.localDescription.sdp);
  13226. session.media.forEach(function (media) {
  13227. if (media.ssrcs != null && media.ssrcs.length > 0) {
  13228. // TODO(gp) maybe exclude FID streams?
  13229. media.ssrcs.forEach(function (ssrc) {
  13230. if (ssrc.attribute !== 'cname') {
  13231. return;
  13232. }
  13233. newssrcs.push({
  13234. 'ssrc': ssrc.id,
  13235. 'type': media.type
  13236. });
  13237. });
  13238. }
  13239. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  13240. {
  13241. newssrcs.push({
  13242. 'ssrc': self.localStreamsSSRC[media.type],
  13243. 'type': media.type
  13244. });
  13245. }
  13246. });
  13247. console.log('new ssrcs', newssrcs);
  13248. // Bind us as local SSRCs owner
  13249. if (newssrcs.length > 0) {
  13250. for (var i = 1; i <= newssrcs.length; i ++) {
  13251. var ssrc = newssrcs[i-1].ssrc;
  13252. var myJid = self.connection.emuc.myroomjid;
  13253. self.ssrcOwners[ssrc] = myJid;
  13254. }
  13255. }
  13256. }
  13257. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13258. function sendKeyframe(pc) {
  13259. console.log('sendkeyframe', pc.iceConnectionState);
  13260. if (pc.iceConnectionState !== 'connected') return; // safe...
  13261. var self = this;
  13262. pc.setRemoteDescription(
  13263. pc.remoteDescription,
  13264. function () {
  13265. pc.createAnswer(
  13266. function (modifiedAnswer) {
  13267. pc.setLocalDescription(
  13268. modifiedAnswer,
  13269. function () {
  13270. // noop
  13271. },
  13272. function (error) {
  13273. console.log('triggerKeyframe setLocalDescription failed', error);
  13274. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  13275. }
  13276. );
  13277. },
  13278. function (error) {
  13279. console.log('triggerKeyframe createAnswer failed', error);
  13280. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  13281. }
  13282. );
  13283. },
  13284. function (error) {
  13285. console.log('triggerKeyframe setRemoteDescription failed', error);
  13286. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  13287. }
  13288. );
  13289. }
  13290. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  13291. var self = this;
  13292. var thessrc;
  13293. var streamId = APP.RTC.getStreamID(data.stream);
  13294. // look up an associated JID for a stream id
  13295. if (!streamId) {
  13296. console.error("No stream ID for", data.stream);
  13297. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  13298. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  13299. var ssrclines
  13300. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  13301. ssrclines = ssrclines.filter(function (line) {
  13302. // NOTE(gp) previously we filtered on the mslabel, but that property
  13303. // is not always present.
  13304. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  13305. if (RTCBrowserType.isTemasysPluginUsed()) {
  13306. return ((line.indexOf('mslabel:' + streamId) !== -1));
  13307. } else {
  13308. return ((line.indexOf('msid:' + streamId) !== -1));
  13309. }
  13310. });
  13311. if (ssrclines.length) {
  13312. thessrc = ssrclines[0].substring(7).split(' ')[0];
  13313. if (!self.ssrcOwners[thessrc]) {
  13314. console.error("No SSRC owner known for: " + thessrc);
  13315. return;
  13316. }
  13317. data.peerjid = self.ssrcOwners[thessrc];
  13318. console.log('associated jid', self.ssrcOwners[thessrc]);
  13319. } else {
  13320. console.error("No SSRC lines for ", streamId);
  13321. }
  13322. }
  13323. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  13324. var isVideo = data.stream.getVideoTracks().length > 0;
  13325. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13326. if (isVideo &&
  13327. data.peerjid && this.peerjid === data.peerjid &&
  13328. data.stream.getVideoTracks().length === 0 &&
  13329. APP.RTC.localVideo.getTracks().length > 0) {
  13330. window.setTimeout(function () {
  13331. sendKeyframe(self.peerconnection);
  13332. }, 3000);
  13333. }
  13334. }
  13335. module.exports = JingleSessionPC;
  13336. },{"../../service/xmpp/XMPPEvents":120,"../RTC/RTCBrowserType":10,"./JingleSession":55,"./LocalSSRCReplacement":57,"./SDP":58,"./SDPDiffer":59,"./SDPUtil":60,"./TraceablePeerConnection":61,"async":71,"sdp-transform":107}],57:[function(require,module,exports){
  13337. /* global $ */
  13338. /*
  13339. Here we do modifications of local video SSRCs. There are 2 situations we have
  13340. to handle:
  13341. 1. We generate SSRC for local recvonly video stream. This is the case when we
  13342. have no local camera and it is not generated automatically, but SSRC=1 is
  13343. used implicitly. If that happens RTCP packets will be dropped by the JVB
  13344. and we won't be able to request video key frames correctly.
  13345. 2. A hack to re-use SSRC of the first video stream for any new stream created
  13346. in future. It turned out that Chrome may keep on using the SSRC of removed
  13347. video stream in RTCP even though a new one has been created. So we just
  13348. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  13349. notifications are blocked once first video SSRC is advertised to the focus.
  13350. What this hack does:
  13351. 1. Stores the SSRC of the first video stream created by
  13352. a) scanning Jingle session-accept/session-invite for existing video SSRC
  13353. b) watching for 'source-add' for new video stream if it has not been
  13354. created in step a)
  13355. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  13356. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  13357. returned to the other parts of the application.
  13358. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  13359. blocks those notifications. This makes Jicofo and all participants think
  13360. that it exists all the time even if the video stream has been removed or
  13361. replaced locally. Thanks to that there is no additional signaling activity
  13362. on video mute or when switching to the desktop stream.
  13363. */
  13364. var SDP = require('./SDP');
  13365. var RTCBrowserType = require('../RTC/RTCBrowserType');
  13366. /**
  13367. * The hack is enabled on all browsers except FF by default
  13368. * FIXME finish the hack once removeStream method is implemented in FF
  13369. * @type {boolean}
  13370. */
  13371. var isEnabled = !RTCBrowserType.isFirefox();
  13372. /**
  13373. * Stored SSRC of local video stream.
  13374. */
  13375. var localVideoSSRC;
  13376. /**
  13377. * SSRC used for recvonly video stream when we have no local camera.
  13378. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  13379. * instead of 1.
  13380. */
  13381. var localRecvOnlySSRC;
  13382. /**
  13383. * cname for <tt>localRecvOnlySSRC</tt>
  13384. */
  13385. var localRecvOnlyCName;
  13386. /**
  13387. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  13388. * from given Jingle IQ.
  13389. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  13390. * @param actionName display name of the action which will be printed in log
  13391. * messages.
  13392. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  13393. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  13394. * other SSRCs left to be signaled after removing it.
  13395. */
  13396. var filterOutSource = function (modifyIq, actionName) {
  13397. var modifyIqTree = $(modifyIq.tree());
  13398. if (!localVideoSSRC)
  13399. return modifyIqTree[0];
  13400. var videoSSRC = modifyIqTree.find(
  13401. '>jingle>content[name="video"]' +
  13402. '>description>source[ssrc="' + localVideoSSRC + '"]');
  13403. if (!videoSSRC.length) {
  13404. return modifyIqTree[0];
  13405. }
  13406. console.info(
  13407. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  13408. videoSSRC.remove();
  13409. // Check if any sources still left to be added/removed
  13410. if (modifyIqTree.find('>jingle>content>description>source').length) {
  13411. return modifyIqTree[0];
  13412. } else {
  13413. return null;
  13414. }
  13415. };
  13416. /**
  13417. * Scans given Jingle IQ for video SSRC and stores it.
  13418. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  13419. */
  13420. var storeLocalVideoSSRC = function (jingleIq) {
  13421. var videoSSRCs =
  13422. $(jingleIq.tree())
  13423. .find('>jingle>content[name="video"]>description>source');
  13424. videoSSRCs.each(function (idx, ssrcElem) {
  13425. if (localVideoSSRC)
  13426. return;
  13427. // We consider SSRC real only if it has msid attribute
  13428. // recvonly streams in FF do not have it as well as local SSRCs
  13429. // we generate for recvonly streams in Chrome
  13430. var ssrSel = $(ssrcElem);
  13431. var msid = ssrSel.find('>parameter[name="msid"]');
  13432. if (msid.length) {
  13433. var ssrcVal = ssrSel.attr('ssrc');
  13434. if (ssrcVal) {
  13435. localVideoSSRC = ssrcVal;
  13436. console.info('Stored local video SSRC' +
  13437. ' for future re-use: ' + localVideoSSRC);
  13438. }
  13439. }
  13440. });
  13441. };
  13442. /**
  13443. * Generates new SSRC for local video recvonly stream.
  13444. * FIXME what about eventual SSRC collision ?
  13445. */
  13446. function generateRecvonlySSRC() {
  13447. //
  13448. localRecvOnlySSRC =
  13449. Math.random().toString(10).substring(2, 11);
  13450. localRecvOnlyCName =
  13451. Math.random().toString(36).substring(2);
  13452. console.info(
  13453. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  13454. ", cname: " + localRecvOnlyCName);
  13455. }
  13456. var LocalSSRCReplacement = {
  13457. /**
  13458. * Method must be called before 'session-initiate' or 'session-invite' is
  13459. * sent. Scans the IQ for local video SSRC and stores it if detected.
  13460. *
  13461. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  13462. * which will be scanned for local video SSRC.
  13463. */
  13464. processSessionInit: function (sessionInit) {
  13465. if (!isEnabled)
  13466. return;
  13467. if (localVideoSSRC) {
  13468. console.error("Local SSRC stored already: " + localVideoSSRC);
  13469. return;
  13470. }
  13471. storeLocalVideoSSRC(sessionInit);
  13472. },
  13473. /**
  13474. * If we have local video SSRC stored searched given
  13475. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  13476. * with the stored one.
  13477. * @param localDescription local description object that will have local
  13478. * video SSRC replaced with the stored one
  13479. * @returns modified <tt>localDescription</tt> object.
  13480. */
  13481. mungeLocalVideoSSRC: function (localDescription) {
  13482. if (!isEnabled)
  13483. return localDescription;
  13484. if (!localDescription) {
  13485. console.warn("localDescription is null or undefined");
  13486. return localDescription;
  13487. }
  13488. // IF we have local video SSRC stored make sure it is replaced
  13489. // with old SSRC
  13490. if (localVideoSSRC) {
  13491. var newSdp = new SDP(localDescription.sdp);
  13492. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  13493. !newSdp.containsSSRC(localVideoSSRC)) {
  13494. // Get new video SSRC
  13495. var map = newSdp.getMediaSsrcMap();
  13496. var videoPart = map[1];
  13497. var videoSSRCs = videoPart.ssrcs;
  13498. var newSSRC = Object.keys(videoSSRCs)[0];
  13499. console.info(
  13500. "Replacing new video SSRC: " + newSSRC +
  13501. " with " + localVideoSSRC);
  13502. localDescription.sdp =
  13503. newSdp.raw.replace(
  13504. new RegExp('a=ssrc:' + newSSRC, 'g'),
  13505. 'a=ssrc:' + localVideoSSRC);
  13506. }
  13507. } else {
  13508. // Make sure we have any SSRC for recvonly video stream
  13509. var sdp = new SDP(localDescription.sdp);
  13510. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  13511. sdp.media[1].indexOf('a=recvonly') !== -1) {
  13512. if (!localRecvOnlySSRC) {
  13513. generateRecvonlySSRC();
  13514. }
  13515. console.info('No SSRC in video recvonly stream' +
  13516. ' - adding SSRC: ' + localRecvOnlySSRC);
  13517. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  13518. ' cname:' + localRecvOnlyCName + '\r\n';
  13519. localDescription.sdp = sdp.session + sdp.media.join('');
  13520. }
  13521. }
  13522. return localDescription;
  13523. },
  13524. /**
  13525. * Method must be called before 'source-add' notification is sent. In case
  13526. * we have local video SSRC advertised already it will be removed from the
  13527. * notification. If no other SSRCs are described by given IQ null will be
  13528. * returned which means that there is no point in sending the notification.
  13529. * @param sourceAdd 'source-add' Jingle IQ to be processed
  13530. * @returns modified 'source-add' IQ which can be sent to the focus or
  13531. * <tt>null</tt> if no notification shall be sent. It is no longer
  13532. * a Strophe IQ Builder instance, but DOM element tree.
  13533. */
  13534. processSourceAdd: function (sourceAdd) {
  13535. if (!isEnabled)
  13536. return sourceAdd;
  13537. if (!localVideoSSRC) {
  13538. // Store local SSRC if available
  13539. storeLocalVideoSSRC(sourceAdd);
  13540. return sourceAdd;
  13541. } else {
  13542. return filterOutSource(sourceAdd, 'source-add');
  13543. }
  13544. },
  13545. /**
  13546. * Method must be called before 'source-remove' notification is sent.
  13547. * Removes local video SSRC from the notification. If there are no other
  13548. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  13549. * means that there is no point in sending the notification.
  13550. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  13551. * @returns modified 'source-remove' IQ which can be sent to the focus or
  13552. * <tt>null</tt> if no notification shall be sent. It is no longer
  13553. * a Strophe IQ Builder instance, but DOM element tree.
  13554. */
  13555. processSourceRemove: function (sourceRemove) {
  13556. if (!isEnabled)
  13557. return sourceRemove;
  13558. return filterOutSource(sourceRemove, 'source-remove');
  13559. },
  13560. /**
  13561. * Turns the hack on or off
  13562. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  13563. * to disable it
  13564. */
  13565. setEnabled: function (enabled) {
  13566. isEnabled = enabled;
  13567. }
  13568. };
  13569. module.exports = LocalSSRCReplacement;
  13570. },{"../RTC/RTCBrowserType":10,"./SDP":58}],58:[function(require,module,exports){
  13571. /* jshint -W117 */
  13572. var SDPUtil = require("./SDPUtil");
  13573. // SDP STUFF
  13574. function SDP(sdp) {
  13575. this.media = sdp.split('\r\nm=');
  13576. for (var i = 1; i < this.media.length; i++) {
  13577. this.media[i] = 'm=' + this.media[i];
  13578. if (i != this.media.length - 1) {
  13579. this.media[i] += '\r\n';
  13580. }
  13581. }
  13582. this.session = this.media.shift() + '\r\n';
  13583. this.raw = this.session + this.media.join('');
  13584. }
  13585. /**
  13586. * Returns map of MediaChannel mapped per channel idx.
  13587. */
  13588. SDP.prototype.getMediaSsrcMap = function() {
  13589. var self = this;
  13590. var media_ssrcs = {};
  13591. var tmp;
  13592. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13593. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13594. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13595. var media = {
  13596. mediaindex: mediaindex,
  13597. mid: mid,
  13598. ssrcs: {},
  13599. ssrcGroups: []
  13600. };
  13601. media_ssrcs[mediaindex] = media;
  13602. tmp.forEach(function (line) {
  13603. var linessrc = line.substring(7).split(' ')[0];
  13604. // allocate new ChannelSsrc
  13605. if(!media.ssrcs[linessrc]) {
  13606. media.ssrcs[linessrc] = {
  13607. ssrc: linessrc,
  13608. lines: []
  13609. };
  13610. }
  13611. media.ssrcs[linessrc].lines.push(line);
  13612. });
  13613. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13614. tmp.forEach(function(line){
  13615. var semantics = line.substr(0, idx).substr(13);
  13616. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13617. if (ssrcs.length != 0) {
  13618. media.ssrcGroups.push({
  13619. semantics: semantics,
  13620. ssrcs: ssrcs
  13621. });
  13622. }
  13623. });
  13624. }
  13625. return media_ssrcs;
  13626. };
  13627. /**
  13628. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13629. * @param ssrc the ssrc to check.
  13630. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13631. */
  13632. SDP.prototype.containsSSRC = function(ssrc) {
  13633. var medias = this.getMediaSsrcMap();
  13634. var contains = false;
  13635. Object.keys(medias).forEach(function(mediaindex){
  13636. var media = medias[mediaindex];
  13637. //console.log("Check", channel, ssrc);
  13638. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13639. contains = true;
  13640. }
  13641. });
  13642. return contains;
  13643. };
  13644. // remove iSAC and CN from SDP
  13645. SDP.prototype.mangle = function () {
  13646. var i, j, mline, lines, rtpmap, newdesc;
  13647. for (i = 0; i < this.media.length; i++) {
  13648. lines = this.media[i].split('\r\n');
  13649. lines.pop(); // remove empty last element
  13650. mline = SDPUtil.parse_mline(lines.shift());
  13651. if (mline.media != 'audio')
  13652. continue;
  13653. newdesc = '';
  13654. mline.fmt.length = 0;
  13655. for (j = 0; j < lines.length; j++) {
  13656. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13657. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13658. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13659. continue;
  13660. mline.fmt.push(rtpmap.id);
  13661. newdesc += lines[j] + '\r\n';
  13662. } else {
  13663. newdesc += lines[j] + '\r\n';
  13664. }
  13665. }
  13666. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13667. this.media[i] += newdesc;
  13668. }
  13669. this.raw = this.session + this.media.join('');
  13670. };
  13671. // remove lines matching prefix from session section
  13672. SDP.prototype.removeSessionLines = function(prefix) {
  13673. var self = this;
  13674. var lines = SDPUtil.find_lines(this.session, prefix);
  13675. lines.forEach(function(line) {
  13676. self.session = self.session.replace(line + '\r\n', '');
  13677. });
  13678. this.raw = this.session + this.media.join('');
  13679. return lines;
  13680. }
  13681. // remove lines matching prefix from a media section specified by mediaindex
  13682. // TODO: non-numeric mediaindex could match mid
  13683. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13684. var self = this;
  13685. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13686. lines.forEach(function(line) {
  13687. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13688. });
  13689. this.raw = this.session + this.media.join('');
  13690. return lines;
  13691. }
  13692. // add content's to a jingle element
  13693. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13694. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13695. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13696. var self = this;
  13697. // new bundle plan
  13698. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13699. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13700. for (i = 0; i < lines.length; i++) {
  13701. tmp = lines[i].split(' ');
  13702. var semantics = tmp.shift().substr(8);
  13703. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13704. for (j = 0; j < tmp.length; j++) {
  13705. elem.c('content', {name: tmp[j]}).up();
  13706. }
  13707. elem.up();
  13708. }
  13709. }
  13710. for (i = 0; i < this.media.length; i++) {
  13711. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13712. if (!(mline.media === 'audio' ||
  13713. mline.media === 'video' ||
  13714. mline.media === 'application'))
  13715. {
  13716. continue;
  13717. }
  13718. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13719. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13720. } else {
  13721. if(ssrcs && ssrcs[mline.media])
  13722. {
  13723. ssrc = ssrcs[mline.media];
  13724. }
  13725. else
  13726. ssrc = false;
  13727. }
  13728. elem.c('content', {creator: thecreator, name: mline.media});
  13729. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13730. // prefer identifier from a=mid if present
  13731. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13732. elem.attrs({ name: mid });
  13733. }
  13734. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13735. {
  13736. elem.c('description',
  13737. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13738. media: mline.media });
  13739. if (ssrc) {
  13740. elem.attrs({ssrc: ssrc});
  13741. }
  13742. for (j = 0; j < mline.fmt.length; j++) {
  13743. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13744. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13745. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13746. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13747. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13748. for (k = 0; k < tmp.length; k++) {
  13749. elem.c('parameter', tmp[k]).up();
  13750. }
  13751. }
  13752. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13753. elem.up();
  13754. }
  13755. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13756. elem.c('encryption', {required: 1});
  13757. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13758. crypto.forEach(function(line) {
  13759. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13760. });
  13761. elem.up(); // end of encryption
  13762. }
  13763. if (ssrc) {
  13764. // new style mapping
  13765. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13766. // FIXME: group by ssrc and support multiple different ssrcs
  13767. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13768. if(ssrclines.length > 0) {
  13769. ssrclines.forEach(function (line) {
  13770. idx = line.indexOf(' ');
  13771. var linessrc = line.substr(0, idx).substr(7);
  13772. if (linessrc != ssrc) {
  13773. elem.up();
  13774. ssrc = linessrc;
  13775. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13776. }
  13777. var kv = line.substr(idx + 1);
  13778. elem.c('parameter');
  13779. if (kv.indexOf(':') == -1) {
  13780. elem.attrs({ name: kv });
  13781. } else {
  13782. var k = kv.split(':', 2)[0];
  13783. elem.attrs({ name: k });
  13784. var v = kv.split(':', 2)[1];
  13785. v = SDPUtil.filter_special_chars(v);
  13786. elem.attrs({ value: v });
  13787. }
  13788. elem.up();
  13789. });
  13790. }
  13791. else
  13792. {
  13793. elem.up();
  13794. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13795. elem.c('parameter');
  13796. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13797. elem.up();
  13798. var msid = null;
  13799. if(mline.media == "audio")
  13800. {
  13801. msid = APP.RTC.localAudio.getId();
  13802. }
  13803. else
  13804. {
  13805. msid = APP.RTC.localVideo.getId();
  13806. }
  13807. if(msid != null)
  13808. {
  13809. msid = SDPUtil.filter_special_chars(msid);
  13810. elem.c('parameter');
  13811. elem.attrs({name: "msid", value:msid});
  13812. elem.up();
  13813. elem.c('parameter');
  13814. elem.attrs({name: "mslabel", value:msid});
  13815. elem.up();
  13816. elem.c('parameter');
  13817. elem.attrs({name: "label", value:msid});
  13818. elem.up();
  13819. }
  13820. }
  13821. elem.up();
  13822. // XEP-0339 handle ssrc-group attributes
  13823. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13824. ssrc_group_lines.forEach(function(line) {
  13825. idx = line.indexOf(' ');
  13826. var semantics = line.substr(0, idx).substr(13);
  13827. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13828. if (ssrcs.length != 0) {
  13829. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13830. ssrcs.forEach(function(ssrc) {
  13831. elem.c('source', { ssrc: ssrc })
  13832. .up();
  13833. });
  13834. elem.up();
  13835. }
  13836. });
  13837. }
  13838. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13839. elem.c('rtcp-mux').up();
  13840. }
  13841. // XEP-0293 -- map a=rtcp-fb:*
  13842. this.RtcpFbToJingle(i, elem, '*');
  13843. // XEP-0294
  13844. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13845. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13846. for (j = 0; j < lines.length; j++) {
  13847. tmp = SDPUtil.parse_extmap(lines[j]);
  13848. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13849. uri: tmp.uri,
  13850. id: tmp.value });
  13851. if (tmp.hasOwnProperty('direction')) {
  13852. switch (tmp.direction) {
  13853. case 'sendonly':
  13854. elem.attrs({senders: 'responder'});
  13855. break;
  13856. case 'recvonly':
  13857. elem.attrs({senders: 'initiator'});
  13858. break;
  13859. case 'sendrecv':
  13860. elem.attrs({senders: 'both'});
  13861. break;
  13862. case 'inactive':
  13863. elem.attrs({senders: 'none'});
  13864. break;
  13865. }
  13866. }
  13867. // TODO: handle params
  13868. elem.up();
  13869. }
  13870. }
  13871. elem.up(); // end of description
  13872. }
  13873. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13874. this.TransportToJingle(i, elem);
  13875. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13876. elem.attrs({senders: 'both'});
  13877. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13878. elem.attrs({senders: 'initiator'});
  13879. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13880. elem.attrs({senders: 'responder'});
  13881. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13882. elem.attrs({senders: 'none'});
  13883. }
  13884. if (mline.port == '0') {
  13885. // estos hack to reject an m-line
  13886. elem.attrs({senders: 'rejected'});
  13887. }
  13888. elem.up(); // end of content
  13889. }
  13890. elem.up();
  13891. return elem;
  13892. };
  13893. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13894. var i = mediaindex;
  13895. var tmp;
  13896. var self = this;
  13897. elem.c('transport');
  13898. // XEP-0343 DTLS/SCTP
  13899. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13900. {
  13901. var sctpmap = SDPUtil.find_line(
  13902. this.media[i], 'a=sctpmap:', self.session);
  13903. if (sctpmap)
  13904. {
  13905. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13906. elem.c('sctpmap',
  13907. {
  13908. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13909. number: sctpAttrs[0], /* SCTP port */
  13910. protocol: sctpAttrs[1], /* protocol */
  13911. });
  13912. // Optional stream count attribute
  13913. if (sctpAttrs.length > 2)
  13914. elem.attrs({ streams: sctpAttrs[2]});
  13915. elem.up();
  13916. }
  13917. }
  13918. // XEP-0320
  13919. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13920. fingerprints.forEach(function(line) {
  13921. tmp = SDPUtil.parse_fingerprint(line);
  13922. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13923. elem.c('fingerprint').t(tmp.fingerprint);
  13924. delete tmp.fingerprint;
  13925. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13926. if (line) {
  13927. tmp.setup = line.substr(8);
  13928. }
  13929. elem.attrs(tmp);
  13930. elem.up(); // end of fingerprint
  13931. });
  13932. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13933. if (tmp) {
  13934. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13935. elem.attrs(tmp);
  13936. // XEP-0176
  13937. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13938. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13939. lines.forEach(function (line) {
  13940. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13941. });
  13942. }
  13943. }
  13944. elem.up(); // end of transport
  13945. }
  13946. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13947. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13948. lines.forEach(function (line) {
  13949. var tmp = SDPUtil.parse_rtcpfb(line);
  13950. if (tmp.type == 'trr-int') {
  13951. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13952. elem.up();
  13953. } else {
  13954. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13955. if (tmp.params.length > 0) {
  13956. elem.attrs({'subtype': tmp.params[0]});
  13957. }
  13958. elem.up();
  13959. }
  13960. });
  13961. };
  13962. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13963. var media = '';
  13964. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13965. if (tmp.length) {
  13966. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13967. if (tmp.attr('value')) {
  13968. media += tmp.attr('value');
  13969. } else {
  13970. media += '0';
  13971. }
  13972. media += '\r\n';
  13973. }
  13974. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13975. tmp.each(function () {
  13976. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13977. if ($(this).attr('subtype')) {
  13978. media += ' ' + $(this).attr('subtype');
  13979. }
  13980. media += '\r\n';
  13981. });
  13982. return media;
  13983. };
  13984. // construct an SDP from a jingle stanza
  13985. SDP.prototype.fromJingle = function (jingle) {
  13986. var self = this;
  13987. this.raw = 'v=0\r\n' +
  13988. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13989. 's=-\r\n' +
  13990. 't=0 0\r\n';
  13991. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13992. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13993. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13994. var contents = $(group).find('>content').map(function (idx, content) {
  13995. return content.getAttribute('name');
  13996. }).get();
  13997. if (contents.length > 0) {
  13998. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13999. }
  14000. });
  14001. }
  14002. this.session = this.raw;
  14003. jingle.find('>content').each(function () {
  14004. var m = self.jingle2media($(this));
  14005. self.media.push(m);
  14006. });
  14007. // reconstruct msid-semantic -- apparently not necessary
  14008. /*
  14009. var msid = SDPUtil.parse_ssrc(this.raw);
  14010. if (msid.hasOwnProperty('mslabel')) {
  14011. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  14012. }
  14013. */
  14014. this.raw = this.session + this.media.join('');
  14015. };
  14016. // translate a jingle content element into an an SDP media part
  14017. SDP.prototype.jingle2media = function (content) {
  14018. var media = '',
  14019. desc = content.find('description'),
  14020. ssrc = desc.attr('ssrc'),
  14021. self = this,
  14022. tmp;
  14023. var sctp = content.find(
  14024. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  14025. tmp = { media: desc.attr('media') };
  14026. tmp.port = '1';
  14027. if (content.attr('senders') == 'rejected') {
  14028. // estos hack to reject an m-line.
  14029. tmp.port = '0';
  14030. }
  14031. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  14032. if (sctp.length)
  14033. tmp.proto = 'DTLS/SCTP';
  14034. else
  14035. tmp.proto = 'RTP/SAVPF';
  14036. } else {
  14037. tmp.proto = 'RTP/AVPF';
  14038. }
  14039. if (!sctp.length)
  14040. {
  14041. tmp.fmt = desc.find('payload-type').map(
  14042. function () { return this.getAttribute('id'); }).get();
  14043. media += SDPUtil.build_mline(tmp) + '\r\n';
  14044. }
  14045. else
  14046. {
  14047. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  14048. media += 'a=sctpmap:' + sctp.attr('number') +
  14049. ' ' + sctp.attr('protocol');
  14050. var streamCount = sctp.attr('streams');
  14051. if (streamCount)
  14052. media += ' ' + streamCount + '\r\n';
  14053. else
  14054. media += '\r\n';
  14055. }
  14056. media += 'c=IN IP4 0.0.0.0\r\n';
  14057. if (!sctp.length)
  14058. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  14059. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  14060. if (tmp.length) {
  14061. if (tmp.attr('ufrag')) {
  14062. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  14063. }
  14064. if (tmp.attr('pwd')) {
  14065. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  14066. }
  14067. tmp.find('>fingerprint').each(function () {
  14068. // FIXME: check namespace at some point
  14069. media += 'a=fingerprint:' + this.getAttribute('hash');
  14070. media += ' ' + $(this).text();
  14071. media += '\r\n';
  14072. if (this.getAttribute('setup')) {
  14073. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  14074. }
  14075. });
  14076. }
  14077. switch (content.attr('senders')) {
  14078. case 'initiator':
  14079. media += 'a=sendonly\r\n';
  14080. break;
  14081. case 'responder':
  14082. media += 'a=recvonly\r\n';
  14083. break;
  14084. case 'none':
  14085. media += 'a=inactive\r\n';
  14086. break;
  14087. case 'both':
  14088. media += 'a=sendrecv\r\n';
  14089. break;
  14090. }
  14091. media += 'a=mid:' + content.attr('name') + '\r\n';
  14092. // <description><rtcp-mux/></description>
  14093. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  14094. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  14095. if (desc.find('rtcp-mux').length) {
  14096. media += 'a=rtcp-mux\r\n';
  14097. }
  14098. if (desc.find('encryption').length) {
  14099. desc.find('encryption>crypto').each(function () {
  14100. media += 'a=crypto:' + this.getAttribute('tag');
  14101. media += ' ' + this.getAttribute('crypto-suite');
  14102. media += ' ' + this.getAttribute('key-params');
  14103. if (this.getAttribute('session-params')) {
  14104. media += ' ' + this.getAttribute('session-params');
  14105. }
  14106. media += '\r\n';
  14107. });
  14108. }
  14109. desc.find('payload-type').each(function () {
  14110. media += SDPUtil.build_rtpmap(this) + '\r\n';
  14111. if ($(this).find('>parameter').length) {
  14112. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  14113. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  14114. media += '\r\n';
  14115. }
  14116. // xep-0293
  14117. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  14118. });
  14119. // xep-0293
  14120. media += self.RtcpFbFromJingle(desc, '*');
  14121. // xep-0294
  14122. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  14123. tmp.each(function () {
  14124. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  14125. });
  14126. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  14127. media += SDPUtil.candidateFromJingle(this);
  14128. });
  14129. // XEP-0339 handle ssrc-group attributes
  14130. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  14131. var semantics = this.getAttribute('semantics');
  14132. var ssrcs = $(this).find('>source').map(function() {
  14133. return this.getAttribute('ssrc');
  14134. }).get();
  14135. if (ssrcs.length != 0) {
  14136. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  14137. }
  14138. });
  14139. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  14140. tmp.each(function () {
  14141. var ssrc = this.getAttribute('ssrc');
  14142. $(this).find('>parameter').each(function () {
  14143. var name = this.getAttribute('name');
  14144. var value = this.getAttribute('value');
  14145. value = SDPUtil.filter_special_chars(value);
  14146. media += 'a=ssrc:' + ssrc + ' ' + name;
  14147. if (value && value.length)
  14148. media += ':' + value;
  14149. media += '\r\n';
  14150. });
  14151. });
  14152. return media;
  14153. };
  14154. module.exports = SDP;
  14155. },{"./SDPUtil":60}],59:[function(require,module,exports){
  14156. var SDPUtil = require("./SDPUtil");
  14157. function SDPDiffer(mySDP, otherSDP) {
  14158. this.mySDP = mySDP;
  14159. this.otherSDP = otherSDP;
  14160. }
  14161. /**
  14162. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  14163. * @param otherSdp the other SDP to check ssrc with.
  14164. */
  14165. SDPDiffer.prototype.getNewMedia = function() {
  14166. // this could be useful in Array.prototype.
  14167. function arrayEquals(array) {
  14168. // if the other array is a falsy value, return
  14169. if (!array)
  14170. return false;
  14171. // compare lengths - can save a lot of time
  14172. if (this.length != array.length)
  14173. return false;
  14174. for (var i = 0, l=this.length; i < l; i++) {
  14175. // Check if we have nested arrays
  14176. if (this[i] instanceof Array && array[i] instanceof Array) {
  14177. // recurse into the nested arrays
  14178. if (!this[i].equals(array[i]))
  14179. return false;
  14180. }
  14181. else if (this[i] != array[i]) {
  14182. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  14183. return false;
  14184. }
  14185. }
  14186. return true;
  14187. }
  14188. var myMedias = this.mySDP.getMediaSsrcMap();
  14189. var othersMedias = this.otherSDP.getMediaSsrcMap();
  14190. var newMedia = {};
  14191. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  14192. var myMedia = myMedias[othersMediaIdx];
  14193. var othersMedia = othersMedias[othersMediaIdx];
  14194. if(!myMedia && othersMedia) {
  14195. // Add whole channel
  14196. newMedia[othersMediaIdx] = othersMedia;
  14197. return;
  14198. }
  14199. // Look for new ssrcs accross the channel
  14200. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  14201. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  14202. // Allocate channel if we've found ssrc that doesn't exist in our channel
  14203. if(!newMedia[othersMediaIdx]){
  14204. newMedia[othersMediaIdx] = {
  14205. mediaindex: othersMedia.mediaindex,
  14206. mid: othersMedia.mid,
  14207. ssrcs: {},
  14208. ssrcGroups: []
  14209. };
  14210. }
  14211. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  14212. }
  14213. });
  14214. // Look for new ssrc groups across the channels
  14215. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  14216. // try to match the other ssrc-group with an ssrc-group of ours
  14217. var matched = false;
  14218. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  14219. var mySsrcGroup = myMedia.ssrcGroups[i];
  14220. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  14221. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  14222. matched = true;
  14223. break;
  14224. }
  14225. }
  14226. if (!matched) {
  14227. // Allocate channel if we've found an ssrc-group that doesn't
  14228. // exist in our channel
  14229. if(!newMedia[othersMediaIdx]){
  14230. newMedia[othersMediaIdx] = {
  14231. mediaindex: othersMedia.mediaindex,
  14232. mid: othersMedia.mid,
  14233. ssrcs: {},
  14234. ssrcGroups: []
  14235. };
  14236. }
  14237. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  14238. }
  14239. });
  14240. });
  14241. return newMedia;
  14242. };
  14243. /**
  14244. * Sends SSRC update IQ.
  14245. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  14246. * @param sid session identifier that will be put into the IQ.
  14247. * @param initiator initiator identifier.
  14248. * @param toJid destination Jid
  14249. * @param isAdd indicates if this is remove or add operation.
  14250. */
  14251. SDPDiffer.prototype.toJingle = function(modify) {
  14252. var sdpMediaSsrcs = this.getNewMedia();
  14253. var self = this;
  14254. // FIXME: only announce video ssrcs since we mix audio and dont need
  14255. // the audio ssrcs therefore
  14256. var modified = false;
  14257. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  14258. modified = true;
  14259. var media = sdpMediaSsrcs[mediaindex];
  14260. modify.c('content', {name: media.mid});
  14261. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  14262. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  14263. // generate sources from lines
  14264. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  14265. var mediaSsrc = media.ssrcs[ssrcNum];
  14266. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  14267. modify.attrs({ssrc: mediaSsrc.ssrc});
  14268. // iterate over ssrc lines
  14269. mediaSsrc.lines.forEach(function (line) {
  14270. var idx = line.indexOf(' ');
  14271. var kv = line.substr(idx + 1);
  14272. modify.c('parameter');
  14273. if (kv.indexOf(':') == -1) {
  14274. modify.attrs({ name: kv });
  14275. } else {
  14276. var nv = kv.split(':', 2);
  14277. var name = nv[0];
  14278. var value = SDPUtil.filter_special_chars(nv[1]);
  14279. modify.attrs({ name: name });
  14280. modify.attrs({ value: value });
  14281. }
  14282. modify.up(); // end of parameter
  14283. });
  14284. modify.up(); // end of source
  14285. });
  14286. // generate source groups from lines
  14287. media.ssrcGroups.forEach(function(ssrcGroup) {
  14288. if (ssrcGroup.ssrcs.length != 0) {
  14289. modify.c('ssrc-group', {
  14290. semantics: ssrcGroup.semantics,
  14291. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  14292. });
  14293. ssrcGroup.ssrcs.forEach(function (ssrc) {
  14294. modify.c('source', { ssrc: ssrc })
  14295. .up(); // end of source
  14296. });
  14297. modify.up(); // end of ssrc-group
  14298. }
  14299. });
  14300. modify.up(); // end of description
  14301. modify.up(); // end of content
  14302. });
  14303. return modified;
  14304. };
  14305. module.exports = SDPDiffer;
  14306. },{"./SDPUtil":60}],60:[function(require,module,exports){
  14307. SDPUtil = {
  14308. filter_special_chars: function (text) {
  14309. return text.replace(/[\\\/\{,\}\+]/g, "");
  14310. },
  14311. iceparams: function (mediadesc, sessiondesc) {
  14312. var data = null;
  14313. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  14314. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  14315. data = {
  14316. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  14317. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  14318. };
  14319. }
  14320. return data;
  14321. },
  14322. parse_iceufrag: function (line) {
  14323. return line.substring(12);
  14324. },
  14325. build_iceufrag: function (frag) {
  14326. return 'a=ice-ufrag:' + frag;
  14327. },
  14328. parse_icepwd: function (line) {
  14329. return line.substring(10);
  14330. },
  14331. build_icepwd: function (pwd) {
  14332. return 'a=ice-pwd:' + pwd;
  14333. },
  14334. parse_mid: function (line) {
  14335. return line.substring(6);
  14336. },
  14337. parse_mline: function (line) {
  14338. var parts = line.substring(2).split(' '),
  14339. data = {};
  14340. data.media = parts.shift();
  14341. data.port = parts.shift();
  14342. data.proto = parts.shift();
  14343. if (parts[parts.length - 1] === '') { // trailing whitespace
  14344. parts.pop();
  14345. }
  14346. data.fmt = parts;
  14347. return data;
  14348. },
  14349. build_mline: function (mline) {
  14350. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  14351. },
  14352. parse_rtpmap: function (line) {
  14353. var parts = line.substring(9).split(' '),
  14354. data = {};
  14355. data.id = parts.shift();
  14356. parts = parts[0].split('/');
  14357. data.name = parts.shift();
  14358. data.clockrate = parts.shift();
  14359. data.channels = parts.length ? parts.shift() : '1';
  14360. return data;
  14361. },
  14362. /**
  14363. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  14364. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  14365. * @returns [SCTP port number, protocol, streams]
  14366. */
  14367. parse_sctpmap: function (line)
  14368. {
  14369. var parts = line.substring(10).split(' ');
  14370. var sctpPort = parts[0];
  14371. var protocol = parts[1];
  14372. // Stream count is optional
  14373. var streamCount = parts.length > 2 ? parts[2] : null;
  14374. return [sctpPort, protocol, streamCount];// SCTP port
  14375. },
  14376. build_rtpmap: function (el) {
  14377. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  14378. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  14379. line += '/' + el.getAttribute('channels');
  14380. }
  14381. return line;
  14382. },
  14383. parse_crypto: function (line) {
  14384. var parts = line.substring(9).split(' '),
  14385. data = {};
  14386. data.tag = parts.shift();
  14387. data['crypto-suite'] = parts.shift();
  14388. data['key-params'] = parts.shift();
  14389. if (parts.length) {
  14390. data['session-params'] = parts.join(' ');
  14391. }
  14392. return data;
  14393. },
  14394. parse_fingerprint: function (line) { // RFC 4572
  14395. var parts = line.substring(14).split(' '),
  14396. data = {};
  14397. data.hash = parts.shift();
  14398. data.fingerprint = parts.shift();
  14399. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  14400. return data;
  14401. },
  14402. parse_fmtp: function (line) {
  14403. var parts = line.split(' '),
  14404. i, key, value,
  14405. data = [];
  14406. parts.shift();
  14407. parts = parts.join(' ').split(';');
  14408. for (i = 0; i < parts.length; i++) {
  14409. key = parts[i].split('=')[0];
  14410. while (key.length && key[0] == ' ') {
  14411. key = key.substring(1);
  14412. }
  14413. value = parts[i].split('=')[1];
  14414. if (key && value) {
  14415. data.push({name: key, value: value});
  14416. } else if (key) {
  14417. // rfc 4733 (DTMF) style stuff
  14418. data.push({name: '', value: key});
  14419. }
  14420. }
  14421. return data;
  14422. },
  14423. parse_icecandidate: function (line) {
  14424. var candidate = {},
  14425. elems = line.split(' ');
  14426. candidate.foundation = elems[0].substring(12);
  14427. candidate.component = elems[1];
  14428. candidate.protocol = elems[2].toLowerCase();
  14429. candidate.priority = elems[3];
  14430. candidate.ip = elems[4];
  14431. candidate.port = elems[5];
  14432. // elems[6] => "typ"
  14433. candidate.type = elems[7];
  14434. candidate.generation = 0; // default value, may be overwritten below
  14435. for (var i = 8; i < elems.length; i += 2) {
  14436. switch (elems[i]) {
  14437. case 'raddr':
  14438. candidate['rel-addr'] = elems[i + 1];
  14439. break;
  14440. case 'rport':
  14441. candidate['rel-port'] = elems[i + 1];
  14442. break;
  14443. case 'generation':
  14444. candidate.generation = elems[i + 1];
  14445. break;
  14446. case 'tcptype':
  14447. candidate.tcptype = elems[i + 1];
  14448. break;
  14449. default: // TODO
  14450. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14451. }
  14452. }
  14453. candidate.network = '1';
  14454. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14455. return candidate;
  14456. },
  14457. build_icecandidate: function (cand) {
  14458. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  14459. line += ' ';
  14460. switch (cand.type) {
  14461. case 'srflx':
  14462. case 'prflx':
  14463. case 'relay':
  14464. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  14465. line += 'raddr';
  14466. line += ' ';
  14467. line += cand['rel-addr'];
  14468. line += ' ';
  14469. line += 'rport';
  14470. line += ' ';
  14471. line += cand['rel-port'];
  14472. line += ' ';
  14473. }
  14474. break;
  14475. }
  14476. if (cand.hasOwnAttribute('tcptype')) {
  14477. line += 'tcptype';
  14478. line += ' ';
  14479. line += cand.tcptype;
  14480. line += ' ';
  14481. }
  14482. line += 'generation';
  14483. line += ' ';
  14484. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  14485. return line;
  14486. },
  14487. parse_ssrc: function (desc) {
  14488. // proprietary mapping of a=ssrc lines
  14489. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  14490. // and parse according to that
  14491. var lines = desc.split('\r\n'),
  14492. data = {};
  14493. for (var i = 0; i < lines.length; i++) {
  14494. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  14495. var idx = lines[i].indexOf(' ');
  14496. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  14497. }
  14498. }
  14499. return data;
  14500. },
  14501. parse_rtcpfb: function (line) {
  14502. var parts = line.substr(10).split(' ');
  14503. var data = {};
  14504. data.pt = parts.shift();
  14505. data.type = parts.shift();
  14506. data.params = parts;
  14507. return data;
  14508. },
  14509. parse_extmap: function (line) {
  14510. var parts = line.substr(9).split(' ');
  14511. var data = {};
  14512. data.value = parts.shift();
  14513. if (data.value.indexOf('/') != -1) {
  14514. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  14515. data.value = data.value.substr(0, data.value.indexOf('/'));
  14516. } else {
  14517. data.direction = 'both';
  14518. }
  14519. data.uri = parts.shift();
  14520. data.params = parts;
  14521. return data;
  14522. },
  14523. find_line: function (haystack, needle, sessionpart) {
  14524. var lines = haystack.split('\r\n');
  14525. for (var i = 0; i < lines.length; i++) {
  14526. if (lines[i].substring(0, needle.length) == needle) {
  14527. return lines[i];
  14528. }
  14529. }
  14530. if (!sessionpart) {
  14531. return false;
  14532. }
  14533. // search session part
  14534. lines = sessionpart.split('\r\n');
  14535. for (var j = 0; j < lines.length; j++) {
  14536. if (lines[j].substring(0, needle.length) == needle) {
  14537. return lines[j];
  14538. }
  14539. }
  14540. return false;
  14541. },
  14542. find_lines: function (haystack, needle, sessionpart) {
  14543. var lines = haystack.split('\r\n'),
  14544. needles = [];
  14545. for (var i = 0; i < lines.length; i++) {
  14546. if (lines[i].substring(0, needle.length) == needle)
  14547. needles.push(lines[i]);
  14548. }
  14549. if (needles.length || !sessionpart) {
  14550. return needles;
  14551. }
  14552. // search session part
  14553. lines = sessionpart.split('\r\n');
  14554. for (var j = 0; j < lines.length; j++) {
  14555. if (lines[j].substring(0, needle.length) == needle) {
  14556. needles.push(lines[j]);
  14557. }
  14558. }
  14559. return needles;
  14560. },
  14561. candidateToJingle: function (line) {
  14562. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14563. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14564. if (line.indexOf('candidate:') === 0) {
  14565. line = 'a=' + line;
  14566. } else if (line.substring(0, 12) != 'a=candidate:') {
  14567. console.log('parseCandidate called with a line that is not a candidate line');
  14568. console.log(line);
  14569. return null;
  14570. }
  14571. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14572. line = line.substring(0, line.length - 2);
  14573. var candidate = {},
  14574. elems = line.split(' '),
  14575. i;
  14576. if (elems[6] != 'typ') {
  14577. console.log('did not find typ in the right place');
  14578. console.log(line);
  14579. return null;
  14580. }
  14581. candidate.foundation = elems[0].substring(12);
  14582. candidate.component = elems[1];
  14583. candidate.protocol = elems[2].toLowerCase();
  14584. candidate.priority = elems[3];
  14585. candidate.ip = elems[4];
  14586. candidate.port = elems[5];
  14587. // elems[6] => "typ"
  14588. candidate.type = elems[7];
  14589. candidate.generation = '0'; // default, may be overwritten below
  14590. for (i = 8; i < elems.length; i += 2) {
  14591. switch (elems[i]) {
  14592. case 'raddr':
  14593. candidate['rel-addr'] = elems[i + 1];
  14594. break;
  14595. case 'rport':
  14596. candidate['rel-port'] = elems[i + 1];
  14597. break;
  14598. case 'generation':
  14599. candidate.generation = elems[i + 1];
  14600. break;
  14601. case 'tcptype':
  14602. candidate.tcptype = elems[i + 1];
  14603. break;
  14604. default: // TODO
  14605. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14606. }
  14607. }
  14608. candidate.network = '1';
  14609. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14610. return candidate;
  14611. },
  14612. candidateFromJingle: function (cand) {
  14613. var line = 'a=candidate:';
  14614. line += cand.getAttribute('foundation');
  14615. line += ' ';
  14616. line += cand.getAttribute('component');
  14617. line += ' ';
  14618. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14619. line += ' ';
  14620. line += cand.getAttribute('priority');
  14621. line += ' ';
  14622. line += cand.getAttribute('ip');
  14623. line += ' ';
  14624. line += cand.getAttribute('port');
  14625. line += ' ';
  14626. line += 'typ';
  14627. line += ' ' + cand.getAttribute('type');
  14628. line += ' ';
  14629. switch (cand.getAttribute('type')) {
  14630. case 'srflx':
  14631. case 'prflx':
  14632. case 'relay':
  14633. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14634. line += 'raddr';
  14635. line += ' ';
  14636. line += cand.getAttribute('rel-addr');
  14637. line += ' ';
  14638. line += 'rport';
  14639. line += ' ';
  14640. line += cand.getAttribute('rel-port');
  14641. line += ' ';
  14642. }
  14643. break;
  14644. }
  14645. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14646. line += 'tcptype';
  14647. line += ' ';
  14648. line += cand.getAttribute('tcptype');
  14649. line += ' ';
  14650. }
  14651. line += 'generation';
  14652. line += ' ';
  14653. line += cand.getAttribute('generation') || '0';
  14654. return line + '\r\n';
  14655. }
  14656. };
  14657. module.exports = SDPUtil;
  14658. },{}],61:[function(require,module,exports){
  14659. var RTC = require('../RTC/RTC');
  14660. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14661. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14662. var SSRCReplacement = require("./LocalSSRCReplacement");
  14663. function TraceablePeerConnection(ice_config, constraints, session) {
  14664. var self = this;
  14665. var RTCPeerConnectionType = null;
  14666. if (RTCBrowserType.isFirefox()) {
  14667. RTCPeerConnectionType = mozRTCPeerConnection;
  14668. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14669. RTCPeerConnectionType = RTCPeerConnection;
  14670. } else {
  14671. RTCPeerConnectionType = webkitRTCPeerConnection;
  14672. }
  14673. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  14674. this.updateLog = [];
  14675. this.stats = {};
  14676. this.statsinterval = null;
  14677. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14678. var Interop = require('sdp-interop').Interop;
  14679. this.interop = new Interop();
  14680. var Simulcast = require('sdp-simulcast');
  14681. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14682. // override as desired
  14683. this.trace = function (what, info) {
  14684. /*console.warn('WTRACE', what, info);
  14685. if (info && RTCBrowserType.isIExplorer()) {
  14686. if (info.length > 1024) {
  14687. console.warn('WTRACE', what, info.substr(1024));
  14688. }
  14689. if (info.length > 2048) {
  14690. console.warn('WTRACE', what, info.substr(2048));
  14691. }
  14692. }*/
  14693. self.updateLog.push({
  14694. time: new Date(),
  14695. type: what,
  14696. value: info || ""
  14697. });
  14698. };
  14699. this.onicecandidate = null;
  14700. this.peerconnection.onicecandidate = function (event) {
  14701. // FIXME: this causes stack overflow with Temasys Plugin
  14702. if (!RTCBrowserType.isTemasysPluginUsed())
  14703. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14704. if (self.onicecandidate !== null) {
  14705. self.onicecandidate(event);
  14706. }
  14707. };
  14708. this.onaddstream = null;
  14709. this.peerconnection.onaddstream = function (event) {
  14710. self.trace('onaddstream', event.stream.id);
  14711. if (self.onaddstream !== null) {
  14712. self.onaddstream(event);
  14713. }
  14714. };
  14715. this.onremovestream = null;
  14716. this.peerconnection.onremovestream = function (event) {
  14717. self.trace('onremovestream', event.stream.id);
  14718. if (self.onremovestream !== null) {
  14719. self.onremovestream(event);
  14720. }
  14721. };
  14722. this.onsignalingstatechange = null;
  14723. this.peerconnection.onsignalingstatechange = function (event) {
  14724. self.trace('onsignalingstatechange', self.signalingState);
  14725. if (self.onsignalingstatechange !== null) {
  14726. self.onsignalingstatechange(event);
  14727. }
  14728. };
  14729. this.oniceconnectionstatechange = null;
  14730. this.peerconnection.oniceconnectionstatechange = function (event) {
  14731. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14732. if (self.oniceconnectionstatechange !== null) {
  14733. self.oniceconnectionstatechange(event);
  14734. }
  14735. };
  14736. this.onnegotiationneeded = null;
  14737. this.peerconnection.onnegotiationneeded = function (event) {
  14738. self.trace('onnegotiationneeded');
  14739. if (self.onnegotiationneeded !== null) {
  14740. self.onnegotiationneeded(event);
  14741. }
  14742. };
  14743. self.ondatachannel = null;
  14744. this.peerconnection.ondatachannel = function (event) {
  14745. self.trace('ondatachannel', event);
  14746. if (self.ondatachannel !== null) {
  14747. self.ondatachannel(event);
  14748. }
  14749. };
  14750. // XXX: do all non-firefox browsers which we support also support this?
  14751. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14752. this.statsinterval = window.setInterval(function() {
  14753. self.peerconnection.getStats(function(stats) {
  14754. var results = stats.result();
  14755. var now = new Date();
  14756. for (var i = 0; i < results.length; ++i) {
  14757. results[i].names().forEach(function (name) {
  14758. var id = results[i].id + '-' + name;
  14759. if (!self.stats[id]) {
  14760. self.stats[id] = {
  14761. startTime: now,
  14762. endTime: now,
  14763. values: [],
  14764. times: []
  14765. };
  14766. }
  14767. self.stats[id].values.push(results[i].stat(name));
  14768. self.stats[id].times.push(now.getTime());
  14769. if (self.stats[id].values.length > self.maxstats) {
  14770. self.stats[id].values.shift();
  14771. self.stats[id].times.shift();
  14772. }
  14773. self.stats[id].endTime = now;
  14774. });
  14775. }
  14776. });
  14777. }, 1000);
  14778. }
  14779. }
  14780. /**
  14781. * Returns a string representation of a SessionDescription object.
  14782. */
  14783. var dumpSDP = function(description) {
  14784. if (typeof description === 'undefined' || description == null) {
  14785. return '';
  14786. }
  14787. return 'type: ' + description.type + '\r\n' + description.sdp;
  14788. };
  14789. /**
  14790. * Takes a SessionDescription object and returns a "normalized" version.
  14791. * Currently it only takes care of ordering the a=ssrc lines.
  14792. */
  14793. var normalizePlanB = function(desc) {
  14794. if (typeof desc !== 'object' || desc === null ||
  14795. typeof desc.sdp !== 'string') {
  14796. console.warn('An empty description was passed as an argument.');
  14797. return desc;
  14798. }
  14799. var transform = require('sdp-transform');
  14800. var session = transform.parse(desc.sdp);
  14801. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14802. Array.isArray(session.media)) {
  14803. session.media.forEach(function (mLine) {
  14804. // Chrome appears to be picky about the order in which a=ssrc lines
  14805. // are listed in an m-line when rtx is enabled (and thus there are
  14806. // a=ssrc-group lines with FID semantics). Specifically if we have
  14807. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14808. // the "a=ssrc:S1" lines, SRD fails.
  14809. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14810. // first.
  14811. var firstSsrcs = [];
  14812. var newSsrcLines = [];
  14813. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14814. mLine.ssrcGroups.forEach(function (group) {
  14815. if (typeof group.semantics !== 'undefined' &&
  14816. group.semantics === 'FID') {
  14817. if (typeof group.ssrcs !== 'undefined') {
  14818. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14819. }
  14820. }
  14821. });
  14822. }
  14823. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14824. for (var i = 0; i<mLine.ssrcs.length; i++){
  14825. if (typeof mLine.ssrcs[i] === 'object'
  14826. && typeof mLine.ssrcs[i].id !== 'undefined'
  14827. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14828. newSsrcLines.push(mLine.ssrcs[i]);
  14829. delete mLine.ssrcs[i];
  14830. }
  14831. }
  14832. for (var i = 0; i<mLine.ssrcs.length; i++){
  14833. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14834. newSsrcLines.push(mLine.ssrcs[i]);
  14835. }
  14836. }
  14837. mLine.ssrcs = newSsrcLines;
  14838. }
  14839. });
  14840. }
  14841. var resStr = transform.write(session);
  14842. return new RTCSessionDescription({
  14843. type: desc.type,
  14844. sdp: resStr
  14845. });
  14846. };
  14847. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14848. TraceablePeerConnection.prototype.__defineGetter__(
  14849. 'signalingState',
  14850. function() { return this.peerconnection.signalingState; });
  14851. TraceablePeerConnection.prototype.__defineGetter__(
  14852. 'iceConnectionState',
  14853. function() { return this.peerconnection.iceConnectionState; });
  14854. TraceablePeerConnection.prototype.__defineGetter__(
  14855. 'localDescription',
  14856. function() {
  14857. var desc = this.peerconnection.localDescription;
  14858. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  14859. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14860. // if we're running on FF, transform to Plan B first.
  14861. if (RTCBrowserType.usesUnifiedPlan()) {
  14862. desc = this.interop.toPlanB(desc);
  14863. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14864. }
  14865. return desc;
  14866. });
  14867. TraceablePeerConnection.prototype.__defineGetter__(
  14868. 'remoteDescription',
  14869. function() {
  14870. var desc = this.peerconnection.remoteDescription;
  14871. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14872. // if we're running on FF, transform to Plan B first.
  14873. if (RTCBrowserType.usesUnifiedPlan()) {
  14874. desc = this.interop.toPlanB(desc);
  14875. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14876. }
  14877. return desc;
  14878. });
  14879. }
  14880. TraceablePeerConnection.prototype.addStream = function (stream) {
  14881. this.trace('addStream', stream.id);
  14882. try
  14883. {
  14884. this.peerconnection.addStream(stream);
  14885. }
  14886. catch (e)
  14887. {
  14888. console.error(e);
  14889. }
  14890. };
  14891. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14892. this.trace('removeStream', stream.id);
  14893. if(stopStreams) {
  14894. stream.getAudioTracks().forEach(function (track) {
  14895. // stop() not supported with IE
  14896. if (track.stop) {
  14897. track.stop();
  14898. }
  14899. });
  14900. stream.getVideoTracks().forEach(function (track) {
  14901. // stop() not supported with IE
  14902. if (track.stop) {
  14903. track.stop();
  14904. }
  14905. });
  14906. if (stream.stop) {
  14907. stream.stop();
  14908. }
  14909. }
  14910. try {
  14911. // FF doesn't support this yet.
  14912. if (this.peerconnection.removeStream)
  14913. this.peerconnection.removeStream(stream);
  14914. } catch (e) {
  14915. console.error(e);
  14916. }
  14917. };
  14918. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14919. this.trace('createDataChannel', label, opts);
  14920. return this.peerconnection.createDataChannel(label, opts);
  14921. };
  14922. TraceablePeerConnection.prototype.setLocalDescription
  14923. = function (description, successCallback, failureCallback) {
  14924. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14925. // if we're running on FF, transform to Plan A first.
  14926. if (RTCBrowserType.usesUnifiedPlan()) {
  14927. description = this.interop.toUnifiedPlan(description);
  14928. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14929. }
  14930. var self = this;
  14931. this.peerconnection.setLocalDescription(description,
  14932. function () {
  14933. self.trace('setLocalDescriptionOnSuccess');
  14934. successCallback();
  14935. },
  14936. function (err) {
  14937. self.trace('setLocalDescriptionOnFailure', err);
  14938. failureCallback(err);
  14939. }
  14940. );
  14941. /*
  14942. if (this.statsinterval === null && this.maxstats > 0) {
  14943. // start gathering stats
  14944. }
  14945. */
  14946. };
  14947. TraceablePeerConnection.prototype.setRemoteDescription
  14948. = function (description, successCallback, failureCallback) {
  14949. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14950. // TODO the focus should squeze or explode the remote simulcast
  14951. description = this.simulcast.mungeRemoteDescription(description);
  14952. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14953. // if we're running on FF, transform to Plan A first.
  14954. if (RTCBrowserType.usesUnifiedPlan()) {
  14955. description = this.interop.toUnifiedPlan(description);
  14956. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14957. }
  14958. if (RTCBrowserType.usesPlanB()) {
  14959. description = normalizePlanB(description);
  14960. }
  14961. var self = this;
  14962. this.peerconnection.setRemoteDescription(description,
  14963. function () {
  14964. self.trace('setRemoteDescriptionOnSuccess');
  14965. successCallback();
  14966. },
  14967. function (err) {
  14968. self.trace('setRemoteDescriptionOnFailure', err);
  14969. failureCallback(err);
  14970. }
  14971. );
  14972. /*
  14973. if (this.statsinterval === null && this.maxstats > 0) {
  14974. // start gathering stats
  14975. }
  14976. */
  14977. };
  14978. TraceablePeerConnection.prototype.close = function () {
  14979. this.trace('stop');
  14980. if (this.statsinterval !== null) {
  14981. window.clearInterval(this.statsinterval);
  14982. this.statsinterval = null;
  14983. }
  14984. this.peerconnection.close();
  14985. };
  14986. TraceablePeerConnection.prototype.createOffer
  14987. = function (successCallback, failureCallback, constraints) {
  14988. var self = this;
  14989. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14990. this.peerconnection.createOffer(
  14991. function (offer) {
  14992. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14993. // NOTE this is not tested because in meet the focus generates the
  14994. // offer.
  14995. // if we're running on FF, transform to Plan B first.
  14996. if (RTCBrowserType.usesUnifiedPlan()) {
  14997. offer = self.interop.toPlanB(offer);
  14998. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14999. }
  15000. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  15001. if (config.enableSimulcast && self.simulcast.isSupported()) {
  15002. offer = self.simulcast.mungeLocalDescription(offer);
  15003. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  15004. }
  15005. successCallback(offer);
  15006. },
  15007. function(err) {
  15008. self.trace('createOfferOnFailure', err);
  15009. failureCallback(err);
  15010. },
  15011. constraints
  15012. );
  15013. };
  15014. TraceablePeerConnection.prototype.createAnswer
  15015. = function (successCallback, failureCallback, constraints) {
  15016. var self = this;
  15017. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  15018. this.peerconnection.createAnswer(
  15019. function (answer) {
  15020. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  15021. // if we're running on FF, transform to Plan A first.
  15022. if (RTCBrowserType.usesUnifiedPlan()) {
  15023. answer = self.interop.toPlanB(answer);
  15024. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  15025. }
  15026. // munge local video SSRC
  15027. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  15028. if (config.enableSimulcast && self.simulcast.isSupported()) {
  15029. answer = self.simulcast.mungeLocalDescription(answer);
  15030. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  15031. }
  15032. successCallback(answer);
  15033. },
  15034. function(err) {
  15035. self.trace('createAnswerOnFailure', err);
  15036. failureCallback(err);
  15037. },
  15038. constraints
  15039. );
  15040. };
  15041. TraceablePeerConnection.prototype.addIceCandidate
  15042. = function (candidate, successCallback, failureCallback) {
  15043. //var self = this;
  15044. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  15045. this.peerconnection.addIceCandidate(candidate);
  15046. /* maybe later
  15047. this.peerconnection.addIceCandidate(candidate,
  15048. function () {
  15049. self.trace('addIceCandidateOnSuccess');
  15050. successCallback();
  15051. },
  15052. function (err) {
  15053. self.trace('addIceCandidateOnFailure', err);
  15054. failureCallback(err);
  15055. }
  15056. );
  15057. */
  15058. };
  15059. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  15060. // TODO: Is this the correct way to handle Opera, Temasys?
  15061. if (RTCBrowserType.isFirefox()) {
  15062. // ignore for now...
  15063. if(!errback)
  15064. errback = function () {};
  15065. this.peerconnection.getStats(null, callback, errback);
  15066. } else {
  15067. this.peerconnection.getStats(callback);
  15068. }
  15069. };
  15070. module.exports = TraceablePeerConnection;
  15071. },{"../../service/xmpp/XMPPEvents":120,"../RTC/RTC":9,"../RTC/RTCBrowserType.js":10,"./LocalSSRCReplacement":57,"sdp-interop":93,"sdp-simulcast":100,"sdp-transform":107}],62:[function(require,module,exports){
  15072. /* global $, $iq, APP, config, messageHandler,
  15073. roomName, sessionTerminated, Strophe, Util */
  15074. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15075. var Settings = require("../settings/Settings");
  15076. var AuthenticationEvents
  15077. = require("../../service/authentication/AuthenticationEvents");
  15078. /**
  15079. * Contains logic responsible for enabling/disabling functionality available
  15080. * only to moderator users.
  15081. */
  15082. var connection = null;
  15083. var focusUserJid;
  15084. function createExpBackoffTimer(step) {
  15085. var count = 1;
  15086. return function (reset) {
  15087. // Reset call
  15088. if (reset) {
  15089. count = 1;
  15090. return;
  15091. }
  15092. // Calculate next timeout
  15093. var timeout = Math.pow(2, count - 1);
  15094. count += 1;
  15095. return timeout * step;
  15096. };
  15097. }
  15098. var getNextTimeout = createExpBackoffTimer(1000);
  15099. var getNextErrorTimeout = createExpBackoffTimer(1000);
  15100. // External authentication stuff
  15101. var externalAuthEnabled = false;
  15102. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  15103. // it will be enabled automatically if focus detects the component through
  15104. // service discovery.
  15105. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  15106. var eventEmitter = null;
  15107. var Moderator = {
  15108. isModerator: function () {
  15109. return connection && connection.emuc.isModerator();
  15110. },
  15111. isPeerModerator: function (peerJid) {
  15112. return connection &&
  15113. connection.emuc.getMemberRole(peerJid) === 'moderator';
  15114. },
  15115. isExternalAuthEnabled: function () {
  15116. return externalAuthEnabled;
  15117. },
  15118. isSipGatewayEnabled: function () {
  15119. return sipGatewayEnabled;
  15120. },
  15121. setConnection: function (con) {
  15122. connection = con;
  15123. },
  15124. init: function (xmpp, emitter) {
  15125. this.xmppService = xmpp;
  15126. eventEmitter = emitter;
  15127. // Message listener that talks to POPUP window
  15128. function listener(event) {
  15129. if (event.data && event.data.sessionId) {
  15130. if (event.origin !== window.location.origin) {
  15131. console.warn("Ignoring sessionId from different origin: " +
  15132. event.origin);
  15133. return;
  15134. }
  15135. localStorage.setItem('sessionId', event.data.sessionId);
  15136. // After popup is closed we will authenticate
  15137. }
  15138. }
  15139. // Register
  15140. if (window.addEventListener) {
  15141. window.addEventListener("message", listener, false);
  15142. } else {
  15143. window.attachEvent("onmessage", listener);
  15144. }
  15145. },
  15146. onMucMemberLeft: function (jid) {
  15147. console.info("Someone left is it focus ? " + jid);
  15148. var resource = Strophe.getResourceFromJid(jid);
  15149. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  15150. console.info(
  15151. "Focus has left the room - leaving conference");
  15152. //hangUp();
  15153. // We'd rather reload to have everything re-initialized
  15154. // FIXME: show some message before reload
  15155. location.reload();
  15156. }
  15157. },
  15158. setFocusUserJid: function (focusJid) {
  15159. if (!focusUserJid) {
  15160. focusUserJid = focusJid;
  15161. console.info("Focus jid set to: " + focusUserJid);
  15162. }
  15163. },
  15164. getFocusUserJid: function () {
  15165. return focusUserJid;
  15166. },
  15167. getFocusComponent: function () {
  15168. // Get focus component address
  15169. var focusComponent = config.hosts.focus;
  15170. // If not specified use default: 'focus.domain'
  15171. if (!focusComponent) {
  15172. focusComponent = 'focus.' + config.hosts.domain;
  15173. }
  15174. return focusComponent;
  15175. },
  15176. createConferenceIq: function (roomName) {
  15177. // Generate create conference IQ
  15178. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15179. // Session Id used for authentication
  15180. var sessionId = localStorage.getItem('sessionId');
  15181. var machineUID = Settings.getSettings().uid;
  15182. console.info(
  15183. "Session ID: " + sessionId + " machine UID: " + machineUID);
  15184. elem.c('conference', {
  15185. xmlns: 'http://jitsi.org/protocol/focus',
  15186. room: roomName,
  15187. 'machine-uid': machineUID
  15188. });
  15189. if (sessionId) {
  15190. elem.attrs({ 'session-id': sessionId});
  15191. }
  15192. if (config.hosts.bridge !== undefined) {
  15193. elem.c(
  15194. 'property',
  15195. { name: 'bridge', value: config.hosts.bridge})
  15196. .up();
  15197. }
  15198. // Tell the focus we have Jigasi configured
  15199. if (config.hosts.call_control !== undefined) {
  15200. elem.c(
  15201. 'property',
  15202. { name: 'call_control', value: config.hosts.call_control})
  15203. .up();
  15204. }
  15205. if (config.channelLastN !== undefined) {
  15206. elem.c(
  15207. 'property',
  15208. { name: 'channelLastN', value: config.channelLastN})
  15209. .up();
  15210. }
  15211. if (config.adaptiveLastN !== undefined) {
  15212. elem.c(
  15213. 'property',
  15214. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  15215. .up();
  15216. }
  15217. if (config.adaptiveSimulcast !== undefined) {
  15218. elem.c(
  15219. 'property',
  15220. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  15221. .up();
  15222. }
  15223. if (config.openSctp !== undefined) {
  15224. elem.c(
  15225. 'property',
  15226. { name: 'openSctp', value: config.openSctp})
  15227. .up();
  15228. }
  15229. if(config.startAudioMuted !== undefined)
  15230. {
  15231. elem.c(
  15232. 'property',
  15233. { name: 'startAudioMuted', value: config.startAudioMuted})
  15234. .up();
  15235. }
  15236. if(config.startVideoMuted !== undefined)
  15237. {
  15238. elem.c(
  15239. 'property',
  15240. { name: 'startVideoMuted', value: config.startVideoMuted})
  15241. .up();
  15242. }
  15243. elem.c(
  15244. 'property',
  15245. { name: 'simulcastMode', value: 'rewriting'})
  15246. .up();
  15247. elem.up();
  15248. return elem;
  15249. },
  15250. parseSessionId: function (resultIq) {
  15251. var sessionId = $(resultIq).find('conference').attr('session-id');
  15252. if (sessionId) {
  15253. console.info('Received sessionId: ' + sessionId);
  15254. localStorage.setItem('sessionId', sessionId);
  15255. }
  15256. },
  15257. parseConfigOptions: function (resultIq) {
  15258. Moderator.setFocusUserJid(
  15259. $(resultIq).find('conference').attr('focusjid'));
  15260. var authenticationEnabled
  15261. = $(resultIq).find(
  15262. '>conference>property' +
  15263. '[name=\'authentication\'][value=\'true\']').length > 0;
  15264. console.info("Authentication enabled: " + authenticationEnabled);
  15265. externalAuthEnabled = $(resultIq).find(
  15266. '>conference>property' +
  15267. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  15268. console.info('External authentication enabled: ' + externalAuthEnabled);
  15269. if (!externalAuthEnabled) {
  15270. // We expect to receive sessionId in 'internal' authentication mode
  15271. Moderator.parseSessionId(resultIq);
  15272. }
  15273. var authIdentity = $(resultIq).find('>conference').attr('identity');
  15274. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  15275. authenticationEnabled, authIdentity);
  15276. // Check if focus has auto-detected Jigasi component(this will be also
  15277. // included if we have passed our host from the config)
  15278. if ($(resultIq).find(
  15279. '>conference>property' +
  15280. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  15281. sipGatewayEnabled = true;
  15282. }
  15283. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  15284. },
  15285. // FIXME: we need to show the fact that we're waiting for the focus
  15286. // to the user(or that focus is not available)
  15287. allocateConferenceFocus: function (roomName, callback) {
  15288. // Try to use focus user JID from the config
  15289. Moderator.setFocusUserJid(config.focusUserJid);
  15290. // Send create conference IQ
  15291. var iq = Moderator.createConferenceIq(roomName);
  15292. var self = this;
  15293. connection.sendIQ(
  15294. iq,
  15295. function (result) {
  15296. // Setup config options
  15297. Moderator.parseConfigOptions(result);
  15298. if ('true' === $(result).find('conference').attr('ready')) {
  15299. // Reset both timers
  15300. getNextTimeout(true);
  15301. getNextErrorTimeout(true);
  15302. // Exec callback
  15303. callback();
  15304. } else {
  15305. var waitMs = getNextTimeout();
  15306. console.info("Waiting for the focus... " + waitMs);
  15307. // Reset error timeout
  15308. getNextErrorTimeout(true);
  15309. window.setTimeout(
  15310. function () {
  15311. Moderator.allocateConferenceFocus(
  15312. roomName, callback);
  15313. }, waitMs);
  15314. }
  15315. },
  15316. function (error) {
  15317. // Invalid session ? remove and try again
  15318. // without session ID to get a new one
  15319. var invalidSession
  15320. = $(error).find('>error>session-invalid').length;
  15321. if (invalidSession) {
  15322. console.info("Session expired! - removing");
  15323. localStorage.removeItem("sessionId");
  15324. }
  15325. if ($(error).find('>error>graceful-shutdown').length) {
  15326. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  15327. return;
  15328. }
  15329. // Check for error returned by the reservation system
  15330. var reservationErr = $(error).find('>error>reservation-error');
  15331. if (reservationErr.length) {
  15332. // Trigger error event
  15333. var errorCode = reservationErr.attr('error-code');
  15334. var errorMsg;
  15335. if ($(error).find('>error>text')) {
  15336. errorMsg = $(error).find('>error>text').text();
  15337. }
  15338. eventEmitter.emit(
  15339. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  15340. return;
  15341. }
  15342. // Not authorized to create new room
  15343. if ($(error).find('>error>not-authorized').length) {
  15344. console.warn("Unauthorized to start the conference", error);
  15345. var toDomain
  15346. = Strophe.getDomainFromJid(error.getAttribute('to'));
  15347. if (toDomain !== config.hosts.anonymousdomain) {
  15348. // FIXME: "is external" should come either from
  15349. // the focus or config.js
  15350. externalAuthEnabled = true;
  15351. }
  15352. eventEmitter.emit(
  15353. XMPPEvents.AUTHENTICATION_REQUIRED,
  15354. function () {
  15355. Moderator.allocateConferenceFocus(
  15356. roomName, callback);
  15357. });
  15358. return;
  15359. }
  15360. var waitMs = getNextErrorTimeout();
  15361. console.error("Focus error, retry after " + waitMs, error);
  15362. // Show message
  15363. var focusComponent = Moderator.getFocusComponent();
  15364. var retrySec = waitMs / 1000;
  15365. // FIXME: message is duplicated ?
  15366. // Do not show in case of session invalid
  15367. // which means just a retry
  15368. if (!invalidSession) {
  15369. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  15370. focusComponent, retrySec);
  15371. }
  15372. // Reset response timeout
  15373. getNextTimeout(true);
  15374. window.setTimeout(
  15375. function () {
  15376. Moderator.allocateConferenceFocus(roomName, callback);
  15377. }, waitMs);
  15378. }
  15379. );
  15380. },
  15381. getLoginUrl: function (roomName, urlCallback) {
  15382. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15383. iq.c('login-url', {
  15384. xmlns: 'http://jitsi.org/protocol/focus',
  15385. room: roomName,
  15386. 'machine-uid': Settings.getSettings().uid
  15387. });
  15388. connection.sendIQ(
  15389. iq,
  15390. function (result) {
  15391. var url = $(result).find('login-url').attr('url');
  15392. url = url = decodeURIComponent(url);
  15393. if (url) {
  15394. console.info("Got auth url: " + url);
  15395. urlCallback(url);
  15396. } else {
  15397. console.error(
  15398. "Failed to get auth url from the focus", result);
  15399. }
  15400. },
  15401. function (error) {
  15402. console.error("Get auth url error", error);
  15403. }
  15404. );
  15405. },
  15406. getPopupLoginUrl: function (roomName, urlCallback) {
  15407. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15408. iq.c('login-url', {
  15409. xmlns: 'http://jitsi.org/protocol/focus',
  15410. room: roomName,
  15411. 'machine-uid': Settings.getSettings().uid,
  15412. popup: true
  15413. });
  15414. connection.sendIQ(
  15415. iq,
  15416. function (result) {
  15417. var url = $(result).find('login-url').attr('url');
  15418. url = url = decodeURIComponent(url);
  15419. if (url) {
  15420. console.info("Got POPUP auth url: " + url);
  15421. urlCallback(url);
  15422. } else {
  15423. console.error(
  15424. "Failed to get POPUP auth url from the focus", result);
  15425. }
  15426. },
  15427. function (error) {
  15428. console.error('Get POPUP auth url error', error);
  15429. }
  15430. );
  15431. },
  15432. logout: function (callback) {
  15433. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15434. var sessionId = localStorage.getItem('sessionId');
  15435. if (!sessionId) {
  15436. callback();
  15437. return;
  15438. }
  15439. iq.c('logout', {
  15440. xmlns: 'http://jitsi.org/protocol/focus',
  15441. 'session-id': sessionId
  15442. });
  15443. connection.sendIQ(
  15444. iq,
  15445. function (result) {
  15446. var logoutUrl = $(result).find('logout').attr('logout-url');
  15447. if (logoutUrl) {
  15448. logoutUrl = decodeURIComponent(logoutUrl);
  15449. }
  15450. console.info("Log out OK, url: " + logoutUrl, result);
  15451. localStorage.removeItem('sessionId');
  15452. callback(logoutUrl);
  15453. },
  15454. function (error) {
  15455. console.error("Logout error", error);
  15456. }
  15457. );
  15458. }
  15459. };
  15460. module.exports = Moderator;
  15461. },{"../../service/authentication/AuthenticationEvents":115,"../../service/xmpp/XMPPEvents":120,"../settings/Settings":49}],63:[function(require,module,exports){
  15462. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  15463. Toolbar, Util */
  15464. var Moderator = require("./moderator");
  15465. var recordingToken = null;
  15466. var recordingEnabled;
  15467. /**
  15468. * Whether to use a jirecon component for recording, or use the videobridge
  15469. * through COLIBRI.
  15470. */
  15471. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  15472. /**
  15473. * The ID of the jirecon recording session. Jirecon generates it when we
  15474. * initially start recording, and it needs to be used in subsequent requests
  15475. * to jirecon.
  15476. */
  15477. var jireconRid = null;
  15478. /**
  15479. * The callback to update the recording button. Currently used from colibri
  15480. * after receiving a pending status.
  15481. */
  15482. var recordingStateChangeCallback = null;
  15483. function setRecordingToken(token) {
  15484. recordingToken = token;
  15485. }
  15486. function setRecordingJirecon(state, token, callback, connection) {
  15487. if (state == recordingEnabled){
  15488. return;
  15489. }
  15490. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  15491. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  15492. action: (state === 'on') ? 'start' : 'stop',
  15493. mucjid: connection.emuc.roomjid});
  15494. if (state === 'off'){
  15495. iq.attrs({rid: jireconRid});
  15496. }
  15497. console.log('Start recording');
  15498. connection.sendIQ(
  15499. iq,
  15500. function (result) {
  15501. // TODO wait for an IQ with the real status, since this is
  15502. // provisional?
  15503. jireconRid = $(result).find('recording').attr('rid');
  15504. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  15505. '(jirecon)' + result);
  15506. recordingEnabled = state;
  15507. if (state === 'off'){
  15508. jireconRid = null;
  15509. }
  15510. callback(state);
  15511. },
  15512. function (error) {
  15513. console.log('Failed to start recording, error: ', error);
  15514. callback(recordingEnabled);
  15515. });
  15516. }
  15517. // Sends a COLIBRI message which enables or disables (according to 'state')
  15518. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  15519. // with the new recording state, according to the IQ.
  15520. function setRecordingColibri(state, token, callback, connection) {
  15521. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  15522. elem.c('conference', {
  15523. xmlns: 'http://jitsi.org/protocol/colibri'
  15524. });
  15525. elem.c('recording', {state: state, token: token});
  15526. connection.sendIQ(elem,
  15527. function (result) {
  15528. console.log('Set recording "', state, '". Result:', result);
  15529. var recordingElem = $(result).find('>conference>recording');
  15530. var newState = recordingElem.attr('state');
  15531. recordingEnabled = newState;
  15532. callback(newState);
  15533. if (newState === 'pending' && recordingStateChangeCallback == null) {
  15534. recordingStateChangeCallback = callback;
  15535. connection.addHandler(function(iq){
  15536. var state = $(iq).find('recording').attr('state');
  15537. if (state)
  15538. recordingStateChangeCallback(state);
  15539. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  15540. }
  15541. },
  15542. function (error) {
  15543. console.warn(error);
  15544. callback(recordingEnabled);
  15545. }
  15546. );
  15547. }
  15548. function setRecording(state, token, callback, connection) {
  15549. if (useJirecon){
  15550. setRecordingJirecon(state, token, callback, connection);
  15551. } else {
  15552. setRecordingColibri(state, token, callback, connection);
  15553. }
  15554. }
  15555. var Recording = {
  15556. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  15557. if (!Moderator.isModerator()) {
  15558. console.log(
  15559. 'non-focus, or conference not yet organized:' +
  15560. ' not enabling recording');
  15561. return;
  15562. }
  15563. var self = this;
  15564. // Jirecon does not (currently) support a token.
  15565. if (!recordingToken && !useJirecon) {
  15566. tokenEmptyCallback(function (value) {
  15567. setRecordingToken(value);
  15568. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  15569. });
  15570. return;
  15571. }
  15572. var oldState = recordingEnabled;
  15573. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  15574. setRecording(newState,
  15575. recordingToken,
  15576. function (state) {
  15577. console.log("New recording state: ", state);
  15578. if (state === oldState) {
  15579. // FIXME: new focus:
  15580. // this will not work when moderator changes
  15581. // during active session. Then it will assume that
  15582. // recording status has changed to true, but it might have
  15583. // been already true(and we only received actual status from
  15584. // the focus).
  15585. //
  15586. // SO we start with status null, so that it is initialized
  15587. // here and will fail only after second click, so if invalid
  15588. // token was used we have to press the button twice before
  15589. // current status will be fetched and token will be reset.
  15590. //
  15591. // Reliable way would be to return authentication error.
  15592. // Or status update when moderator connects.
  15593. // Or we have to stop recording session when current
  15594. // moderator leaves the room.
  15595. // Failed to change, reset the token because it might
  15596. // have been wrong
  15597. setRecordingToken(null);
  15598. }
  15599. recordingStateChangeCallback(state);
  15600. },
  15601. connection
  15602. );
  15603. }
  15604. };
  15605. module.exports = Recording;
  15606. },{"./moderator":62}],64:[function(require,module,exports){
  15607. /* jshint -W117 */
  15608. /* a simple MUC connection plugin
  15609. * can only handle a single MUC room
  15610. */
  15611. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15612. var Moderator = require("./moderator");
  15613. module.exports = function(XMPP, eventEmitter) {
  15614. Strophe.addConnectionPlugin('emuc', {
  15615. connection: null,
  15616. roomjid: null,
  15617. myroomjid: null,
  15618. members: {},
  15619. list_members: [], // so we can elect a new focus
  15620. presMap: {},
  15621. preziMap: {},
  15622. joined: false,
  15623. isOwner: false,
  15624. role: null,
  15625. focusMucJid: null,
  15626. bridgeIsDown: false,
  15627. init: function (conn) {
  15628. this.connection = conn;
  15629. },
  15630. initPresenceMap: function (myroomjid) {
  15631. this.presMap['to'] = myroomjid;
  15632. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15633. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15634. this.addAudioInfoToPresence(true);
  15635. }
  15636. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15637. this.addVideoInfoToPresence(true);
  15638. }
  15639. },
  15640. doJoin: function (jid, password) {
  15641. this.myroomjid = jid;
  15642. console.info("Joined MUC as " + this.myroomjid);
  15643. this.initPresenceMap(this.myroomjid);
  15644. if (!this.roomjid) {
  15645. this.roomjid = Strophe.getBareJidFromJid(jid);
  15646. // add handlers (just once)
  15647. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15648. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15649. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15650. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15651. }
  15652. if (password !== undefined) {
  15653. this.presMap['password'] = password;
  15654. }
  15655. this.sendPresence();
  15656. },
  15657. doLeave: function () {
  15658. console.log("do leave", this.myroomjid);
  15659. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15660. this.presMap.length = 0;
  15661. this.connection.send(pres);
  15662. },
  15663. createNonAnonymousRoom: function () {
  15664. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15665. var getForm = $iq({type: 'get', to: this.roomjid})
  15666. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15667. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15668. var self = this;
  15669. this.connection.sendIQ(getForm, function (form) {
  15670. if (!$(form).find(
  15671. '>query>x[xmlns="jabber:x:data"]' +
  15672. '>field[var="muc#roomconfig_whois"]').length) {
  15673. console.error('non-anonymous rooms not supported');
  15674. return;
  15675. }
  15676. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15677. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15678. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15679. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15680. .c('value')
  15681. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15682. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15683. .c('value').t('anyone').up().up();
  15684. self.connection.sendIQ(formSubmit);
  15685. }, function (error) {
  15686. console.error("Error getting room configuration form");
  15687. });
  15688. },
  15689. onPresence: function (pres) {
  15690. var from = pres.getAttribute('from');
  15691. // What is this for? A workaround for something?
  15692. if (pres.getAttribute('type')) {
  15693. return true;
  15694. }
  15695. // Parse etherpad tag.
  15696. var etherpad = $(pres).find('>etherpad');
  15697. if (etherpad.length) {
  15698. if (config.etherpad_base) {
  15699. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15700. }
  15701. }
  15702. // Parse prezi tag.
  15703. var presentation = $(pres).find('>prezi');
  15704. if (presentation.length) {
  15705. var url = presentation.attr('url');
  15706. var current = presentation.find('>current').text();
  15707. console.log('presentation info received from', from, url);
  15708. if (this.preziMap[from] == null) {
  15709. this.preziMap[from] = url;
  15710. $(document).trigger('presentationadded.muc', [from, url, current]);
  15711. }
  15712. else {
  15713. $(document).trigger('gotoslide.muc', [from, url, current]);
  15714. }
  15715. }
  15716. else if (this.preziMap[from] != null) {
  15717. var url = this.preziMap[from];
  15718. delete this.preziMap[from];
  15719. $(document).trigger('presentationremoved.muc', [from, url]);
  15720. }
  15721. // Parse audio info tag.
  15722. var audioMuted = $(pres).find('>audiomuted');
  15723. if (audioMuted.length) {
  15724. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  15725. from, (audioMuted.text() === "true"));
  15726. }
  15727. // Parse video info tag.
  15728. var videoMuted = $(pres).find('>videomuted');
  15729. if (videoMuted.length) {
  15730. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  15731. from, (videoMuted.text() === "true"));
  15732. }
  15733. var startMuted = $(pres).find('>startmuted');
  15734. if (startMuted.length)
  15735. {
  15736. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15737. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  15738. }
  15739. var devices = $(pres).find('>devices');
  15740. if(devices.length)
  15741. {
  15742. var audio = devices.find('>audio');
  15743. var video = devices.find('>video');
  15744. var devicesValues = {audio: false, video: false};
  15745. if(audio.length && audio.text() === "true")
  15746. {
  15747. devicesValues.audio = true;
  15748. }
  15749. if(video.length && video.text() === "true")
  15750. {
  15751. devicesValues.video = true;
  15752. }
  15753. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15754. Strophe.getResourceFromJid(from), devicesValues);
  15755. }
  15756. var videoType = $(pres).find('>videoType');
  15757. if (videoType.length)
  15758. {
  15759. if (videoType.text().length)
  15760. {
  15761. eventEmitter.emit(XMPPEvents.VIDEO_TYPE,
  15762. Strophe.getResourceFromJid(from), videoType.text());
  15763. }
  15764. }
  15765. var stats = $(pres).find('>stats');
  15766. if (stats.length) {
  15767. var statsObj = {};
  15768. Strophe.forEachChild(stats[0], "stat", function (el) {
  15769. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15770. });
  15771. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15772. }
  15773. // Parse status.
  15774. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15775. this.isOwner = true;
  15776. this.createNonAnonymousRoom();
  15777. }
  15778. // Parse roles.
  15779. var member = {};
  15780. member.show = $(pres).find('>show').text();
  15781. member.status = $(pres).find('>status').text();
  15782. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15783. member.affiliation = tmp.attr('affiliation');
  15784. member.role = tmp.attr('role');
  15785. // Focus recognition
  15786. member.jid = tmp.attr('jid');
  15787. member.isFocus = false;
  15788. if (member.jid
  15789. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15790. member.isFocus = true;
  15791. }
  15792. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15793. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  15794. if (from == this.myroomjid) {
  15795. if (member.affiliation == 'owner') this.isOwner = true;
  15796. if (this.role !== member.role) {
  15797. this.role = member.role;
  15798. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15799. from, member, pres, Moderator.isModerator());
  15800. }
  15801. if (!this.joined) {
  15802. this.joined = true;
  15803. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15804. this.list_members.push(from);
  15805. }
  15806. } else if (this.members[from] === undefined) {
  15807. // new participant
  15808. this.members[from] = member;
  15809. this.list_members.push(from);
  15810. console.log('entered', from, member);
  15811. if (member.isFocus) {
  15812. this.focusMucJid = from;
  15813. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15814. }
  15815. else {
  15816. var id = $(pres).find('>userId').text();
  15817. var email = $(pres).find('>email');
  15818. if (email.length > 0) {
  15819. id = email.text();
  15820. }
  15821. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15822. }
  15823. } else {
  15824. // Presence update for existing participant
  15825. // Watch role change:
  15826. if (this.members[from].role != member.role) {
  15827. this.members[from].role = member.role;
  15828. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15829. member.role, member.displayName);
  15830. }
  15831. }
  15832. // Always trigger presence to update bindings
  15833. this.parsePresence(from, member, pres);
  15834. // Trigger status message update
  15835. if (member.status) {
  15836. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15837. }
  15838. return true;
  15839. },
  15840. onPresenceUnavailable: function (pres) {
  15841. var from = pres.getAttribute('from');
  15842. // room destroyed ?
  15843. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15844. '>destroy').length) {
  15845. var reason;
  15846. var reasonSelect = $(pres).find(
  15847. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15848. '>destroy>reason');
  15849. if (reasonSelect.length) {
  15850. reason = reasonSelect.text();
  15851. }
  15852. XMPP.disposeConference(false);
  15853. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15854. return true;
  15855. }
  15856. // Status code 110 indicates that this notification is "self-presence".
  15857. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15858. delete this.members[from];
  15859. this.list_members.splice(this.list_members.indexOf(from), 1);
  15860. this.onParticipantLeft(from);
  15861. }
  15862. // If the status code is 110 this means we're leaving and we would like
  15863. // to remove everyone else from our view, so we trigger the event.
  15864. else if (this.list_members.length > 1) {
  15865. for (var i = 0; i < this.list_members.length; i++) {
  15866. var member = this.list_members[i];
  15867. delete this.members[i];
  15868. this.list_members.splice(i, 1);
  15869. this.onParticipantLeft(member);
  15870. }
  15871. }
  15872. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15873. $(document).trigger('kicked.muc', [from]);
  15874. if (this.myroomjid === from) {
  15875. XMPP.disposeConference(false);
  15876. eventEmitter.emit(XMPPEvents.KICKED);
  15877. }
  15878. }
  15879. return true;
  15880. },
  15881. onPresenceError: function (pres) {
  15882. var from = pres.getAttribute('from');
  15883. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15884. console.log('on password required', from);
  15885. var self = this;
  15886. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15887. self.doJoin(from, value);
  15888. });
  15889. } else if ($(pres).find(
  15890. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15891. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15892. if (toDomain === config.hosts.anonymousdomain) {
  15893. // enter the room by replying with 'not-authorized'. This would
  15894. // result in reconnection from authorized domain.
  15895. // We're either missing Jicofo/Prosody config for anonymous
  15896. // domains or something is wrong.
  15897. // XMPP.promptLogin();
  15898. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15899. } else {
  15900. console.warn('onPresError ', pres);
  15901. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15902. }
  15903. } else {
  15904. console.warn('onPresError ', pres);
  15905. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15906. }
  15907. return true;
  15908. },
  15909. sendMessage: function (body, nickname) {
  15910. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15911. msg.c('body', body).up();
  15912. if (nickname) {
  15913. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15914. }
  15915. this.connection.send(msg);
  15916. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15917. },
  15918. setSubject: function (subject) {
  15919. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15920. msg.c('subject', subject);
  15921. this.connection.send(msg);
  15922. console.log("topic changed to " + subject);
  15923. },
  15924. onMessage: function (msg) {
  15925. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15926. var from = msg.getAttribute('from');
  15927. var nick =
  15928. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15929. .text() ||
  15930. Strophe.getResourceFromJid(from);
  15931. var txt = $(msg).find('>body').text();
  15932. var type = msg.getAttribute("type");
  15933. if (type == "error") {
  15934. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15935. $(msg).find('>text').text(), txt);
  15936. return true;
  15937. }
  15938. var subject = $(msg).find('>subject');
  15939. if (subject.length) {
  15940. var subjectText = subject.text();
  15941. if (subjectText || subjectText == "") {
  15942. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15943. console.log("Subject is changed to " + subjectText);
  15944. }
  15945. }
  15946. // xep-0203 delay
  15947. var stamp = $(msg).find('>delay').attr('stamp');
  15948. if (!stamp) {
  15949. // or xep-0091 delay, UTC timestamp
  15950. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15951. if (stamp) {
  15952. // the format is CCYYMMDDThh:mm:ss
  15953. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15954. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15955. }
  15956. }
  15957. if (txt) {
  15958. console.log('chat', nick, txt);
  15959. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15960. from, nick, txt, this.myroomjid, stamp);
  15961. }
  15962. return true;
  15963. },
  15964. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15965. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15966. var ob = this;
  15967. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15968. function (res) {
  15969. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15970. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15971. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15972. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15973. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15974. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15975. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15976. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15977. ob.connection.sendIQ(formsubmit,
  15978. onSuccess,
  15979. onError);
  15980. } else {
  15981. onNotSupported();
  15982. }
  15983. }, onError);
  15984. },
  15985. kick: function (jid) {
  15986. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15987. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15988. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15989. .c('reason').t('You have been kicked.').up().up().up();
  15990. this.connection.sendIQ(
  15991. kickIQ,
  15992. function (result) {
  15993. console.log('Kick participant with jid: ', jid, result);
  15994. },
  15995. function (error) {
  15996. console.log('Kick participant error: ', error);
  15997. });
  15998. },
  15999. sendPresence: function () {
  16000. if (!this.presMap['to']) {
  16001. // Too early to send presence - not initialized
  16002. return;
  16003. }
  16004. var pres = $pres({to: this.presMap['to'] });
  16005. pres.c('x', {xmlns: this.presMap['xns']});
  16006. if (this.presMap['password']) {
  16007. pres.c('password').t(this.presMap['password']).up();
  16008. }
  16009. pres.up();
  16010. // Send XEP-0115 'c' stanza that contains our capabilities info
  16011. if (this.connection.caps) {
  16012. this.connection.caps.node = config.clientNode;
  16013. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  16014. }
  16015. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  16016. .t(navigator.userAgent).up();
  16017. if (this.presMap['bridgeIsDown']) {
  16018. pres.c('bridgeIsDown').up();
  16019. }
  16020. if (this.presMap['email']) {
  16021. pres.c('email').t(this.presMap['email']).up();
  16022. }
  16023. if (this.presMap['userId']) {
  16024. pres.c('userId').t(this.presMap['userId']).up();
  16025. }
  16026. if (this.presMap['displayName']) {
  16027. // XEP-0172
  16028. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  16029. .t(this.presMap['displayName']).up();
  16030. }
  16031. if(this.presMap["devices"])
  16032. {
  16033. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  16034. .c('video').t(this.presMap['devices'].video).up().up();
  16035. }
  16036. if (this.presMap['audions']) {
  16037. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  16038. .t(this.presMap['audiomuted']).up();
  16039. }
  16040. if (this.presMap['videons']) {
  16041. pres.c('videomuted', {xmlns: this.presMap['videons']})
  16042. .t(this.presMap['videomuted']).up();
  16043. }
  16044. if (this.presMap['videoTypeNs']) {
  16045. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  16046. .t(this.presMap['videoType']).up();
  16047. }
  16048. if (this.presMap['statsns']) {
  16049. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  16050. for (var stat in this.presMap["stats"])
  16051. if (this.presMap["stats"][stat] != null)
  16052. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  16053. pres.up();
  16054. }
  16055. if (this.presMap['prezins']) {
  16056. pres.c('prezi',
  16057. {xmlns: this.presMap['prezins'],
  16058. 'url': this.presMap['preziurl']})
  16059. .c('current').t(this.presMap['prezicurrent']).up().up();
  16060. }
  16061. if(this.presMap["startMuted"] !== undefined)
  16062. {
  16063. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  16064. video: this.presMap["startMuted"].video,
  16065. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  16066. delete this.presMap["startMuted"];
  16067. }
  16068. pres.up();
  16069. this.connection.send(pres);
  16070. },
  16071. addDisplayNameToPresence: function (displayName) {
  16072. this.presMap['displayName'] = displayName;
  16073. },
  16074. addDevicesToPresence: function (devices) {
  16075. this.presMap['devices'] = devices;
  16076. },
  16077. /**
  16078. * Adds the info about the type of our video stream.
  16079. * @param videoType 'camera' or 'screen'
  16080. */
  16081. addVideoTypeToPresence: function (videoType) {
  16082. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  16083. this.presMap['videoType'] = videoType;
  16084. },
  16085. addPreziToPresence: function (url, currentSlide) {
  16086. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  16087. this.presMap['preziurl'] = url;
  16088. this.presMap['prezicurrent'] = currentSlide;
  16089. },
  16090. removePreziFromPresence: function () {
  16091. delete this.presMap['prezins'];
  16092. delete this.presMap['preziurl'];
  16093. delete this.presMap['prezicurrent'];
  16094. },
  16095. addCurrentSlideToPresence: function (currentSlide) {
  16096. this.presMap['prezicurrent'] = currentSlide;
  16097. },
  16098. getPrezi: function (roomjid) {
  16099. return this.preziMap[roomjid];
  16100. },
  16101. addAudioInfoToPresence: function (isMuted) {
  16102. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  16103. this.presMap['audiomuted'] = isMuted.toString();
  16104. },
  16105. addVideoInfoToPresence: function (isMuted) {
  16106. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  16107. this.presMap['videomuted'] = isMuted.toString();
  16108. },
  16109. addConnectionInfoToPresence: function (stats) {
  16110. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  16111. this.presMap['stats'] = stats;
  16112. },
  16113. findJidFromResource: function (resourceJid) {
  16114. if (resourceJid &&
  16115. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  16116. return this.myroomjid;
  16117. }
  16118. var peerJid = null;
  16119. Object.keys(this.members).some(function (jid) {
  16120. peerJid = jid;
  16121. return Strophe.getResourceFromJid(jid) === resourceJid;
  16122. });
  16123. return peerJid;
  16124. },
  16125. addBridgeIsDownToPresence: function () {
  16126. this.presMap['bridgeIsDown'] = true;
  16127. },
  16128. addEmailToPresence: function (email) {
  16129. this.presMap['email'] = email;
  16130. },
  16131. addUserIdToPresence: function (userId) {
  16132. this.presMap['userId'] = userId;
  16133. },
  16134. addStartMutedToPresence: function (audio, video) {
  16135. this.presMap["startMuted"] = {audio: audio, video: video};
  16136. },
  16137. isModerator: function () {
  16138. return this.role === 'moderator';
  16139. },
  16140. getMemberRole: function (peerJid) {
  16141. if (this.members[peerJid]) {
  16142. return this.members[peerJid].role;
  16143. }
  16144. return null;
  16145. },
  16146. onParticipantLeft: function (jid) {
  16147. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  16148. this.connection.jingle.terminateByJid(jid);
  16149. if (this.getPrezi(jid)) {
  16150. $(document).trigger('presentationremoved.muc',
  16151. [jid, this.getPrezi(jid)]);
  16152. }
  16153. Moderator.onMucMemberLeft(jid);
  16154. },
  16155. parsePresence: function (from, member, pres) {
  16156. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  16157. this.bridgeIsDown = true;
  16158. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  16159. }
  16160. if(member.isFocus)
  16161. return;
  16162. var displayName = !config.displayJids
  16163. ? member.displayName : Strophe.getResourceFromJid(from);
  16164. if (displayName && displayName.length > 0) {
  16165. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  16166. }
  16167. var id = $(pres).find('>userID').text();
  16168. var email = $(pres).find('>email');
  16169. if (email.length > 0) {
  16170. id = email.text();
  16171. }
  16172. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  16173. }
  16174. });
  16175. };
  16176. },{"../../service/xmpp/XMPPEvents":120,"./moderator":62}],65:[function(require,module,exports){
  16177. /* jshint -W117 */
  16178. var JingleSession = require("./JingleSessionPC");
  16179. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16180. var RTCBrowserType = require("../RTC/RTCBrowserType");
  16181. module.exports = function(XMPP, eventEmitter) {
  16182. Strophe.addConnectionPlugin('jingle', {
  16183. connection: null,
  16184. sessions: {},
  16185. jid2session: {},
  16186. ice_config: {iceServers: []},
  16187. pc_constraints: {},
  16188. activecall: null,
  16189. media_constraints: {
  16190. mandatory: {
  16191. 'OfferToReceiveAudio': true,
  16192. 'OfferToReceiveVideo': true
  16193. }
  16194. // MozDontOfferDataChannel: true when this is firefox
  16195. },
  16196. init: function (conn) {
  16197. this.connection = conn;
  16198. if (this.connection.disco) {
  16199. // http://xmpp.org/extensions/xep-0167.html#support
  16200. // http://xmpp.org/extensions/xep-0176.html#support
  16201. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  16202. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  16203. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  16204. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  16205. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  16206. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  16207. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  16208. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  16209. || RTCBrowserType.isTemasysPluginUsed()) {
  16210. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  16211. }
  16212. // this is dealt with by SDP O/A so we don't need to announce this
  16213. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  16214. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  16215. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  16216. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  16217. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  16218. }
  16219. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  16220. },
  16221. onJingle: function (iq) {
  16222. var sid = $(iq).find('jingle').attr('sid');
  16223. var action = $(iq).find('jingle').attr('action');
  16224. var fromJid = iq.getAttribute('from');
  16225. // send ack first
  16226. var ack = $iq({type: 'result',
  16227. to: fromJid,
  16228. id: iq.getAttribute('id')
  16229. });
  16230. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  16231. var sess = this.sessions[sid];
  16232. if ('session-initiate' != action) {
  16233. if (sess === null) {
  16234. ack.type = 'error';
  16235. ack.c('error', {type: 'cancel'})
  16236. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  16237. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  16238. this.connection.send(ack);
  16239. return true;
  16240. }
  16241. // local jid is not checked
  16242. if (fromJid != sess.peerjid) {
  16243. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  16244. ack.type = 'error';
  16245. ack.c('error', {type: 'cancel'})
  16246. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  16247. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  16248. this.connection.send(ack);
  16249. return true;
  16250. }
  16251. } else if (sess !== undefined) {
  16252. // existing session with same session id
  16253. // this might be out-of-order if the sess.peerjid is the same as from
  16254. ack.type = 'error';
  16255. ack.c('error', {type: 'cancel'})
  16256. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  16257. console.warn('duplicate session id', sid);
  16258. this.connection.send(ack);
  16259. return true;
  16260. }
  16261. // FIXME: check for a defined action
  16262. this.connection.send(ack);
  16263. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  16264. switch (action) {
  16265. case 'session-initiate':
  16266. var startMuted = $(iq).find('jingle>startmuted');
  16267. if (startMuted && startMuted.length > 0) {
  16268. var audioMuted = startMuted.attr("audio");
  16269. var videoMuted = startMuted.attr("video");
  16270. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  16271. audioMuted === "true", videoMuted === "true");
  16272. }
  16273. sess = new JingleSession(
  16274. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  16275. this.connection, XMPP, eventEmitter);
  16276. // configure session
  16277. sess.media_constraints = this.media_constraints;
  16278. sess.pc_constraints = this.pc_constraints;
  16279. sess.ice_config = this.ice_config;
  16280. sess.initialize(fromJid, false);
  16281. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  16282. sess.setOffer($(iq).find('>jingle'));
  16283. this.sessions[sess.sid] = sess;
  16284. this.jid2session[sess.peerjid] = sess;
  16285. // the callback should either
  16286. // .sendAnswer and .accept
  16287. // or .sendTerminate -- not necessarily synchronous
  16288. // TODO: do we check activecall == null?
  16289. this.connection.jingle.activecall = sess;
  16290. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  16291. // TODO: check affiliation and/or role
  16292. console.log('emuc data for', sess.peerjid,
  16293. this.connection.emuc.members[sess.peerjid]);
  16294. sess.sendAnswer();
  16295. sess.accept();
  16296. break;
  16297. case 'session-accept':
  16298. sess.setAnswer($(iq).find('>jingle'));
  16299. sess.accept();
  16300. $(document).trigger('callaccepted.jingle', [sess.sid]);
  16301. break;
  16302. case 'session-terminate':
  16303. // If this is not the focus sending the terminate, we have
  16304. // nothing more to do here.
  16305. if (Object.keys(this.sessions).length < 1
  16306. || !(this.sessions[Object.keys(this.sessions)[0]]
  16307. instanceof JingleSession))
  16308. {
  16309. break;
  16310. }
  16311. console.log('terminating...', sess.sid);
  16312. sess.terminate();
  16313. this.terminate(sess.sid);
  16314. if ($(iq).find('>jingle>reason').length) {
  16315. $(document).trigger('callterminated.jingle', [
  16316. sess.sid,
  16317. sess.peerjid,
  16318. $(iq).find('>jingle>reason>:first')[0].tagName,
  16319. $(iq).find('>jingle>reason>text').text()
  16320. ]);
  16321. } else {
  16322. $(document).trigger('callterminated.jingle',
  16323. [sess.sid, sess.peerjid]);
  16324. }
  16325. break;
  16326. case 'transport-info':
  16327. sess.addIceCandidate($(iq).find('>jingle>content'));
  16328. break;
  16329. case 'session-info':
  16330. var affected;
  16331. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16332. $(document).trigger('ringing.jingle', [sess.sid]);
  16333. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16334. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16335. $(document).trigger('mute.jingle', [sess.sid, affected]);
  16336. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16337. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16338. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  16339. }
  16340. break;
  16341. case 'addsource': // FIXME: proprietary, un-jingleish
  16342. case 'source-add': // FIXME: proprietary
  16343. sess.addSource($(iq).find('>jingle>content'), fromJid);
  16344. break;
  16345. case 'removesource': // FIXME: proprietary, un-jingleish
  16346. case 'source-remove': // FIXME: proprietary
  16347. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  16348. break;
  16349. default:
  16350. console.warn('jingle action not implemented', action);
  16351. break;
  16352. }
  16353. return true;
  16354. },
  16355. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  16356. var sess = new JingleSession(myjid || this.connection.jid,
  16357. Math.random().toString(36).substr(2, 12), // random string
  16358. this.connection, XMPP, eventEmitter);
  16359. // configure session
  16360. sess.media_constraints = this.media_constraints;
  16361. sess.pc_constraints = this.pc_constraints;
  16362. sess.ice_config = this.ice_config;
  16363. sess.initialize(peerjid, true);
  16364. this.sessions[sess.sid] = sess;
  16365. this.jid2session[sess.peerjid] = sess;
  16366. sess.sendOffer();
  16367. return sess;
  16368. },
  16369. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  16370. if (sid === null || sid === undefined) {
  16371. for (sid in this.sessions) {
  16372. if (this.sessions[sid].state != 'ended') {
  16373. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16374. this.sessions[sid].terminate();
  16375. }
  16376. delete this.jid2session[this.sessions[sid].peerjid];
  16377. delete this.sessions[sid];
  16378. }
  16379. } else if (this.sessions.hasOwnProperty(sid)) {
  16380. if (this.sessions[sid].state != 'ended') {
  16381. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16382. this.sessions[sid].terminate();
  16383. }
  16384. delete this.jid2session[this.sessions[sid].peerjid];
  16385. delete this.sessions[sid];
  16386. }
  16387. },
  16388. // Used to terminate a session when an unavailable presence is received.
  16389. terminateByJid: function (jid) {
  16390. if (this.jid2session.hasOwnProperty(jid)) {
  16391. var sess = this.jid2session[jid];
  16392. if (sess) {
  16393. sess.terminate();
  16394. console.log('peer went away silently', jid);
  16395. delete this.sessions[sess.sid];
  16396. delete this.jid2session[jid];
  16397. $(document).trigger('callterminated.jingle',
  16398. [sess.sid, jid], 'gone');
  16399. }
  16400. }
  16401. },
  16402. terminateRemoteByJid: function (jid, reason) {
  16403. if (this.jid2session.hasOwnProperty(jid)) {
  16404. var sess = this.jid2session[jid];
  16405. if (sess) {
  16406. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  16407. sess.terminate();
  16408. console.log('terminate peer with jid', sess.sid, jid);
  16409. delete this.sessions[sess.sid];
  16410. delete this.jid2session[jid];
  16411. $(document).trigger('callterminated.jingle',
  16412. [sess.sid, jid, 'kicked']);
  16413. }
  16414. }
  16415. },
  16416. getStunAndTurnCredentials: function () {
  16417. // get stun and turn configuration from server via xep-0215
  16418. // uses time-limited credentials as described in
  16419. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  16420. //
  16421. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  16422. // for a prosody module which implements this
  16423. //
  16424. // currently, this doesn't work with updateIce and therefore credentials with a long
  16425. // validity have to be fetched before creating the peerconnection
  16426. // TODO: implement refresh via updateIce as described in
  16427. // https://code.google.com/p/webrtc/issues/detail?id=1650
  16428. var self = this;
  16429. this.connection.sendIQ(
  16430. $iq({type: 'get', to: this.connection.domain})
  16431. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  16432. function (res) {
  16433. var iceservers = [];
  16434. $(res).find('>services>service').each(function (idx, el) {
  16435. el = $(el);
  16436. var dict = {};
  16437. var type = el.attr('type');
  16438. switch (type) {
  16439. case 'stun':
  16440. dict.url = 'stun:' + el.attr('host');
  16441. if (el.attr('port')) {
  16442. dict.url += ':' + el.attr('port');
  16443. }
  16444. iceservers.push(dict);
  16445. break;
  16446. case 'turn':
  16447. case 'turns':
  16448. dict.url = type + ':';
  16449. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  16450. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  16451. dict.url += el.attr('username') + '@';
  16452. } else {
  16453. dict.username = el.attr('username'); // only works in M28
  16454. }
  16455. }
  16456. dict.url += el.attr('host');
  16457. if (el.attr('port') && el.attr('port') != '3478') {
  16458. dict.url += ':' + el.attr('port');
  16459. }
  16460. if (el.attr('transport') && el.attr('transport') != 'udp') {
  16461. dict.url += '?transport=' + el.attr('transport');
  16462. }
  16463. if (el.attr('password')) {
  16464. dict.credential = el.attr('password');
  16465. }
  16466. iceservers.push(dict);
  16467. break;
  16468. }
  16469. });
  16470. self.ice_config.iceServers = iceservers;
  16471. },
  16472. function (err) {
  16473. console.warn('getting turn credentials failed', err);
  16474. console.warn('is mod_turncredentials or similar installed?');
  16475. }
  16476. );
  16477. // implement push?
  16478. },
  16479. /**
  16480. * Returns the data saved in 'updateLog' in a format to be logged.
  16481. */
  16482. getLog: function () {
  16483. var data = {};
  16484. var self = this;
  16485. Object.keys(this.sessions).forEach(function (sid) {
  16486. var session = self.sessions[sid];
  16487. if (session.peerconnection && session.peerconnection.updateLog) {
  16488. // FIXME: should probably be a .dump call
  16489. data["jingle_" + session.sid] = {
  16490. updateLog: session.peerconnection.updateLog,
  16491. stats: session.peerconnection.stats,
  16492. url: window.location.href
  16493. };
  16494. }
  16495. });
  16496. return data;
  16497. }
  16498. });
  16499. };
  16500. },{"../../service/xmpp/XMPPEvents":120,"../RTC/RTCBrowserType":10,"./JingleSessionPC":56}],66:[function(require,module,exports){
  16501. /* global Strophe */
  16502. module.exports = function () {
  16503. Strophe.addConnectionPlugin('logger', {
  16504. // logs raw stanzas and makes them available for download as JSON
  16505. connection: null,
  16506. log: [],
  16507. init: function (conn) {
  16508. this.connection = conn;
  16509. this.connection.rawInput = this.log_incoming.bind(this);
  16510. this.connection.rawOutput = this.log_outgoing.bind(this);
  16511. },
  16512. log_incoming: function (stanza) {
  16513. this.log.push([new Date().getTime(), 'incoming', stanza]);
  16514. },
  16515. log_outgoing: function (stanza) {
  16516. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  16517. }
  16518. });
  16519. };
  16520. },{}],67:[function(require,module,exports){
  16521. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  16522. setAudioMuted, Strophe */
  16523. /**
  16524. * Moderate connection plugin.
  16525. */
  16526. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16527. module.exports = function (XMPP, eventEmitter) {
  16528. Strophe.addConnectionPlugin('moderate', {
  16529. connection: null,
  16530. init: function (conn) {
  16531. this.connection = conn;
  16532. this.connection.addHandler(this.onMute.bind(this),
  16533. 'http://jitsi.org/jitmeet/audio',
  16534. 'iq',
  16535. 'set',
  16536. null,
  16537. null);
  16538. },
  16539. setMute: function (jid, mute) {
  16540. console.info("set mute", mute);
  16541. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  16542. .c('mute', {
  16543. xmlns: 'http://jitsi.org/jitmeet/audio',
  16544. jid: jid
  16545. })
  16546. .t(mute.toString())
  16547. .up();
  16548. this.connection.sendIQ(
  16549. iqToFocus,
  16550. function (result) {
  16551. console.log('set mute', result);
  16552. },
  16553. function (error) {
  16554. console.log('set mute error', error);
  16555. });
  16556. },
  16557. onMute: function (iq) {
  16558. var from = iq.getAttribute('from');
  16559. if (from !== this.connection.emuc.focusMucJid) {
  16560. console.warn("Ignored mute from non focus peer");
  16561. return false;
  16562. }
  16563. var mute = $(iq).find('mute');
  16564. if (mute.length) {
  16565. var doMuteAudio = mute.text() === "true";
  16566. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16567. XMPP.forceMuted = doMuteAudio;
  16568. }
  16569. return true;
  16570. },
  16571. eject: function (jid) {
  16572. // We're not the focus, so can't terminate
  16573. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16574. this.connection.emuc.kick(jid);
  16575. }
  16576. });
  16577. }
  16578. },{"../../service/xmpp/XMPPEvents":120}],68:[function(require,module,exports){
  16579. /* jshint -W117 */
  16580. module.exports = function() {
  16581. Strophe.addConnectionPlugin('rayo',
  16582. {
  16583. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16584. connection: null,
  16585. init: function (conn) {
  16586. this.connection = conn;
  16587. if (this.connection.disco) {
  16588. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16589. }
  16590. this.connection.addHandler(
  16591. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16592. },
  16593. onRayo: function (iq) {
  16594. console.info("Rayo IQ", iq);
  16595. },
  16596. dial: function (to, from, roomName, roomPass) {
  16597. var self = this;
  16598. var req = $iq(
  16599. {
  16600. type: 'set',
  16601. to: this.connection.emuc.focusMucJid
  16602. }
  16603. );
  16604. req.c('dial',
  16605. {
  16606. xmlns: this.RAYO_XMLNS,
  16607. to: to,
  16608. from: from
  16609. });
  16610. req.c('header',
  16611. {
  16612. name: 'JvbRoomName',
  16613. value: roomName
  16614. }).up();
  16615. if (roomPass !== null && roomPass.length) {
  16616. req.c('header',
  16617. {
  16618. name: 'JvbRoomPassword',
  16619. value: roomPass
  16620. }).up();
  16621. }
  16622. this.connection.sendIQ(
  16623. req,
  16624. function (result) {
  16625. console.info('Dial result ', result);
  16626. var resource = $(result).find('ref').attr('uri');
  16627. this.call_resource = resource.substr('xmpp:'.length);
  16628. console.info(
  16629. "Received call resource: " + this.call_resource);
  16630. },
  16631. function (error) {
  16632. console.info('Dial error ', error);
  16633. }
  16634. );
  16635. },
  16636. hang_up: function () {
  16637. if (!this.call_resource) {
  16638. console.warn("No call in progress");
  16639. return;
  16640. }
  16641. var self = this;
  16642. var req = $iq(
  16643. {
  16644. type: 'set',
  16645. to: this.call_resource
  16646. }
  16647. );
  16648. req.c('hangup',
  16649. {
  16650. xmlns: this.RAYO_XMLNS
  16651. });
  16652. this.connection.sendIQ(
  16653. req,
  16654. function (result) {
  16655. console.info('Hangup result ', result);
  16656. self.call_resource = null;
  16657. },
  16658. function (error) {
  16659. console.info('Hangup error ', error);
  16660. self.call_resource = null;
  16661. }
  16662. );
  16663. }
  16664. }
  16665. );
  16666. };
  16667. },{}],69:[function(require,module,exports){
  16668. /**
  16669. * Strophe logger implementation. Logs from level WARN and above.
  16670. */
  16671. module.exports = function () {
  16672. Strophe.log = function (level, msg) {
  16673. switch (level) {
  16674. case Strophe.LogLevel.WARN:
  16675. console.warn("Strophe: " + msg);
  16676. break;
  16677. case Strophe.LogLevel.ERROR:
  16678. case Strophe.LogLevel.FATAL:
  16679. console.error("Strophe: " + msg);
  16680. break;
  16681. }
  16682. };
  16683. Strophe.getStatusString = function (status) {
  16684. switch (status) {
  16685. case Strophe.Status.ERROR:
  16686. return "ERROR";
  16687. case Strophe.Status.CONNECTING:
  16688. return "CONNECTING";
  16689. case Strophe.Status.CONNFAIL:
  16690. return "CONNFAIL";
  16691. case Strophe.Status.AUTHENTICATING:
  16692. return "AUTHENTICATING";
  16693. case Strophe.Status.AUTHFAIL:
  16694. return "AUTHFAIL";
  16695. case Strophe.Status.CONNECTED:
  16696. return "CONNECTED";
  16697. case Strophe.Status.DISCONNECTED:
  16698. return "DISCONNECTED";
  16699. case Strophe.Status.DISCONNECTING:
  16700. return "DISCONNECTING";
  16701. case Strophe.Status.ATTACHED:
  16702. return "ATTACHED";
  16703. default:
  16704. return "unknown";
  16705. }
  16706. };
  16707. };
  16708. },{}],70:[function(require,module,exports){
  16709. /* global $, APP, config, Strophe*/
  16710. var Moderator = require("./moderator");
  16711. var EventEmitter = require("events");
  16712. var Recording = require("./recording");
  16713. var SDP = require("./SDP");
  16714. var Settings = require("../settings/Settings");
  16715. var Pako = require("pako");
  16716. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16717. var RTCEvents = require("../../service/RTC/RTCEvents");
  16718. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16719. var retry = require('retry');
  16720. var eventEmitter = new EventEmitter();
  16721. var connection = null;
  16722. var authenticatedUser = false;
  16723. function connect(jid, password) {
  16724. var faultTolerantConnect = retry.operation({
  16725. retries: 3
  16726. });
  16727. // fault tolerant connect
  16728. faultTolerantConnect.attempt(function () {
  16729. connection = XMPP.createConnection();
  16730. Moderator.setConnection(connection);
  16731. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16732. if (config.useIPv6) {
  16733. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16734. if (!connection.jingle.pc_constraints.optional)
  16735. connection.jingle.pc_constraints.optional = [];
  16736. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16737. }
  16738. // Include user info in MUC presence
  16739. var settings = Settings.getSettings();
  16740. if (settings.email) {
  16741. connection.emuc.addEmailToPresence(settings.email);
  16742. }
  16743. if (settings.uid) {
  16744. connection.emuc.addUserIdToPresence(settings.uid);
  16745. }
  16746. if (settings.displayName) {
  16747. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16748. }
  16749. // connection.connect() starts the connection process.
  16750. //
  16751. // As the connection process proceeds, the user supplied callback will
  16752. // be triggered multiple times with status updates. The callback should
  16753. // take two arguments - the status code and the error condition.
  16754. //
  16755. // The status code will be one of the values in the Strophe.Status
  16756. // constants. The error condition will be one of the conditions defined
  16757. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16758. //
  16759. // The Parameters wait, hold and route are optional and only relevant
  16760. // for BOSH connections. Please see XEP 124 for a more detailed
  16761. // explanation of the optional parameters.
  16762. //
  16763. // Connection status constants for use by the connection handler
  16764. // callback.
  16765. //
  16766. // Status.ERROR - An error has occurred (websockets specific)
  16767. // Status.CONNECTING - The connection is currently being made
  16768. // Status.CONNFAIL - The connection attempt failed
  16769. // Status.AUTHENTICATING - The connection is authenticating
  16770. // Status.AUTHFAIL - The authentication attempt failed
  16771. // Status.CONNECTED - The connection has succeeded
  16772. // Status.DISCONNECTED - The connection has been terminated
  16773. // Status.DISCONNECTING - The connection is currently being terminated
  16774. // Status.ATTACHED - The connection has been attached
  16775. var anonymousConnectionFailed = false;
  16776. var connectionFailed = false;
  16777. var lastErrorMsg;
  16778. connection.connect(jid, password, function (status, msg) {
  16779. console.log('Strophe status changed to',
  16780. Strophe.getStatusString(status), msg);
  16781. if (status === Strophe.Status.CONNECTED) {
  16782. if (config.useStunTurn) {
  16783. connection.jingle.getStunAndTurnCredentials();
  16784. }
  16785. console.info("My Jabber ID: " + connection.jid);
  16786. if (password)
  16787. authenticatedUser = true;
  16788. maybeDoJoin();
  16789. } else if (status === Strophe.Status.CONNFAIL) {
  16790. if (msg === 'x-strophe-bad-non-anon-jid') {
  16791. anonymousConnectionFailed = true;
  16792. } else {
  16793. connectionFailed = true;
  16794. }
  16795. lastErrorMsg = msg;
  16796. } else if (status === Strophe.Status.DISCONNECTED) {
  16797. if (anonymousConnectionFailed) {
  16798. // prompt user for username and password
  16799. XMPP.promptLogin();
  16800. } else {
  16801. // Strophe already has built-in HTTP/BOSH error handling and
  16802. // request retry logic. Requests are resent automatically
  16803. // until their error count reaches 5. Strophe.js disconnects
  16804. // if the error count is > 5. We are not replicating this
  16805. // here.
  16806. //
  16807. // The "problem" is that failed HTTP/BOSH requests don't
  16808. // trigger a callback with a status update, so when a
  16809. // callback with status Strophe.Status.DISCONNECTED arrives,
  16810. // we can't be sure if it's a graceful disconnect or if it's
  16811. // triggered by some HTTP/BOSH error.
  16812. //
  16813. // But that's a minor issue in Jitsi Meet as we never
  16814. // disconnect anyway, not even when the user closes the
  16815. // browser window (which is kind of wrong, but the point is
  16816. // that we should never ever get disconnected).
  16817. //
  16818. // On the other hand, failed connections due to XMPP layer
  16819. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16820. //
  16821. // Here we implement retry logic for failed connections due
  16822. // to XMPP layer errors and we display an error to the user
  16823. // if we get disconnected from the XMPP server permanently.
  16824. // If the connection failed, retry.
  16825. if (connectionFailed &&
  16826. faultTolerantConnect.retry("connection-failed")) {
  16827. return;
  16828. }
  16829. // If we failed to connect to the XMPP server, fire an event
  16830. // to let all the interested module now about it.
  16831. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16832. msg ? msg : lastErrorMsg);
  16833. }
  16834. } else if (status === Strophe.Status.AUTHFAIL) {
  16835. // wrong password or username, prompt user
  16836. XMPP.promptLogin();
  16837. }
  16838. });
  16839. });
  16840. }
  16841. function maybeDoJoin() {
  16842. if (connection && connection.connected &&
  16843. Strophe.getResourceFromJid(connection.jid) &&
  16844. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16845. // .connected is true while connecting?
  16846. doJoin();
  16847. }
  16848. }
  16849. function doJoin() {
  16850. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16851. }
  16852. function initStrophePlugins()
  16853. {
  16854. require("./strophe.emuc")(XMPP, eventEmitter);
  16855. require("./strophe.jingle")(XMPP, eventEmitter);
  16856. require("./strophe.moderate")(XMPP, eventEmitter);
  16857. require("./strophe.util")();
  16858. require("./strophe.rayo")();
  16859. require("./strophe.logger")();
  16860. }
  16861. /**
  16862. * If given <tt>localStream</tt> is video one this method will advertise it's
  16863. * video type in MUC presence.
  16864. * @param localStream new or modified <tt>LocalStream</tt>.
  16865. */
  16866. function broadcastLocalVideoType(localStream) {
  16867. if (localStream.videoType)
  16868. XMPP.addToPresence('videoType', localStream.videoType);
  16869. }
  16870. function registerListeners() {
  16871. APP.RTC.addStreamListener(
  16872. function (localStream) {
  16873. maybeDoJoin();
  16874. broadcastLocalVideoType(localStream);
  16875. },
  16876. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16877. );
  16878. APP.RTC.addStreamListener(
  16879. broadcastLocalVideoType,
  16880. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16881. );
  16882. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16883. XMPP.addToPresence("devices", devices);
  16884. });
  16885. }
  16886. var unload = (function () {
  16887. var unloaded = false;
  16888. return function () {
  16889. if (unloaded) { return; }
  16890. unloaded = true;
  16891. if (connection && connection.connected) {
  16892. // ensure signout
  16893. $.ajax({
  16894. type: 'POST',
  16895. url: config.bosh,
  16896. async: false,
  16897. cache: false,
  16898. contentType: 'application/xml',
  16899. data: "<body rid='" +
  16900. (connection.rid || connection._proto.rid) +
  16901. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16902. (connection.sid || connection._proto.sid) +
  16903. "' type='terminate'>" +
  16904. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16905. "</body>",
  16906. success: function (data) {
  16907. console.log('signed out');
  16908. console.log(data);
  16909. },
  16910. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16911. console.log('signout error',
  16912. textStatus + ' (' + errorThrown + ')');
  16913. }
  16914. });
  16915. }
  16916. XMPP.disposeConference(true);
  16917. };
  16918. })();
  16919. function setupEvents() {
  16920. // In recent versions of FF the 'beforeunload' event is not fired when the
  16921. // window or the tab is closed. It is only fired when we leave the page
  16922. // (change URL). If this participant doesn't unload properly, then it
  16923. // becomes a ghost for the rest of the participants that stay in the
  16924. // conference. Thankfully handling the 'unload' event in addition to the
  16925. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16926. // method at least once.
  16927. //
  16928. // The 'unload' method can safely be run multiple times, it will actually do
  16929. // something only the first time that it's run, so we're don't have to worry
  16930. // about browsers that fire both events.
  16931. $(window).bind('beforeunload', unload);
  16932. $(window).bind('unload', unload);
  16933. }
  16934. var XMPP = {
  16935. getConnection: function(){ return connection; },
  16936. sessionTerminated: false,
  16937. /**
  16938. * XMPP connection status
  16939. */
  16940. Status: Strophe.Status,
  16941. /**
  16942. * Remembers if we were muted by the focus.
  16943. * @type {boolean}
  16944. */
  16945. forceMuted: false,
  16946. start: function () {
  16947. setupEvents();
  16948. initStrophePlugins();
  16949. registerListeners();
  16950. Moderator.init(this, eventEmitter);
  16951. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16952. // Force authenticated domain if room is appended with '?login=true'
  16953. if (config.hosts.anonymousdomain &&
  16954. window.location.search.indexOf("login=true") !== -1) {
  16955. configDomain = config.hosts.domain;
  16956. }
  16957. var jid = configDomain || window.location.hostname;
  16958. connect(jid, null);
  16959. },
  16960. createConnection: function () {
  16961. var bosh = config.bosh || '/http-bind';
  16962. return new Strophe.Connection(bosh);
  16963. },
  16964. getStatusString: function (status) {
  16965. return Strophe.getStatusString(status);
  16966. },
  16967. promptLogin: function () {
  16968. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16969. },
  16970. joinRoom: function(roomName, useNicks, nick) {
  16971. var roomjid = roomName;
  16972. if (useNicks) {
  16973. if (nick) {
  16974. roomjid += '/' + nick;
  16975. } else {
  16976. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16977. }
  16978. } else {
  16979. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16980. if(!authenticatedUser)
  16981. tmpJid = tmpJid.substr(0, 8);
  16982. roomjid += '/' + tmpJid;
  16983. }
  16984. connection.emuc.doJoin(roomjid);
  16985. },
  16986. myJid: function () {
  16987. if(!connection)
  16988. return null;
  16989. return connection.emuc.myroomjid;
  16990. },
  16991. myResource: function () {
  16992. if(!connection || ! connection.emuc.myroomjid)
  16993. return null;
  16994. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16995. },
  16996. disposeConference: function (onUnload) {
  16997. var handler = connection.jingle.activecall;
  16998. if (handler && handler.peerconnection) {
  16999. // FIXME: probably removing streams is not required and close() should
  17000. // be enough
  17001. if (APP.RTC.localAudio) {
  17002. handler.peerconnection.removeStream(
  17003. APP.RTC.localAudio.getOriginalStream(), onUnload);
  17004. }
  17005. if (APP.RTC.localVideo) {
  17006. handler.peerconnection.removeStream(
  17007. APP.RTC.localVideo.getOriginalStream(), onUnload);
  17008. }
  17009. handler.peerconnection.close();
  17010. }
  17011. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  17012. connection.jingle.activecall = null;
  17013. if (!onUnload) {
  17014. this.sessionTerminated = true;
  17015. connection.emuc.doLeave();
  17016. }
  17017. },
  17018. addListener: function(type, listener) {
  17019. eventEmitter.on(type, listener);
  17020. },
  17021. removeListener: function (type, listener) {
  17022. eventEmitter.removeListener(type, listener);
  17023. },
  17024. allocateConferenceFocus: function(roomName, callback) {
  17025. Moderator.allocateConferenceFocus(roomName, callback);
  17026. },
  17027. getLoginUrl: function (roomName, callback) {
  17028. Moderator.getLoginUrl(roomName, callback);
  17029. },
  17030. getPopupLoginUrl: function (roomName, callback) {
  17031. Moderator.getPopupLoginUrl(roomName, callback);
  17032. },
  17033. isModerator: function () {
  17034. return Moderator.isModerator();
  17035. },
  17036. isSipGatewayEnabled: function () {
  17037. return Moderator.isSipGatewayEnabled();
  17038. },
  17039. isExternalAuthEnabled: function () {
  17040. return Moderator.isExternalAuthEnabled();
  17041. },
  17042. isConferenceInProgress: function () {
  17043. return connection && connection.jingle.activecall &&
  17044. connection.jingle.activecall.peerconnection;
  17045. },
  17046. switchStreams: function (stream, oldStream, callback, isAudio) {
  17047. if (this.isConferenceInProgress()) {
  17048. // FIXME: will block switchInProgress on true value in case of exception
  17049. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  17050. } else {
  17051. // We are done immediately
  17052. console.warn("No conference handler or conference not started yet");
  17053. callback();
  17054. }
  17055. },
  17056. sendVideoInfoPresence: function (mute) {
  17057. if(!connection)
  17058. return;
  17059. connection.emuc.addVideoInfoToPresence(mute);
  17060. connection.emuc.sendPresence();
  17061. },
  17062. setVideoMute: function (mute, callback, options) {
  17063. if(!connection)
  17064. return;
  17065. var self = this;
  17066. var localCallback = function (mute) {
  17067. self.sendVideoInfoPresence(mute);
  17068. return callback(mute);
  17069. };
  17070. if(connection.jingle.activecall)
  17071. {
  17072. connection.jingle.activecall.setVideoMute(
  17073. mute, localCallback, options);
  17074. }
  17075. else {
  17076. localCallback(mute);
  17077. }
  17078. },
  17079. setAudioMute: function (mute, callback) {
  17080. if (!(connection && APP.RTC.localAudio)) {
  17081. return false;
  17082. }
  17083. if (this.forceMuted && !mute) {
  17084. console.info("Asking focus for unmute");
  17085. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  17086. // FIXME: wait for result before resetting muted status
  17087. this.forceMuted = false;
  17088. }
  17089. if (mute == APP.RTC.localAudio.isMuted()) {
  17090. // Nothing to do
  17091. return true;
  17092. }
  17093. APP.RTC.localAudio.setMute(mute);
  17094. this.sendAudioInfoPresence(mute, callback);
  17095. return true;
  17096. },
  17097. sendAudioInfoPresence: function(mute, callback) {
  17098. if(connection) {
  17099. connection.emuc.addAudioInfoToPresence(mute);
  17100. connection.emuc.sendPresence();
  17101. }
  17102. callback();
  17103. return true;
  17104. },
  17105. toggleRecording: function (tokenEmptyCallback,
  17106. recordingStateChangeCallback) {
  17107. Recording.toggleRecording(tokenEmptyCallback,
  17108. recordingStateChangeCallback, connection);
  17109. },
  17110. addToPresence: function (name, value, dontSend) {
  17111. switch (name) {
  17112. case "displayName":
  17113. connection.emuc.addDisplayNameToPresence(value);
  17114. break;
  17115. case "prezi":
  17116. connection.emuc.addPreziToPresence(value, 0);
  17117. break;
  17118. case "preziSlide":
  17119. connection.emuc.addCurrentSlideToPresence(value);
  17120. break;
  17121. case "connectionQuality":
  17122. connection.emuc.addConnectionInfoToPresence(value);
  17123. break;
  17124. case "email":
  17125. connection.emuc.addEmailToPresence(value);
  17126. break;
  17127. case "devices":
  17128. connection.emuc.addDevicesToPresence(value);
  17129. break;
  17130. case "videoType":
  17131. connection.emuc.addVideoTypeToPresence(value);
  17132. break;
  17133. case "startMuted":
  17134. if(!Moderator.isModerator())
  17135. return;
  17136. connection.emuc.addStartMutedToPresence(value[0],
  17137. value[1]);
  17138. break;
  17139. default :
  17140. console.log("Unknown tag for presence: " + name);
  17141. return;
  17142. }
  17143. if (!dontSend)
  17144. connection.emuc.sendPresence();
  17145. },
  17146. /**
  17147. * Sends 'data' as a log message to the focus. Returns true iff a message
  17148. * was sent.
  17149. * @param data
  17150. * @returns {boolean} true iff a message was sent.
  17151. */
  17152. sendLogs: function (data) {
  17153. if(!connection.emuc.focusMucJid)
  17154. return false;
  17155. var deflate = true;
  17156. var content = JSON.stringify(data);
  17157. if (deflate) {
  17158. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  17159. }
  17160. content = Base64.encode(content);
  17161. // XEP-0337-ish
  17162. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  17163. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  17164. id: 'PeerConnectionStats'});
  17165. message.c('message').t(content).up();
  17166. if (deflate) {
  17167. message.c('tag', {name: "deflated", value: "true"}).up();
  17168. }
  17169. message.up();
  17170. connection.send(message);
  17171. return true;
  17172. },
  17173. // Gets the logs from strophe.jingle.
  17174. getJingleLog: function () {
  17175. return connection.jingle ? connection.jingle.getLog() : {};
  17176. },
  17177. // Gets the logs from strophe.
  17178. getXmppLog: function () {
  17179. return connection.logger ? connection.logger.log : null;
  17180. },
  17181. getPrezi: function () {
  17182. return connection.emuc.getPrezi(this.myJid());
  17183. },
  17184. removePreziFromPresence: function () {
  17185. connection.emuc.removePreziFromPresence();
  17186. connection.emuc.sendPresence();
  17187. },
  17188. sendChatMessage: function (message, nickname) {
  17189. connection.emuc.sendMessage(message, nickname);
  17190. },
  17191. setSubject: function (topic) {
  17192. connection.emuc.setSubject(topic);
  17193. },
  17194. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  17195. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  17196. },
  17197. dial: function (to, from, roomName,roomPass) {
  17198. connection.rayo.dial(to, from, roomName,roomPass);
  17199. },
  17200. setMute: function (jid, mute) {
  17201. connection.moderate.setMute(jid, mute);
  17202. },
  17203. eject: function (jid) {
  17204. connection.moderate.eject(jid);
  17205. },
  17206. logout: function (callback) {
  17207. Moderator.logout(callback);
  17208. },
  17209. findJidFromResource: function (resource) {
  17210. return connection.emuc.findJidFromResource(resource);
  17211. },
  17212. getMembers: function () {
  17213. return connection.emuc.members;
  17214. },
  17215. getJidFromSSRC: function (ssrc) {
  17216. if (!this.isConferenceInProgress())
  17217. return null;
  17218. return connection.jingle.activecall.getSsrcOwner(ssrc);
  17219. },
  17220. // Returns true iff we have joined the MUC.
  17221. isMUCJoined: function () {
  17222. return connection.emuc.joined;
  17223. },
  17224. getSessions: function () {
  17225. return connection.jingle.sessions;
  17226. },
  17227. removeStream: function (stream) {
  17228. if (!this.isConferenceInProgress())
  17229. return;
  17230. connection.jingle.activecall.peerconnection.removeStream(stream);
  17231. }
  17232. };
  17233. module.exports = XMPP;
  17234. },{"../../service/RTC/RTCEvents":111,"../../service/RTC/StreamEventTypes":113,"../../service/xmpp/XMPPEvents":120,"../settings/Settings":49,"./SDP":58,"./moderator":62,"./recording":63,"./strophe.emuc":64,"./strophe.jingle":65,"./strophe.logger":66,"./strophe.moderate":67,"./strophe.rayo":68,"./strophe.util":69,"events":1,"pako":73,"retry":89}],71:[function(require,module,exports){
  17235. (function (process){
  17236. /*!
  17237. * async
  17238. * https://github.com/caolan/async
  17239. *
  17240. * Copyright 2010-2014 Caolan McMahon
  17241. * Released under the MIT license
  17242. */
  17243. /*jshint onevar: false, indent:4 */
  17244. /*global setImmediate: false, setTimeout: false, console: false */
  17245. (function () {
  17246. var async = {};
  17247. // global on the server, window in the browser
  17248. var root, previous_async;
  17249. root = this;
  17250. if (root != null) {
  17251. previous_async = root.async;
  17252. }
  17253. async.noConflict = function () {
  17254. root.async = previous_async;
  17255. return async;
  17256. };
  17257. function only_once(fn) {
  17258. var called = false;
  17259. return function() {
  17260. if (called) throw new Error("Callback was already called.");
  17261. called = true;
  17262. fn.apply(root, arguments);
  17263. }
  17264. }
  17265. //// cross-browser compatiblity functions ////
  17266. var _toString = Object.prototype.toString;
  17267. var _isArray = Array.isArray || function (obj) {
  17268. return _toString.call(obj) === '[object Array]';
  17269. };
  17270. var _each = function (arr, iterator) {
  17271. if (arr.forEach) {
  17272. return arr.forEach(iterator);
  17273. }
  17274. for (var i = 0; i < arr.length; i += 1) {
  17275. iterator(arr[i], i, arr);
  17276. }
  17277. };
  17278. var _map = function (arr, iterator) {
  17279. if (arr.map) {
  17280. return arr.map(iterator);
  17281. }
  17282. var results = [];
  17283. _each(arr, function (x, i, a) {
  17284. results.push(iterator(x, i, a));
  17285. });
  17286. return results;
  17287. };
  17288. var _reduce = function (arr, iterator, memo) {
  17289. if (arr.reduce) {
  17290. return arr.reduce(iterator, memo);
  17291. }
  17292. _each(arr, function (x, i, a) {
  17293. memo = iterator(memo, x, i, a);
  17294. });
  17295. return memo;
  17296. };
  17297. var _keys = function (obj) {
  17298. if (Object.keys) {
  17299. return Object.keys(obj);
  17300. }
  17301. var keys = [];
  17302. for (var k in obj) {
  17303. if (obj.hasOwnProperty(k)) {
  17304. keys.push(k);
  17305. }
  17306. }
  17307. return keys;
  17308. };
  17309. //// exported async module functions ////
  17310. //// nextTick implementation with browser-compatible fallback ////
  17311. if (typeof process === 'undefined' || !(process.nextTick)) {
  17312. if (typeof setImmediate === 'function') {
  17313. async.nextTick = function (fn) {
  17314. // not a direct alias for IE10 compatibility
  17315. setImmediate(fn);
  17316. };
  17317. async.setImmediate = async.nextTick;
  17318. }
  17319. else {
  17320. async.nextTick = function (fn) {
  17321. setTimeout(fn, 0);
  17322. };
  17323. async.setImmediate = async.nextTick;
  17324. }
  17325. }
  17326. else {
  17327. async.nextTick = process.nextTick;
  17328. if (typeof setImmediate !== 'undefined') {
  17329. async.setImmediate = function (fn) {
  17330. // not a direct alias for IE10 compatibility
  17331. setImmediate(fn);
  17332. };
  17333. }
  17334. else {
  17335. async.setImmediate = async.nextTick;
  17336. }
  17337. }
  17338. async.each = function (arr, iterator, callback) {
  17339. callback = callback || function () {};
  17340. if (!arr.length) {
  17341. return callback();
  17342. }
  17343. var completed = 0;
  17344. _each(arr, function (x) {
  17345. iterator(x, only_once(done) );
  17346. });
  17347. function done(err) {
  17348. if (err) {
  17349. callback(err);
  17350. callback = function () {};
  17351. }
  17352. else {
  17353. completed += 1;
  17354. if (completed >= arr.length) {
  17355. callback();
  17356. }
  17357. }
  17358. }
  17359. };
  17360. async.forEach = async.each;
  17361. async.eachSeries = function (arr, iterator, callback) {
  17362. callback = callback || function () {};
  17363. if (!arr.length) {
  17364. return callback();
  17365. }
  17366. var completed = 0;
  17367. var iterate = function () {
  17368. iterator(arr[completed], function (err) {
  17369. if (err) {
  17370. callback(err);
  17371. callback = function () {};
  17372. }
  17373. else {
  17374. completed += 1;
  17375. if (completed >= arr.length) {
  17376. callback();
  17377. }
  17378. else {
  17379. iterate();
  17380. }
  17381. }
  17382. });
  17383. };
  17384. iterate();
  17385. };
  17386. async.forEachSeries = async.eachSeries;
  17387. async.eachLimit = function (arr, limit, iterator, callback) {
  17388. var fn = _eachLimit(limit);
  17389. fn.apply(null, [arr, iterator, callback]);
  17390. };
  17391. async.forEachLimit = async.eachLimit;
  17392. var _eachLimit = function (limit) {
  17393. return function (arr, iterator, callback) {
  17394. callback = callback || function () {};
  17395. if (!arr.length || limit <= 0) {
  17396. return callback();
  17397. }
  17398. var completed = 0;
  17399. var started = 0;
  17400. var running = 0;
  17401. (function replenish () {
  17402. if (completed >= arr.length) {
  17403. return callback();
  17404. }
  17405. while (running < limit && started < arr.length) {
  17406. started += 1;
  17407. running += 1;
  17408. iterator(arr[started - 1], function (err) {
  17409. if (err) {
  17410. callback(err);
  17411. callback = function () {};
  17412. }
  17413. else {
  17414. completed += 1;
  17415. running -= 1;
  17416. if (completed >= arr.length) {
  17417. callback();
  17418. }
  17419. else {
  17420. replenish();
  17421. }
  17422. }
  17423. });
  17424. }
  17425. })();
  17426. };
  17427. };
  17428. var doParallel = function (fn) {
  17429. return function () {
  17430. var args = Array.prototype.slice.call(arguments);
  17431. return fn.apply(null, [async.each].concat(args));
  17432. };
  17433. };
  17434. var doParallelLimit = function(limit, fn) {
  17435. return function () {
  17436. var args = Array.prototype.slice.call(arguments);
  17437. return fn.apply(null, [_eachLimit(limit)].concat(args));
  17438. };
  17439. };
  17440. var doSeries = function (fn) {
  17441. return function () {
  17442. var args = Array.prototype.slice.call(arguments);
  17443. return fn.apply(null, [async.eachSeries].concat(args));
  17444. };
  17445. };
  17446. var _asyncMap = function (eachfn, arr, iterator, callback) {
  17447. arr = _map(arr, function (x, i) {
  17448. return {index: i, value: x};
  17449. });
  17450. if (!callback) {
  17451. eachfn(arr, function (x, callback) {
  17452. iterator(x.value, function (err) {
  17453. callback(err);
  17454. });
  17455. });
  17456. } else {
  17457. var results = [];
  17458. eachfn(arr, function (x, callback) {
  17459. iterator(x.value, function (err, v) {
  17460. results[x.index] = v;
  17461. callback(err);
  17462. });
  17463. }, function (err) {
  17464. callback(err, results);
  17465. });
  17466. }
  17467. };
  17468. async.map = doParallel(_asyncMap);
  17469. async.mapSeries = doSeries(_asyncMap);
  17470. async.mapLimit = function (arr, limit, iterator, callback) {
  17471. return _mapLimit(limit)(arr, iterator, callback);
  17472. };
  17473. var _mapLimit = function(limit) {
  17474. return doParallelLimit(limit, _asyncMap);
  17475. };
  17476. // reduce only has a series version, as doing reduce in parallel won't
  17477. // work in many situations.
  17478. async.reduce = function (arr, memo, iterator, callback) {
  17479. async.eachSeries(arr, function (x, callback) {
  17480. iterator(memo, x, function (err, v) {
  17481. memo = v;
  17482. callback(err);
  17483. });
  17484. }, function (err) {
  17485. callback(err, memo);
  17486. });
  17487. };
  17488. // inject alias
  17489. async.inject = async.reduce;
  17490. // foldl alias
  17491. async.foldl = async.reduce;
  17492. async.reduceRight = function (arr, memo, iterator, callback) {
  17493. var reversed = _map(arr, function (x) {
  17494. return x;
  17495. }).reverse();
  17496. async.reduce(reversed, memo, iterator, callback);
  17497. };
  17498. // foldr alias
  17499. async.foldr = async.reduceRight;
  17500. var _filter = function (eachfn, arr, iterator, callback) {
  17501. var results = [];
  17502. arr = _map(arr, function (x, i) {
  17503. return {index: i, value: x};
  17504. });
  17505. eachfn(arr, function (x, callback) {
  17506. iterator(x.value, function (v) {
  17507. if (v) {
  17508. results.push(x);
  17509. }
  17510. callback();
  17511. });
  17512. }, function (err) {
  17513. callback(_map(results.sort(function (a, b) {
  17514. return a.index - b.index;
  17515. }), function (x) {
  17516. return x.value;
  17517. }));
  17518. });
  17519. };
  17520. async.filter = doParallel(_filter);
  17521. async.filterSeries = doSeries(_filter);
  17522. // select alias
  17523. async.select = async.filter;
  17524. async.selectSeries = async.filterSeries;
  17525. var _reject = function (eachfn, arr, iterator, callback) {
  17526. var results = [];
  17527. arr = _map(arr, function (x, i) {
  17528. return {index: i, value: x};
  17529. });
  17530. eachfn(arr, function (x, callback) {
  17531. iterator(x.value, function (v) {
  17532. if (!v) {
  17533. results.push(x);
  17534. }
  17535. callback();
  17536. });
  17537. }, function (err) {
  17538. callback(_map(results.sort(function (a, b) {
  17539. return a.index - b.index;
  17540. }), function (x) {
  17541. return x.value;
  17542. }));
  17543. });
  17544. };
  17545. async.reject = doParallel(_reject);
  17546. async.rejectSeries = doSeries(_reject);
  17547. var _detect = function (eachfn, arr, iterator, main_callback) {
  17548. eachfn(arr, function (x, callback) {
  17549. iterator(x, function (result) {
  17550. if (result) {
  17551. main_callback(x);
  17552. main_callback = function () {};
  17553. }
  17554. else {
  17555. callback();
  17556. }
  17557. });
  17558. }, function (err) {
  17559. main_callback();
  17560. });
  17561. };
  17562. async.detect = doParallel(_detect);
  17563. async.detectSeries = doSeries(_detect);
  17564. async.some = function (arr, iterator, main_callback) {
  17565. async.each(arr, function (x, callback) {
  17566. iterator(x, function (v) {
  17567. if (v) {
  17568. main_callback(true);
  17569. main_callback = function () {};
  17570. }
  17571. callback();
  17572. });
  17573. }, function (err) {
  17574. main_callback(false);
  17575. });
  17576. };
  17577. // any alias
  17578. async.any = async.some;
  17579. async.every = function (arr, iterator, main_callback) {
  17580. async.each(arr, function (x, callback) {
  17581. iterator(x, function (v) {
  17582. if (!v) {
  17583. main_callback(false);
  17584. main_callback = function () {};
  17585. }
  17586. callback();
  17587. });
  17588. }, function (err) {
  17589. main_callback(true);
  17590. });
  17591. };
  17592. // all alias
  17593. async.all = async.every;
  17594. async.sortBy = function (arr, iterator, callback) {
  17595. async.map(arr, function (x, callback) {
  17596. iterator(x, function (err, criteria) {
  17597. if (err) {
  17598. callback(err);
  17599. }
  17600. else {
  17601. callback(null, {value: x, criteria: criteria});
  17602. }
  17603. });
  17604. }, function (err, results) {
  17605. if (err) {
  17606. return callback(err);
  17607. }
  17608. else {
  17609. var fn = function (left, right) {
  17610. var a = left.criteria, b = right.criteria;
  17611. return a < b ? -1 : a > b ? 1 : 0;
  17612. };
  17613. callback(null, _map(results.sort(fn), function (x) {
  17614. return x.value;
  17615. }));
  17616. }
  17617. });
  17618. };
  17619. async.auto = function (tasks, callback) {
  17620. callback = callback || function () {};
  17621. var keys = _keys(tasks);
  17622. var remainingTasks = keys.length
  17623. if (!remainingTasks) {
  17624. return callback();
  17625. }
  17626. var results = {};
  17627. var listeners = [];
  17628. var addListener = function (fn) {
  17629. listeners.unshift(fn);
  17630. };
  17631. var removeListener = function (fn) {
  17632. for (var i = 0; i < listeners.length; i += 1) {
  17633. if (listeners[i] === fn) {
  17634. listeners.splice(i, 1);
  17635. return;
  17636. }
  17637. }
  17638. };
  17639. var taskComplete = function () {
  17640. remainingTasks--
  17641. _each(listeners.slice(0), function (fn) {
  17642. fn();
  17643. });
  17644. };
  17645. addListener(function () {
  17646. if (!remainingTasks) {
  17647. var theCallback = callback;
  17648. // prevent final callback from calling itself if it errors
  17649. callback = function () {};
  17650. theCallback(null, results);
  17651. }
  17652. });
  17653. _each(keys, function (k) {
  17654. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17655. var taskCallback = function (err) {
  17656. var args = Array.prototype.slice.call(arguments, 1);
  17657. if (args.length <= 1) {
  17658. args = args[0];
  17659. }
  17660. if (err) {
  17661. var safeResults = {};
  17662. _each(_keys(results), function(rkey) {
  17663. safeResults[rkey] = results[rkey];
  17664. });
  17665. safeResults[k] = args;
  17666. callback(err, safeResults);
  17667. // stop subsequent errors hitting callback multiple times
  17668. callback = function () {};
  17669. }
  17670. else {
  17671. results[k] = args;
  17672. async.setImmediate(taskComplete);
  17673. }
  17674. };
  17675. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17676. var ready = function () {
  17677. return _reduce(requires, function (a, x) {
  17678. return (a && results.hasOwnProperty(x));
  17679. }, true) && !results.hasOwnProperty(k);
  17680. };
  17681. if (ready()) {
  17682. task[task.length - 1](taskCallback, results);
  17683. }
  17684. else {
  17685. var listener = function () {
  17686. if (ready()) {
  17687. removeListener(listener);
  17688. task[task.length - 1](taskCallback, results);
  17689. }
  17690. };
  17691. addListener(listener);
  17692. }
  17693. });
  17694. };
  17695. async.retry = function(times, task, callback) {
  17696. var DEFAULT_TIMES = 5;
  17697. var attempts = [];
  17698. // Use defaults if times not passed
  17699. if (typeof times === 'function') {
  17700. callback = task;
  17701. task = times;
  17702. times = DEFAULT_TIMES;
  17703. }
  17704. // Make sure times is a number
  17705. times = parseInt(times, 10) || DEFAULT_TIMES;
  17706. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17707. var retryAttempt = function(task, finalAttempt) {
  17708. return function(seriesCallback) {
  17709. task(function(err, result){
  17710. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17711. }, wrappedResults);
  17712. };
  17713. };
  17714. while (times) {
  17715. attempts.push(retryAttempt(task, !(times-=1)));
  17716. }
  17717. async.series(attempts, function(done, data){
  17718. data = data[data.length - 1];
  17719. (wrappedCallback || callback)(data.err, data.result);
  17720. });
  17721. }
  17722. // If a callback is passed, run this as a controll flow
  17723. return callback ? wrappedTask() : wrappedTask
  17724. };
  17725. async.waterfall = function (tasks, callback) {
  17726. callback = callback || function () {};
  17727. if (!_isArray(tasks)) {
  17728. var err = new Error('First argument to waterfall must be an array of functions');
  17729. return callback(err);
  17730. }
  17731. if (!tasks.length) {
  17732. return callback();
  17733. }
  17734. var wrapIterator = function (iterator) {
  17735. return function (err) {
  17736. if (err) {
  17737. callback.apply(null, arguments);
  17738. callback = function () {};
  17739. }
  17740. else {
  17741. var args = Array.prototype.slice.call(arguments, 1);
  17742. var next = iterator.next();
  17743. if (next) {
  17744. args.push(wrapIterator(next));
  17745. }
  17746. else {
  17747. args.push(callback);
  17748. }
  17749. async.setImmediate(function () {
  17750. iterator.apply(null, args);
  17751. });
  17752. }
  17753. };
  17754. };
  17755. wrapIterator(async.iterator(tasks))();
  17756. };
  17757. var _parallel = function(eachfn, tasks, callback) {
  17758. callback = callback || function () {};
  17759. if (_isArray(tasks)) {
  17760. eachfn.map(tasks, function (fn, callback) {
  17761. if (fn) {
  17762. fn(function (err) {
  17763. var args = Array.prototype.slice.call(arguments, 1);
  17764. if (args.length <= 1) {
  17765. args = args[0];
  17766. }
  17767. callback.call(null, err, args);
  17768. });
  17769. }
  17770. }, callback);
  17771. }
  17772. else {
  17773. var results = {};
  17774. eachfn.each(_keys(tasks), function (k, callback) {
  17775. tasks[k](function (err) {
  17776. var args = Array.prototype.slice.call(arguments, 1);
  17777. if (args.length <= 1) {
  17778. args = args[0];
  17779. }
  17780. results[k] = args;
  17781. callback(err);
  17782. });
  17783. }, function (err) {
  17784. callback(err, results);
  17785. });
  17786. }
  17787. };
  17788. async.parallel = function (tasks, callback) {
  17789. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17790. };
  17791. async.parallelLimit = function(tasks, limit, callback) {
  17792. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17793. };
  17794. async.series = function (tasks, callback) {
  17795. callback = callback || function () {};
  17796. if (_isArray(tasks)) {
  17797. async.mapSeries(tasks, function (fn, callback) {
  17798. if (fn) {
  17799. fn(function (err) {
  17800. var args = Array.prototype.slice.call(arguments, 1);
  17801. if (args.length <= 1) {
  17802. args = args[0];
  17803. }
  17804. callback.call(null, err, args);
  17805. });
  17806. }
  17807. }, callback);
  17808. }
  17809. else {
  17810. var results = {};
  17811. async.eachSeries(_keys(tasks), function (k, callback) {
  17812. tasks[k](function (err) {
  17813. var args = Array.prototype.slice.call(arguments, 1);
  17814. if (args.length <= 1) {
  17815. args = args[0];
  17816. }
  17817. results[k] = args;
  17818. callback(err);
  17819. });
  17820. }, function (err) {
  17821. callback(err, results);
  17822. });
  17823. }
  17824. };
  17825. async.iterator = function (tasks) {
  17826. var makeCallback = function (index) {
  17827. var fn = function () {
  17828. if (tasks.length) {
  17829. tasks[index].apply(null, arguments);
  17830. }
  17831. return fn.next();
  17832. };
  17833. fn.next = function () {
  17834. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17835. };
  17836. return fn;
  17837. };
  17838. return makeCallback(0);
  17839. };
  17840. async.apply = function (fn) {
  17841. var args = Array.prototype.slice.call(arguments, 1);
  17842. return function () {
  17843. return fn.apply(
  17844. null, args.concat(Array.prototype.slice.call(arguments))
  17845. );
  17846. };
  17847. };
  17848. var _concat = function (eachfn, arr, fn, callback) {
  17849. var r = [];
  17850. eachfn(arr, function (x, cb) {
  17851. fn(x, function (err, y) {
  17852. r = r.concat(y || []);
  17853. cb(err);
  17854. });
  17855. }, function (err) {
  17856. callback(err, r);
  17857. });
  17858. };
  17859. async.concat = doParallel(_concat);
  17860. async.concatSeries = doSeries(_concat);
  17861. async.whilst = function (test, iterator, callback) {
  17862. if (test()) {
  17863. iterator(function (err) {
  17864. if (err) {
  17865. return callback(err);
  17866. }
  17867. async.whilst(test, iterator, callback);
  17868. });
  17869. }
  17870. else {
  17871. callback();
  17872. }
  17873. };
  17874. async.doWhilst = function (iterator, test, callback) {
  17875. iterator(function (err) {
  17876. if (err) {
  17877. return callback(err);
  17878. }
  17879. var args = Array.prototype.slice.call(arguments, 1);
  17880. if (test.apply(null, args)) {
  17881. async.doWhilst(iterator, test, callback);
  17882. }
  17883. else {
  17884. callback();
  17885. }
  17886. });
  17887. };
  17888. async.until = function (test, iterator, callback) {
  17889. if (!test()) {
  17890. iterator(function (err) {
  17891. if (err) {
  17892. return callback(err);
  17893. }
  17894. async.until(test, iterator, callback);
  17895. });
  17896. }
  17897. else {
  17898. callback();
  17899. }
  17900. };
  17901. async.doUntil = function (iterator, test, callback) {
  17902. iterator(function (err) {
  17903. if (err) {
  17904. return callback(err);
  17905. }
  17906. var args = Array.prototype.slice.call(arguments, 1);
  17907. if (!test.apply(null, args)) {
  17908. async.doUntil(iterator, test, callback);
  17909. }
  17910. else {
  17911. callback();
  17912. }
  17913. });
  17914. };
  17915. async.queue = function (worker, concurrency) {
  17916. if (concurrency === undefined) {
  17917. concurrency = 1;
  17918. }
  17919. function _insert(q, data, pos, callback) {
  17920. if (!q.started){
  17921. q.started = true;
  17922. }
  17923. if (!_isArray(data)) {
  17924. data = [data];
  17925. }
  17926. if(data.length == 0) {
  17927. // call drain immediately if there are no tasks
  17928. return async.setImmediate(function() {
  17929. if (q.drain) {
  17930. q.drain();
  17931. }
  17932. });
  17933. }
  17934. _each(data, function(task) {
  17935. var item = {
  17936. data: task,
  17937. callback: typeof callback === 'function' ? callback : null
  17938. };
  17939. if (pos) {
  17940. q.tasks.unshift(item);
  17941. } else {
  17942. q.tasks.push(item);
  17943. }
  17944. if (q.saturated && q.tasks.length === q.concurrency) {
  17945. q.saturated();
  17946. }
  17947. async.setImmediate(q.process);
  17948. });
  17949. }
  17950. var workers = 0;
  17951. var q = {
  17952. tasks: [],
  17953. concurrency: concurrency,
  17954. saturated: null,
  17955. empty: null,
  17956. drain: null,
  17957. started: false,
  17958. paused: false,
  17959. push: function (data, callback) {
  17960. _insert(q, data, false, callback);
  17961. },
  17962. kill: function () {
  17963. q.drain = null;
  17964. q.tasks = [];
  17965. },
  17966. unshift: function (data, callback) {
  17967. _insert(q, data, true, callback);
  17968. },
  17969. process: function () {
  17970. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17971. var task = q.tasks.shift();
  17972. if (q.empty && q.tasks.length === 0) {
  17973. q.empty();
  17974. }
  17975. workers += 1;
  17976. var next = function () {
  17977. workers -= 1;
  17978. if (task.callback) {
  17979. task.callback.apply(task, arguments);
  17980. }
  17981. if (q.drain && q.tasks.length + workers === 0) {
  17982. q.drain();
  17983. }
  17984. q.process();
  17985. };
  17986. var cb = only_once(next);
  17987. worker(task.data, cb);
  17988. }
  17989. },
  17990. length: function () {
  17991. return q.tasks.length;
  17992. },
  17993. running: function () {
  17994. return workers;
  17995. },
  17996. idle: function() {
  17997. return q.tasks.length + workers === 0;
  17998. },
  17999. pause: function () {
  18000. if (q.paused === true) { return; }
  18001. q.paused = true;
  18002. q.process();
  18003. },
  18004. resume: function () {
  18005. if (q.paused === false) { return; }
  18006. q.paused = false;
  18007. q.process();
  18008. }
  18009. };
  18010. return q;
  18011. };
  18012. async.priorityQueue = function (worker, concurrency) {
  18013. function _compareTasks(a, b){
  18014. return a.priority - b.priority;
  18015. };
  18016. function _binarySearch(sequence, item, compare) {
  18017. var beg = -1,
  18018. end = sequence.length - 1;
  18019. while (beg < end) {
  18020. var mid = beg + ((end - beg + 1) >>> 1);
  18021. if (compare(item, sequence[mid]) >= 0) {
  18022. beg = mid;
  18023. } else {
  18024. end = mid - 1;
  18025. }
  18026. }
  18027. return beg;
  18028. }
  18029. function _insert(q, data, priority, callback) {
  18030. if (!q.started){
  18031. q.started = true;
  18032. }
  18033. if (!_isArray(data)) {
  18034. data = [data];
  18035. }
  18036. if(data.length == 0) {
  18037. // call drain immediately if there are no tasks
  18038. return async.setImmediate(function() {
  18039. if (q.drain) {
  18040. q.drain();
  18041. }
  18042. });
  18043. }
  18044. _each(data, function(task) {
  18045. var item = {
  18046. data: task,
  18047. priority: priority,
  18048. callback: typeof callback === 'function' ? callback : null
  18049. };
  18050. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  18051. if (q.saturated && q.tasks.length === q.concurrency) {
  18052. q.saturated();
  18053. }
  18054. async.setImmediate(q.process);
  18055. });
  18056. }
  18057. // Start with a normal queue
  18058. var q = async.queue(worker, concurrency);
  18059. // Override push to accept second parameter representing priority
  18060. q.push = function (data, priority, callback) {
  18061. _insert(q, data, priority, callback);
  18062. };
  18063. // Remove unshift function
  18064. delete q.unshift;
  18065. return q;
  18066. };
  18067. async.cargo = function (worker, payload) {
  18068. var working = false,
  18069. tasks = [];
  18070. var cargo = {
  18071. tasks: tasks,
  18072. payload: payload,
  18073. saturated: null,
  18074. empty: null,
  18075. drain: null,
  18076. drained: true,
  18077. push: function (data, callback) {
  18078. if (!_isArray(data)) {
  18079. data = [data];
  18080. }
  18081. _each(data, function(task) {
  18082. tasks.push({
  18083. data: task,
  18084. callback: typeof callback === 'function' ? callback : null
  18085. });
  18086. cargo.drained = false;
  18087. if (cargo.saturated && tasks.length === payload) {
  18088. cargo.saturated();
  18089. }
  18090. });
  18091. async.setImmediate(cargo.process);
  18092. },
  18093. process: function process() {
  18094. if (working) return;
  18095. if (tasks.length === 0) {
  18096. if(cargo.drain && !cargo.drained) cargo.drain();
  18097. cargo.drained = true;
  18098. return;
  18099. }
  18100. var ts = typeof payload === 'number'
  18101. ? tasks.splice(0, payload)
  18102. : tasks.splice(0, tasks.length);
  18103. var ds = _map(ts, function (task) {
  18104. return task.data;
  18105. });
  18106. if(cargo.empty) cargo.empty();
  18107. working = true;
  18108. worker(ds, function () {
  18109. working = false;
  18110. var args = arguments;
  18111. _each(ts, function (data) {
  18112. if (data.callback) {
  18113. data.callback.apply(null, args);
  18114. }
  18115. });
  18116. process();
  18117. });
  18118. },
  18119. length: function () {
  18120. return tasks.length;
  18121. },
  18122. running: function () {
  18123. return working;
  18124. }
  18125. };
  18126. return cargo;
  18127. };
  18128. var _console_fn = function (name) {
  18129. return function (fn) {
  18130. var args = Array.prototype.slice.call(arguments, 1);
  18131. fn.apply(null, args.concat([function (err) {
  18132. var args = Array.prototype.slice.call(arguments, 1);
  18133. if (typeof console !== 'undefined') {
  18134. if (err) {
  18135. if (console.error) {
  18136. console.error(err);
  18137. }
  18138. }
  18139. else if (console[name]) {
  18140. _each(args, function (x) {
  18141. console[name](x);
  18142. });
  18143. }
  18144. }
  18145. }]));
  18146. };
  18147. };
  18148. async.log = _console_fn('log');
  18149. async.dir = _console_fn('dir');
  18150. /*async.info = _console_fn('info');
  18151. async.warn = _console_fn('warn');
  18152. async.error = _console_fn('error');*/
  18153. async.memoize = function (fn, hasher) {
  18154. var memo = {};
  18155. var queues = {};
  18156. hasher = hasher || function (x) {
  18157. return x;
  18158. };
  18159. var memoized = function () {
  18160. var args = Array.prototype.slice.call(arguments);
  18161. var callback = args.pop();
  18162. var key = hasher.apply(null, args);
  18163. if (key in memo) {
  18164. async.nextTick(function () {
  18165. callback.apply(null, memo[key]);
  18166. });
  18167. }
  18168. else if (key in queues) {
  18169. queues[key].push(callback);
  18170. }
  18171. else {
  18172. queues[key] = [callback];
  18173. fn.apply(null, args.concat([function () {
  18174. memo[key] = arguments;
  18175. var q = queues[key];
  18176. delete queues[key];
  18177. for (var i = 0, l = q.length; i < l; i++) {
  18178. q[i].apply(null, arguments);
  18179. }
  18180. }]));
  18181. }
  18182. };
  18183. memoized.memo = memo;
  18184. memoized.unmemoized = fn;
  18185. return memoized;
  18186. };
  18187. async.unmemoize = function (fn) {
  18188. return function () {
  18189. return (fn.unmemoized || fn).apply(null, arguments);
  18190. };
  18191. };
  18192. async.times = function (count, iterator, callback) {
  18193. var counter = [];
  18194. for (var i = 0; i < count; i++) {
  18195. counter.push(i);
  18196. }
  18197. return async.map(counter, iterator, callback);
  18198. };
  18199. async.timesSeries = function (count, iterator, callback) {
  18200. var counter = [];
  18201. for (var i = 0; i < count; i++) {
  18202. counter.push(i);
  18203. }
  18204. return async.mapSeries(counter, iterator, callback);
  18205. };
  18206. async.seq = function (/* functions... */) {
  18207. var fns = arguments;
  18208. return function () {
  18209. var that = this;
  18210. var args = Array.prototype.slice.call(arguments);
  18211. var callback = args.pop();
  18212. async.reduce(fns, args, function (newargs, fn, cb) {
  18213. fn.apply(that, newargs.concat([function () {
  18214. var err = arguments[0];
  18215. var nextargs = Array.prototype.slice.call(arguments, 1);
  18216. cb(err, nextargs);
  18217. }]))
  18218. },
  18219. function (err, results) {
  18220. callback.apply(that, [err].concat(results));
  18221. });
  18222. };
  18223. };
  18224. async.compose = function (/* functions... */) {
  18225. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  18226. };
  18227. var _applyEach = function (eachfn, fns /*args...*/) {
  18228. var go = function () {
  18229. var that = this;
  18230. var args = Array.prototype.slice.call(arguments);
  18231. var callback = args.pop();
  18232. return eachfn(fns, function (fn, cb) {
  18233. fn.apply(that, args.concat([cb]));
  18234. },
  18235. callback);
  18236. };
  18237. if (arguments.length > 2) {
  18238. var args = Array.prototype.slice.call(arguments, 2);
  18239. return go.apply(this, args);
  18240. }
  18241. else {
  18242. return go;
  18243. }
  18244. };
  18245. async.applyEach = doParallel(_applyEach);
  18246. async.applyEachSeries = doSeries(_applyEach);
  18247. async.forever = function (fn, callback) {
  18248. function next(err) {
  18249. if (err) {
  18250. if (callback) {
  18251. return callback(err);
  18252. }
  18253. throw err;
  18254. }
  18255. fn(next);
  18256. }
  18257. next();
  18258. };
  18259. // Node.js
  18260. if (typeof module !== 'undefined' && module.exports) {
  18261. module.exports = async;
  18262. }
  18263. // AMD / RequireJS
  18264. else if (typeof define !== 'undefined' && define.amd) {
  18265. define([], function () {
  18266. return async;
  18267. });
  18268. }
  18269. // included directly via <script> tag
  18270. else {
  18271. root.async = async;
  18272. }
  18273. }());
  18274. }).call(this,require('_process'))
  18275. },{"_process":2}],72:[function(require,module,exports){
  18276. // i18next, v1.7.7
  18277. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  18278. // Distributed under MIT license
  18279. // http://i18next.com
  18280. (function() {
  18281. // add indexOf to non ECMA-262 standard compliant browsers
  18282. if (!Array.prototype.indexOf) {
  18283. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  18284. "use strict";
  18285. if (this == null) {
  18286. throw new TypeError();
  18287. }
  18288. var t = Object(this);
  18289. var len = t.length >>> 0;
  18290. if (len === 0) {
  18291. return -1;
  18292. }
  18293. var n = 0;
  18294. if (arguments.length > 0) {
  18295. n = Number(arguments[1]);
  18296. if (n != n) { // shortcut for verifying if it's NaN
  18297. n = 0;
  18298. } else if (n != 0 && n != Infinity && n != -Infinity) {
  18299. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18300. }
  18301. }
  18302. if (n >= len) {
  18303. return -1;
  18304. }
  18305. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  18306. for (; k < len; k++) {
  18307. if (k in t && t[k] === searchElement) {
  18308. return k;
  18309. }
  18310. }
  18311. return -1;
  18312. }
  18313. }
  18314. // add lastIndexOf to non ECMA-262 standard compliant browsers
  18315. if (!Array.prototype.lastIndexOf) {
  18316. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  18317. "use strict";
  18318. if (this == null) {
  18319. throw new TypeError();
  18320. }
  18321. var t = Object(this);
  18322. var len = t.length >>> 0;
  18323. if (len === 0) {
  18324. return -1;
  18325. }
  18326. var n = len;
  18327. if (arguments.length > 1) {
  18328. n = Number(arguments[1]);
  18329. if (n != n) {
  18330. n = 0;
  18331. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  18332. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18333. }
  18334. }
  18335. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  18336. for (; k >= 0; k--) {
  18337. if (k in t && t[k] === searchElement) {
  18338. return k;
  18339. }
  18340. }
  18341. return -1;
  18342. };
  18343. }
  18344. // Add string trim for IE8.
  18345. if (typeof String.prototype.trim !== 'function') {
  18346. String.prototype.trim = function() {
  18347. return this.replace(/^\s+|\s+$/g, '');
  18348. }
  18349. }
  18350. var root = this
  18351. , $ = root.jQuery || root.Zepto
  18352. , i18n = {}
  18353. , resStore = {}
  18354. , currentLng
  18355. , replacementCounter = 0
  18356. , languages = []
  18357. , initialized = false
  18358. , sync = {};
  18359. // Export the i18next object for **CommonJS**.
  18360. // If we're not in CommonJS, add `i18n` to the
  18361. // global object or to jquery.
  18362. if (typeof module !== 'undefined' && module.exports) {
  18363. if (!$) {
  18364. try {
  18365. $ = require('jquery');
  18366. } catch(e) {
  18367. // just ignore
  18368. }
  18369. }
  18370. if ($) {
  18371. $.i18n = $.i18n || i18n;
  18372. }
  18373. module.exports = i18n;
  18374. } else {
  18375. if ($) {
  18376. $.i18n = $.i18n || i18n;
  18377. }
  18378. root.i18n = root.i18n || i18n;
  18379. }
  18380. sync = {
  18381. load: function(lngs, options, cb) {
  18382. if (options.useLocalStorage) {
  18383. sync._loadLocal(lngs, options, function(err, store) {
  18384. var missingLngs = [];
  18385. for (var i = 0, len = lngs.length; i < len; i++) {
  18386. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  18387. }
  18388. if (missingLngs.length > 0) {
  18389. sync._fetch(missingLngs, options, function(err, fetched) {
  18390. f.extend(store, fetched);
  18391. sync._storeLocal(fetched);
  18392. cb(null, store);
  18393. });
  18394. } else {
  18395. cb(null, store);
  18396. }
  18397. });
  18398. } else {
  18399. sync._fetch(lngs, options, function(err, store){
  18400. cb(null, store);
  18401. });
  18402. }
  18403. },
  18404. _loadLocal: function(lngs, options, cb) {
  18405. var store = {}
  18406. , nowMS = new Date().getTime();
  18407. if(window.localStorage) {
  18408. var todo = lngs.length;
  18409. f.each(lngs, function(key, lng) {
  18410. var local = window.localStorage.getItem('res_' + lng);
  18411. if (local) {
  18412. local = JSON.parse(local);
  18413. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  18414. store[lng] = local;
  18415. }
  18416. }
  18417. todo--; // wait for all done befor callback
  18418. if (todo === 0) cb(null, store);
  18419. });
  18420. }
  18421. },
  18422. _storeLocal: function(store) {
  18423. if(window.localStorage) {
  18424. for (var m in store) {
  18425. store[m].i18nStamp = new Date().getTime();
  18426. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  18427. }
  18428. }
  18429. return;
  18430. },
  18431. _fetch: function(lngs, options, cb) {
  18432. var ns = options.ns
  18433. , store = {};
  18434. if (!options.dynamicLoad) {
  18435. var todo = ns.namespaces.length * lngs.length
  18436. , errors;
  18437. // load each file individual
  18438. f.each(ns.namespaces, function(nsIndex, nsValue) {
  18439. f.each(lngs, function(lngIndex, lngValue) {
  18440. // Call this once our translation has returned.
  18441. var loadComplete = function(err, data) {
  18442. if (err) {
  18443. errors = errors || [];
  18444. errors.push(err);
  18445. }
  18446. store[lngValue] = store[lngValue] || {};
  18447. store[lngValue][nsValue] = data;
  18448. todo--; // wait for all done befor callback
  18449. if (todo === 0) cb(errors, store);
  18450. };
  18451. if(typeof options.customLoad == 'function'){
  18452. // Use the specified custom callback.
  18453. options.customLoad(lngValue, nsValue, options, loadComplete);
  18454. } else {
  18455. //~ // Use our inbuilt sync.
  18456. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  18457. }
  18458. });
  18459. });
  18460. } else {
  18461. // Call this once our translation has returned.
  18462. var loadComplete = function(err, data) {
  18463. cb(null, data);
  18464. };
  18465. if(typeof options.customLoad == 'function'){
  18466. // Use the specified custom callback.
  18467. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  18468. } else {
  18469. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  18470. // load all needed stuff once
  18471. f.ajax({
  18472. url: url,
  18473. success: function(data, status, xhr) {
  18474. f.log('loaded: ' + url);
  18475. loadComplete(null, data);
  18476. },
  18477. error : function(xhr, status, error) {
  18478. f.log('failed loading: ' + url);
  18479. loadComplete('failed loading resource.json error: ' + error);
  18480. },
  18481. dataType: "json",
  18482. async : options.getAsync
  18483. });
  18484. }
  18485. }
  18486. },
  18487. _fetchOne: function(lng, ns, options, done) {
  18488. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  18489. f.ajax({
  18490. url: url,
  18491. success: function(data, status, xhr) {
  18492. f.log('loaded: ' + url);
  18493. done(null, data);
  18494. },
  18495. error : function(xhr, status, error) {
  18496. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  18497. // file loaded but invalid json, stop waste time !
  18498. f.error('There is a typo in: ' + url);
  18499. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  18500. f.log('Does not exist: ' + url);
  18501. } else {
  18502. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  18503. f.log(theStatus + ' when loading ' + url);
  18504. }
  18505. done(error, {});
  18506. },
  18507. dataType: "json",
  18508. async : options.getAsync
  18509. });
  18510. },
  18511. postMissing: function(lng, ns, key, defaultValue, lngs) {
  18512. var payload = {};
  18513. payload[key] = defaultValue;
  18514. var urls = [];
  18515. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  18516. for (var i = 0; i < o.fallbackLng.length; i++) {
  18517. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  18518. }
  18519. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  18520. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  18521. } else if (o.sendMissingTo === 'all') {
  18522. for (var i = 0, l = lngs.length; i < l; i++) {
  18523. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  18524. }
  18525. }
  18526. for (var y = 0, len = urls.length; y < len; y++) {
  18527. var item = urls[y];
  18528. f.ajax({
  18529. url: item.url,
  18530. type: o.sendType,
  18531. data: payload,
  18532. success: function(data, status, xhr) {
  18533. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18534. // add key to resStore
  18535. var keys = key.split('.');
  18536. var x = 0;
  18537. var value = resStore[item.lng][ns];
  18538. while (keys[x]) {
  18539. if (x === keys.length - 1) {
  18540. value = value[keys[x]] = defaultValue;
  18541. } else {
  18542. value = value[keys[x]] = value[keys[x]] || {};
  18543. }
  18544. x++;
  18545. }
  18546. },
  18547. error : function(xhr, status, error) {
  18548. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18549. },
  18550. dataType: "json",
  18551. async : o.postAsync
  18552. });
  18553. }
  18554. },
  18555. reload: reload
  18556. };
  18557. // defaults
  18558. var o = {
  18559. lng: undefined,
  18560. load: 'all',
  18561. preload: [],
  18562. lowerCaseLng: false,
  18563. returnObjectTrees: false,
  18564. fallbackLng: ['dev'],
  18565. fallbackNS: [],
  18566. detectLngQS: 'setLng',
  18567. detectLngFromLocalStorage: false,
  18568. ns: 'translation',
  18569. fallbackOnNull: true,
  18570. fallbackOnEmpty: false,
  18571. fallbackToDefaultNS: false,
  18572. nsseparator: ':',
  18573. keyseparator: '.',
  18574. selectorAttr: 'data-i18n',
  18575. debug: false,
  18576. resGetPath: 'locales/__lng__/__ns__.json',
  18577. resPostPath: 'locales/add/__lng__/__ns__',
  18578. getAsync: true,
  18579. postAsync: true,
  18580. resStore: undefined,
  18581. useLocalStorage: false,
  18582. localStorageExpirationTime: 7*24*60*60*1000,
  18583. dynamicLoad: false,
  18584. sendMissing: false,
  18585. sendMissingTo: 'fallback', // current | all
  18586. sendType: 'POST',
  18587. interpolationPrefix: '__',
  18588. interpolationSuffix: '__',
  18589. defaultVariables: false,
  18590. reusePrefix: '$t(',
  18591. reuseSuffix: ')',
  18592. pluralSuffix: '_plural',
  18593. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18594. contextNotFound: ['context_not_found', Math.random()].join(''),
  18595. escapeInterpolation: false,
  18596. indefiniteSuffix: '_indefinite',
  18597. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18598. setJqueryExt: true,
  18599. defaultValueFromContent: true,
  18600. useDataAttrOptions: false,
  18601. cookieExpirationTime: undefined,
  18602. useCookie: true,
  18603. cookieName: 'i18next',
  18604. cookieDomain: undefined,
  18605. objectTreeKeyHandler: undefined,
  18606. postProcess: undefined,
  18607. parseMissingKey: undefined,
  18608. missingKeyHandler: sync.postMissing,
  18609. shortcutFunction: 'sprintf' // or: defaultValue
  18610. };
  18611. function _extend(target, source) {
  18612. if (!source || typeof source === 'function') {
  18613. return target;
  18614. }
  18615. for (var attr in source) { target[attr] = source[attr]; }
  18616. return target;
  18617. }
  18618. function _deepExtend(target, source) {
  18619. for (var prop in source)
  18620. if (prop in target)
  18621. _deepExtend(target[prop], source[prop]);
  18622. else
  18623. target[prop] = source[prop];
  18624. return target;
  18625. }
  18626. function _each(object, callback, args) {
  18627. var name, i = 0,
  18628. length = object.length,
  18629. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18630. if (args) {
  18631. if (isObj) {
  18632. for (name in object) {
  18633. if (callback.apply(object[name], args) === false) {
  18634. break;
  18635. }
  18636. }
  18637. } else {
  18638. for ( ; i < length; ) {
  18639. if (callback.apply(object[i++], args) === false) {
  18640. break;
  18641. }
  18642. }
  18643. }
  18644. // A special, fast, case for the most common use of each
  18645. } else {
  18646. if (isObj) {
  18647. for (name in object) {
  18648. if (callback.call(object[name], name, object[name]) === false) {
  18649. break;
  18650. }
  18651. }
  18652. } else {
  18653. for ( ; i < length; ) {
  18654. if (callback.call(object[i], i, object[i++]) === false) {
  18655. break;
  18656. }
  18657. }
  18658. }
  18659. }
  18660. return object;
  18661. }
  18662. var _entityMap = {
  18663. "&": "&amp;",
  18664. "<": "&lt;",
  18665. ">": "&gt;",
  18666. '"': '&quot;',
  18667. "'": '&#39;',
  18668. "/": '&#x2F;'
  18669. };
  18670. function _escape(data) {
  18671. if (typeof data === 'string') {
  18672. return data.replace(/[&<>"'\/]/g, function (s) {
  18673. return _entityMap[s];
  18674. });
  18675. }else{
  18676. return data;
  18677. }
  18678. }
  18679. function _ajax(options) {
  18680. // v0.5.0 of https://github.com/goloroden/http.js
  18681. var getXhr = function (callback) {
  18682. // Use the native XHR object if the browser supports it.
  18683. if (window.XMLHttpRequest) {
  18684. return callback(null, new XMLHttpRequest());
  18685. } else if (window.ActiveXObject) {
  18686. // In Internet Explorer check for ActiveX versions of the XHR object.
  18687. try {
  18688. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18689. } catch (e) {
  18690. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18691. }
  18692. }
  18693. // If no XHR support was found, throw an error.
  18694. return callback(new Error());
  18695. };
  18696. var encodeUsingUrlEncoding = function (data) {
  18697. if(typeof data === 'string') {
  18698. return data;
  18699. }
  18700. var result = [];
  18701. for(var dataItem in data) {
  18702. if(data.hasOwnProperty(dataItem)) {
  18703. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18704. }
  18705. }
  18706. return result.join('&');
  18707. };
  18708. var utf8 = function (text) {
  18709. text = text.replace(/\r\n/g, '\n');
  18710. var result = '';
  18711. for(var i = 0; i < text.length; i++) {
  18712. var c = text.charCodeAt(i);
  18713. if(c < 128) {
  18714. result += String.fromCharCode(c);
  18715. } else if((c > 127) && (c < 2048)) {
  18716. result += String.fromCharCode((c >> 6) | 192);
  18717. result += String.fromCharCode((c & 63) | 128);
  18718. } else {
  18719. result += String.fromCharCode((c >> 12) | 224);
  18720. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18721. result += String.fromCharCode((c & 63) | 128);
  18722. }
  18723. }
  18724. return result;
  18725. };
  18726. var base64 = function (text) {
  18727. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18728. text = utf8(text);
  18729. var result = '',
  18730. chr1, chr2, chr3,
  18731. enc1, enc2, enc3, enc4,
  18732. i = 0;
  18733. do {
  18734. chr1 = text.charCodeAt(i++);
  18735. chr2 = text.charCodeAt(i++);
  18736. chr3 = text.charCodeAt(i++);
  18737. enc1 = chr1 >> 2;
  18738. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18739. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18740. enc4 = chr3 & 63;
  18741. if(isNaN(chr2)) {
  18742. enc3 = enc4 = 64;
  18743. } else if(isNaN(chr3)) {
  18744. enc4 = 64;
  18745. }
  18746. result +=
  18747. keyStr.charAt(enc1) +
  18748. keyStr.charAt(enc2) +
  18749. keyStr.charAt(enc3) +
  18750. keyStr.charAt(enc4);
  18751. chr1 = chr2 = chr3 = '';
  18752. enc1 = enc2 = enc3 = enc4 = '';
  18753. } while(i < text.length);
  18754. return result;
  18755. };
  18756. var mergeHeaders = function () {
  18757. // Use the first header object as base.
  18758. var result = arguments[0];
  18759. // Iterate through the remaining header objects and add them.
  18760. for(var i = 1; i < arguments.length; i++) {
  18761. var currentHeaders = arguments[i];
  18762. for(var header in currentHeaders) {
  18763. if(currentHeaders.hasOwnProperty(header)) {
  18764. result[header] = currentHeaders[header];
  18765. }
  18766. }
  18767. }
  18768. // Return the merged headers.
  18769. return result;
  18770. };
  18771. var ajax = function (method, url, options, callback) {
  18772. // Adjust parameters.
  18773. if(typeof options === 'function') {
  18774. callback = options;
  18775. options = {};
  18776. }
  18777. // Set default parameter values.
  18778. options.cache = options.cache || false;
  18779. options.data = options.data || {};
  18780. options.headers = options.headers || {};
  18781. options.jsonp = options.jsonp || false;
  18782. options.async = options.async === undefined ? true : options.async;
  18783. // Merge the various header objects.
  18784. var headers = mergeHeaders({
  18785. 'accept': '*/*',
  18786. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18787. }, ajax.headers, options.headers);
  18788. // Encode the data according to the content-type.
  18789. var payload;
  18790. if (headers['content-type'] === 'application/json') {
  18791. payload = JSON.stringify(options.data);
  18792. } else {
  18793. payload = encodeUsingUrlEncoding(options.data);
  18794. }
  18795. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18796. // if neccessary.
  18797. if(method === 'GET') {
  18798. // Setup the query string.
  18799. var queryString = [];
  18800. if(payload) {
  18801. queryString.push(payload);
  18802. payload = null;
  18803. }
  18804. // Handle caching.
  18805. if(!options.cache) {
  18806. queryString.push('_=' + (new Date()).getTime());
  18807. }
  18808. // If neccessary prepare the query string for a JSONP call.
  18809. if(options.jsonp) {
  18810. queryString.push('callback=' + options.jsonp);
  18811. queryString.push('jsonp=' + options.jsonp);
  18812. }
  18813. // Merge the query string and attach it to the url.
  18814. queryString = queryString.join('&');
  18815. if (queryString.length > 1) {
  18816. if (url.indexOf('?') > -1) {
  18817. url += '&' + queryString;
  18818. } else {
  18819. url += '?' + queryString;
  18820. }
  18821. }
  18822. // Make a JSONP call if neccessary.
  18823. if(options.jsonp) {
  18824. var head = document.getElementsByTagName('head')[0];
  18825. var script = document.createElement('script');
  18826. script.type = 'text/javascript';
  18827. script.src = url;
  18828. head.appendChild(script);
  18829. return;
  18830. }
  18831. }
  18832. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18833. getXhr(function (err, xhr) {
  18834. if(err) return callback(err);
  18835. // Open the request.
  18836. xhr.open(method, url, options.async);
  18837. // Set the request headers.
  18838. for(var header in headers) {
  18839. if(headers.hasOwnProperty(header)) {
  18840. xhr.setRequestHeader(header, headers[header]);
  18841. }
  18842. }
  18843. // Handle the request events.
  18844. xhr.onreadystatechange = function () {
  18845. if(xhr.readyState === 4) {
  18846. var data = xhr.responseText || '';
  18847. // If no callback is given, return.
  18848. if(!callback) {
  18849. return;
  18850. }
  18851. // Return an object that provides access to the data as text and JSON.
  18852. callback(xhr.status, {
  18853. text: function () {
  18854. return data;
  18855. },
  18856. json: function () {
  18857. try {
  18858. return JSON.parse(data)
  18859. } catch (e) {
  18860. f.error('Can not parse JSON. URL: ' + url);
  18861. return {};
  18862. }
  18863. }
  18864. });
  18865. }
  18866. };
  18867. // Actually send the XHR request.
  18868. xhr.send(payload);
  18869. });
  18870. };
  18871. // Define the external interface.
  18872. var http = {
  18873. authBasic: function (username, password) {
  18874. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18875. },
  18876. connect: function (url, options, callback) {
  18877. return ajax('CONNECT', url, options, callback);
  18878. },
  18879. del: function (url, options, callback) {
  18880. return ajax('DELETE', url, options, callback);
  18881. },
  18882. get: function (url, options, callback) {
  18883. return ajax('GET', url, options, callback);
  18884. },
  18885. head: function (url, options, callback) {
  18886. return ajax('HEAD', url, options, callback);
  18887. },
  18888. headers: function (headers) {
  18889. ajax.headers = headers || {};
  18890. },
  18891. isAllowed: function (url, verb, callback) {
  18892. this.options(url, function (status, data) {
  18893. callback(data.text().indexOf(verb) !== -1);
  18894. });
  18895. },
  18896. options: function (url, options, callback) {
  18897. return ajax('OPTIONS', url, options, callback);
  18898. },
  18899. patch: function (url, options, callback) {
  18900. return ajax('PATCH', url, options, callback);
  18901. },
  18902. post: function (url, options, callback) {
  18903. return ajax('POST', url, options, callback);
  18904. },
  18905. put: function (url, options, callback) {
  18906. return ajax('PUT', url, options, callback);
  18907. },
  18908. trace: function (url, options, callback) {
  18909. return ajax('TRACE', url, options, callback);
  18910. }
  18911. };
  18912. var methode = options.type ? options.type.toLowerCase() : 'get';
  18913. http[methode](options.url, options, function (status, data) {
  18914. // file: protocol always gives status code 0, so check for data
  18915. if (status === 200 || (status === 0 && data.text())) {
  18916. options.success(data.json(), status, null);
  18917. } else {
  18918. options.error(data.text(), status, null);
  18919. }
  18920. });
  18921. }
  18922. var _cookie = {
  18923. create: function(name,value,minutes,domain) {
  18924. var expires;
  18925. if (minutes) {
  18926. var date = new Date();
  18927. date.setTime(date.getTime()+(minutes*60*1000));
  18928. expires = "; expires="+date.toGMTString();
  18929. }
  18930. else expires = "";
  18931. domain = (domain)? "domain="+domain+";" : "";
  18932. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18933. },
  18934. read: function(name) {
  18935. var nameEQ = name + "=";
  18936. var ca = document.cookie.split(';');
  18937. for(var i=0;i < ca.length;i++) {
  18938. var c = ca[i];
  18939. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18940. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18941. }
  18942. return null;
  18943. },
  18944. remove: function(name) {
  18945. this.create(name,"",-1);
  18946. }
  18947. };
  18948. var cookie_noop = {
  18949. create: function(name,value,minutes,domain) {},
  18950. read: function(name) { return null; },
  18951. remove: function(name) {}
  18952. };
  18953. // move dependent functions to a container so that
  18954. // they can be overriden easier in no jquery environment (node.js)
  18955. var f = {
  18956. extend: $ ? $.extend : _extend,
  18957. deepExtend: _deepExtend,
  18958. each: $ ? $.each : _each,
  18959. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18960. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18961. detectLanguage: detectLanguage,
  18962. escape: _escape,
  18963. log: function(str) {
  18964. if (o.debug && typeof console !== "undefined") console.log(str);
  18965. },
  18966. error: function(str) {
  18967. if (typeof console !== "undefined") console.error(str);
  18968. },
  18969. getCountyIndexOfLng: function(lng) {
  18970. var lng_index = 0;
  18971. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18972. return lng_index;
  18973. },
  18974. toLanguages: function(lng) {
  18975. var log = this.log;
  18976. function applyCase(l) {
  18977. var ret = l;
  18978. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18979. var parts = l.split('-');
  18980. ret = o.lowerCaseLng ?
  18981. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18982. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18983. } else {
  18984. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18985. }
  18986. return ret;
  18987. }
  18988. var languages = [];
  18989. var whitelist = o.lngWhitelist || false;
  18990. var addLanguage = function(language){
  18991. //reject langs not whitelisted
  18992. if(!whitelist || whitelist.indexOf(language) > -1){
  18993. languages.push(language);
  18994. }else{
  18995. log('rejecting non-whitelisted language: ' + language);
  18996. }
  18997. };
  18998. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18999. var parts = lng.split('-');
  19000. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  19001. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  19002. } else {
  19003. addLanguage(applyCase(lng));
  19004. }
  19005. for (var i = 0; i < o.fallbackLng.length; i++) {
  19006. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  19007. }
  19008. return languages;
  19009. },
  19010. regexEscape: function(str) {
  19011. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  19012. },
  19013. regexReplacementEscape: function(strOrFn) {
  19014. if (typeof strOrFn === 'string') {
  19015. return strOrFn.replace(/\$/g, "$$$$");
  19016. } else {
  19017. return strOrFn;
  19018. }
  19019. },
  19020. localStorage: {
  19021. setItem: function(key, value) {
  19022. if (window.localStorage) {
  19023. try {
  19024. window.localStorage.setItem(key, value);
  19025. } catch (e) {
  19026. f.log('failed to set value for key "' + key + '" to localStorage.');
  19027. }
  19028. }
  19029. }
  19030. }
  19031. };
  19032. function init(options, cb) {
  19033. if (typeof options === 'function') {
  19034. cb = options;
  19035. options = {};
  19036. }
  19037. options = options || {};
  19038. // override defaults with passed in options
  19039. f.extend(o, options);
  19040. delete o.fixLng; /* passed in each time */
  19041. // override functions: .log(), .detectLanguage(), etc
  19042. if (o.functions) {
  19043. delete o.functions;
  19044. f.extend(f, options.functions);
  19045. }
  19046. // create namespace object if namespace is passed in as string
  19047. if (typeof o.ns == 'string') {
  19048. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  19049. }
  19050. // fallback namespaces
  19051. if (typeof o.fallbackNS == 'string') {
  19052. o.fallbackNS = [o.fallbackNS];
  19053. }
  19054. // fallback languages
  19055. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  19056. o.fallbackLng = [o.fallbackLng];
  19057. }
  19058. // escape prefix/suffix
  19059. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  19060. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  19061. if (!o.lng) o.lng = f.detectLanguage();
  19062. languages = f.toLanguages(o.lng);
  19063. currentLng = languages[0];
  19064. f.log('currentLng set to: ' + currentLng);
  19065. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  19066. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  19067. }
  19068. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  19069. f.localStorage.setItem('i18next_lng', currentLng);
  19070. }
  19071. var lngTranslate = translate;
  19072. if (options.fixLng) {
  19073. lngTranslate = function(key, options) {
  19074. options = options || {};
  19075. options.lng = options.lng || lngTranslate.lng;
  19076. return translate(key, options);
  19077. };
  19078. lngTranslate.lng = currentLng;
  19079. }
  19080. pluralExtensions.setCurrentLng(currentLng);
  19081. // add JQuery extensions
  19082. if ($ && o.setJqueryExt) addJqueryFunct();
  19083. // jQuery deferred
  19084. var deferred;
  19085. if ($ && $.Deferred) {
  19086. deferred = $.Deferred();
  19087. }
  19088. // return immidiatly if res are passed in
  19089. if (o.resStore) {
  19090. resStore = o.resStore;
  19091. initialized = true;
  19092. if (cb) cb(lngTranslate);
  19093. if (deferred) deferred.resolve(lngTranslate);
  19094. if (deferred) return deferred.promise();
  19095. return;
  19096. }
  19097. // languages to load
  19098. var lngsToLoad = f.toLanguages(o.lng);
  19099. if (typeof o.preload === 'string') o.preload = [o.preload];
  19100. for (var i = 0, l = o.preload.length; i < l; i++) {
  19101. var pres = f.toLanguages(o.preload[i]);
  19102. for (var y = 0, len = pres.length; y < len; y++) {
  19103. if (lngsToLoad.indexOf(pres[y]) < 0) {
  19104. lngsToLoad.push(pres[y]);
  19105. }
  19106. }
  19107. }
  19108. // else load them
  19109. i18n.sync.load(lngsToLoad, o, function(err, store) {
  19110. resStore = store;
  19111. initialized = true;
  19112. if (cb) cb(lngTranslate);
  19113. if (deferred) deferred.resolve(lngTranslate);
  19114. });
  19115. if (deferred) return deferred.promise();
  19116. }
  19117. function preload(lngs, cb) {
  19118. if (typeof lngs === 'string') lngs = [lngs];
  19119. for (var i = 0, l = lngs.length; i < l; i++) {
  19120. if (o.preload.indexOf(lngs[i]) < 0) {
  19121. o.preload.push(lngs[i]);
  19122. }
  19123. }
  19124. return init(cb);
  19125. }
  19126. function addResourceBundle(lng, ns, resources, deep) {
  19127. if (typeof ns !== 'string') {
  19128. resources = ns;
  19129. ns = o.ns.defaultNs;
  19130. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19131. o.ns.namespaces.push(ns);
  19132. }
  19133. resStore[lng] = resStore[lng] || {};
  19134. resStore[lng][ns] = resStore[lng][ns] || {};
  19135. if (deep) {
  19136. f.deepExtend(resStore[lng][ns], resources);
  19137. } else {
  19138. f.extend(resStore[lng][ns], resources);
  19139. }
  19140. }
  19141. function hasResourceBundle(lng, ns) {
  19142. if (typeof ns !== 'string') {
  19143. ns = o.ns.defaultNs;
  19144. }
  19145. resStore[lng] = resStore[lng] || {};
  19146. var res = resStore[lng][ns] || {};
  19147. var hasValues = false;
  19148. for(var prop in res) {
  19149. if (res.hasOwnProperty(prop)) {
  19150. hasValues = true;
  19151. }
  19152. }
  19153. return hasValues;
  19154. }
  19155. function removeResourceBundle(lng, ns) {
  19156. if (typeof ns !== 'string') {
  19157. ns = o.ns.defaultNs;
  19158. }
  19159. resStore[lng] = resStore[lng] || {};
  19160. resStore[lng][ns] = {};
  19161. }
  19162. function addResource(lng, ns, key, value) {
  19163. if (typeof ns !== 'string') {
  19164. resource = ns;
  19165. ns = o.ns.defaultNs;
  19166. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19167. o.ns.namespaces.push(ns);
  19168. }
  19169. resStore[lng] = resStore[lng] || {};
  19170. resStore[lng][ns] = resStore[lng][ns] || {};
  19171. var keys = key.split(o.keyseparator);
  19172. var x = 0;
  19173. var node = resStore[lng][ns];
  19174. var origRef = node;
  19175. while (keys[x]) {
  19176. if (x == keys.length - 1)
  19177. node[keys[x]] = value;
  19178. else {
  19179. if (node[keys[x]] == null)
  19180. node[keys[x]] = {};
  19181. node = node[keys[x]];
  19182. }
  19183. x++;
  19184. }
  19185. }
  19186. function addResources(lng, ns, resources) {
  19187. if (typeof ns !== 'string') {
  19188. resource = ns;
  19189. ns = o.ns.defaultNs;
  19190. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19191. o.ns.namespaces.push(ns);
  19192. }
  19193. for (var m in resources) {
  19194. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  19195. }
  19196. }
  19197. function setDefaultNamespace(ns) {
  19198. o.ns.defaultNs = ns;
  19199. }
  19200. function loadNamespace(namespace, cb) {
  19201. loadNamespaces([namespace], cb);
  19202. }
  19203. function loadNamespaces(namespaces, cb) {
  19204. var opts = {
  19205. dynamicLoad: o.dynamicLoad,
  19206. resGetPath: o.resGetPath,
  19207. getAsync: o.getAsync,
  19208. customLoad: o.customLoad,
  19209. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  19210. };
  19211. // languages to load
  19212. var lngsToLoad = f.toLanguages(o.lng);
  19213. if (typeof o.preload === 'string') o.preload = [o.preload];
  19214. for (var i = 0, l = o.preload.length; i < l; i++) {
  19215. var pres = f.toLanguages(o.preload[i]);
  19216. for (var y = 0, len = pres.length; y < len; y++) {
  19217. if (lngsToLoad.indexOf(pres[y]) < 0) {
  19218. lngsToLoad.push(pres[y]);
  19219. }
  19220. }
  19221. }
  19222. // check if we have to load
  19223. var lngNeedLoad = [];
  19224. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  19225. var needLoad = false;
  19226. var resSet = resStore[lngsToLoad[a]];
  19227. if (resSet) {
  19228. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  19229. if (!resSet[namespaces[b]]) needLoad = true;
  19230. }
  19231. } else {
  19232. needLoad = true;
  19233. }
  19234. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  19235. }
  19236. if (lngNeedLoad.length) {
  19237. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  19238. var todo = namespaces.length * lngNeedLoad.length;
  19239. // load each file individual
  19240. f.each(namespaces, function(nsIndex, nsValue) {
  19241. // append namespace to namespace array
  19242. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  19243. o.ns.namespaces.push(nsValue);
  19244. }
  19245. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  19246. resStore[lngValue] = resStore[lngValue] || {};
  19247. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  19248. todo--; // wait for all done befor callback
  19249. if (todo === 0 && cb) {
  19250. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  19251. cb();
  19252. }
  19253. });
  19254. });
  19255. });
  19256. } else {
  19257. if (cb) cb();
  19258. }
  19259. }
  19260. function setLng(lng, options, cb) {
  19261. if (typeof options === 'function') {
  19262. cb = options;
  19263. options = {};
  19264. } else if (!options) {
  19265. options = {};
  19266. }
  19267. options.lng = lng;
  19268. return init(options, cb);
  19269. }
  19270. function lng() {
  19271. return currentLng;
  19272. }
  19273. function reload(cb) {
  19274. resStore = {};
  19275. setLng(currentLng, cb);
  19276. }
  19277. function addJqueryFunct() {
  19278. // $.t shortcut
  19279. $.t = $.t || translate;
  19280. function parse(ele, key, options) {
  19281. if (key.length === 0) return;
  19282. var attr = 'text';
  19283. if (key.indexOf('[') === 0) {
  19284. var parts = key.split(']');
  19285. key = parts[1];
  19286. attr = parts[0].substr(1, parts[0].length-1);
  19287. }
  19288. if (key.indexOf(';') === key.length-1) {
  19289. key = key.substr(0, key.length-2);
  19290. }
  19291. var optionsToUse;
  19292. if (attr === 'html') {
  19293. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19294. ele.html($.t(key, optionsToUse));
  19295. } else if (attr === 'text') {
  19296. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  19297. ele.text($.t(key, optionsToUse));
  19298. } else if (attr === 'prepend') {
  19299. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19300. ele.prepend($.t(key, optionsToUse));
  19301. } else if (attr === 'append') {
  19302. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19303. ele.append($.t(key, optionsToUse));
  19304. } else if (attr.indexOf("data-") === 0) {
  19305. var dataAttr = attr.substr(("data-").length);
  19306. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  19307. var translated = $.t(key, optionsToUse);
  19308. //we change into the data cache
  19309. ele.data(dataAttr, translated);
  19310. //we change into the dom
  19311. ele.attr(attr, translated);
  19312. } else {
  19313. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  19314. ele.attr(attr, $.t(key, optionsToUse));
  19315. }
  19316. }
  19317. function localize(ele, options) {
  19318. var key = ele.attr(o.selectorAttr);
  19319. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  19320. if (!key) return;
  19321. var target = ele
  19322. , targetSelector = ele.data("i18n-target");
  19323. if (targetSelector) {
  19324. target = ele.find(targetSelector) || ele;
  19325. }
  19326. if (!options && o.useDataAttrOptions === true) {
  19327. options = ele.data("i18n-options");
  19328. }
  19329. options = options || {};
  19330. if (key.indexOf(';') >= 0) {
  19331. var keys = key.split(';');
  19332. $.each(keys, function(m, k) {
  19333. if (k !== '') parse(target, k, options);
  19334. });
  19335. } else {
  19336. parse(target, key, options);
  19337. }
  19338. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  19339. }
  19340. // fn
  19341. $.fn.i18n = function (options) {
  19342. return this.each(function() {
  19343. // localize element itself
  19344. localize($(this), options);
  19345. // localize childs
  19346. var elements = $(this).find('[' + o.selectorAttr + ']');
  19347. elements.each(function() {
  19348. localize($(this), options);
  19349. });
  19350. });
  19351. };
  19352. }
  19353. function applyReplacement(str, replacementHash, nestedKey, options) {
  19354. if (!str) return str;
  19355. options = options || replacementHash; // first call uses replacement hash combined with options
  19356. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  19357. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  19358. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  19359. , unEscapingSuffix = 'HTML'+suffix;
  19360. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  19361. f.each(hash, function(key, value) {
  19362. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  19363. if (typeof value === 'object' && value !== null) {
  19364. str = applyReplacement(str, value, nextKey, options);
  19365. } else {
  19366. if (options.escapeInterpolation || o.escapeInterpolation) {
  19367. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  19368. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  19369. } else {
  19370. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  19371. }
  19372. // str = options.escapeInterpolation;
  19373. }
  19374. });
  19375. return str;
  19376. }
  19377. // append it to functions
  19378. f.applyReplacement = applyReplacement;
  19379. function applyReuse(translated, options) {
  19380. var comma = ',';
  19381. var options_open = '{';
  19382. var options_close = '}';
  19383. var opts = f.extend({}, options);
  19384. delete opts.postProcess;
  19385. while (translated.indexOf(o.reusePrefix) != -1) {
  19386. replacementCounter++;
  19387. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  19388. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  19389. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  19390. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  19391. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  19392. if (index_of_end_of_closing <= index_of_opening) {
  19393. f.error('there is an missing closing in following translation value', translated);
  19394. return '';
  19395. }
  19396. if (token_without_symbols.indexOf(comma) != -1) {
  19397. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  19398. 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) {
  19399. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  19400. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  19401. try {
  19402. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  19403. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  19404. } catch (e) {
  19405. }
  19406. }
  19407. }
  19408. var translated_token = _translate(token_without_symbols, opts);
  19409. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  19410. }
  19411. return translated;
  19412. }
  19413. function hasContext(options) {
  19414. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  19415. }
  19416. function needsPlural(options, lng) {
  19417. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  19418. }
  19419. function needsIndefiniteArticle(options) {
  19420. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  19421. }
  19422. function exists(key, options) {
  19423. options = options || {};
  19424. var notFound = _getDefaultValue(key, options)
  19425. , found = _find(key, options);
  19426. return found !== undefined || found === notFound;
  19427. }
  19428. function translate(key, options) {
  19429. options = options || {};
  19430. if (!initialized) {
  19431. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  19432. return options.defaultValue || '';
  19433. };
  19434. replacementCounter = 0;
  19435. return _translate.apply(null, arguments);
  19436. }
  19437. function _getDefaultValue(key, options) {
  19438. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  19439. }
  19440. function _injectSprintfProcessor() {
  19441. var values = [];
  19442. // mh: build array from second argument onwards
  19443. for (var i = 1; i < arguments.length; i++) {
  19444. values.push(arguments[i]);
  19445. }
  19446. return {
  19447. postProcess: 'sprintf',
  19448. sprintf: values
  19449. };
  19450. }
  19451. function _translate(potentialKeys, options) {
  19452. if (options && typeof options !== 'object') {
  19453. if (o.shortcutFunction === 'sprintf') {
  19454. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  19455. options = _injectSprintfProcessor.apply(null, arguments);
  19456. } else if (o.shortcutFunction === 'defaultValue') {
  19457. options = {
  19458. defaultValue: options
  19459. }
  19460. }
  19461. } else {
  19462. options = options || {};
  19463. }
  19464. if (typeof o.defaultVariables === 'object') {
  19465. options = f.extend({}, o.defaultVariables, options);
  19466. }
  19467. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  19468. if (typeof potentialKeys === 'string') {
  19469. potentialKeys = [potentialKeys];
  19470. }
  19471. var key = potentialKeys[0];
  19472. if (potentialKeys.length > 1) {
  19473. for (var i = 0; i < potentialKeys.length; i++) {
  19474. key = potentialKeys[i];
  19475. if (exists(key, options)) {
  19476. break;
  19477. }
  19478. }
  19479. }
  19480. var notFound = _getDefaultValue(key, options)
  19481. , found = _find(key, options)
  19482. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  19483. , ns = options.ns || o.ns.defaultNs
  19484. , parts;
  19485. // split ns and key
  19486. if (key.indexOf(o.nsseparator) > -1) {
  19487. parts = key.split(o.nsseparator);
  19488. ns = parts[0];
  19489. key = parts[1];
  19490. }
  19491. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  19492. if (options.lng) {
  19493. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  19494. } else {
  19495. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  19496. }
  19497. }
  19498. var postProcessor = options.postProcess || o.postProcess;
  19499. if (found !== undefined && postProcessor) {
  19500. if (postProcessors[postProcessor]) {
  19501. found = postProcessors[postProcessor](found, key, options);
  19502. }
  19503. }
  19504. // process notFound if function exists
  19505. var splitNotFound = notFound;
  19506. if (notFound.indexOf(o.nsseparator) > -1) {
  19507. parts = notFound.split(o.nsseparator);
  19508. splitNotFound = parts[1];
  19509. }
  19510. if (splitNotFound === key && o.parseMissingKey) {
  19511. notFound = o.parseMissingKey(notFound);
  19512. }
  19513. if (found === undefined) {
  19514. notFound = applyReplacement(notFound, options);
  19515. notFound = applyReuse(notFound, options);
  19516. if (postProcessor && postProcessors[postProcessor]) {
  19517. var val = _getDefaultValue(key, options);
  19518. found = postProcessors[postProcessor](val, key, options);
  19519. }
  19520. }
  19521. return (found !== undefined) ? found : notFound;
  19522. }
  19523. function _find(key, options) {
  19524. options = options || {};
  19525. var optionWithoutCount, translated
  19526. , notFound = _getDefaultValue(key, options)
  19527. , lngs = languages;
  19528. if (!resStore) { return notFound; } // no resStore to translate from
  19529. // CI mode
  19530. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19531. // passed in lng
  19532. if (options.lngs) lngs = options.lngs;
  19533. if (options.lng) {
  19534. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19535. if (!resStore[lngs[0]]) {
  19536. var oldAsync = o.getAsync;
  19537. o.getAsync = false;
  19538. i18n.sync.load(lngs, o, function(err, store) {
  19539. f.extend(resStore, store);
  19540. o.getAsync = oldAsync;
  19541. });
  19542. }
  19543. }
  19544. var ns = options.ns || o.ns.defaultNs;
  19545. if (key.indexOf(o.nsseparator) > -1) {
  19546. var parts = key.split(o.nsseparator);
  19547. ns = parts[0];
  19548. key = parts[1];
  19549. }
  19550. if (hasContext(options)) {
  19551. optionWithoutCount = f.extend({}, options);
  19552. delete optionWithoutCount.context;
  19553. optionWithoutCount.defaultValue = o.contextNotFound;
  19554. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19555. translated = translate(contextKey, optionWithoutCount);
  19556. if (translated != o.contextNotFound) {
  19557. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19558. } // else continue translation with original/nonContext key
  19559. }
  19560. if (needsPlural(options, lngs[0])) {
  19561. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19562. delete optionWithoutCount.count;
  19563. delete optionWithoutCount.lng;
  19564. optionWithoutCount.defaultValue = o.pluralNotFound;
  19565. var pluralKey;
  19566. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19567. pluralKey = ns + o.nsseparator + key;
  19568. } else {
  19569. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19570. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19571. if (pluralExtension >= 0) {
  19572. pluralKey = pluralKey + '_' + pluralExtension;
  19573. } else if (pluralExtension === 1) {
  19574. pluralKey = ns + o.nsseparator + key; // singular
  19575. }
  19576. }
  19577. translated = translate(pluralKey, optionWithoutCount);
  19578. if (translated != o.pluralNotFound) {
  19579. return applyReplacement(translated, {
  19580. count: options.count,
  19581. interpolationPrefix: options.interpolationPrefix,
  19582. interpolationSuffix: options.interpolationSuffix
  19583. }); // apply replacement for count only
  19584. } else if (lngs.length > 1) {
  19585. // remove failed lng
  19586. var clone = lngs.slice();
  19587. clone.shift();
  19588. options = f.extend(options, { lngs: clone });
  19589. delete options.lng;
  19590. // retry with fallbacks
  19591. translated = translate(ns + o.nsseparator + key, options);
  19592. if (translated != o.pluralNotFound) return translated;
  19593. } else {
  19594. return translated;
  19595. }
  19596. }
  19597. if (needsIndefiniteArticle(options)) {
  19598. var optionsWithoutIndef = f.extend({}, options);
  19599. delete optionsWithoutIndef.indefinite_article;
  19600. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19601. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19602. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19603. translated = translate(indefiniteKey, optionsWithoutIndef);
  19604. if (translated != o.indefiniteNotFound) {
  19605. return translated;
  19606. }
  19607. }
  19608. var found;
  19609. var keys = key.split(o.keyseparator);
  19610. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19611. if (found !== undefined) break;
  19612. var l = lngs[i];
  19613. var x = 0;
  19614. var value = resStore[l] && resStore[l][ns];
  19615. while (keys[x]) {
  19616. value = value && value[keys[x]];
  19617. x++;
  19618. }
  19619. if (value !== undefined) {
  19620. var valueType = Object.prototype.toString.apply(value);
  19621. if (typeof value === 'string') {
  19622. value = applyReplacement(value, options);
  19623. value = applyReuse(value, options);
  19624. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19625. value = value.join('\n');
  19626. value = applyReplacement(value, options);
  19627. value = applyReuse(value, options);
  19628. } else if (value === null && o.fallbackOnNull === true) {
  19629. value = undefined;
  19630. } else if (value !== null) {
  19631. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19632. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19633. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19634. } else {
  19635. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19636. 'returned an object instead of string.';
  19637. f.log(value);
  19638. }
  19639. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19640. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19641. f.each(value, function(m) {
  19642. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19643. });
  19644. value = copy;
  19645. }
  19646. }
  19647. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19648. value = undefined;
  19649. found = value;
  19650. }
  19651. }
  19652. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19653. // set flag for fallback lookup - avoid recursion
  19654. options.isFallbackLookup = true;
  19655. if (o.fallbackNS.length) {
  19656. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19657. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19658. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19659. /* compare value without namespace */
  19660. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19661. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19662. if (foundValue !== notFoundValue) break;
  19663. }
  19664. }
  19665. } else {
  19666. found = _find(key, options); // fallback to default NS
  19667. }
  19668. options.isFallbackLookup = false;
  19669. }
  19670. return found;
  19671. }
  19672. function detectLanguage() {
  19673. var detectedLng;
  19674. var whitelist = o.lngWhitelist || [];
  19675. var userLngChoices = [];
  19676. // get from qs
  19677. var qsParm = [];
  19678. if (typeof window !== 'undefined') {
  19679. (function() {
  19680. var query = window.location.search.substring(1);
  19681. var params = query.split('&');
  19682. for (var i=0; i<params.length; i++) {
  19683. var pos = params[i].indexOf('=');
  19684. if (pos > 0) {
  19685. var key = params[i].substring(0,pos);
  19686. if (key == o.detectLngQS) {
  19687. userLngChoices.push(params[i].substring(pos+1));
  19688. }
  19689. }
  19690. }
  19691. })();
  19692. }
  19693. // get from cookie
  19694. if (o.useCookie && typeof document !== 'undefined') {
  19695. var c = f.cookie.read(o.cookieName);
  19696. if (c) userLngChoices.push(c);
  19697. }
  19698. // get from localStorage
  19699. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19700. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19701. }
  19702. // get from navigator
  19703. if (typeof navigator !== 'undefined') {
  19704. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19705. for (var i=0;i<navigator.languages.length;i++) {
  19706. userLngChoices.push(navigator.languages[i]);
  19707. }
  19708. }
  19709. if (navigator.userLanguage) {
  19710. userLngChoices.push(navigator.userLanguage);
  19711. }
  19712. if (navigator.language) {
  19713. userLngChoices.push(navigator.language);
  19714. }
  19715. }
  19716. (function() {
  19717. for (var i=0;i<userLngChoices.length;i++) {
  19718. var lng = userLngChoices[i];
  19719. if (lng.indexOf('-') > -1) {
  19720. var parts = lng.split('-');
  19721. lng = o.lowerCaseLng ?
  19722. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19723. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19724. }
  19725. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19726. detectedLng = lng;
  19727. break;
  19728. }
  19729. }
  19730. })();
  19731. //fallback
  19732. if (!detectedLng){
  19733. detectedLng = o.fallbackLng[0];
  19734. }
  19735. return detectedLng;
  19736. }
  19737. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19738. /* [code, name, numbers, pluralsType] */
  19739. var _rules = [
  19740. ["ach", "Acholi", [1,2], 1],
  19741. ["af", "Afrikaans",[1,2], 2],
  19742. ["ak", "Akan", [1,2], 1],
  19743. ["am", "Amharic", [1,2], 1],
  19744. ["an", "Aragonese",[1,2], 2],
  19745. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19746. ["arn", "Mapudungun",[1,2], 1],
  19747. ["ast", "Asturian", [1,2], 2],
  19748. ["ay", "Aymará", [1], 3],
  19749. ["az", "Azerbaijani",[1,2],2],
  19750. ["be", "Belarusian",[1,2,5],4],
  19751. ["bg", "Bulgarian",[1,2], 2],
  19752. ["bn", "Bengali", [1,2], 2],
  19753. ["bo", "Tibetan", [1], 3],
  19754. ["br", "Breton", [1,2], 1],
  19755. ["bs", "Bosnian", [1,2,5],4],
  19756. ["ca", "Catalan", [1,2], 2],
  19757. ["cgg", "Chiga", [1], 3],
  19758. ["cs", "Czech", [1,2,5],6],
  19759. ["csb", "Kashubian",[1,2,5],7],
  19760. ["cy", "Welsh", [1,2,3,8],8],
  19761. ["da", "Danish", [1,2], 2],
  19762. ["de", "German", [1,2], 2],
  19763. ["dev", "Development Fallback", [1,2], 2],
  19764. ["dz", "Dzongkha", [1], 3],
  19765. ["el", "Greek", [1,2], 2],
  19766. ["en", "English", [1,2], 2],
  19767. ["eo", "Esperanto",[1,2], 2],
  19768. ["es", "Spanish", [1,2], 2],
  19769. ["es_ar","Argentinean Spanish", [1,2], 2],
  19770. ["et", "Estonian", [1,2], 2],
  19771. ["eu", "Basque", [1,2], 2],
  19772. ["fa", "Persian", [1], 3],
  19773. ["fi", "Finnish", [1,2], 2],
  19774. ["fil", "Filipino", [1,2], 1],
  19775. ["fo", "Faroese", [1,2], 2],
  19776. ["fr", "French", [1,2], 9],
  19777. ["fur", "Friulian", [1,2], 2],
  19778. ["fy", "Frisian", [1,2], 2],
  19779. ["ga", "Irish", [1,2,3,7,11],10],
  19780. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19781. ["gl", "Galician", [1,2], 2],
  19782. ["gu", "Gujarati", [1,2], 2],
  19783. ["gun", "Gun", [1,2], 1],
  19784. ["ha", "Hausa", [1,2], 2],
  19785. ["he", "Hebrew", [1,2], 2],
  19786. ["hi", "Hindi", [1,2], 2],
  19787. ["hr", "Croatian", [1,2,5],4],
  19788. ["hu", "Hungarian",[1,2], 2],
  19789. ["hy", "Armenian", [1,2], 2],
  19790. ["ia", "Interlingua",[1,2],2],
  19791. ["id", "Indonesian",[1], 3],
  19792. ["is", "Icelandic",[1,2], 12],
  19793. ["it", "Italian", [1,2], 2],
  19794. ["ja", "Japanese", [1], 3],
  19795. ["jbo", "Lojban", [1], 3],
  19796. ["jv", "Javanese", [0,1], 13],
  19797. ["ka", "Georgian", [1], 3],
  19798. ["kk", "Kazakh", [1], 3],
  19799. ["km", "Khmer", [1], 3],
  19800. ["kn", "Kannada", [1,2], 2],
  19801. ["ko", "Korean", [1], 3],
  19802. ["ku", "Kurdish", [1,2], 2],
  19803. ["kw", "Cornish", [1,2,3,4],14],
  19804. ["ky", "Kyrgyz", [1], 3],
  19805. ["lb", "Letzeburgesch",[1,2],2],
  19806. ["ln", "Lingala", [1,2], 1],
  19807. ["lo", "Lao", [1], 3],
  19808. ["lt", "Lithuanian",[1,2,10],15],
  19809. ["lv", "Latvian", [1,2,0],16],
  19810. ["mai", "Maithili", [1,2], 2],
  19811. ["mfe", "Mauritian Creole",[1,2],1],
  19812. ["mg", "Malagasy", [1,2], 1],
  19813. ["mi", "Maori", [1,2], 1],
  19814. ["mk", "Macedonian",[1,2],17],
  19815. ["ml", "Malayalam",[1,2], 2],
  19816. ["mn", "Mongolian",[1,2], 2],
  19817. ["mnk", "Mandinka", [0,1,2],18],
  19818. ["mr", "Marathi", [1,2], 2],
  19819. ["ms", "Malay", [1], 3],
  19820. ["mt", "Maltese", [1,2,11,20],19],
  19821. ["nah", "Nahuatl", [1,2], 2],
  19822. ["nap", "Neapolitan",[1,2], 2],
  19823. ["nb", "Norwegian Bokmal",[1,2],2],
  19824. ["ne", "Nepali", [1,2], 2],
  19825. ["nl", "Dutch", [1,2], 2],
  19826. ["nn", "Norwegian Nynorsk",[1,2],2],
  19827. ["no", "Norwegian",[1,2], 2],
  19828. ["nso", "Northern Sotho",[1,2],2],
  19829. ["oc", "Occitan", [1,2], 1],
  19830. ["or", "Oriya", [2,1], 2],
  19831. ["pa", "Punjabi", [1,2], 2],
  19832. ["pap", "Papiamento",[1,2], 2],
  19833. ["pl", "Polish", [1,2,5],7],
  19834. ["pms", "Piemontese",[1,2], 2],
  19835. ["ps", "Pashto", [1,2], 2],
  19836. ["pt", "Portuguese",[1,2], 2],
  19837. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19838. ["rm", "Romansh", [1,2], 2],
  19839. ["ro", "Romanian", [1,2,20],20],
  19840. ["ru", "Russian", [1,2,5],4],
  19841. ["sah", "Yakut", [1], 3],
  19842. ["sco", "Scots", [1,2], 2],
  19843. ["se", "Northern Sami",[1,2], 2],
  19844. ["si", "Sinhala", [1,2], 2],
  19845. ["sk", "Slovak", [1,2,5],6],
  19846. ["sl", "Slovenian",[5,1,2,3],21],
  19847. ["so", "Somali", [1,2], 2],
  19848. ["son", "Songhay", [1,2], 2],
  19849. ["sq", "Albanian", [1,2], 2],
  19850. ["sr", "Serbian", [1,2,5],4],
  19851. ["su", "Sundanese",[1], 3],
  19852. ["sv", "Swedish", [1,2], 2],
  19853. ["sw", "Swahili", [1,2], 2],
  19854. ["ta", "Tamil", [1,2], 2],
  19855. ["te", "Telugu", [1,2], 2],
  19856. ["tg", "Tajik", [1,2], 1],
  19857. ["th", "Thai", [1], 3],
  19858. ["ti", "Tigrinya", [1,2], 1],
  19859. ["tk", "Turkmen", [1,2], 2],
  19860. ["tr", "Turkish", [1,2], 1],
  19861. ["tt", "Tatar", [1], 3],
  19862. ["ug", "Uyghur", [1], 3],
  19863. ["uk", "Ukrainian",[1,2,5],4],
  19864. ["ur", "Urdu", [1,2], 2],
  19865. ["uz", "Uzbek", [1,2], 1],
  19866. ["vi", "Vietnamese",[1], 3],
  19867. ["wa", "Walloon", [1,2], 1],
  19868. ["wo", "Wolof", [1], 3],
  19869. ["yo", "Yoruba", [1,2], 2],
  19870. ["zh", "Chinese", [1], 3]
  19871. ];
  19872. var _rulesPluralsTypes = {
  19873. 1: function(n) {return Number(n > 1);},
  19874. 2: function(n) {return Number(n != 1);},
  19875. 3: function(n) {return 0;},
  19876. 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);},
  19877. 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);},
  19878. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19879. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19880. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19881. 9: function(n) {return Number(n >= 2);},
  19882. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19883. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19884. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19885. 13: function(n) {return Number(n !== 0);},
  19886. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19887. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19888. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19889. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19890. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19891. 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);},
  19892. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19893. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19894. };
  19895. var pluralExtensions = {
  19896. rules: (function () {
  19897. var l, rules = {};
  19898. for (l=_rules.length; l-- ;) {
  19899. rules[_rules[l][0]] = {
  19900. name: _rules[l][1],
  19901. numbers: _rules[l][2],
  19902. plurals: _rulesPluralsTypes[_rules[l][3]]
  19903. }
  19904. }
  19905. return rules;
  19906. }()),
  19907. // you can add your own pluralExtensions
  19908. addRule: function(lng, obj) {
  19909. pluralExtensions.rules[lng] = obj;
  19910. },
  19911. setCurrentLng: function(lng) {
  19912. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19913. var parts = lng.split('-');
  19914. pluralExtensions.currentRule = {
  19915. lng: lng,
  19916. rule: pluralExtensions.rules[parts[0]]
  19917. };
  19918. }
  19919. },
  19920. needsPlural: function(lng, count) {
  19921. var parts = lng.split('-');
  19922. var ext;
  19923. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19924. ext = pluralExtensions.currentRule.rule;
  19925. } else {
  19926. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19927. }
  19928. if (ext && ext.numbers.length <= 1) {
  19929. return false;
  19930. } else {
  19931. return this.get(lng, count) !== 1;
  19932. }
  19933. },
  19934. get: function(lng, count) {
  19935. var parts = lng.split('-');
  19936. function getResult(l, c) {
  19937. var ext;
  19938. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19939. ext = pluralExtensions.currentRule.rule;
  19940. } else {
  19941. ext = pluralExtensions.rules[l];
  19942. }
  19943. if (ext) {
  19944. var i;
  19945. if (ext.noAbs) {
  19946. i = ext.plurals(c);
  19947. } else {
  19948. i = ext.plurals(Math.abs(c));
  19949. }
  19950. var number = ext.numbers[i];
  19951. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19952. if (number === 2) {
  19953. number = -1; // regular plural
  19954. } else if (number === 1) {
  19955. number = 1; // singular
  19956. }
  19957. }//console.log(count + '-' + number);
  19958. return number;
  19959. } else {
  19960. return c === 1 ? '1' : '-1';
  19961. }
  19962. }
  19963. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19964. }
  19965. };
  19966. var postProcessors = {};
  19967. var addPostProcessor = function(name, fc) {
  19968. postProcessors[name] = fc;
  19969. };
  19970. // sprintf support
  19971. var sprintf = (function() {
  19972. function get_type(variable) {
  19973. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19974. }
  19975. function str_repeat(input, multiplier) {
  19976. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19977. return output.join('');
  19978. }
  19979. var str_format = function() {
  19980. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19981. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19982. }
  19983. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19984. };
  19985. str_format.format = function(parse_tree, argv) {
  19986. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19987. for (i = 0; i < tree_length; i++) {
  19988. node_type = get_type(parse_tree[i]);
  19989. if (node_type === 'string') {
  19990. output.push(parse_tree[i]);
  19991. }
  19992. else if (node_type === 'array') {
  19993. match = parse_tree[i]; // convenience purposes only
  19994. if (match[2]) { // keyword argument
  19995. arg = argv[cursor];
  19996. for (k = 0; k < match[2].length; k++) {
  19997. if (!arg.hasOwnProperty(match[2][k])) {
  19998. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19999. }
  20000. arg = arg[match[2][k]];
  20001. }
  20002. }
  20003. else if (match[1]) { // positional argument (explicit)
  20004. arg = argv[match[1]];
  20005. }
  20006. else { // positional argument (implicit)
  20007. arg = argv[cursor++];
  20008. }
  20009. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  20010. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  20011. }
  20012. switch (match[8]) {
  20013. case 'b': arg = arg.toString(2); break;
  20014. case 'c': arg = String.fromCharCode(arg); break;
  20015. case 'd': arg = parseInt(arg, 10); break;
  20016. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  20017. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  20018. case 'o': arg = arg.toString(8); break;
  20019. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  20020. case 'u': arg = Math.abs(arg); break;
  20021. case 'x': arg = arg.toString(16); break;
  20022. case 'X': arg = arg.toString(16).toUpperCase(); break;
  20023. }
  20024. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  20025. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  20026. pad_length = match[6] - String(arg).length;
  20027. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  20028. output.push(match[5] ? arg + pad : pad + arg);
  20029. }
  20030. }
  20031. return output.join('');
  20032. };
  20033. str_format.cache = {};
  20034. str_format.parse = function(fmt) {
  20035. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  20036. while (_fmt) {
  20037. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  20038. parse_tree.push(match[0]);
  20039. }
  20040. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  20041. parse_tree.push('%');
  20042. }
  20043. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  20044. if (match[2]) {
  20045. arg_names |= 1;
  20046. var field_list = [], replacement_field = match[2], field_match = [];
  20047. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  20048. field_list.push(field_match[1]);
  20049. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  20050. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  20051. field_list.push(field_match[1]);
  20052. }
  20053. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  20054. field_list.push(field_match[1]);
  20055. }
  20056. else {
  20057. throw('[sprintf] huh?');
  20058. }
  20059. }
  20060. }
  20061. else {
  20062. throw('[sprintf] huh?');
  20063. }
  20064. match[2] = field_list;
  20065. }
  20066. else {
  20067. arg_names |= 2;
  20068. }
  20069. if (arg_names === 3) {
  20070. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  20071. }
  20072. parse_tree.push(match);
  20073. }
  20074. else {
  20075. throw('[sprintf] huh?');
  20076. }
  20077. _fmt = _fmt.substring(match[0].length);
  20078. }
  20079. return parse_tree;
  20080. };
  20081. return str_format;
  20082. })();
  20083. var vsprintf = function(fmt, argv) {
  20084. argv.unshift(fmt);
  20085. return sprintf.apply(null, argv);
  20086. };
  20087. addPostProcessor("sprintf", function(val, key, opts) {
  20088. if (!opts.sprintf) return val;
  20089. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  20090. return vsprintf(val, opts.sprintf);
  20091. } else if (typeof opts.sprintf === 'object') {
  20092. return sprintf(val, opts.sprintf);
  20093. }
  20094. return val;
  20095. });
  20096. // public api interface
  20097. i18n.init = init;
  20098. i18n.setLng = setLng;
  20099. i18n.preload = preload;
  20100. i18n.addResourceBundle = addResourceBundle;
  20101. i18n.hasResourceBundle = hasResourceBundle;
  20102. i18n.addResource = addResource;
  20103. i18n.addResources = addResources;
  20104. i18n.removeResourceBundle = removeResourceBundle;
  20105. i18n.loadNamespace = loadNamespace;
  20106. i18n.loadNamespaces = loadNamespaces;
  20107. i18n.setDefaultNamespace = setDefaultNamespace;
  20108. i18n.t = translate;
  20109. i18n.translate = translate;
  20110. i18n.exists = exists;
  20111. i18n.detectLanguage = f.detectLanguage;
  20112. i18n.pluralExtensions = pluralExtensions;
  20113. i18n.sync = sync;
  20114. i18n.functions = f;
  20115. i18n.lng = lng;
  20116. i18n.addPostProcessor = addPostProcessor;
  20117. i18n.options = o;
  20118. })();
  20119. },{"jquery":"jquery"}],73:[function(require,module,exports){
  20120. // Top level file is just a mixin of submodules & constants
  20121. 'use strict';
  20122. var assign = require('./lib/utils/common').assign;
  20123. var deflate = require('./lib/deflate');
  20124. var inflate = require('./lib/inflate');
  20125. var constants = require('./lib/zlib/constants');
  20126. var pako = {};
  20127. assign(pako, deflate, inflate, constants);
  20128. module.exports = pako;
  20129. },{"./lib/deflate":74,"./lib/inflate":75,"./lib/utils/common":76,"./lib/zlib/constants":79}],74:[function(require,module,exports){
  20130. 'use strict';
  20131. var zlib_deflate = require('./zlib/deflate.js');
  20132. var utils = require('./utils/common');
  20133. var strings = require('./utils/strings');
  20134. var msg = require('./zlib/messages');
  20135. var zstream = require('./zlib/zstream');
  20136. var toString = Object.prototype.toString;
  20137. /* Public constants ==========================================================*/
  20138. /* ===========================================================================*/
  20139. var Z_NO_FLUSH = 0;
  20140. var Z_FINISH = 4;
  20141. var Z_OK = 0;
  20142. var Z_STREAM_END = 1;
  20143. var Z_SYNC_FLUSH = 2;
  20144. var Z_DEFAULT_COMPRESSION = -1;
  20145. var Z_DEFAULT_STRATEGY = 0;
  20146. var Z_DEFLATED = 8;
  20147. /* ===========================================================================*/
  20148. /**
  20149. * class Deflate
  20150. *
  20151. * Generic JS-style wrapper for zlib calls. If you don't need
  20152. * streaming behaviour - use more simple functions: [[deflate]],
  20153. * [[deflateRaw]] and [[gzip]].
  20154. **/
  20155. /* internal
  20156. * Deflate.chunks -> Array
  20157. *
  20158. * Chunks of output data, if [[Deflate#onData]] not overriden.
  20159. **/
  20160. /**
  20161. * Deflate.result -> Uint8Array|Array
  20162. *
  20163. * Compressed result, generated by default [[Deflate#onData]]
  20164. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  20165. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  20166. * push a chunk with explicit flush (call [[Deflate#push]] with
  20167. * `Z_SYNC_FLUSH` param).
  20168. **/
  20169. /**
  20170. * Deflate.err -> Number
  20171. *
  20172. * Error code after deflate finished. 0 (Z_OK) on success.
  20173. * You will not need it in real life, because deflate errors
  20174. * are possible only on wrong options or bad `onData` / `onEnd`
  20175. * custom handlers.
  20176. **/
  20177. /**
  20178. * Deflate.msg -> String
  20179. *
  20180. * Error message, if [[Deflate.err]] != 0
  20181. **/
  20182. /**
  20183. * new Deflate(options)
  20184. * - options (Object): zlib deflate options.
  20185. *
  20186. * Creates new deflator instance with specified params. Throws exception
  20187. * on bad params. Supported options:
  20188. *
  20189. * - `level`
  20190. * - `windowBits`
  20191. * - `memLevel`
  20192. * - `strategy`
  20193. *
  20194. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20195. * for more information on these.
  20196. *
  20197. * Additional options, for internal needs:
  20198. *
  20199. * - `chunkSize` - size of generated data chunks (16K by default)
  20200. * - `raw` (Boolean) - do raw deflate
  20201. * - `gzip` (Boolean) - create gzip wrapper
  20202. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20203. * (each char code [0..255])
  20204. * - `header` (Object) - custom header for gzip
  20205. * - `text` (Boolean) - true if compressed data believed to be text
  20206. * - `time` (Number) - modification time, unix timestamp
  20207. * - `os` (Number) - operation system code
  20208. * - `extra` (Array) - array of bytes with extra data (max 65536)
  20209. * - `name` (String) - file name (binary string)
  20210. * - `comment` (String) - comment (binary string)
  20211. * - `hcrc` (Boolean) - true if header crc should be added
  20212. *
  20213. * ##### Example:
  20214. *
  20215. * ```javascript
  20216. * var pako = require('pako')
  20217. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20218. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20219. *
  20220. * var deflate = new pako.Deflate({ level: 3});
  20221. *
  20222. * deflate.push(chunk1, false);
  20223. * deflate.push(chunk2, true); // true -> last chunk
  20224. *
  20225. * if (deflate.err) { throw new Error(deflate.err); }
  20226. *
  20227. * console.log(deflate.result);
  20228. * ```
  20229. **/
  20230. var Deflate = function(options) {
  20231. this.options = utils.assign({
  20232. level: Z_DEFAULT_COMPRESSION,
  20233. method: Z_DEFLATED,
  20234. chunkSize: 16384,
  20235. windowBits: 15,
  20236. memLevel: 8,
  20237. strategy: Z_DEFAULT_STRATEGY,
  20238. to: ''
  20239. }, options || {});
  20240. var opt = this.options;
  20241. if (opt.raw && (opt.windowBits > 0)) {
  20242. opt.windowBits = -opt.windowBits;
  20243. }
  20244. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  20245. opt.windowBits += 16;
  20246. }
  20247. this.err = 0; // error code, if happens (0 = Z_OK)
  20248. this.msg = ''; // error message
  20249. this.ended = false; // used to avoid multiple onEnd() calls
  20250. this.chunks = []; // chunks of compressed data
  20251. this.strm = new zstream();
  20252. this.strm.avail_out = 0;
  20253. var status = zlib_deflate.deflateInit2(
  20254. this.strm,
  20255. opt.level,
  20256. opt.method,
  20257. opt.windowBits,
  20258. opt.memLevel,
  20259. opt.strategy
  20260. );
  20261. if (status !== Z_OK) {
  20262. throw new Error(msg[status]);
  20263. }
  20264. if (opt.header) {
  20265. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  20266. }
  20267. };
  20268. /**
  20269. * Deflate#push(data[, mode]) -> Boolean
  20270. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  20271. * converted to utf8 byte sequence.
  20272. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20273. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20274. *
  20275. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  20276. * new compressed chunks. Returns `true` on success. The last data block must have
  20277. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20278. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20279. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  20280. *
  20281. * On fail call [[Deflate#onEnd]] with error code and return false.
  20282. *
  20283. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20284. * array format is detected automatically). Also, don't skip last param and always
  20285. * use the same type in your code (boolean or number). That will improve JS speed.
  20286. *
  20287. * For regular `Array`-s make sure all elements are [0..255].
  20288. *
  20289. * ##### Example
  20290. *
  20291. * ```javascript
  20292. * push(chunk, false); // push one of data chunks
  20293. * ...
  20294. * push(chunk, true); // push last chunk
  20295. * ```
  20296. **/
  20297. Deflate.prototype.push = function(data, mode) {
  20298. var strm = this.strm;
  20299. var chunkSize = this.options.chunkSize;
  20300. var status, _mode;
  20301. if (this.ended) { return false; }
  20302. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  20303. // Convert data if needed
  20304. if (typeof data === 'string') {
  20305. // If we need to compress text, change encoding to utf8.
  20306. strm.input = strings.string2buf(data);
  20307. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20308. strm.input = new Uint8Array(data);
  20309. } else {
  20310. strm.input = data;
  20311. }
  20312. strm.next_in = 0;
  20313. strm.avail_in = strm.input.length;
  20314. do {
  20315. if (strm.avail_out === 0) {
  20316. strm.output = new utils.Buf8(chunkSize);
  20317. strm.next_out = 0;
  20318. strm.avail_out = chunkSize;
  20319. }
  20320. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  20321. if (status !== Z_STREAM_END && status !== Z_OK) {
  20322. this.onEnd(status);
  20323. this.ended = true;
  20324. return false;
  20325. }
  20326. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  20327. if (this.options.to === 'string') {
  20328. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  20329. } else {
  20330. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20331. }
  20332. }
  20333. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  20334. // Finalize on the last chunk.
  20335. if (_mode === Z_FINISH) {
  20336. status = zlib_deflate.deflateEnd(this.strm);
  20337. this.onEnd(status);
  20338. this.ended = true;
  20339. return status === Z_OK;
  20340. }
  20341. // callback interim results if Z_SYNC_FLUSH.
  20342. if (_mode === Z_SYNC_FLUSH) {
  20343. this.onEnd(Z_OK);
  20344. strm.avail_out = 0;
  20345. return true;
  20346. }
  20347. return true;
  20348. };
  20349. /**
  20350. * Deflate#onData(chunk) -> Void
  20351. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20352. * on js engine support. When string output requested, each chunk
  20353. * will be string.
  20354. *
  20355. * By default, stores data blocks in `chunks[]` property and glue
  20356. * those in `onEnd`. Override this handler, if you need another behaviour.
  20357. **/
  20358. Deflate.prototype.onData = function(chunk) {
  20359. this.chunks.push(chunk);
  20360. };
  20361. /**
  20362. * Deflate#onEnd(status) -> Void
  20363. * - status (Number): deflate status. 0 (Z_OK) on success,
  20364. * other if not.
  20365. *
  20366. * Called once after you tell deflate that the input stream is
  20367. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20368. * or if an error happened. By default - join collected chunks,
  20369. * free memory and fill `results` / `err` properties.
  20370. **/
  20371. Deflate.prototype.onEnd = function(status) {
  20372. // On success - join
  20373. if (status === Z_OK) {
  20374. if (this.options.to === 'string') {
  20375. this.result = this.chunks.join('');
  20376. } else {
  20377. this.result = utils.flattenChunks(this.chunks);
  20378. }
  20379. }
  20380. this.chunks = [];
  20381. this.err = status;
  20382. this.msg = this.strm.msg;
  20383. };
  20384. /**
  20385. * deflate(data[, options]) -> Uint8Array|Array|String
  20386. * - data (Uint8Array|Array|String): input data to compress.
  20387. * - options (Object): zlib deflate options.
  20388. *
  20389. * Compress `data` with deflate alrorythm and `options`.
  20390. *
  20391. * Supported options are:
  20392. *
  20393. * - level
  20394. * - windowBits
  20395. * - memLevel
  20396. * - strategy
  20397. *
  20398. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20399. * for more information on these.
  20400. *
  20401. * Sugar (options):
  20402. *
  20403. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20404. * negative windowBits implicitly.
  20405. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20406. * (each char code [0..255])
  20407. *
  20408. * ##### Example:
  20409. *
  20410. * ```javascript
  20411. * var pako = require('pako')
  20412. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  20413. *
  20414. * console.log(pako.deflate(data));
  20415. * ```
  20416. **/
  20417. function deflate(input, options) {
  20418. var deflator = new Deflate(options);
  20419. deflator.push(input, true);
  20420. // That will never happens, if you don't cheat with options :)
  20421. if (deflator.err) { throw deflator.msg; }
  20422. return deflator.result;
  20423. }
  20424. /**
  20425. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  20426. * - data (Uint8Array|Array|String): input data to compress.
  20427. * - options (Object): zlib deflate options.
  20428. *
  20429. * The same as [[deflate]], but creates raw data, without wrapper
  20430. * (header and adler32 crc).
  20431. **/
  20432. function deflateRaw(input, options) {
  20433. options = options || {};
  20434. options.raw = true;
  20435. return deflate(input, options);
  20436. }
  20437. /**
  20438. * gzip(data[, options]) -> Uint8Array|Array|String
  20439. * - data (Uint8Array|Array|String): input data to compress.
  20440. * - options (Object): zlib deflate options.
  20441. *
  20442. * The same as [[deflate]], but create gzip wrapper instead of
  20443. * deflate one.
  20444. **/
  20445. function gzip(input, options) {
  20446. options = options || {};
  20447. options.gzip = true;
  20448. return deflate(input, options);
  20449. }
  20450. exports.Deflate = Deflate;
  20451. exports.deflate = deflate;
  20452. exports.deflateRaw = deflateRaw;
  20453. exports.gzip = gzip;
  20454. },{"./utils/common":76,"./utils/strings":77,"./zlib/deflate.js":81,"./zlib/messages":86,"./zlib/zstream":88}],75:[function(require,module,exports){
  20455. 'use strict';
  20456. var zlib_inflate = require('./zlib/inflate.js');
  20457. var utils = require('./utils/common');
  20458. var strings = require('./utils/strings');
  20459. var c = require('./zlib/constants');
  20460. var msg = require('./zlib/messages');
  20461. var zstream = require('./zlib/zstream');
  20462. var gzheader = require('./zlib/gzheader');
  20463. var toString = Object.prototype.toString;
  20464. /**
  20465. * class Inflate
  20466. *
  20467. * Generic JS-style wrapper for zlib calls. If you don't need
  20468. * streaming behaviour - use more simple functions: [[inflate]]
  20469. * and [[inflateRaw]].
  20470. **/
  20471. /* internal
  20472. * inflate.chunks -> Array
  20473. *
  20474. * Chunks of output data, if [[Inflate#onData]] not overriden.
  20475. **/
  20476. /**
  20477. * Inflate.result -> Uint8Array|Array|String
  20478. *
  20479. * Uncompressed result, generated by default [[Inflate#onData]]
  20480. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  20481. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  20482. * push a chunk with explicit flush (call [[Inflate#push]] with
  20483. * `Z_SYNC_FLUSH` param).
  20484. **/
  20485. /**
  20486. * Inflate.err -> Number
  20487. *
  20488. * Error code after inflate finished. 0 (Z_OK) on success.
  20489. * Should be checked if broken data possible.
  20490. **/
  20491. /**
  20492. * Inflate.msg -> String
  20493. *
  20494. * Error message, if [[Inflate.err]] != 0
  20495. **/
  20496. /**
  20497. * new Inflate(options)
  20498. * - options (Object): zlib inflate options.
  20499. *
  20500. * Creates new inflator instance with specified params. Throws exception
  20501. * on bad params. Supported options:
  20502. *
  20503. * - `windowBits`
  20504. *
  20505. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20506. * for more information on these.
  20507. *
  20508. * Additional options, for internal needs:
  20509. *
  20510. * - `chunkSize` - size of generated data chunks (16K by default)
  20511. * - `raw` (Boolean) - do raw inflate
  20512. * - `to` (String) - if equal to 'string', then result will be converted
  20513. * from utf8 to utf16 (javascript) string. When string output requested,
  20514. * chunk length can differ from `chunkSize`, depending on content.
  20515. *
  20516. * By default, when no options set, autodetect deflate/gzip data format via
  20517. * wrapper header.
  20518. *
  20519. * ##### Example:
  20520. *
  20521. * ```javascript
  20522. * var pako = require('pako')
  20523. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20524. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20525. *
  20526. * var inflate = new pako.Inflate({ level: 3});
  20527. *
  20528. * inflate.push(chunk1, false);
  20529. * inflate.push(chunk2, true); // true -> last chunk
  20530. *
  20531. * if (inflate.err) { throw new Error(inflate.err); }
  20532. *
  20533. * console.log(inflate.result);
  20534. * ```
  20535. **/
  20536. var Inflate = function(options) {
  20537. this.options = utils.assign({
  20538. chunkSize: 16384,
  20539. windowBits: 0,
  20540. to: ''
  20541. }, options || {});
  20542. var opt = this.options;
  20543. // Force window size for `raw` data, if not set directly,
  20544. // because we have no header for autodetect.
  20545. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20546. opt.windowBits = -opt.windowBits;
  20547. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20548. }
  20549. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20550. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20551. !(options && options.windowBits)) {
  20552. opt.windowBits += 32;
  20553. }
  20554. // Gzip header has no info about windows size, we can do autodetect only
  20555. // for deflate. So, if window size not set, force it to max when gzip possible
  20556. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20557. // bit 3 (16) -> gzipped data
  20558. // bit 4 (32) -> autodetect gzip/deflate
  20559. if ((opt.windowBits & 15) === 0) {
  20560. opt.windowBits |= 15;
  20561. }
  20562. }
  20563. this.err = 0; // error code, if happens (0 = Z_OK)
  20564. this.msg = ''; // error message
  20565. this.ended = false; // used to avoid multiple onEnd() calls
  20566. this.chunks = []; // chunks of compressed data
  20567. this.strm = new zstream();
  20568. this.strm.avail_out = 0;
  20569. var status = zlib_inflate.inflateInit2(
  20570. this.strm,
  20571. opt.windowBits
  20572. );
  20573. if (status !== c.Z_OK) {
  20574. throw new Error(msg[status]);
  20575. }
  20576. this.header = new gzheader();
  20577. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20578. };
  20579. /**
  20580. * Inflate#push(data[, mode]) -> Boolean
  20581. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20582. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20583. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20584. *
  20585. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20586. * new output chunks. Returns `true` on success. The last data block must have
  20587. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20588. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20589. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20590. *
  20591. * On fail call [[Inflate#onEnd]] with error code and return false.
  20592. *
  20593. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20594. * format is detected automatically). Also, don't skip last param and always
  20595. * use the same type in your code (boolean or number). That will improve JS speed.
  20596. *
  20597. * For regular `Array`-s make sure all elements are [0..255].
  20598. *
  20599. * ##### Example
  20600. *
  20601. * ```javascript
  20602. * push(chunk, false); // push one of data chunks
  20603. * ...
  20604. * push(chunk, true); // push last chunk
  20605. * ```
  20606. **/
  20607. Inflate.prototype.push = function(data, mode) {
  20608. var strm = this.strm;
  20609. var chunkSize = this.options.chunkSize;
  20610. var status, _mode;
  20611. var next_out_utf8, tail, utf8str;
  20612. if (this.ended) { return false; }
  20613. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20614. // Convert data if needed
  20615. if (typeof data === 'string') {
  20616. // Only binary strings can be decompressed on practice
  20617. strm.input = strings.binstring2buf(data);
  20618. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20619. strm.input = new Uint8Array(data);
  20620. } else {
  20621. strm.input = data;
  20622. }
  20623. strm.next_in = 0;
  20624. strm.avail_in = strm.input.length;
  20625. do {
  20626. if (strm.avail_out === 0) {
  20627. strm.output = new utils.Buf8(chunkSize);
  20628. strm.next_out = 0;
  20629. strm.avail_out = chunkSize;
  20630. }
  20631. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20632. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20633. this.onEnd(status);
  20634. this.ended = true;
  20635. return false;
  20636. }
  20637. if (strm.next_out) {
  20638. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20639. if (this.options.to === 'string') {
  20640. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20641. tail = strm.next_out - next_out_utf8;
  20642. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20643. // move tail
  20644. strm.next_out = tail;
  20645. strm.avail_out = chunkSize - tail;
  20646. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20647. this.onData(utf8str);
  20648. } else {
  20649. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20650. }
  20651. }
  20652. }
  20653. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20654. if (status === c.Z_STREAM_END) {
  20655. _mode = c.Z_FINISH;
  20656. }
  20657. // Finalize on the last chunk.
  20658. if (_mode === c.Z_FINISH) {
  20659. status = zlib_inflate.inflateEnd(this.strm);
  20660. this.onEnd(status);
  20661. this.ended = true;
  20662. return status === c.Z_OK;
  20663. }
  20664. // callback interim results if Z_SYNC_FLUSH.
  20665. if (_mode === c.Z_SYNC_FLUSH) {
  20666. this.onEnd(c.Z_OK);
  20667. strm.avail_out = 0;
  20668. return true;
  20669. }
  20670. return true;
  20671. };
  20672. /**
  20673. * Inflate#onData(chunk) -> Void
  20674. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20675. * on js engine support. When string output requested, each chunk
  20676. * will be string.
  20677. *
  20678. * By default, stores data blocks in `chunks[]` property and glue
  20679. * those in `onEnd`. Override this handler, if you need another behaviour.
  20680. **/
  20681. Inflate.prototype.onData = function(chunk) {
  20682. this.chunks.push(chunk);
  20683. };
  20684. /**
  20685. * Inflate#onEnd(status) -> Void
  20686. * - status (Number): inflate status. 0 (Z_OK) on success,
  20687. * other if not.
  20688. *
  20689. * Called either after you tell inflate that the input stream is
  20690. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20691. * or if an error happened. By default - join collected chunks,
  20692. * free memory and fill `results` / `err` properties.
  20693. **/
  20694. Inflate.prototype.onEnd = function(status) {
  20695. // On success - join
  20696. if (status === c.Z_OK) {
  20697. if (this.options.to === 'string') {
  20698. // Glue & convert here, until we teach pako to send
  20699. // utf8 alligned strings to onData
  20700. this.result = this.chunks.join('');
  20701. } else {
  20702. this.result = utils.flattenChunks(this.chunks);
  20703. }
  20704. }
  20705. this.chunks = [];
  20706. this.err = status;
  20707. this.msg = this.strm.msg;
  20708. };
  20709. /**
  20710. * inflate(data[, options]) -> Uint8Array|Array|String
  20711. * - data (Uint8Array|Array|String): input data to decompress.
  20712. * - options (Object): zlib inflate options.
  20713. *
  20714. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20715. * format via wrapper header by default. That's why we don't provide
  20716. * separate `ungzip` method.
  20717. *
  20718. * Supported options are:
  20719. *
  20720. * - windowBits
  20721. *
  20722. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20723. * for more information.
  20724. *
  20725. * Sugar (options):
  20726. *
  20727. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20728. * negative windowBits implicitly.
  20729. * - `to` (String) - if equal to 'string', then result will be converted
  20730. * from utf8 to utf16 (javascript) string. When string output requested,
  20731. * chunk length can differ from `chunkSize`, depending on content.
  20732. *
  20733. *
  20734. * ##### Example:
  20735. *
  20736. * ```javascript
  20737. * var pako = require('pako')
  20738. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20739. * , output;
  20740. *
  20741. * try {
  20742. * output = pako.inflate(input);
  20743. * } catch (err)
  20744. * console.log(err);
  20745. * }
  20746. * ```
  20747. **/
  20748. function inflate(input, options) {
  20749. var inflator = new Inflate(options);
  20750. inflator.push(input, true);
  20751. // That will never happens, if you don't cheat with options :)
  20752. if (inflator.err) { throw inflator.msg; }
  20753. return inflator.result;
  20754. }
  20755. /**
  20756. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20757. * - data (Uint8Array|Array|String): input data to decompress.
  20758. * - options (Object): zlib inflate options.
  20759. *
  20760. * The same as [[inflate]], but creates raw data, without wrapper
  20761. * (header and adler32 crc).
  20762. **/
  20763. function inflateRaw(input, options) {
  20764. options = options || {};
  20765. options.raw = true;
  20766. return inflate(input, options);
  20767. }
  20768. /**
  20769. * ungzip(data[, options]) -> Uint8Array|Array|String
  20770. * - data (Uint8Array|Array|String): input data to decompress.
  20771. * - options (Object): zlib inflate options.
  20772. *
  20773. * Just shortcut to [[inflate]], because it autodetects format
  20774. * by header.content. Done for convenience.
  20775. **/
  20776. exports.Inflate = Inflate;
  20777. exports.inflate = inflate;
  20778. exports.inflateRaw = inflateRaw;
  20779. exports.ungzip = inflate;
  20780. },{"./utils/common":76,"./utils/strings":77,"./zlib/constants":79,"./zlib/gzheader":82,"./zlib/inflate.js":84,"./zlib/messages":86,"./zlib/zstream":88}],76:[function(require,module,exports){
  20781. 'use strict';
  20782. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20783. (typeof Uint16Array !== 'undefined') &&
  20784. (typeof Int32Array !== 'undefined');
  20785. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20786. var sources = Array.prototype.slice.call(arguments, 1);
  20787. while (sources.length) {
  20788. var source = sources.shift();
  20789. if (!source) { continue; }
  20790. if (typeof source !== 'object') {
  20791. throw new TypeError(source + 'must be non-object');
  20792. }
  20793. for (var p in source) {
  20794. if (source.hasOwnProperty(p)) {
  20795. obj[p] = source[p];
  20796. }
  20797. }
  20798. }
  20799. return obj;
  20800. };
  20801. // reduce buffer size, avoiding mem copy
  20802. exports.shrinkBuf = function (buf, size) {
  20803. if (buf.length === size) { return buf; }
  20804. if (buf.subarray) { return buf.subarray(0, size); }
  20805. buf.length = size;
  20806. return buf;
  20807. };
  20808. var fnTyped = {
  20809. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20810. if (src.subarray && dest.subarray) {
  20811. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20812. return;
  20813. }
  20814. // Fallback to ordinary array
  20815. for (var i=0; i<len; i++) {
  20816. dest[dest_offs + i] = src[src_offs + i];
  20817. }
  20818. },
  20819. // Join array of chunks to single array.
  20820. flattenChunks: function(chunks) {
  20821. var i, l, len, pos, chunk, result;
  20822. // calculate data length
  20823. len = 0;
  20824. for (i=0, l=chunks.length; i<l; i++) {
  20825. len += chunks[i].length;
  20826. }
  20827. // join chunks
  20828. result = new Uint8Array(len);
  20829. pos = 0;
  20830. for (i=0, l=chunks.length; i<l; i++) {
  20831. chunk = chunks[i];
  20832. result.set(chunk, pos);
  20833. pos += chunk.length;
  20834. }
  20835. return result;
  20836. }
  20837. };
  20838. var fnUntyped = {
  20839. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20840. for (var i=0; i<len; i++) {
  20841. dest[dest_offs + i] = src[src_offs + i];
  20842. }
  20843. },
  20844. // Join array of chunks to single array.
  20845. flattenChunks: function(chunks) {
  20846. return [].concat.apply([], chunks);
  20847. }
  20848. };
  20849. // Enable/Disable typed arrays use, for testing
  20850. //
  20851. exports.setTyped = function (on) {
  20852. if (on) {
  20853. exports.Buf8 = Uint8Array;
  20854. exports.Buf16 = Uint16Array;
  20855. exports.Buf32 = Int32Array;
  20856. exports.assign(exports, fnTyped);
  20857. } else {
  20858. exports.Buf8 = Array;
  20859. exports.Buf16 = Array;
  20860. exports.Buf32 = Array;
  20861. exports.assign(exports, fnUntyped);
  20862. }
  20863. };
  20864. exports.setTyped(TYPED_OK);
  20865. },{}],77:[function(require,module,exports){
  20866. // String encode/decode helpers
  20867. 'use strict';
  20868. var utils = require('./common');
  20869. // Quick check if we can use fast array to bin string conversion
  20870. //
  20871. // - apply(Array) can fail on Android 2.2
  20872. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20873. //
  20874. var STR_APPLY_OK = true;
  20875. var STR_APPLY_UIA_OK = true;
  20876. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20877. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20878. // Table with utf8 lengths (calculated by first byte of sequence)
  20879. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20880. // because max possible codepoint is 0x10ffff
  20881. var _utf8len = new utils.Buf8(256);
  20882. for (var q=0; q<256; q++) {
  20883. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20884. }
  20885. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20886. // convert string to array (typed, when possible)
  20887. exports.string2buf = function (str) {
  20888. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20889. // count binary size
  20890. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20891. c = str.charCodeAt(m_pos);
  20892. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20893. c2 = str.charCodeAt(m_pos+1);
  20894. if ((c2 & 0xfc00) === 0xdc00) {
  20895. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20896. m_pos++;
  20897. }
  20898. }
  20899. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20900. }
  20901. // allocate buffer
  20902. buf = new utils.Buf8(buf_len);
  20903. // convert
  20904. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20905. c = str.charCodeAt(m_pos);
  20906. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20907. c2 = str.charCodeAt(m_pos+1);
  20908. if ((c2 & 0xfc00) === 0xdc00) {
  20909. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20910. m_pos++;
  20911. }
  20912. }
  20913. if (c < 0x80) {
  20914. /* one byte */
  20915. buf[i++] = c;
  20916. } else if (c < 0x800) {
  20917. /* two bytes */
  20918. buf[i++] = 0xC0 | (c >>> 6);
  20919. buf[i++] = 0x80 | (c & 0x3f);
  20920. } else if (c < 0x10000) {
  20921. /* three bytes */
  20922. buf[i++] = 0xE0 | (c >>> 12);
  20923. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20924. buf[i++] = 0x80 | (c & 0x3f);
  20925. } else {
  20926. /* four bytes */
  20927. buf[i++] = 0xf0 | (c >>> 18);
  20928. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20929. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20930. buf[i++] = 0x80 | (c & 0x3f);
  20931. }
  20932. }
  20933. return buf;
  20934. };
  20935. // Helper (used in 2 places)
  20936. function buf2binstring(buf, len) {
  20937. // use fallback for big arrays to avoid stack overflow
  20938. if (len < 65537) {
  20939. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20940. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20941. }
  20942. }
  20943. var result = '';
  20944. for (var i=0; i < len; i++) {
  20945. result += String.fromCharCode(buf[i]);
  20946. }
  20947. return result;
  20948. }
  20949. // Convert byte array to binary string
  20950. exports.buf2binstring = function(buf) {
  20951. return buf2binstring(buf, buf.length);
  20952. };
  20953. // Convert binary string (typed, when possible)
  20954. exports.binstring2buf = function(str) {
  20955. var buf = new utils.Buf8(str.length);
  20956. for (var i=0, len=buf.length; i < len; i++) {
  20957. buf[i] = str.charCodeAt(i);
  20958. }
  20959. return buf;
  20960. };
  20961. // convert array to string
  20962. exports.buf2string = function (buf, max) {
  20963. var i, out, c, c_len;
  20964. var len = max || buf.length;
  20965. // Reserve max possible length (2 words per char)
  20966. // NB: by unknown reasons, Array is significantly faster for
  20967. // String.fromCharCode.apply than Uint16Array.
  20968. var utf16buf = new Array(len*2);
  20969. for (out=0, i=0; i<len;) {
  20970. c = buf[i++];
  20971. // quick process ascii
  20972. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20973. c_len = _utf8len[c];
  20974. // skip 5 & 6 byte codes
  20975. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20976. // apply mask on first byte
  20977. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20978. // join the rest
  20979. while (c_len > 1 && i < len) {
  20980. c = (c << 6) | (buf[i++] & 0x3f);
  20981. c_len--;
  20982. }
  20983. // terminated by end of string?
  20984. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20985. if (c < 0x10000) {
  20986. utf16buf[out++] = c;
  20987. } else {
  20988. c -= 0x10000;
  20989. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20990. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20991. }
  20992. }
  20993. return buf2binstring(utf16buf, out);
  20994. };
  20995. // Calculate max possible position in utf8 buffer,
  20996. // that will not break sequence. If that's not possible
  20997. // - (very small limits) return max size as is.
  20998. //
  20999. // buf[] - utf8 bytes array
  21000. // max - length limit (mandatory);
  21001. exports.utf8border = function(buf, max) {
  21002. var pos;
  21003. max = max || buf.length;
  21004. if (max > buf.length) { max = buf.length; }
  21005. // go back from last position, until start of sequence found
  21006. pos = max-1;
  21007. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  21008. // Fuckup - very small and broken sequence,
  21009. // return max, because we should return something anyway.
  21010. if (pos < 0) { return max; }
  21011. // If we came to start of buffer - that means vuffer is too small,
  21012. // return max too.
  21013. if (pos === 0) { return max; }
  21014. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  21015. };
  21016. },{"./common":76}],78:[function(require,module,exports){
  21017. 'use strict';
  21018. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  21019. // It doesn't worth to make additional optimizationa as in original.
  21020. // Small size is preferable.
  21021. function adler32(adler, buf, len, pos) {
  21022. var s1 = (adler & 0xffff) |0,
  21023. s2 = ((adler >>> 16) & 0xffff) |0,
  21024. n = 0;
  21025. while (len !== 0) {
  21026. // Set limit ~ twice less than 5552, to keep
  21027. // s2 in 31-bits, because we force signed ints.
  21028. // in other case %= will fail.
  21029. n = len > 2000 ? 2000 : len;
  21030. len -= n;
  21031. do {
  21032. s1 = (s1 + buf[pos++]) |0;
  21033. s2 = (s2 + s1) |0;
  21034. } while (--n);
  21035. s1 %= 65521;
  21036. s2 %= 65521;
  21037. }
  21038. return (s1 | (s2 << 16)) |0;
  21039. }
  21040. module.exports = adler32;
  21041. },{}],79:[function(require,module,exports){
  21042. module.exports = {
  21043. /* Allowed flush values; see deflate() and inflate() below for details */
  21044. Z_NO_FLUSH: 0,
  21045. Z_PARTIAL_FLUSH: 1,
  21046. Z_SYNC_FLUSH: 2,
  21047. Z_FULL_FLUSH: 3,
  21048. Z_FINISH: 4,
  21049. Z_BLOCK: 5,
  21050. Z_TREES: 6,
  21051. /* Return codes for the compression/decompression functions. Negative values
  21052. * are errors, positive values are used for special but normal events.
  21053. */
  21054. Z_OK: 0,
  21055. Z_STREAM_END: 1,
  21056. Z_NEED_DICT: 2,
  21057. Z_ERRNO: -1,
  21058. Z_STREAM_ERROR: -2,
  21059. Z_DATA_ERROR: -3,
  21060. //Z_MEM_ERROR: -4,
  21061. Z_BUF_ERROR: -5,
  21062. //Z_VERSION_ERROR: -6,
  21063. /* compression levels */
  21064. Z_NO_COMPRESSION: 0,
  21065. Z_BEST_SPEED: 1,
  21066. Z_BEST_COMPRESSION: 9,
  21067. Z_DEFAULT_COMPRESSION: -1,
  21068. Z_FILTERED: 1,
  21069. Z_HUFFMAN_ONLY: 2,
  21070. Z_RLE: 3,
  21071. Z_FIXED: 4,
  21072. Z_DEFAULT_STRATEGY: 0,
  21073. /* Possible values of the data_type field (though see inflate()) */
  21074. Z_BINARY: 0,
  21075. Z_TEXT: 1,
  21076. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  21077. Z_UNKNOWN: 2,
  21078. /* The deflate compression method */
  21079. Z_DEFLATED: 8
  21080. //Z_NULL: null // Use -1 or null inline, depending on var type
  21081. };
  21082. },{}],80:[function(require,module,exports){
  21083. 'use strict';
  21084. // Note: we can't get significant speed boost here.
  21085. // So write code to minimize size - no pregenerated tables
  21086. // and array tools dependencies.
  21087. // Use ordinary array, since untyped makes no boost here
  21088. function makeTable() {
  21089. var c, table = [];
  21090. for (var n =0; n < 256; n++) {
  21091. c = n;
  21092. for (var k =0; k < 8; k++) {
  21093. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  21094. }
  21095. table[n] = c;
  21096. }
  21097. return table;
  21098. }
  21099. // Create table on load. Just 255 signed longs. Not a problem.
  21100. var crcTable = makeTable();
  21101. function crc32(crc, buf, len, pos) {
  21102. var t = crcTable,
  21103. end = pos + len;
  21104. crc = crc ^ (-1);
  21105. for (var i = pos; i < end; i++) {
  21106. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  21107. }
  21108. return (crc ^ (-1)); // >>> 0;
  21109. }
  21110. module.exports = crc32;
  21111. },{}],81:[function(require,module,exports){
  21112. 'use strict';
  21113. var utils = require('../utils/common');
  21114. var trees = require('./trees');
  21115. var adler32 = require('./adler32');
  21116. var crc32 = require('./crc32');
  21117. var msg = require('./messages');
  21118. /* Public constants ==========================================================*/
  21119. /* ===========================================================================*/
  21120. /* Allowed flush values; see deflate() and inflate() below for details */
  21121. var Z_NO_FLUSH = 0;
  21122. var Z_PARTIAL_FLUSH = 1;
  21123. //var Z_SYNC_FLUSH = 2;
  21124. var Z_FULL_FLUSH = 3;
  21125. var Z_FINISH = 4;
  21126. var Z_BLOCK = 5;
  21127. //var Z_TREES = 6;
  21128. /* Return codes for the compression/decompression functions. Negative values
  21129. * are errors, positive values are used for special but normal events.
  21130. */
  21131. var Z_OK = 0;
  21132. var Z_STREAM_END = 1;
  21133. //var Z_NEED_DICT = 2;
  21134. //var Z_ERRNO = -1;
  21135. var Z_STREAM_ERROR = -2;
  21136. var Z_DATA_ERROR = -3;
  21137. //var Z_MEM_ERROR = -4;
  21138. var Z_BUF_ERROR = -5;
  21139. //var Z_VERSION_ERROR = -6;
  21140. /* compression levels */
  21141. //var Z_NO_COMPRESSION = 0;
  21142. //var Z_BEST_SPEED = 1;
  21143. //var Z_BEST_COMPRESSION = 9;
  21144. var Z_DEFAULT_COMPRESSION = -1;
  21145. var Z_FILTERED = 1;
  21146. var Z_HUFFMAN_ONLY = 2;
  21147. var Z_RLE = 3;
  21148. var Z_FIXED = 4;
  21149. var Z_DEFAULT_STRATEGY = 0;
  21150. /* Possible values of the data_type field (though see inflate()) */
  21151. //var Z_BINARY = 0;
  21152. //var Z_TEXT = 1;
  21153. //var Z_ASCII = 1; // = Z_TEXT
  21154. var Z_UNKNOWN = 2;
  21155. /* The deflate compression method */
  21156. var Z_DEFLATED = 8;
  21157. /*============================================================================*/
  21158. var MAX_MEM_LEVEL = 9;
  21159. /* Maximum value for memLevel in deflateInit2 */
  21160. var MAX_WBITS = 15;
  21161. /* 32K LZ77 window */
  21162. var DEF_MEM_LEVEL = 8;
  21163. var LENGTH_CODES = 29;
  21164. /* number of length codes, not counting the special END_BLOCK code */
  21165. var LITERALS = 256;
  21166. /* number of literal bytes 0..255 */
  21167. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21168. /* number of Literal or Length codes, including the END_BLOCK code */
  21169. var D_CODES = 30;
  21170. /* number of distance codes */
  21171. var BL_CODES = 19;
  21172. /* number of codes used to transfer the bit lengths */
  21173. var HEAP_SIZE = 2*L_CODES + 1;
  21174. /* maximum heap size */
  21175. var MAX_BITS = 15;
  21176. /* All codes must not exceed MAX_BITS bits */
  21177. var MIN_MATCH = 3;
  21178. var MAX_MATCH = 258;
  21179. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  21180. var PRESET_DICT = 0x20;
  21181. var INIT_STATE = 42;
  21182. var EXTRA_STATE = 69;
  21183. var NAME_STATE = 73;
  21184. var COMMENT_STATE = 91;
  21185. var HCRC_STATE = 103;
  21186. var BUSY_STATE = 113;
  21187. var FINISH_STATE = 666;
  21188. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  21189. var BS_BLOCK_DONE = 2; /* block flush performed */
  21190. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  21191. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  21192. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  21193. function err(strm, errorCode) {
  21194. strm.msg = msg[errorCode];
  21195. return errorCode;
  21196. }
  21197. function rank(f) {
  21198. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  21199. }
  21200. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21201. /* =========================================================================
  21202. * Flush as much pending output as possible. All deflate() output goes
  21203. * through this function so some applications may wish to modify it
  21204. * to avoid allocating a large strm->output buffer and copying into it.
  21205. * (See also read_buf()).
  21206. */
  21207. function flush_pending(strm) {
  21208. var s = strm.state;
  21209. //_tr_flush_bits(s);
  21210. var len = s.pending;
  21211. if (len > strm.avail_out) {
  21212. len = strm.avail_out;
  21213. }
  21214. if (len === 0) { return; }
  21215. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  21216. strm.next_out += len;
  21217. s.pending_out += len;
  21218. strm.total_out += len;
  21219. strm.avail_out -= len;
  21220. s.pending -= len;
  21221. if (s.pending === 0) {
  21222. s.pending_out = 0;
  21223. }
  21224. }
  21225. function flush_block_only (s, last) {
  21226. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  21227. s.block_start = s.strstart;
  21228. flush_pending(s.strm);
  21229. }
  21230. function put_byte(s, b) {
  21231. s.pending_buf[s.pending++] = b;
  21232. }
  21233. /* =========================================================================
  21234. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  21235. * IN assertion: the stream state is correct and there is enough room in
  21236. * pending_buf.
  21237. */
  21238. function putShortMSB(s, b) {
  21239. // put_byte(s, (Byte)(b >> 8));
  21240. // put_byte(s, (Byte)(b & 0xff));
  21241. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  21242. s.pending_buf[s.pending++] = b & 0xff;
  21243. }
  21244. /* ===========================================================================
  21245. * Read a new buffer from the current input stream, update the adler32
  21246. * and total number of bytes read. All deflate() input goes through
  21247. * this function so some applications may wish to modify it to avoid
  21248. * allocating a large strm->input buffer and copying from it.
  21249. * (See also flush_pending()).
  21250. */
  21251. function read_buf(strm, buf, start, size) {
  21252. var len = strm.avail_in;
  21253. if (len > size) { len = size; }
  21254. if (len === 0) { return 0; }
  21255. strm.avail_in -= len;
  21256. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  21257. if (strm.state.wrap === 1) {
  21258. strm.adler = adler32(strm.adler, buf, len, start);
  21259. }
  21260. else if (strm.state.wrap === 2) {
  21261. strm.adler = crc32(strm.adler, buf, len, start);
  21262. }
  21263. strm.next_in += len;
  21264. strm.total_in += len;
  21265. return len;
  21266. }
  21267. /* ===========================================================================
  21268. * Set match_start to the longest match starting at the given string and
  21269. * return its length. Matches shorter or equal to prev_length are discarded,
  21270. * in which case the result is equal to prev_length and match_start is
  21271. * garbage.
  21272. * IN assertions: cur_match is the head of the hash chain for the current
  21273. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  21274. * OUT assertion: the match length is not greater than s->lookahead.
  21275. */
  21276. function longest_match(s, cur_match) {
  21277. var chain_length = s.max_chain_length; /* max hash chain length */
  21278. var scan = s.strstart; /* current string */
  21279. var match; /* matched string */
  21280. var len; /* length of current match */
  21281. var best_len = s.prev_length; /* best match length so far */
  21282. var nice_match = s.nice_match; /* stop if match long enough */
  21283. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  21284. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  21285. var _win = s.window; // shortcut
  21286. var wmask = s.w_mask;
  21287. var prev = s.prev;
  21288. /* Stop when cur_match becomes <= limit. To simplify the code,
  21289. * we prevent matches with the string of window index 0.
  21290. */
  21291. var strend = s.strstart + MAX_MATCH;
  21292. var scan_end1 = _win[scan + best_len - 1];
  21293. var scan_end = _win[scan + best_len];
  21294. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  21295. * It is easy to get rid of this optimization if necessary.
  21296. */
  21297. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  21298. /* Do not waste too much time if we already have a good match: */
  21299. if (s.prev_length >= s.good_match) {
  21300. chain_length >>= 2;
  21301. }
  21302. /* Do not look for matches beyond the end of the input. This is necessary
  21303. * to make deflate deterministic.
  21304. */
  21305. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  21306. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  21307. do {
  21308. // Assert(cur_match < s->strstart, "no future");
  21309. match = cur_match;
  21310. /* Skip to next match if the match length cannot increase
  21311. * or if the match length is less than 2. Note that the checks below
  21312. * for insufficient lookahead only occur occasionally for performance
  21313. * reasons. Therefore uninitialized memory will be accessed, and
  21314. * conditional jumps will be made that depend on those values.
  21315. * However the length of the match is limited to the lookahead, so
  21316. * the output of deflate is not affected by the uninitialized values.
  21317. */
  21318. if (_win[match + best_len] !== scan_end ||
  21319. _win[match + best_len - 1] !== scan_end1 ||
  21320. _win[match] !== _win[scan] ||
  21321. _win[++match] !== _win[scan + 1]) {
  21322. continue;
  21323. }
  21324. /* The check at best_len-1 can be removed because it will be made
  21325. * again later. (This heuristic is not always a win.)
  21326. * It is not necessary to compare scan[2] and match[2] since they
  21327. * are always equal when the other bytes match, given that
  21328. * the hash keys are equal and that HASH_BITS >= 8.
  21329. */
  21330. scan += 2;
  21331. match++;
  21332. // Assert(*scan == *match, "match[2]?");
  21333. /* We check for insufficient lookahead only every 8th comparison;
  21334. * the 256th check will be made at strstart+258.
  21335. */
  21336. do {
  21337. /*jshint noempty:false*/
  21338. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21339. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21340. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21341. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21342. scan < strend);
  21343. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  21344. len = MAX_MATCH - (strend - scan);
  21345. scan = strend - MAX_MATCH;
  21346. if (len > best_len) {
  21347. s.match_start = cur_match;
  21348. best_len = len;
  21349. if (len >= nice_match) {
  21350. break;
  21351. }
  21352. scan_end1 = _win[scan + best_len - 1];
  21353. scan_end = _win[scan + best_len];
  21354. }
  21355. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  21356. if (best_len <= s.lookahead) {
  21357. return best_len;
  21358. }
  21359. return s.lookahead;
  21360. }
  21361. /* ===========================================================================
  21362. * Fill the window when the lookahead becomes insufficient.
  21363. * Updates strstart and lookahead.
  21364. *
  21365. * IN assertion: lookahead < MIN_LOOKAHEAD
  21366. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  21367. * At least one byte has been read, or avail_in == 0; reads are
  21368. * performed for at least two bytes (required for the zip translate_eol
  21369. * option -- not supported here).
  21370. */
  21371. function fill_window(s) {
  21372. var _w_size = s.w_size;
  21373. var p, n, m, more, str;
  21374. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  21375. do {
  21376. more = s.window_size - s.lookahead - s.strstart;
  21377. // JS ints have 32 bit, block below not needed
  21378. /* Deal with !@#$% 64K limit: */
  21379. //if (sizeof(int) <= 2) {
  21380. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  21381. // more = wsize;
  21382. //
  21383. // } else if (more == (unsigned)(-1)) {
  21384. // /* Very unlikely, but possible on 16 bit machine if
  21385. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  21386. // */
  21387. // more--;
  21388. // }
  21389. //}
  21390. /* If the window is almost full and there is insufficient lookahead,
  21391. * move the upper half to the lower one to make room in the upper half.
  21392. */
  21393. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  21394. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  21395. s.match_start -= _w_size;
  21396. s.strstart -= _w_size;
  21397. /* we now have strstart >= MAX_DIST */
  21398. s.block_start -= _w_size;
  21399. /* Slide the hash table (could be avoided with 32 bit values
  21400. at the expense of memory usage). We slide even when level == 0
  21401. to keep the hash table consistent if we switch back to level > 0
  21402. later. (Using level 0 permanently is not an optimal usage of
  21403. zlib, so we don't care about this pathological case.)
  21404. */
  21405. n = s.hash_size;
  21406. p = n;
  21407. do {
  21408. m = s.head[--p];
  21409. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  21410. } while (--n);
  21411. n = _w_size;
  21412. p = n;
  21413. do {
  21414. m = s.prev[--p];
  21415. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  21416. /* If n is not on any hash chain, prev[n] is garbage but
  21417. * its value will never be used.
  21418. */
  21419. } while (--n);
  21420. more += _w_size;
  21421. }
  21422. if (s.strm.avail_in === 0) {
  21423. break;
  21424. }
  21425. /* If there was no sliding:
  21426. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  21427. * more == window_size - lookahead - strstart
  21428. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  21429. * => more >= window_size - 2*WSIZE + 2
  21430. * In the BIG_MEM or MMAP case (not yet supported),
  21431. * window_size == input_size + MIN_LOOKAHEAD &&
  21432. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  21433. * Otherwise, window_size == 2*WSIZE so more >= 2.
  21434. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  21435. */
  21436. //Assert(more >= 2, "more < 2");
  21437. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  21438. s.lookahead += n;
  21439. /* Initialize the hash value now that we have some input: */
  21440. if (s.lookahead + s.insert >= MIN_MATCH) {
  21441. str = s.strstart - s.insert;
  21442. s.ins_h = s.window[str];
  21443. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  21444. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  21445. //#if MIN_MATCH != 3
  21446. // Call update_hash() MIN_MATCH-3 more times
  21447. //#endif
  21448. while (s.insert) {
  21449. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21450. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  21451. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21452. s.head[s.ins_h] = str;
  21453. str++;
  21454. s.insert--;
  21455. if (s.lookahead + s.insert < MIN_MATCH) {
  21456. break;
  21457. }
  21458. }
  21459. }
  21460. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  21461. * but this is not important since only literal bytes will be emitted.
  21462. */
  21463. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  21464. /* If the WIN_INIT bytes after the end of the current data have never been
  21465. * written, then zero those bytes in order to avoid memory check reports of
  21466. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  21467. * the longest match routines. Update the high water mark for the next
  21468. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  21469. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  21470. */
  21471. // if (s.high_water < s.window_size) {
  21472. // var curr = s.strstart + s.lookahead;
  21473. // var init = 0;
  21474. //
  21475. // if (s.high_water < curr) {
  21476. // /* Previous high water mark below current data -- zero WIN_INIT
  21477. // * bytes or up to end of window, whichever is less.
  21478. // */
  21479. // init = s.window_size - curr;
  21480. // if (init > WIN_INIT)
  21481. // init = WIN_INIT;
  21482. // zmemzero(s->window + curr, (unsigned)init);
  21483. // s->high_water = curr + init;
  21484. // }
  21485. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  21486. // /* High water mark at or above current data, but below current data
  21487. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  21488. // * to end of window, whichever is less.
  21489. // */
  21490. // init = (ulg)curr + WIN_INIT - s->high_water;
  21491. // if (init > s->window_size - s->high_water)
  21492. // init = s->window_size - s->high_water;
  21493. // zmemzero(s->window + s->high_water, (unsigned)init);
  21494. // s->high_water += init;
  21495. // }
  21496. // }
  21497. //
  21498. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  21499. // "not enough room for search");
  21500. }
  21501. /* ===========================================================================
  21502. * Copy without compression as much as possible from the input stream, return
  21503. * the current block state.
  21504. * This function does not insert new strings in the dictionary since
  21505. * uncompressible data is probably not useful. This function is used
  21506. * only for the level=0 compression option.
  21507. * NOTE: this function should be optimized to avoid extra copying from
  21508. * window to pending_buf.
  21509. */
  21510. function deflate_stored(s, flush) {
  21511. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  21512. * to pending_buf_size, and each stored block has a 5 byte header:
  21513. */
  21514. var max_block_size = 0xffff;
  21515. if (max_block_size > s.pending_buf_size - 5) {
  21516. max_block_size = s.pending_buf_size - 5;
  21517. }
  21518. /* Copy as much as possible from input to output: */
  21519. for (;;) {
  21520. /* Fill the window as much as possible: */
  21521. if (s.lookahead <= 1) {
  21522. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  21523. // s->block_start >= (long)s->w_size, "slide too late");
  21524. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21525. // s.block_start >= s.w_size)) {
  21526. // throw new Error("slide too late");
  21527. // }
  21528. fill_window(s);
  21529. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21530. return BS_NEED_MORE;
  21531. }
  21532. if (s.lookahead === 0) {
  21533. break;
  21534. }
  21535. /* flush the current block */
  21536. }
  21537. //Assert(s->block_start >= 0L, "block gone");
  21538. // if (s.block_start < 0) throw new Error("block gone");
  21539. s.strstart += s.lookahead;
  21540. s.lookahead = 0;
  21541. /* Emit a stored block if pending_buf will be full: */
  21542. var max_start = s.block_start + max_block_size;
  21543. if (s.strstart === 0 || s.strstart >= max_start) {
  21544. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21545. s.lookahead = s.strstart - max_start;
  21546. s.strstart = max_start;
  21547. /*** FLUSH_BLOCK(s, 0); ***/
  21548. flush_block_only(s, false);
  21549. if (s.strm.avail_out === 0) {
  21550. return BS_NEED_MORE;
  21551. }
  21552. /***/
  21553. }
  21554. /* Flush if we may have to slide, otherwise block_start may become
  21555. * negative and the data will be gone:
  21556. */
  21557. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21558. /*** FLUSH_BLOCK(s, 0); ***/
  21559. flush_block_only(s, false);
  21560. if (s.strm.avail_out === 0) {
  21561. return BS_NEED_MORE;
  21562. }
  21563. /***/
  21564. }
  21565. }
  21566. s.insert = 0;
  21567. if (flush === Z_FINISH) {
  21568. /*** FLUSH_BLOCK(s, 1); ***/
  21569. flush_block_only(s, true);
  21570. if (s.strm.avail_out === 0) {
  21571. return BS_FINISH_STARTED;
  21572. }
  21573. /***/
  21574. return BS_FINISH_DONE;
  21575. }
  21576. if (s.strstart > s.block_start) {
  21577. /*** FLUSH_BLOCK(s, 0); ***/
  21578. flush_block_only(s, false);
  21579. if (s.strm.avail_out === 0) {
  21580. return BS_NEED_MORE;
  21581. }
  21582. /***/
  21583. }
  21584. return BS_NEED_MORE;
  21585. }
  21586. /* ===========================================================================
  21587. * Compress as much as possible from the input stream, return the current
  21588. * block state.
  21589. * This function does not perform lazy evaluation of matches and inserts
  21590. * new strings in the dictionary only for unmatched strings or for short
  21591. * matches. It is used only for the fast compression options.
  21592. */
  21593. function deflate_fast(s, flush) {
  21594. var hash_head; /* head of the hash chain */
  21595. var bflush; /* set if current block must be flushed */
  21596. for (;;) {
  21597. /* Make sure that we always have enough lookahead, except
  21598. * at the end of the input file. We need MAX_MATCH bytes
  21599. * for the next match, plus MIN_MATCH bytes to insert the
  21600. * string following the next match.
  21601. */
  21602. if (s.lookahead < MIN_LOOKAHEAD) {
  21603. fill_window(s);
  21604. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21605. return BS_NEED_MORE;
  21606. }
  21607. if (s.lookahead === 0) {
  21608. break; /* flush the current block */
  21609. }
  21610. }
  21611. /* Insert the string window[strstart .. strstart+2] in the
  21612. * dictionary, and set hash_head to the head of the hash chain:
  21613. */
  21614. hash_head = 0/*NIL*/;
  21615. if (s.lookahead >= MIN_MATCH) {
  21616. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21617. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21618. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21619. s.head[s.ins_h] = s.strstart;
  21620. /***/
  21621. }
  21622. /* Find the longest match, discarding those <= prev_length.
  21623. * At this point we have always match_length < MIN_MATCH
  21624. */
  21625. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21626. /* To simplify the code, we prevent matches with the string
  21627. * of window index 0 (in particular we have to avoid a match
  21628. * of the string with itself at the start of the input file).
  21629. */
  21630. s.match_length = longest_match(s, hash_head);
  21631. /* longest_match() sets match_start */
  21632. }
  21633. if (s.match_length >= MIN_MATCH) {
  21634. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21635. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21636. s.match_length - MIN_MATCH, bflush); ***/
  21637. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21638. s.lookahead -= s.match_length;
  21639. /* Insert new strings in the hash table only if the match length
  21640. * is not too large. This saves time but degrades compression.
  21641. */
  21642. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21643. s.match_length--; /* string at strstart already in table */
  21644. do {
  21645. s.strstart++;
  21646. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21647. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21648. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21649. s.head[s.ins_h] = s.strstart;
  21650. /***/
  21651. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21652. * always MIN_MATCH bytes ahead.
  21653. */
  21654. } while (--s.match_length !== 0);
  21655. s.strstart++;
  21656. } else
  21657. {
  21658. s.strstart += s.match_length;
  21659. s.match_length = 0;
  21660. s.ins_h = s.window[s.strstart];
  21661. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21662. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21663. //#if MIN_MATCH != 3
  21664. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21665. //#endif
  21666. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21667. * matter since it will be recomputed at next deflate call.
  21668. */
  21669. }
  21670. } else {
  21671. /* No match, output a literal byte */
  21672. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21673. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21674. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21675. s.lookahead--;
  21676. s.strstart++;
  21677. }
  21678. if (bflush) {
  21679. /*** FLUSH_BLOCK(s, 0); ***/
  21680. flush_block_only(s, false);
  21681. if (s.strm.avail_out === 0) {
  21682. return BS_NEED_MORE;
  21683. }
  21684. /***/
  21685. }
  21686. }
  21687. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21688. if (flush === Z_FINISH) {
  21689. /*** FLUSH_BLOCK(s, 1); ***/
  21690. flush_block_only(s, true);
  21691. if (s.strm.avail_out === 0) {
  21692. return BS_FINISH_STARTED;
  21693. }
  21694. /***/
  21695. return BS_FINISH_DONE;
  21696. }
  21697. if (s.last_lit) {
  21698. /*** FLUSH_BLOCK(s, 0); ***/
  21699. flush_block_only(s, false);
  21700. if (s.strm.avail_out === 0) {
  21701. return BS_NEED_MORE;
  21702. }
  21703. /***/
  21704. }
  21705. return BS_BLOCK_DONE;
  21706. }
  21707. /* ===========================================================================
  21708. * Same as above, but achieves better compression. We use a lazy
  21709. * evaluation for matches: a match is finally adopted only if there is
  21710. * no better match at the next window position.
  21711. */
  21712. function deflate_slow(s, flush) {
  21713. var hash_head; /* head of hash chain */
  21714. var bflush; /* set if current block must be flushed */
  21715. var max_insert;
  21716. /* Process the input block. */
  21717. for (;;) {
  21718. /* Make sure that we always have enough lookahead, except
  21719. * at the end of the input file. We need MAX_MATCH bytes
  21720. * for the next match, plus MIN_MATCH bytes to insert the
  21721. * string following the next match.
  21722. */
  21723. if (s.lookahead < MIN_LOOKAHEAD) {
  21724. fill_window(s);
  21725. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21726. return BS_NEED_MORE;
  21727. }
  21728. if (s.lookahead === 0) { break; } /* flush the current block */
  21729. }
  21730. /* Insert the string window[strstart .. strstart+2] in the
  21731. * dictionary, and set hash_head to the head of the hash chain:
  21732. */
  21733. hash_head = 0/*NIL*/;
  21734. if (s.lookahead >= MIN_MATCH) {
  21735. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21736. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21737. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21738. s.head[s.ins_h] = s.strstart;
  21739. /***/
  21740. }
  21741. /* Find the longest match, discarding those <= prev_length.
  21742. */
  21743. s.prev_length = s.match_length;
  21744. s.prev_match = s.match_start;
  21745. s.match_length = MIN_MATCH-1;
  21746. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21747. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21748. /* To simplify the code, we prevent matches with the string
  21749. * of window index 0 (in particular we have to avoid a match
  21750. * of the string with itself at the start of the input file).
  21751. */
  21752. s.match_length = longest_match(s, hash_head);
  21753. /* longest_match() sets match_start */
  21754. if (s.match_length <= 5 &&
  21755. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21756. /* If prev_match is also MIN_MATCH, match_start is garbage
  21757. * but we will ignore the current match anyway.
  21758. */
  21759. s.match_length = MIN_MATCH-1;
  21760. }
  21761. }
  21762. /* If there was a match at the previous step and the current
  21763. * match is not better, output the previous match:
  21764. */
  21765. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21766. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21767. /* Do not insert strings in hash table beyond this. */
  21768. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21769. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21770. s.prev_length - MIN_MATCH, bflush);***/
  21771. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21772. /* Insert in hash table all strings up to the end of the match.
  21773. * strstart-1 and strstart are already inserted. If there is not
  21774. * enough lookahead, the last two strings are not inserted in
  21775. * the hash table.
  21776. */
  21777. s.lookahead -= s.prev_length-1;
  21778. s.prev_length -= 2;
  21779. do {
  21780. if (++s.strstart <= max_insert) {
  21781. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21782. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21783. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21784. s.head[s.ins_h] = s.strstart;
  21785. /***/
  21786. }
  21787. } while (--s.prev_length !== 0);
  21788. s.match_available = 0;
  21789. s.match_length = MIN_MATCH-1;
  21790. s.strstart++;
  21791. if (bflush) {
  21792. /*** FLUSH_BLOCK(s, 0); ***/
  21793. flush_block_only(s, false);
  21794. if (s.strm.avail_out === 0) {
  21795. return BS_NEED_MORE;
  21796. }
  21797. /***/
  21798. }
  21799. } else if (s.match_available) {
  21800. /* If there was no match at the previous position, output a
  21801. * single literal. If there was a match but the current match
  21802. * is longer, truncate the previous match to a single literal.
  21803. */
  21804. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21805. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21806. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21807. if (bflush) {
  21808. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21809. flush_block_only(s, false);
  21810. /***/
  21811. }
  21812. s.strstart++;
  21813. s.lookahead--;
  21814. if (s.strm.avail_out === 0) {
  21815. return BS_NEED_MORE;
  21816. }
  21817. } else {
  21818. /* There is no previous match to compare with, wait for
  21819. * the next step to decide.
  21820. */
  21821. s.match_available = 1;
  21822. s.strstart++;
  21823. s.lookahead--;
  21824. }
  21825. }
  21826. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21827. if (s.match_available) {
  21828. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21829. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21830. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21831. s.match_available = 0;
  21832. }
  21833. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21834. if (flush === Z_FINISH) {
  21835. /*** FLUSH_BLOCK(s, 1); ***/
  21836. flush_block_only(s, true);
  21837. if (s.strm.avail_out === 0) {
  21838. return BS_FINISH_STARTED;
  21839. }
  21840. /***/
  21841. return BS_FINISH_DONE;
  21842. }
  21843. if (s.last_lit) {
  21844. /*** FLUSH_BLOCK(s, 0); ***/
  21845. flush_block_only(s, false);
  21846. if (s.strm.avail_out === 0) {
  21847. return BS_NEED_MORE;
  21848. }
  21849. /***/
  21850. }
  21851. return BS_BLOCK_DONE;
  21852. }
  21853. /* ===========================================================================
  21854. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21855. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21856. * deflate switches away from Z_RLE.)
  21857. */
  21858. function deflate_rle(s, flush) {
  21859. var bflush; /* set if current block must be flushed */
  21860. var prev; /* byte at distance one to match */
  21861. var scan, strend; /* scan goes up to strend for length of run */
  21862. var _win = s.window;
  21863. for (;;) {
  21864. /* Make sure that we always have enough lookahead, except
  21865. * at the end of the input file. We need MAX_MATCH bytes
  21866. * for the longest run, plus one for the unrolled loop.
  21867. */
  21868. if (s.lookahead <= MAX_MATCH) {
  21869. fill_window(s);
  21870. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21871. return BS_NEED_MORE;
  21872. }
  21873. if (s.lookahead === 0) { break; } /* flush the current block */
  21874. }
  21875. /* See how many times the previous byte repeats */
  21876. s.match_length = 0;
  21877. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21878. scan = s.strstart - 1;
  21879. prev = _win[scan];
  21880. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21881. strend = s.strstart + MAX_MATCH;
  21882. do {
  21883. /*jshint noempty:false*/
  21884. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21885. prev === _win[++scan] && prev === _win[++scan] &&
  21886. prev === _win[++scan] && prev === _win[++scan] &&
  21887. prev === _win[++scan] && prev === _win[++scan] &&
  21888. scan < strend);
  21889. s.match_length = MAX_MATCH - (strend - scan);
  21890. if (s.match_length > s.lookahead) {
  21891. s.match_length = s.lookahead;
  21892. }
  21893. }
  21894. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21895. }
  21896. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21897. if (s.match_length >= MIN_MATCH) {
  21898. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21899. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21900. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21901. s.lookahead -= s.match_length;
  21902. s.strstart += s.match_length;
  21903. s.match_length = 0;
  21904. } else {
  21905. /* No match, output a literal byte */
  21906. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21907. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21908. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21909. s.lookahead--;
  21910. s.strstart++;
  21911. }
  21912. if (bflush) {
  21913. /*** FLUSH_BLOCK(s, 0); ***/
  21914. flush_block_only(s, false);
  21915. if (s.strm.avail_out === 0) {
  21916. return BS_NEED_MORE;
  21917. }
  21918. /***/
  21919. }
  21920. }
  21921. s.insert = 0;
  21922. if (flush === Z_FINISH) {
  21923. /*** FLUSH_BLOCK(s, 1); ***/
  21924. flush_block_only(s, true);
  21925. if (s.strm.avail_out === 0) {
  21926. return BS_FINISH_STARTED;
  21927. }
  21928. /***/
  21929. return BS_FINISH_DONE;
  21930. }
  21931. if (s.last_lit) {
  21932. /*** FLUSH_BLOCK(s, 0); ***/
  21933. flush_block_only(s, false);
  21934. if (s.strm.avail_out === 0) {
  21935. return BS_NEED_MORE;
  21936. }
  21937. /***/
  21938. }
  21939. return BS_BLOCK_DONE;
  21940. }
  21941. /* ===========================================================================
  21942. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21943. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21944. */
  21945. function deflate_huff(s, flush) {
  21946. var bflush; /* set if current block must be flushed */
  21947. for (;;) {
  21948. /* Make sure that we have a literal to write. */
  21949. if (s.lookahead === 0) {
  21950. fill_window(s);
  21951. if (s.lookahead === 0) {
  21952. if (flush === Z_NO_FLUSH) {
  21953. return BS_NEED_MORE;
  21954. }
  21955. break; /* flush the current block */
  21956. }
  21957. }
  21958. /* Output a literal byte */
  21959. s.match_length = 0;
  21960. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21961. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21962. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21963. s.lookahead--;
  21964. s.strstart++;
  21965. if (bflush) {
  21966. /*** FLUSH_BLOCK(s, 0); ***/
  21967. flush_block_only(s, false);
  21968. if (s.strm.avail_out === 0) {
  21969. return BS_NEED_MORE;
  21970. }
  21971. /***/
  21972. }
  21973. }
  21974. s.insert = 0;
  21975. if (flush === Z_FINISH) {
  21976. /*** FLUSH_BLOCK(s, 1); ***/
  21977. flush_block_only(s, true);
  21978. if (s.strm.avail_out === 0) {
  21979. return BS_FINISH_STARTED;
  21980. }
  21981. /***/
  21982. return BS_FINISH_DONE;
  21983. }
  21984. if (s.last_lit) {
  21985. /*** FLUSH_BLOCK(s, 0); ***/
  21986. flush_block_only(s, false);
  21987. if (s.strm.avail_out === 0) {
  21988. return BS_NEED_MORE;
  21989. }
  21990. /***/
  21991. }
  21992. return BS_BLOCK_DONE;
  21993. }
  21994. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21995. * the desired pack level (0..9). The values given below have been tuned to
  21996. * exclude worst case performance for pathological files. Better values may be
  21997. * found for specific files.
  21998. */
  21999. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  22000. this.good_length = good_length;
  22001. this.max_lazy = max_lazy;
  22002. this.nice_length = nice_length;
  22003. this.max_chain = max_chain;
  22004. this.func = func;
  22005. };
  22006. var configuration_table;
  22007. configuration_table = [
  22008. /* good lazy nice chain */
  22009. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  22010. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  22011. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  22012. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  22013. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  22014. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  22015. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  22016. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  22017. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  22018. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  22019. ];
  22020. /* ===========================================================================
  22021. * Initialize the "longest match" routines for a new zlib stream
  22022. */
  22023. function lm_init(s) {
  22024. s.window_size = 2 * s.w_size;
  22025. /*** CLEAR_HASH(s); ***/
  22026. zero(s.head); // Fill with NIL (= 0);
  22027. /* Set the default configuration parameters:
  22028. */
  22029. s.max_lazy_match = configuration_table[s.level].max_lazy;
  22030. s.good_match = configuration_table[s.level].good_length;
  22031. s.nice_match = configuration_table[s.level].nice_length;
  22032. s.max_chain_length = configuration_table[s.level].max_chain;
  22033. s.strstart = 0;
  22034. s.block_start = 0;
  22035. s.lookahead = 0;
  22036. s.insert = 0;
  22037. s.match_length = s.prev_length = MIN_MATCH - 1;
  22038. s.match_available = 0;
  22039. s.ins_h = 0;
  22040. }
  22041. function DeflateState() {
  22042. this.strm = null; /* pointer back to this zlib stream */
  22043. this.status = 0; /* as the name implies */
  22044. this.pending_buf = null; /* output still pending */
  22045. this.pending_buf_size = 0; /* size of pending_buf */
  22046. this.pending_out = 0; /* next pending byte to output to the stream */
  22047. this.pending = 0; /* nb of bytes in the pending buffer */
  22048. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22049. this.gzhead = null; /* gzip header information to write */
  22050. this.gzindex = 0; /* where in extra, name, or comment */
  22051. this.method = Z_DEFLATED; /* can only be DEFLATED */
  22052. this.last_flush = -1; /* value of flush param for previous deflate call */
  22053. this.w_size = 0; /* LZ77 window size (32K by default) */
  22054. this.w_bits = 0; /* log2(w_size) (8..16) */
  22055. this.w_mask = 0; /* w_size - 1 */
  22056. this.window = null;
  22057. /* Sliding window. Input bytes are read into the second half of the window,
  22058. * and move to the first half later to keep a dictionary of at least wSize
  22059. * bytes. With this organization, matches are limited to a distance of
  22060. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  22061. * performed with a length multiple of the block size.
  22062. */
  22063. this.window_size = 0;
  22064. /* Actual size of window: 2*wSize, except when the user input buffer
  22065. * is directly used as sliding window.
  22066. */
  22067. this.prev = null;
  22068. /* Link to older string with same hash index. To limit the size of this
  22069. * array to 64K, this link is maintained only for the last 32K strings.
  22070. * An index in this array is thus a window index modulo 32K.
  22071. */
  22072. this.head = null; /* Heads of the hash chains or NIL. */
  22073. this.ins_h = 0; /* hash index of string to be inserted */
  22074. this.hash_size = 0; /* number of elements in hash table */
  22075. this.hash_bits = 0; /* log2(hash_size) */
  22076. this.hash_mask = 0; /* hash_size-1 */
  22077. this.hash_shift = 0;
  22078. /* Number of bits by which ins_h must be shifted at each input
  22079. * step. It must be such that after MIN_MATCH steps, the oldest
  22080. * byte no longer takes part in the hash key, that is:
  22081. * hash_shift * MIN_MATCH >= hash_bits
  22082. */
  22083. this.block_start = 0;
  22084. /* Window position at the beginning of the current output block. Gets
  22085. * negative when the window is moved backwards.
  22086. */
  22087. this.match_length = 0; /* length of best match */
  22088. this.prev_match = 0; /* previous match */
  22089. this.match_available = 0; /* set if previous match exists */
  22090. this.strstart = 0; /* start of string to insert */
  22091. this.match_start = 0; /* start of matching string */
  22092. this.lookahead = 0; /* number of valid bytes ahead in window */
  22093. this.prev_length = 0;
  22094. /* Length of the best match at previous step. Matches not greater than this
  22095. * are discarded. This is used in the lazy match evaluation.
  22096. */
  22097. this.max_chain_length = 0;
  22098. /* To speed up deflation, hash chains are never searched beyond this
  22099. * length. A higher limit improves compression ratio but degrades the
  22100. * speed.
  22101. */
  22102. this.max_lazy_match = 0;
  22103. /* Attempt to find a better match only when the current match is strictly
  22104. * smaller than this value. This mechanism is used only for compression
  22105. * levels >= 4.
  22106. */
  22107. // That's alias to max_lazy_match, don't use directly
  22108. //this.max_insert_length = 0;
  22109. /* Insert new strings in the hash table only if the match length is not
  22110. * greater than this length. This saves time but degrades compression.
  22111. * max_insert_length is used only for compression levels <= 3.
  22112. */
  22113. this.level = 0; /* compression level (1..9) */
  22114. this.strategy = 0; /* favor or force Huffman coding*/
  22115. this.good_match = 0;
  22116. /* Use a faster search when the previous match is longer than this */
  22117. this.nice_match = 0; /* Stop searching when current match exceeds this */
  22118. /* used by trees.c: */
  22119. /* Didn't use ct_data typedef below to suppress compiler warning */
  22120. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  22121. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  22122. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  22123. // Use flat array of DOUBLE size, with interleaved fata,
  22124. // because JS does not support effective
  22125. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  22126. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  22127. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  22128. zero(this.dyn_ltree);
  22129. zero(this.dyn_dtree);
  22130. zero(this.bl_tree);
  22131. this.l_desc = null; /* desc. for literal tree */
  22132. this.d_desc = null; /* desc. for distance tree */
  22133. this.bl_desc = null; /* desc. for bit length tree */
  22134. //ush bl_count[MAX_BITS+1];
  22135. this.bl_count = new utils.Buf16(MAX_BITS+1);
  22136. /* number of codes at each bit length for an optimal tree */
  22137. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  22138. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  22139. zero(this.heap);
  22140. this.heap_len = 0; /* number of elements in the heap */
  22141. this.heap_max = 0; /* element of largest frequency */
  22142. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  22143. * The same heap array is used to build all trees.
  22144. */
  22145. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  22146. zero(this.depth);
  22147. /* Depth of each subtree used as tie breaker for trees of equal frequency
  22148. */
  22149. this.l_buf = 0; /* buffer index for literals or lengths */
  22150. this.lit_bufsize = 0;
  22151. /* Size of match buffer for literals/lengths. There are 4 reasons for
  22152. * limiting lit_bufsize to 64K:
  22153. * - frequencies can be kept in 16 bit counters
  22154. * - if compression is not successful for the first block, all input
  22155. * data is still in the window so we can still emit a stored block even
  22156. * when input comes from standard input. (This can also be done for
  22157. * all blocks if lit_bufsize is not greater than 32K.)
  22158. * - if compression is not successful for a file smaller than 64K, we can
  22159. * even emit a stored file instead of a stored block (saving 5 bytes).
  22160. * This is applicable only for zip (not gzip or zlib).
  22161. * - creating new Huffman trees less frequently may not provide fast
  22162. * adaptation to changes in the input data statistics. (Take for
  22163. * example a binary file with poorly compressible code followed by
  22164. * a highly compressible string table.) Smaller buffer sizes give
  22165. * fast adaptation but have of course the overhead of transmitting
  22166. * trees more frequently.
  22167. * - I can't count above 4
  22168. */
  22169. this.last_lit = 0; /* running index in l_buf */
  22170. this.d_buf = 0;
  22171. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  22172. * the same number of elements. To use different lengths, an extra flag
  22173. * array would be necessary.
  22174. */
  22175. this.opt_len = 0; /* bit length of current block with optimal trees */
  22176. this.static_len = 0; /* bit length of current block with static trees */
  22177. this.matches = 0; /* number of string matches in current block */
  22178. this.insert = 0; /* bytes at end of window left to insert */
  22179. this.bi_buf = 0;
  22180. /* Output buffer. bits are inserted starting at the bottom (least
  22181. * significant bits).
  22182. */
  22183. this.bi_valid = 0;
  22184. /* Number of valid bits in bi_buf. All bits above the last valid bit
  22185. * are always zero.
  22186. */
  22187. // Used for window memory init. We safely ignore it for JS. That makes
  22188. // sense only for pointers and memory check tools.
  22189. //this.high_water = 0;
  22190. /* High water mark offset in window for initialized bytes -- bytes above
  22191. * this are set to zero in order to avoid memory check warnings when
  22192. * longest match routines access bytes past the input. This is then
  22193. * updated to the new high water mark.
  22194. */
  22195. }
  22196. function deflateResetKeep(strm) {
  22197. var s;
  22198. if (!strm || !strm.state) {
  22199. return err(strm, Z_STREAM_ERROR);
  22200. }
  22201. strm.total_in = strm.total_out = 0;
  22202. strm.data_type = Z_UNKNOWN;
  22203. s = strm.state;
  22204. s.pending = 0;
  22205. s.pending_out = 0;
  22206. if (s.wrap < 0) {
  22207. s.wrap = -s.wrap;
  22208. /* was made negative by deflate(..., Z_FINISH); */
  22209. }
  22210. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  22211. strm.adler = (s.wrap === 2) ?
  22212. 0 // crc32(0, Z_NULL, 0)
  22213. :
  22214. 1; // adler32(0, Z_NULL, 0)
  22215. s.last_flush = Z_NO_FLUSH;
  22216. trees._tr_init(s);
  22217. return Z_OK;
  22218. }
  22219. function deflateReset(strm) {
  22220. var ret = deflateResetKeep(strm);
  22221. if (ret === Z_OK) {
  22222. lm_init(strm.state);
  22223. }
  22224. return ret;
  22225. }
  22226. function deflateSetHeader(strm, head) {
  22227. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22228. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  22229. strm.state.gzhead = head;
  22230. return Z_OK;
  22231. }
  22232. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  22233. if (!strm) { // === Z_NULL
  22234. return Z_STREAM_ERROR;
  22235. }
  22236. var wrap = 1;
  22237. if (level === Z_DEFAULT_COMPRESSION) {
  22238. level = 6;
  22239. }
  22240. if (windowBits < 0) { /* suppress zlib wrapper */
  22241. wrap = 0;
  22242. windowBits = -windowBits;
  22243. }
  22244. else if (windowBits > 15) {
  22245. wrap = 2; /* write gzip wrapper instead */
  22246. windowBits -= 16;
  22247. }
  22248. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  22249. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  22250. strategy < 0 || strategy > Z_FIXED) {
  22251. return err(strm, Z_STREAM_ERROR);
  22252. }
  22253. if (windowBits === 8) {
  22254. windowBits = 9;
  22255. }
  22256. /* until 256-byte window bug fixed */
  22257. var s = new DeflateState();
  22258. strm.state = s;
  22259. s.strm = strm;
  22260. s.wrap = wrap;
  22261. s.gzhead = null;
  22262. s.w_bits = windowBits;
  22263. s.w_size = 1 << s.w_bits;
  22264. s.w_mask = s.w_size - 1;
  22265. s.hash_bits = memLevel + 7;
  22266. s.hash_size = 1 << s.hash_bits;
  22267. s.hash_mask = s.hash_size - 1;
  22268. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  22269. s.window = new utils.Buf8(s.w_size * 2);
  22270. s.head = new utils.Buf16(s.hash_size);
  22271. s.prev = new utils.Buf16(s.w_size);
  22272. // Don't need mem init magic for JS.
  22273. //s.high_water = 0; /* nothing written to s->window yet */
  22274. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  22275. s.pending_buf_size = s.lit_bufsize * 4;
  22276. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  22277. s.d_buf = s.lit_bufsize >> 1;
  22278. s.l_buf = (1 + 2) * s.lit_bufsize;
  22279. s.level = level;
  22280. s.strategy = strategy;
  22281. s.method = method;
  22282. return deflateReset(strm);
  22283. }
  22284. function deflateInit(strm, level) {
  22285. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  22286. }
  22287. function deflate(strm, flush) {
  22288. var old_flush, s;
  22289. var beg, val; // for gzip header write only
  22290. if (!strm || !strm.state ||
  22291. flush > Z_BLOCK || flush < 0) {
  22292. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  22293. }
  22294. s = strm.state;
  22295. if (!strm.output ||
  22296. (!strm.input && strm.avail_in !== 0) ||
  22297. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  22298. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  22299. }
  22300. s.strm = strm; /* just in case */
  22301. old_flush = s.last_flush;
  22302. s.last_flush = flush;
  22303. /* Write the header */
  22304. if (s.status === INIT_STATE) {
  22305. if (s.wrap === 2) { // GZIP header
  22306. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22307. put_byte(s, 31);
  22308. put_byte(s, 139);
  22309. put_byte(s, 8);
  22310. if (!s.gzhead) { // s->gzhead == Z_NULL
  22311. put_byte(s, 0);
  22312. put_byte(s, 0);
  22313. put_byte(s, 0);
  22314. put_byte(s, 0);
  22315. put_byte(s, 0);
  22316. put_byte(s, s.level === 9 ? 2 :
  22317. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22318. 4 : 0));
  22319. put_byte(s, OS_CODE);
  22320. s.status = BUSY_STATE;
  22321. }
  22322. else {
  22323. put_byte(s, (s.gzhead.text ? 1 : 0) +
  22324. (s.gzhead.hcrc ? 2 : 0) +
  22325. (!s.gzhead.extra ? 0 : 4) +
  22326. (!s.gzhead.name ? 0 : 8) +
  22327. (!s.gzhead.comment ? 0 : 16)
  22328. );
  22329. put_byte(s, s.gzhead.time & 0xff);
  22330. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  22331. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  22332. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  22333. put_byte(s, s.level === 9 ? 2 :
  22334. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22335. 4 : 0));
  22336. put_byte(s, s.gzhead.os & 0xff);
  22337. if (s.gzhead.extra && s.gzhead.extra.length) {
  22338. put_byte(s, s.gzhead.extra.length & 0xff);
  22339. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  22340. }
  22341. if (s.gzhead.hcrc) {
  22342. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  22343. }
  22344. s.gzindex = 0;
  22345. s.status = EXTRA_STATE;
  22346. }
  22347. }
  22348. else // DEFLATE header
  22349. {
  22350. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  22351. var level_flags = -1;
  22352. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  22353. level_flags = 0;
  22354. } else if (s.level < 6) {
  22355. level_flags = 1;
  22356. } else if (s.level === 6) {
  22357. level_flags = 2;
  22358. } else {
  22359. level_flags = 3;
  22360. }
  22361. header |= (level_flags << 6);
  22362. if (s.strstart !== 0) { header |= PRESET_DICT; }
  22363. header += 31 - (header % 31);
  22364. s.status = BUSY_STATE;
  22365. putShortMSB(s, header);
  22366. /* Save the adler32 of the preset dictionary: */
  22367. if (s.strstart !== 0) {
  22368. putShortMSB(s, strm.adler >>> 16);
  22369. putShortMSB(s, strm.adler & 0xffff);
  22370. }
  22371. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  22372. }
  22373. }
  22374. //#ifdef GZIP
  22375. if (s.status === EXTRA_STATE) {
  22376. if (s.gzhead.extra/* != Z_NULL*/) {
  22377. beg = s.pending; /* start of bytes to update crc */
  22378. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  22379. if (s.pending === s.pending_buf_size) {
  22380. if (s.gzhead.hcrc && s.pending > beg) {
  22381. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22382. }
  22383. flush_pending(strm);
  22384. beg = s.pending;
  22385. if (s.pending === s.pending_buf_size) {
  22386. break;
  22387. }
  22388. }
  22389. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  22390. s.gzindex++;
  22391. }
  22392. if (s.gzhead.hcrc && s.pending > beg) {
  22393. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22394. }
  22395. if (s.gzindex === s.gzhead.extra.length) {
  22396. s.gzindex = 0;
  22397. s.status = NAME_STATE;
  22398. }
  22399. }
  22400. else {
  22401. s.status = NAME_STATE;
  22402. }
  22403. }
  22404. if (s.status === NAME_STATE) {
  22405. if (s.gzhead.name/* != Z_NULL*/) {
  22406. beg = s.pending; /* start of bytes to update crc */
  22407. //int val;
  22408. do {
  22409. if (s.pending === s.pending_buf_size) {
  22410. if (s.gzhead.hcrc && s.pending > beg) {
  22411. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22412. }
  22413. flush_pending(strm);
  22414. beg = s.pending;
  22415. if (s.pending === s.pending_buf_size) {
  22416. val = 1;
  22417. break;
  22418. }
  22419. }
  22420. // JS specific: little magic to add zero terminator to end of string
  22421. if (s.gzindex < s.gzhead.name.length) {
  22422. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  22423. } else {
  22424. val = 0;
  22425. }
  22426. put_byte(s, val);
  22427. } while (val !== 0);
  22428. if (s.gzhead.hcrc && s.pending > beg) {
  22429. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22430. }
  22431. if (val === 0) {
  22432. s.gzindex = 0;
  22433. s.status = COMMENT_STATE;
  22434. }
  22435. }
  22436. else {
  22437. s.status = COMMENT_STATE;
  22438. }
  22439. }
  22440. if (s.status === COMMENT_STATE) {
  22441. if (s.gzhead.comment/* != Z_NULL*/) {
  22442. beg = s.pending; /* start of bytes to update crc */
  22443. //int val;
  22444. do {
  22445. if (s.pending === s.pending_buf_size) {
  22446. if (s.gzhead.hcrc && s.pending > beg) {
  22447. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22448. }
  22449. flush_pending(strm);
  22450. beg = s.pending;
  22451. if (s.pending === s.pending_buf_size) {
  22452. val = 1;
  22453. break;
  22454. }
  22455. }
  22456. // JS specific: little magic to add zero terminator to end of string
  22457. if (s.gzindex < s.gzhead.comment.length) {
  22458. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  22459. } else {
  22460. val = 0;
  22461. }
  22462. put_byte(s, val);
  22463. } while (val !== 0);
  22464. if (s.gzhead.hcrc && s.pending > beg) {
  22465. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22466. }
  22467. if (val === 0) {
  22468. s.status = HCRC_STATE;
  22469. }
  22470. }
  22471. else {
  22472. s.status = HCRC_STATE;
  22473. }
  22474. }
  22475. if (s.status === HCRC_STATE) {
  22476. if (s.gzhead.hcrc) {
  22477. if (s.pending + 2 > s.pending_buf_size) {
  22478. flush_pending(strm);
  22479. }
  22480. if (s.pending + 2 <= s.pending_buf_size) {
  22481. put_byte(s, strm.adler & 0xff);
  22482. put_byte(s, (strm.adler >> 8) & 0xff);
  22483. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22484. s.status = BUSY_STATE;
  22485. }
  22486. }
  22487. else {
  22488. s.status = BUSY_STATE;
  22489. }
  22490. }
  22491. //#endif
  22492. /* Flush as much pending output as possible */
  22493. if (s.pending !== 0) {
  22494. flush_pending(strm);
  22495. if (strm.avail_out === 0) {
  22496. /* Since avail_out is 0, deflate will be called again with
  22497. * more output space, but possibly with both pending and
  22498. * avail_in equal to zero. There won't be anything to do,
  22499. * but this is not an error situation so make sure we
  22500. * return OK instead of BUF_ERROR at next call of deflate:
  22501. */
  22502. s.last_flush = -1;
  22503. return Z_OK;
  22504. }
  22505. /* Make sure there is something to do and avoid duplicate consecutive
  22506. * flushes. For repeated and useless calls with Z_FINISH, we keep
  22507. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  22508. */
  22509. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  22510. flush !== Z_FINISH) {
  22511. return err(strm, Z_BUF_ERROR);
  22512. }
  22513. /* User must not provide more input after the first FINISH: */
  22514. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  22515. return err(strm, Z_BUF_ERROR);
  22516. }
  22517. /* Start a new block or continue the current one.
  22518. */
  22519. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  22520. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  22521. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  22522. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  22523. configuration_table[s.level].func(s, flush));
  22524. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22525. s.status = FINISH_STATE;
  22526. }
  22527. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22528. if (strm.avail_out === 0) {
  22529. s.last_flush = -1;
  22530. /* avoid BUF_ERROR next call, see above */
  22531. }
  22532. return Z_OK;
  22533. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22534. * of deflate should use the same flush parameter to make sure
  22535. * that the flush is complete. So we don't have to output an
  22536. * empty block here, this will be done at next call. This also
  22537. * ensures that for a very small output buffer, we emit at most
  22538. * one empty block.
  22539. */
  22540. }
  22541. if (bstate === BS_BLOCK_DONE) {
  22542. if (flush === Z_PARTIAL_FLUSH) {
  22543. trees._tr_align(s);
  22544. }
  22545. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22546. trees._tr_stored_block(s, 0, 0, false);
  22547. /* For a full flush, this empty block will be recognized
  22548. * as a special marker by inflate_sync().
  22549. */
  22550. if (flush === Z_FULL_FLUSH) {
  22551. /*** CLEAR_HASH(s); ***/ /* forget history */
  22552. zero(s.head); // Fill with NIL (= 0);
  22553. if (s.lookahead === 0) {
  22554. s.strstart = 0;
  22555. s.block_start = 0;
  22556. s.insert = 0;
  22557. }
  22558. }
  22559. }
  22560. flush_pending(strm);
  22561. if (strm.avail_out === 0) {
  22562. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22563. return Z_OK;
  22564. }
  22565. }
  22566. }
  22567. //Assert(strm->avail_out > 0, "bug2");
  22568. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22569. if (flush !== Z_FINISH) { return Z_OK; }
  22570. if (s.wrap <= 0) { return Z_STREAM_END; }
  22571. /* Write the trailer */
  22572. if (s.wrap === 2) {
  22573. put_byte(s, strm.adler & 0xff);
  22574. put_byte(s, (strm.adler >> 8) & 0xff);
  22575. put_byte(s, (strm.adler >> 16) & 0xff);
  22576. put_byte(s, (strm.adler >> 24) & 0xff);
  22577. put_byte(s, strm.total_in & 0xff);
  22578. put_byte(s, (strm.total_in >> 8) & 0xff);
  22579. put_byte(s, (strm.total_in >> 16) & 0xff);
  22580. put_byte(s, (strm.total_in >> 24) & 0xff);
  22581. }
  22582. else
  22583. {
  22584. putShortMSB(s, strm.adler >>> 16);
  22585. putShortMSB(s, strm.adler & 0xffff);
  22586. }
  22587. flush_pending(strm);
  22588. /* If avail_out is zero, the application will call deflate again
  22589. * to flush the rest.
  22590. */
  22591. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22592. /* write the trailer only once! */
  22593. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22594. }
  22595. function deflateEnd(strm) {
  22596. var status;
  22597. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22598. return Z_STREAM_ERROR;
  22599. }
  22600. status = strm.state.status;
  22601. if (status !== INIT_STATE &&
  22602. status !== EXTRA_STATE &&
  22603. status !== NAME_STATE &&
  22604. status !== COMMENT_STATE &&
  22605. status !== HCRC_STATE &&
  22606. status !== BUSY_STATE &&
  22607. status !== FINISH_STATE
  22608. ) {
  22609. return err(strm, Z_STREAM_ERROR);
  22610. }
  22611. strm.state = null;
  22612. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22613. }
  22614. /* =========================================================================
  22615. * Copy the source state to the destination state
  22616. */
  22617. //function deflateCopy(dest, source) {
  22618. //
  22619. //}
  22620. exports.deflateInit = deflateInit;
  22621. exports.deflateInit2 = deflateInit2;
  22622. exports.deflateReset = deflateReset;
  22623. exports.deflateResetKeep = deflateResetKeep;
  22624. exports.deflateSetHeader = deflateSetHeader;
  22625. exports.deflate = deflate;
  22626. exports.deflateEnd = deflateEnd;
  22627. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22628. /* Not implemented
  22629. exports.deflateBound = deflateBound;
  22630. exports.deflateCopy = deflateCopy;
  22631. exports.deflateSetDictionary = deflateSetDictionary;
  22632. exports.deflateParams = deflateParams;
  22633. exports.deflatePending = deflatePending;
  22634. exports.deflatePrime = deflatePrime;
  22635. exports.deflateTune = deflateTune;
  22636. */
  22637. },{"../utils/common":76,"./adler32":78,"./crc32":80,"./messages":86,"./trees":87}],82:[function(require,module,exports){
  22638. 'use strict';
  22639. function GZheader() {
  22640. /* true if compressed data believed to be text */
  22641. this.text = 0;
  22642. /* modification time */
  22643. this.time = 0;
  22644. /* extra flags (not used when writing a gzip file) */
  22645. this.xflags = 0;
  22646. /* operating system */
  22647. this.os = 0;
  22648. /* pointer to extra field or Z_NULL if none */
  22649. this.extra = null;
  22650. /* extra field length (valid if extra != Z_NULL) */
  22651. this.extra_len = 0; // Actually, we don't need it in JS,
  22652. // but leave for few code modifications
  22653. //
  22654. // Setup limits is not necessary because in js we should not preallocate memory
  22655. // for inflate use constant limit in 65536 bytes
  22656. //
  22657. /* space at extra (only when reading header) */
  22658. // this.extra_max = 0;
  22659. /* pointer to zero-terminated file name or Z_NULL */
  22660. this.name = '';
  22661. /* space at name (only when reading header) */
  22662. // this.name_max = 0;
  22663. /* pointer to zero-terminated comment or Z_NULL */
  22664. this.comment = '';
  22665. /* space at comment (only when reading header) */
  22666. // this.comm_max = 0;
  22667. /* true if there was or will be a header crc */
  22668. this.hcrc = 0;
  22669. /* true when done reading gzip header (not used when writing a gzip file) */
  22670. this.done = false;
  22671. }
  22672. module.exports = GZheader;
  22673. },{}],83:[function(require,module,exports){
  22674. 'use strict';
  22675. // See state defs from inflate.js
  22676. var BAD = 30; /* got a data error -- remain here until reset */
  22677. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22678. /*
  22679. Decode literal, length, and distance codes and write out the resulting
  22680. literal and match bytes until either not enough input or output is
  22681. available, an end-of-block is encountered, or a data error is encountered.
  22682. When large enough input and output buffers are supplied to inflate(), for
  22683. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22684. inflate execution time is spent in this routine.
  22685. Entry assumptions:
  22686. state.mode === LEN
  22687. strm.avail_in >= 6
  22688. strm.avail_out >= 258
  22689. start >= strm.avail_out
  22690. state.bits < 8
  22691. On return, state.mode is one of:
  22692. LEN -- ran out of enough output space or enough available input
  22693. TYPE -- reached end of block code, inflate() to interpret next block
  22694. BAD -- error in block data
  22695. Notes:
  22696. - The maximum input bits used by a length/distance pair is 15 bits for the
  22697. length code, 5 bits for the length extra, 15 bits for the distance code,
  22698. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22699. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22700. checking for available input while decoding.
  22701. - The maximum bytes that a single length/distance pair can output is 258
  22702. bytes, which is the maximum length that can be coded. inflate_fast()
  22703. requires strm.avail_out >= 258 for each loop to avoid checking for
  22704. output space.
  22705. */
  22706. module.exports = function inflate_fast(strm, start) {
  22707. var state;
  22708. var _in; /* local strm.input */
  22709. var last; /* have enough input while in < last */
  22710. var _out; /* local strm.output */
  22711. var beg; /* inflate()'s initial strm.output */
  22712. var end; /* while out < end, enough space available */
  22713. //#ifdef INFLATE_STRICT
  22714. var dmax; /* maximum distance from zlib header */
  22715. //#endif
  22716. var wsize; /* window size or zero if not using window */
  22717. var whave; /* valid bytes in the window */
  22718. var wnext; /* window write index */
  22719. var window; /* allocated sliding window, if wsize != 0 */
  22720. var hold; /* local strm.hold */
  22721. var bits; /* local strm.bits */
  22722. var lcode; /* local strm.lencode */
  22723. var dcode; /* local strm.distcode */
  22724. var lmask; /* mask for first level of length codes */
  22725. var dmask; /* mask for first level of distance codes */
  22726. var here; /* retrieved table entry */
  22727. var op; /* code bits, operation, extra bits, or */
  22728. /* window position, window bytes to copy */
  22729. var len; /* match length, unused bytes */
  22730. var dist; /* match distance */
  22731. var from; /* where to copy match from */
  22732. var from_source;
  22733. var input, output; // JS specific, because we have no pointers
  22734. /* copy state to local variables */
  22735. state = strm.state;
  22736. //here = state.here;
  22737. _in = strm.next_in;
  22738. input = strm.input;
  22739. last = _in + (strm.avail_in - 5);
  22740. _out = strm.next_out;
  22741. output = strm.output;
  22742. beg = _out - (start - strm.avail_out);
  22743. end = _out + (strm.avail_out - 257);
  22744. //#ifdef INFLATE_STRICT
  22745. dmax = state.dmax;
  22746. //#endif
  22747. wsize = state.wsize;
  22748. whave = state.whave;
  22749. wnext = state.wnext;
  22750. window = state.window;
  22751. hold = state.hold;
  22752. bits = state.bits;
  22753. lcode = state.lencode;
  22754. dcode = state.distcode;
  22755. lmask = (1 << state.lenbits) - 1;
  22756. dmask = (1 << state.distbits) - 1;
  22757. /* decode literals and length/distances until end-of-block or not enough
  22758. input data or output space */
  22759. top:
  22760. do {
  22761. if (bits < 15) {
  22762. hold += input[_in++] << bits;
  22763. bits += 8;
  22764. hold += input[_in++] << bits;
  22765. bits += 8;
  22766. }
  22767. here = lcode[hold & lmask];
  22768. dolen:
  22769. for (;;) { // Goto emulation
  22770. op = here >>> 24/*here.bits*/;
  22771. hold >>>= op;
  22772. bits -= op;
  22773. op = (here >>> 16) & 0xff/*here.op*/;
  22774. if (op === 0) { /* literal */
  22775. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22776. // "inflate: literal '%c'\n" :
  22777. // "inflate: literal 0x%02x\n", here.val));
  22778. output[_out++] = here & 0xffff/*here.val*/;
  22779. }
  22780. else if (op & 16) { /* length base */
  22781. len = here & 0xffff/*here.val*/;
  22782. op &= 15; /* number of extra bits */
  22783. if (op) {
  22784. if (bits < op) {
  22785. hold += input[_in++] << bits;
  22786. bits += 8;
  22787. }
  22788. len += hold & ((1 << op) - 1);
  22789. hold >>>= op;
  22790. bits -= op;
  22791. }
  22792. //Tracevv((stderr, "inflate: length %u\n", len));
  22793. if (bits < 15) {
  22794. hold += input[_in++] << bits;
  22795. bits += 8;
  22796. hold += input[_in++] << bits;
  22797. bits += 8;
  22798. }
  22799. here = dcode[hold & dmask];
  22800. dodist:
  22801. for (;;) { // goto emulation
  22802. op = here >>> 24/*here.bits*/;
  22803. hold >>>= op;
  22804. bits -= op;
  22805. op = (here >>> 16) & 0xff/*here.op*/;
  22806. if (op & 16) { /* distance base */
  22807. dist = here & 0xffff/*here.val*/;
  22808. op &= 15; /* number of extra bits */
  22809. if (bits < op) {
  22810. hold += input[_in++] << bits;
  22811. bits += 8;
  22812. if (bits < op) {
  22813. hold += input[_in++] << bits;
  22814. bits += 8;
  22815. }
  22816. }
  22817. dist += hold & ((1 << op) - 1);
  22818. //#ifdef INFLATE_STRICT
  22819. if (dist > dmax) {
  22820. strm.msg = 'invalid distance too far back';
  22821. state.mode = BAD;
  22822. break top;
  22823. }
  22824. //#endif
  22825. hold >>>= op;
  22826. bits -= op;
  22827. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22828. op = _out - beg; /* max distance in output */
  22829. if (dist > op) { /* see if copy from window */
  22830. op = dist - op; /* distance back in window */
  22831. if (op > whave) {
  22832. if (state.sane) {
  22833. strm.msg = 'invalid distance too far back';
  22834. state.mode = BAD;
  22835. break top;
  22836. }
  22837. // (!) This block is disabled in zlib defailts,
  22838. // don't enable it for binary compatibility
  22839. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22840. // if (len <= op - whave) {
  22841. // do {
  22842. // output[_out++] = 0;
  22843. // } while (--len);
  22844. // continue top;
  22845. // }
  22846. // len -= op - whave;
  22847. // do {
  22848. // output[_out++] = 0;
  22849. // } while (--op > whave);
  22850. // if (op === 0) {
  22851. // from = _out - dist;
  22852. // do {
  22853. // output[_out++] = output[from++];
  22854. // } while (--len);
  22855. // continue top;
  22856. // }
  22857. //#endif
  22858. }
  22859. from = 0; // window index
  22860. from_source = window;
  22861. if (wnext === 0) { /* very common case */
  22862. from += wsize - op;
  22863. if (op < len) { /* some from window */
  22864. len -= op;
  22865. do {
  22866. output[_out++] = window[from++];
  22867. } while (--op);
  22868. from = _out - dist; /* rest from output */
  22869. from_source = output;
  22870. }
  22871. }
  22872. else if (wnext < op) { /* wrap around window */
  22873. from += wsize + wnext - op;
  22874. op -= wnext;
  22875. if (op < len) { /* some from end of window */
  22876. len -= op;
  22877. do {
  22878. output[_out++] = window[from++];
  22879. } while (--op);
  22880. from = 0;
  22881. if (wnext < len) { /* some from start of window */
  22882. op = wnext;
  22883. len -= op;
  22884. do {
  22885. output[_out++] = window[from++];
  22886. } while (--op);
  22887. from = _out - dist; /* rest from output */
  22888. from_source = output;
  22889. }
  22890. }
  22891. }
  22892. else { /* contiguous in window */
  22893. from += wnext - op;
  22894. if (op < len) { /* some from window */
  22895. len -= op;
  22896. do {
  22897. output[_out++] = window[from++];
  22898. } while (--op);
  22899. from = _out - dist; /* rest from output */
  22900. from_source = output;
  22901. }
  22902. }
  22903. while (len > 2) {
  22904. output[_out++] = from_source[from++];
  22905. output[_out++] = from_source[from++];
  22906. output[_out++] = from_source[from++];
  22907. len -= 3;
  22908. }
  22909. if (len) {
  22910. output[_out++] = from_source[from++];
  22911. if (len > 1) {
  22912. output[_out++] = from_source[from++];
  22913. }
  22914. }
  22915. }
  22916. else {
  22917. from = _out - dist; /* copy direct from output */
  22918. do { /* minimum length is three */
  22919. output[_out++] = output[from++];
  22920. output[_out++] = output[from++];
  22921. output[_out++] = output[from++];
  22922. len -= 3;
  22923. } while (len > 2);
  22924. if (len) {
  22925. output[_out++] = output[from++];
  22926. if (len > 1) {
  22927. output[_out++] = output[from++];
  22928. }
  22929. }
  22930. }
  22931. }
  22932. else if ((op & 64) === 0) { /* 2nd level distance code */
  22933. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22934. continue dodist;
  22935. }
  22936. else {
  22937. strm.msg = 'invalid distance code';
  22938. state.mode = BAD;
  22939. break top;
  22940. }
  22941. break; // need to emulate goto via "continue"
  22942. }
  22943. }
  22944. else if ((op & 64) === 0) { /* 2nd level length code */
  22945. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22946. continue dolen;
  22947. }
  22948. else if (op & 32) { /* end-of-block */
  22949. //Tracevv((stderr, "inflate: end of block\n"));
  22950. state.mode = TYPE;
  22951. break top;
  22952. }
  22953. else {
  22954. strm.msg = 'invalid literal/length code';
  22955. state.mode = BAD;
  22956. break top;
  22957. }
  22958. break; // need to emulate goto via "continue"
  22959. }
  22960. } while (_in < last && _out < end);
  22961. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22962. len = bits >> 3;
  22963. _in -= len;
  22964. bits -= len << 3;
  22965. hold &= (1 << bits) - 1;
  22966. /* update state and return */
  22967. strm.next_in = _in;
  22968. strm.next_out = _out;
  22969. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22970. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22971. state.hold = hold;
  22972. state.bits = bits;
  22973. return;
  22974. };
  22975. },{}],84:[function(require,module,exports){
  22976. 'use strict';
  22977. var utils = require('../utils/common');
  22978. var adler32 = require('./adler32');
  22979. var crc32 = require('./crc32');
  22980. var inflate_fast = require('./inffast');
  22981. var inflate_table = require('./inftrees');
  22982. var CODES = 0;
  22983. var LENS = 1;
  22984. var DISTS = 2;
  22985. /* Public constants ==========================================================*/
  22986. /* ===========================================================================*/
  22987. /* Allowed flush values; see deflate() and inflate() below for details */
  22988. //var Z_NO_FLUSH = 0;
  22989. //var Z_PARTIAL_FLUSH = 1;
  22990. //var Z_SYNC_FLUSH = 2;
  22991. //var Z_FULL_FLUSH = 3;
  22992. var Z_FINISH = 4;
  22993. var Z_BLOCK = 5;
  22994. var Z_TREES = 6;
  22995. /* Return codes for the compression/decompression functions. Negative values
  22996. * are errors, positive values are used for special but normal events.
  22997. */
  22998. var Z_OK = 0;
  22999. var Z_STREAM_END = 1;
  23000. var Z_NEED_DICT = 2;
  23001. //var Z_ERRNO = -1;
  23002. var Z_STREAM_ERROR = -2;
  23003. var Z_DATA_ERROR = -3;
  23004. var Z_MEM_ERROR = -4;
  23005. var Z_BUF_ERROR = -5;
  23006. //var Z_VERSION_ERROR = -6;
  23007. /* The deflate compression method */
  23008. var Z_DEFLATED = 8;
  23009. /* STATES ====================================================================*/
  23010. /* ===========================================================================*/
  23011. var HEAD = 1; /* i: waiting for magic header */
  23012. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  23013. var TIME = 3; /* i: waiting for modification time (gzip) */
  23014. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  23015. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  23016. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  23017. var NAME = 7; /* i: waiting for end of file name (gzip) */
  23018. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  23019. var HCRC = 9; /* i: waiting for header crc (gzip) */
  23020. var DICTID = 10; /* i: waiting for dictionary check value */
  23021. var DICT = 11; /* waiting for inflateSetDictionary() call */
  23022. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  23023. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  23024. var STORED = 14; /* i: waiting for stored size (length and complement) */
  23025. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  23026. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  23027. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  23028. var LENLENS = 18; /* i: waiting for code length code lengths */
  23029. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  23030. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  23031. var LEN = 21; /* i: waiting for length/lit/eob code */
  23032. var LENEXT = 22; /* i: waiting for length extra bits */
  23033. var DIST = 23; /* i: waiting for distance code */
  23034. var DISTEXT = 24; /* i: waiting for distance extra bits */
  23035. var MATCH = 25; /* o: waiting for output space to copy string */
  23036. var LIT = 26; /* o: waiting for output space to write literal */
  23037. var CHECK = 27; /* i: waiting for 32-bit check value */
  23038. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  23039. var DONE = 29; /* finished check, done -- remain here until reset */
  23040. var BAD = 30; /* got a data error -- remain here until reset */
  23041. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  23042. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  23043. /* ===========================================================================*/
  23044. var ENOUGH_LENS = 852;
  23045. var ENOUGH_DISTS = 592;
  23046. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23047. var MAX_WBITS = 15;
  23048. /* 32K LZ77 window */
  23049. var DEF_WBITS = MAX_WBITS;
  23050. function ZSWAP32(q) {
  23051. return (((q >>> 24) & 0xff) +
  23052. ((q >>> 8) & 0xff00) +
  23053. ((q & 0xff00) << 8) +
  23054. ((q & 0xff) << 24));
  23055. }
  23056. function InflateState() {
  23057. this.mode = 0; /* current inflate mode */
  23058. this.last = false; /* true if processing last block */
  23059. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  23060. this.havedict = false; /* true if dictionary provided */
  23061. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  23062. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  23063. this.check = 0; /* protected copy of check value */
  23064. this.total = 0; /* protected copy of output count */
  23065. // TODO: may be {}
  23066. this.head = null; /* where to save gzip header information */
  23067. /* sliding window */
  23068. this.wbits = 0; /* log base 2 of requested window size */
  23069. this.wsize = 0; /* window size or zero if not using window */
  23070. this.whave = 0; /* valid bytes in the window */
  23071. this.wnext = 0; /* window write index */
  23072. this.window = null; /* allocated sliding window, if needed */
  23073. /* bit accumulator */
  23074. this.hold = 0; /* input bit accumulator */
  23075. this.bits = 0; /* number of bits in "in" */
  23076. /* for string and stored block copying */
  23077. this.length = 0; /* literal or length of data to copy */
  23078. this.offset = 0; /* distance back to copy string from */
  23079. /* for table and code decoding */
  23080. this.extra = 0; /* extra bits needed */
  23081. /* fixed and dynamic code tables */
  23082. this.lencode = null; /* starting table for length/literal codes */
  23083. this.distcode = null; /* starting table for distance codes */
  23084. this.lenbits = 0; /* index bits for lencode */
  23085. this.distbits = 0; /* index bits for distcode */
  23086. /* dynamic table building */
  23087. this.ncode = 0; /* number of code length code lengths */
  23088. this.nlen = 0; /* number of length code lengths */
  23089. this.ndist = 0; /* number of distance code lengths */
  23090. this.have = 0; /* number of code lengths in lens[] */
  23091. this.next = null; /* next available space in codes[] */
  23092. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  23093. this.work = new utils.Buf16(288); /* work area for code table building */
  23094. /*
  23095. because we don't have pointers in js, we use lencode and distcode directly
  23096. as buffers so we don't need codes
  23097. */
  23098. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  23099. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  23100. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  23101. this.sane = 0; /* if false, allow invalid distance too far */
  23102. this.back = 0; /* bits back of last unprocessed length/lit */
  23103. this.was = 0; /* initial length of match */
  23104. }
  23105. function inflateResetKeep(strm) {
  23106. var state;
  23107. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23108. state = strm.state;
  23109. strm.total_in = strm.total_out = state.total = 0;
  23110. strm.msg = ''; /*Z_NULL*/
  23111. if (state.wrap) { /* to support ill-conceived Java test suite */
  23112. strm.adler = state.wrap & 1;
  23113. }
  23114. state.mode = HEAD;
  23115. state.last = 0;
  23116. state.havedict = 0;
  23117. state.dmax = 32768;
  23118. state.head = null/*Z_NULL*/;
  23119. state.hold = 0;
  23120. state.bits = 0;
  23121. //state.lencode = state.distcode = state.next = state.codes;
  23122. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  23123. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  23124. state.sane = 1;
  23125. state.back = -1;
  23126. //Tracev((stderr, "inflate: reset\n"));
  23127. return Z_OK;
  23128. }
  23129. function inflateReset(strm) {
  23130. var state;
  23131. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23132. state = strm.state;
  23133. state.wsize = 0;
  23134. state.whave = 0;
  23135. state.wnext = 0;
  23136. return inflateResetKeep(strm);
  23137. }
  23138. function inflateReset2(strm, windowBits) {
  23139. var wrap;
  23140. var state;
  23141. /* get the state */
  23142. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23143. state = strm.state;
  23144. /* extract wrap request from windowBits parameter */
  23145. if (windowBits < 0) {
  23146. wrap = 0;
  23147. windowBits = -windowBits;
  23148. }
  23149. else {
  23150. wrap = (windowBits >> 4) + 1;
  23151. if (windowBits < 48) {
  23152. windowBits &= 15;
  23153. }
  23154. }
  23155. /* set number of window bits, free window if different */
  23156. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  23157. return Z_STREAM_ERROR;
  23158. }
  23159. if (state.window !== null && state.wbits !== windowBits) {
  23160. state.window = null;
  23161. }
  23162. /* update state and reset the rest of it */
  23163. state.wrap = wrap;
  23164. state.wbits = windowBits;
  23165. return inflateReset(strm);
  23166. }
  23167. function inflateInit2(strm, windowBits) {
  23168. var ret;
  23169. var state;
  23170. if (!strm) { return Z_STREAM_ERROR; }
  23171. //strm.msg = Z_NULL; /* in case we return an error */
  23172. state = new InflateState();
  23173. //if (state === Z_NULL) return Z_MEM_ERROR;
  23174. //Tracev((stderr, "inflate: allocated\n"));
  23175. strm.state = state;
  23176. state.window = null/*Z_NULL*/;
  23177. ret = inflateReset2(strm, windowBits);
  23178. if (ret !== Z_OK) {
  23179. strm.state = null/*Z_NULL*/;
  23180. }
  23181. return ret;
  23182. }
  23183. function inflateInit(strm) {
  23184. return inflateInit2(strm, DEF_WBITS);
  23185. }
  23186. /*
  23187. Return state with length and distance decoding tables and index sizes set to
  23188. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  23189. If BUILDFIXED is defined, then instead this routine builds the tables the
  23190. first time it's called, and returns those tables the first time and
  23191. thereafter. This reduces the size of the code by about 2K bytes, in
  23192. exchange for a little execution time. However, BUILDFIXED should not be
  23193. used for threaded applications, since the rewriting of the tables and virgin
  23194. may not be thread-safe.
  23195. */
  23196. var virgin = true;
  23197. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  23198. function fixedtables(state) {
  23199. /* build fixed huffman tables if first call (may not be thread safe) */
  23200. if (virgin) {
  23201. var sym;
  23202. lenfix = new utils.Buf32(512);
  23203. distfix = new utils.Buf32(32);
  23204. /* literal/length table */
  23205. sym = 0;
  23206. while (sym < 144) { state.lens[sym++] = 8; }
  23207. while (sym < 256) { state.lens[sym++] = 9; }
  23208. while (sym < 280) { state.lens[sym++] = 7; }
  23209. while (sym < 288) { state.lens[sym++] = 8; }
  23210. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  23211. /* distance table */
  23212. sym = 0;
  23213. while (sym < 32) { state.lens[sym++] = 5; }
  23214. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  23215. /* do this just once */
  23216. virgin = false;
  23217. }
  23218. state.lencode = lenfix;
  23219. state.lenbits = 9;
  23220. state.distcode = distfix;
  23221. state.distbits = 5;
  23222. }
  23223. /*
  23224. Update the window with the last wsize (normally 32K) bytes written before
  23225. returning. If window does not exist yet, create it. This is only called
  23226. when a window is already in use, or when output has been written during this
  23227. inflate call, but the end of the deflate stream has not been reached yet.
  23228. It is also called to create a window for dictionary data when a dictionary
  23229. is loaded.
  23230. Providing output buffers larger than 32K to inflate() should provide a speed
  23231. advantage, since only the last 32K of output is copied to the sliding window
  23232. upon return from inflate(), and since all distances after the first 32K of
  23233. output will fall in the output data, making match copies simpler and faster.
  23234. The advantage may be dependent on the size of the processor's data caches.
  23235. */
  23236. function updatewindow(strm, src, end, copy) {
  23237. var dist;
  23238. var state = strm.state;
  23239. /* if it hasn't been done already, allocate space for the window */
  23240. if (state.window === null) {
  23241. state.wsize = 1 << state.wbits;
  23242. state.wnext = 0;
  23243. state.whave = 0;
  23244. state.window = new utils.Buf8(state.wsize);
  23245. }
  23246. /* copy state->wsize or less output bytes into the circular window */
  23247. if (copy >= state.wsize) {
  23248. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  23249. state.wnext = 0;
  23250. state.whave = state.wsize;
  23251. }
  23252. else {
  23253. dist = state.wsize - state.wnext;
  23254. if (dist > copy) {
  23255. dist = copy;
  23256. }
  23257. //zmemcpy(state->window + state->wnext, end - copy, dist);
  23258. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  23259. copy -= dist;
  23260. if (copy) {
  23261. //zmemcpy(state->window, end - copy, copy);
  23262. utils.arraySet(state.window,src, end - copy, copy, 0);
  23263. state.wnext = copy;
  23264. state.whave = state.wsize;
  23265. }
  23266. else {
  23267. state.wnext += dist;
  23268. if (state.wnext === state.wsize) { state.wnext = 0; }
  23269. if (state.whave < state.wsize) { state.whave += dist; }
  23270. }
  23271. }
  23272. return 0;
  23273. }
  23274. function inflate(strm, flush) {
  23275. var state;
  23276. var input, output; // input/output buffers
  23277. var next; /* next input INDEX */
  23278. var put; /* next output INDEX */
  23279. var have, left; /* available input and output */
  23280. var hold; /* bit buffer */
  23281. var bits; /* bits in bit buffer */
  23282. var _in, _out; /* save starting available input and output */
  23283. var copy; /* number of stored or match bytes to copy */
  23284. var from; /* where to copy match bytes from */
  23285. var from_source;
  23286. var here = 0; /* current decoding table entry */
  23287. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  23288. //var last; /* parent table entry */
  23289. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  23290. var len; /* length to copy for repeats, bits to drop */
  23291. var ret; /* return code */
  23292. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  23293. var opts;
  23294. var n; // temporary var for NEED_BITS
  23295. var order = /* permutation of code lengths */
  23296. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  23297. if (!strm || !strm.state || !strm.output ||
  23298. (!strm.input && strm.avail_in !== 0)) {
  23299. return Z_STREAM_ERROR;
  23300. }
  23301. state = strm.state;
  23302. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  23303. //--- LOAD() ---
  23304. put = strm.next_out;
  23305. output = strm.output;
  23306. left = strm.avail_out;
  23307. next = strm.next_in;
  23308. input = strm.input;
  23309. have = strm.avail_in;
  23310. hold = state.hold;
  23311. bits = state.bits;
  23312. //---
  23313. _in = have;
  23314. _out = left;
  23315. ret = Z_OK;
  23316. inf_leave: // goto emulation
  23317. for (;;) {
  23318. switch (state.mode) {
  23319. case HEAD:
  23320. if (state.wrap === 0) {
  23321. state.mode = TYPEDO;
  23322. break;
  23323. }
  23324. //=== NEEDBITS(16);
  23325. while (bits < 16) {
  23326. if (have === 0) { break inf_leave; }
  23327. have--;
  23328. hold += input[next++] << bits;
  23329. bits += 8;
  23330. }
  23331. //===//
  23332. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  23333. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  23334. //=== CRC2(state.check, hold);
  23335. hbuf[0] = hold & 0xff;
  23336. hbuf[1] = (hold >>> 8) & 0xff;
  23337. state.check = crc32(state.check, hbuf, 2, 0);
  23338. //===//
  23339. //=== INITBITS();
  23340. hold = 0;
  23341. bits = 0;
  23342. //===//
  23343. state.mode = FLAGS;
  23344. break;
  23345. }
  23346. state.flags = 0; /* expect zlib header */
  23347. if (state.head) {
  23348. state.head.done = false;
  23349. }
  23350. if (!(state.wrap & 1) || /* check if zlib header allowed */
  23351. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  23352. strm.msg = 'incorrect header check';
  23353. state.mode = BAD;
  23354. break;
  23355. }
  23356. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  23357. strm.msg = 'unknown compression method';
  23358. state.mode = BAD;
  23359. break;
  23360. }
  23361. //--- DROPBITS(4) ---//
  23362. hold >>>= 4;
  23363. bits -= 4;
  23364. //---//
  23365. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  23366. if (state.wbits === 0) {
  23367. state.wbits = len;
  23368. }
  23369. else if (len > state.wbits) {
  23370. strm.msg = 'invalid window size';
  23371. state.mode = BAD;
  23372. break;
  23373. }
  23374. state.dmax = 1 << len;
  23375. //Tracev((stderr, "inflate: zlib header ok\n"));
  23376. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23377. state.mode = hold & 0x200 ? DICTID : TYPE;
  23378. //=== INITBITS();
  23379. hold = 0;
  23380. bits = 0;
  23381. //===//
  23382. break;
  23383. case FLAGS:
  23384. //=== NEEDBITS(16); */
  23385. while (bits < 16) {
  23386. if (have === 0) { break inf_leave; }
  23387. have--;
  23388. hold += input[next++] << bits;
  23389. bits += 8;
  23390. }
  23391. //===//
  23392. state.flags = hold;
  23393. if ((state.flags & 0xff) !== Z_DEFLATED) {
  23394. strm.msg = 'unknown compression method';
  23395. state.mode = BAD;
  23396. break;
  23397. }
  23398. if (state.flags & 0xe000) {
  23399. strm.msg = 'unknown header flags set';
  23400. state.mode = BAD;
  23401. break;
  23402. }
  23403. if (state.head) {
  23404. state.head.text = ((hold >> 8) & 1);
  23405. }
  23406. if (state.flags & 0x0200) {
  23407. //=== CRC2(state.check, hold);
  23408. hbuf[0] = hold & 0xff;
  23409. hbuf[1] = (hold >>> 8) & 0xff;
  23410. state.check = crc32(state.check, hbuf, 2, 0);
  23411. //===//
  23412. }
  23413. //=== INITBITS();
  23414. hold = 0;
  23415. bits = 0;
  23416. //===//
  23417. state.mode = TIME;
  23418. /* falls through */
  23419. case TIME:
  23420. //=== NEEDBITS(32); */
  23421. while (bits < 32) {
  23422. if (have === 0) { break inf_leave; }
  23423. have--;
  23424. hold += input[next++] << bits;
  23425. bits += 8;
  23426. }
  23427. //===//
  23428. if (state.head) {
  23429. state.head.time = hold;
  23430. }
  23431. if (state.flags & 0x0200) {
  23432. //=== CRC4(state.check, hold)
  23433. hbuf[0] = hold & 0xff;
  23434. hbuf[1] = (hold >>> 8) & 0xff;
  23435. hbuf[2] = (hold >>> 16) & 0xff;
  23436. hbuf[3] = (hold >>> 24) & 0xff;
  23437. state.check = crc32(state.check, hbuf, 4, 0);
  23438. //===
  23439. }
  23440. //=== INITBITS();
  23441. hold = 0;
  23442. bits = 0;
  23443. //===//
  23444. state.mode = OS;
  23445. /* falls through */
  23446. case OS:
  23447. //=== NEEDBITS(16); */
  23448. while (bits < 16) {
  23449. if (have === 0) { break inf_leave; }
  23450. have--;
  23451. hold += input[next++] << bits;
  23452. bits += 8;
  23453. }
  23454. //===//
  23455. if (state.head) {
  23456. state.head.xflags = (hold & 0xff);
  23457. state.head.os = (hold >> 8);
  23458. }
  23459. if (state.flags & 0x0200) {
  23460. //=== CRC2(state.check, hold);
  23461. hbuf[0] = hold & 0xff;
  23462. hbuf[1] = (hold >>> 8) & 0xff;
  23463. state.check = crc32(state.check, hbuf, 2, 0);
  23464. //===//
  23465. }
  23466. //=== INITBITS();
  23467. hold = 0;
  23468. bits = 0;
  23469. //===//
  23470. state.mode = EXLEN;
  23471. /* falls through */
  23472. case EXLEN:
  23473. if (state.flags & 0x0400) {
  23474. //=== NEEDBITS(16); */
  23475. while (bits < 16) {
  23476. if (have === 0) { break inf_leave; }
  23477. have--;
  23478. hold += input[next++] << bits;
  23479. bits += 8;
  23480. }
  23481. //===//
  23482. state.length = hold;
  23483. if (state.head) {
  23484. state.head.extra_len = hold;
  23485. }
  23486. if (state.flags & 0x0200) {
  23487. //=== CRC2(state.check, hold);
  23488. hbuf[0] = hold & 0xff;
  23489. hbuf[1] = (hold >>> 8) & 0xff;
  23490. state.check = crc32(state.check, hbuf, 2, 0);
  23491. //===//
  23492. }
  23493. //=== INITBITS();
  23494. hold = 0;
  23495. bits = 0;
  23496. //===//
  23497. }
  23498. else if (state.head) {
  23499. state.head.extra = null/*Z_NULL*/;
  23500. }
  23501. state.mode = EXTRA;
  23502. /* falls through */
  23503. case EXTRA:
  23504. if (state.flags & 0x0400) {
  23505. copy = state.length;
  23506. if (copy > have) { copy = have; }
  23507. if (copy) {
  23508. if (state.head) {
  23509. len = state.head.extra_len - state.length;
  23510. if (!state.head.extra) {
  23511. // Use untyped array for more conveniend processing later
  23512. state.head.extra = new Array(state.head.extra_len);
  23513. }
  23514. utils.arraySet(
  23515. state.head.extra,
  23516. input,
  23517. next,
  23518. // extra field is limited to 65536 bytes
  23519. // - no need for additional size check
  23520. copy,
  23521. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  23522. len
  23523. );
  23524. //zmemcpy(state.head.extra + len, next,
  23525. // len + copy > state.head.extra_max ?
  23526. // state.head.extra_max - len : copy);
  23527. }
  23528. if (state.flags & 0x0200) {
  23529. state.check = crc32(state.check, input, copy, next);
  23530. }
  23531. have -= copy;
  23532. next += copy;
  23533. state.length -= copy;
  23534. }
  23535. if (state.length) { break inf_leave; }
  23536. }
  23537. state.length = 0;
  23538. state.mode = NAME;
  23539. /* falls through */
  23540. case NAME:
  23541. if (state.flags & 0x0800) {
  23542. if (have === 0) { break inf_leave; }
  23543. copy = 0;
  23544. do {
  23545. // TODO: 2 or 1 bytes?
  23546. len = input[next + copy++];
  23547. /* use constant limit because in js we should not preallocate memory */
  23548. if (state.head && len &&
  23549. (state.length < 65536 /*state.head.name_max*/)) {
  23550. state.head.name += String.fromCharCode(len);
  23551. }
  23552. } while (len && copy < have);
  23553. if (state.flags & 0x0200) {
  23554. state.check = crc32(state.check, input, copy, next);
  23555. }
  23556. have -= copy;
  23557. next += copy;
  23558. if (len) { break inf_leave; }
  23559. }
  23560. else if (state.head) {
  23561. state.head.name = null;
  23562. }
  23563. state.length = 0;
  23564. state.mode = COMMENT;
  23565. /* falls through */
  23566. case COMMENT:
  23567. if (state.flags & 0x1000) {
  23568. if (have === 0) { break inf_leave; }
  23569. copy = 0;
  23570. do {
  23571. len = input[next + copy++];
  23572. /* use constant limit because in js we should not preallocate memory */
  23573. if (state.head && len &&
  23574. (state.length < 65536 /*state.head.comm_max*/)) {
  23575. state.head.comment += String.fromCharCode(len);
  23576. }
  23577. } while (len && copy < have);
  23578. if (state.flags & 0x0200) {
  23579. state.check = crc32(state.check, input, copy, next);
  23580. }
  23581. have -= copy;
  23582. next += copy;
  23583. if (len) { break inf_leave; }
  23584. }
  23585. else if (state.head) {
  23586. state.head.comment = null;
  23587. }
  23588. state.mode = HCRC;
  23589. /* falls through */
  23590. case HCRC:
  23591. if (state.flags & 0x0200) {
  23592. //=== NEEDBITS(16); */
  23593. while (bits < 16) {
  23594. if (have === 0) { break inf_leave; }
  23595. have--;
  23596. hold += input[next++] << bits;
  23597. bits += 8;
  23598. }
  23599. //===//
  23600. if (hold !== (state.check & 0xffff)) {
  23601. strm.msg = 'header crc mismatch';
  23602. state.mode = BAD;
  23603. break;
  23604. }
  23605. //=== INITBITS();
  23606. hold = 0;
  23607. bits = 0;
  23608. //===//
  23609. }
  23610. if (state.head) {
  23611. state.head.hcrc = ((state.flags >> 9) & 1);
  23612. state.head.done = true;
  23613. }
  23614. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23615. state.mode = TYPE;
  23616. break;
  23617. case DICTID:
  23618. //=== NEEDBITS(32); */
  23619. while (bits < 32) {
  23620. if (have === 0) { break inf_leave; }
  23621. have--;
  23622. hold += input[next++] << bits;
  23623. bits += 8;
  23624. }
  23625. //===//
  23626. strm.adler = state.check = ZSWAP32(hold);
  23627. //=== INITBITS();
  23628. hold = 0;
  23629. bits = 0;
  23630. //===//
  23631. state.mode = DICT;
  23632. /* falls through */
  23633. case DICT:
  23634. if (state.havedict === 0) {
  23635. //--- RESTORE() ---
  23636. strm.next_out = put;
  23637. strm.avail_out = left;
  23638. strm.next_in = next;
  23639. strm.avail_in = have;
  23640. state.hold = hold;
  23641. state.bits = bits;
  23642. //---
  23643. return Z_NEED_DICT;
  23644. }
  23645. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23646. state.mode = TYPE;
  23647. /* falls through */
  23648. case TYPE:
  23649. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23650. /* falls through */
  23651. case TYPEDO:
  23652. if (state.last) {
  23653. //--- BYTEBITS() ---//
  23654. hold >>>= bits & 7;
  23655. bits -= bits & 7;
  23656. //---//
  23657. state.mode = CHECK;
  23658. break;
  23659. }
  23660. //=== NEEDBITS(3); */
  23661. while (bits < 3) {
  23662. if (have === 0) { break inf_leave; }
  23663. have--;
  23664. hold += input[next++] << bits;
  23665. bits += 8;
  23666. }
  23667. //===//
  23668. state.last = (hold & 0x01)/*BITS(1)*/;
  23669. //--- DROPBITS(1) ---//
  23670. hold >>>= 1;
  23671. bits -= 1;
  23672. //---//
  23673. switch ((hold & 0x03)/*BITS(2)*/) {
  23674. case 0: /* stored block */
  23675. //Tracev((stderr, "inflate: stored block%s\n",
  23676. // state.last ? " (last)" : ""));
  23677. state.mode = STORED;
  23678. break;
  23679. case 1: /* fixed block */
  23680. fixedtables(state);
  23681. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23682. // state.last ? " (last)" : ""));
  23683. state.mode = LEN_; /* decode codes */
  23684. if (flush === Z_TREES) {
  23685. //--- DROPBITS(2) ---//
  23686. hold >>>= 2;
  23687. bits -= 2;
  23688. //---//
  23689. break inf_leave;
  23690. }
  23691. break;
  23692. case 2: /* dynamic block */
  23693. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23694. // state.last ? " (last)" : ""));
  23695. state.mode = TABLE;
  23696. break;
  23697. case 3:
  23698. strm.msg = 'invalid block type';
  23699. state.mode = BAD;
  23700. }
  23701. //--- DROPBITS(2) ---//
  23702. hold >>>= 2;
  23703. bits -= 2;
  23704. //---//
  23705. break;
  23706. case STORED:
  23707. //--- BYTEBITS() ---// /* go to byte boundary */
  23708. hold >>>= bits & 7;
  23709. bits -= bits & 7;
  23710. //---//
  23711. //=== NEEDBITS(32); */
  23712. while (bits < 32) {
  23713. if (have === 0) { break inf_leave; }
  23714. have--;
  23715. hold += input[next++] << bits;
  23716. bits += 8;
  23717. }
  23718. //===//
  23719. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23720. strm.msg = 'invalid stored block lengths';
  23721. state.mode = BAD;
  23722. break;
  23723. }
  23724. state.length = hold & 0xffff;
  23725. //Tracev((stderr, "inflate: stored length %u\n",
  23726. // state.length));
  23727. //=== INITBITS();
  23728. hold = 0;
  23729. bits = 0;
  23730. //===//
  23731. state.mode = COPY_;
  23732. if (flush === Z_TREES) { break inf_leave; }
  23733. /* falls through */
  23734. case COPY_:
  23735. state.mode = COPY;
  23736. /* falls through */
  23737. case COPY:
  23738. copy = state.length;
  23739. if (copy) {
  23740. if (copy > have) { copy = have; }
  23741. if (copy > left) { copy = left; }
  23742. if (copy === 0) { break inf_leave; }
  23743. //--- zmemcpy(put, next, copy); ---
  23744. utils.arraySet(output, input, next, copy, put);
  23745. //---//
  23746. have -= copy;
  23747. next += copy;
  23748. left -= copy;
  23749. put += copy;
  23750. state.length -= copy;
  23751. break;
  23752. }
  23753. //Tracev((stderr, "inflate: stored end\n"));
  23754. state.mode = TYPE;
  23755. break;
  23756. case TABLE:
  23757. //=== NEEDBITS(14); */
  23758. while (bits < 14) {
  23759. if (have === 0) { break inf_leave; }
  23760. have--;
  23761. hold += input[next++] << bits;
  23762. bits += 8;
  23763. }
  23764. //===//
  23765. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23766. //--- DROPBITS(5) ---//
  23767. hold >>>= 5;
  23768. bits -= 5;
  23769. //---//
  23770. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23771. //--- DROPBITS(5) ---//
  23772. hold >>>= 5;
  23773. bits -= 5;
  23774. //---//
  23775. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23776. //--- DROPBITS(4) ---//
  23777. hold >>>= 4;
  23778. bits -= 4;
  23779. //---//
  23780. //#ifndef PKZIP_BUG_WORKAROUND
  23781. if (state.nlen > 286 || state.ndist > 30) {
  23782. strm.msg = 'too many length or distance symbols';
  23783. state.mode = BAD;
  23784. break;
  23785. }
  23786. //#endif
  23787. //Tracev((stderr, "inflate: table sizes ok\n"));
  23788. state.have = 0;
  23789. state.mode = LENLENS;
  23790. /* falls through */
  23791. case LENLENS:
  23792. while (state.have < state.ncode) {
  23793. //=== NEEDBITS(3);
  23794. while (bits < 3) {
  23795. if (have === 0) { break inf_leave; }
  23796. have--;
  23797. hold += input[next++] << bits;
  23798. bits += 8;
  23799. }
  23800. //===//
  23801. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23802. //--- DROPBITS(3) ---//
  23803. hold >>>= 3;
  23804. bits -= 3;
  23805. //---//
  23806. }
  23807. while (state.have < 19) {
  23808. state.lens[order[state.have++]] = 0;
  23809. }
  23810. // We have separate tables & no pointers. 2 commented lines below not needed.
  23811. //state.next = state.codes;
  23812. //state.lencode = state.next;
  23813. // Switch to use dynamic table
  23814. state.lencode = state.lendyn;
  23815. state.lenbits = 7;
  23816. opts = {bits: state.lenbits};
  23817. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23818. state.lenbits = opts.bits;
  23819. if (ret) {
  23820. strm.msg = 'invalid code lengths set';
  23821. state.mode = BAD;
  23822. break;
  23823. }
  23824. //Tracev((stderr, "inflate: code lengths ok\n"));
  23825. state.have = 0;
  23826. state.mode = CODELENS;
  23827. /* falls through */
  23828. case CODELENS:
  23829. while (state.have < state.nlen + state.ndist) {
  23830. for (;;) {
  23831. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23832. here_bits = here >>> 24;
  23833. here_op = (here >>> 16) & 0xff;
  23834. here_val = here & 0xffff;
  23835. if ((here_bits) <= bits) { break; }
  23836. //--- PULLBYTE() ---//
  23837. if (have === 0) { break inf_leave; }
  23838. have--;
  23839. hold += input[next++] << bits;
  23840. bits += 8;
  23841. //---//
  23842. }
  23843. if (here_val < 16) {
  23844. //--- DROPBITS(here.bits) ---//
  23845. hold >>>= here_bits;
  23846. bits -= here_bits;
  23847. //---//
  23848. state.lens[state.have++] = here_val;
  23849. }
  23850. else {
  23851. if (here_val === 16) {
  23852. //=== NEEDBITS(here.bits + 2);
  23853. n = here_bits + 2;
  23854. while (bits < n) {
  23855. if (have === 0) { break inf_leave; }
  23856. have--;
  23857. hold += input[next++] << bits;
  23858. bits += 8;
  23859. }
  23860. //===//
  23861. //--- DROPBITS(here.bits) ---//
  23862. hold >>>= here_bits;
  23863. bits -= here_bits;
  23864. //---//
  23865. if (state.have === 0) {
  23866. strm.msg = 'invalid bit length repeat';
  23867. state.mode = BAD;
  23868. break;
  23869. }
  23870. len = state.lens[state.have - 1];
  23871. copy = 3 + (hold & 0x03);//BITS(2);
  23872. //--- DROPBITS(2) ---//
  23873. hold >>>= 2;
  23874. bits -= 2;
  23875. //---//
  23876. }
  23877. else if (here_val === 17) {
  23878. //=== NEEDBITS(here.bits + 3);
  23879. n = here_bits + 3;
  23880. while (bits < n) {
  23881. if (have === 0) { break inf_leave; }
  23882. have--;
  23883. hold += input[next++] << bits;
  23884. bits += 8;
  23885. }
  23886. //===//
  23887. //--- DROPBITS(here.bits) ---//
  23888. hold >>>= here_bits;
  23889. bits -= here_bits;
  23890. //---//
  23891. len = 0;
  23892. copy = 3 + (hold & 0x07);//BITS(3);
  23893. //--- DROPBITS(3) ---//
  23894. hold >>>= 3;
  23895. bits -= 3;
  23896. //---//
  23897. }
  23898. else {
  23899. //=== NEEDBITS(here.bits + 7);
  23900. n = here_bits + 7;
  23901. while (bits < n) {
  23902. if (have === 0) { break inf_leave; }
  23903. have--;
  23904. hold += input[next++] << bits;
  23905. bits += 8;
  23906. }
  23907. //===//
  23908. //--- DROPBITS(here.bits) ---//
  23909. hold >>>= here_bits;
  23910. bits -= here_bits;
  23911. //---//
  23912. len = 0;
  23913. copy = 11 + (hold & 0x7f);//BITS(7);
  23914. //--- DROPBITS(7) ---//
  23915. hold >>>= 7;
  23916. bits -= 7;
  23917. //---//
  23918. }
  23919. if (state.have + copy > state.nlen + state.ndist) {
  23920. strm.msg = 'invalid bit length repeat';
  23921. state.mode = BAD;
  23922. break;
  23923. }
  23924. while (copy--) {
  23925. state.lens[state.have++] = len;
  23926. }
  23927. }
  23928. }
  23929. /* handle error breaks in while */
  23930. if (state.mode === BAD) { break; }
  23931. /* check for end-of-block code (better have one) */
  23932. if (state.lens[256] === 0) {
  23933. strm.msg = 'invalid code -- missing end-of-block';
  23934. state.mode = BAD;
  23935. break;
  23936. }
  23937. /* build code tables -- note: do not change the lenbits or distbits
  23938. values here (9 and 6) without reading the comments in inftrees.h
  23939. concerning the ENOUGH constants, which depend on those values */
  23940. state.lenbits = 9;
  23941. opts = {bits: state.lenbits};
  23942. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23943. // We have separate tables & no pointers. 2 commented lines below not needed.
  23944. // state.next_index = opts.table_index;
  23945. state.lenbits = opts.bits;
  23946. // state.lencode = state.next;
  23947. if (ret) {
  23948. strm.msg = 'invalid literal/lengths set';
  23949. state.mode = BAD;
  23950. break;
  23951. }
  23952. state.distbits = 6;
  23953. //state.distcode.copy(state.codes);
  23954. // Switch to use dynamic table
  23955. state.distcode = state.distdyn;
  23956. opts = {bits: state.distbits};
  23957. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23958. // We have separate tables & no pointers. 2 commented lines below not needed.
  23959. // state.next_index = opts.table_index;
  23960. state.distbits = opts.bits;
  23961. // state.distcode = state.next;
  23962. if (ret) {
  23963. strm.msg = 'invalid distances set';
  23964. state.mode = BAD;
  23965. break;
  23966. }
  23967. //Tracev((stderr, 'inflate: codes ok\n'));
  23968. state.mode = LEN_;
  23969. if (flush === Z_TREES) { break inf_leave; }
  23970. /* falls through */
  23971. case LEN_:
  23972. state.mode = LEN;
  23973. /* falls through */
  23974. case LEN:
  23975. if (have >= 6 && left >= 258) {
  23976. //--- RESTORE() ---
  23977. strm.next_out = put;
  23978. strm.avail_out = left;
  23979. strm.next_in = next;
  23980. strm.avail_in = have;
  23981. state.hold = hold;
  23982. state.bits = bits;
  23983. //---
  23984. inflate_fast(strm, _out);
  23985. //--- LOAD() ---
  23986. put = strm.next_out;
  23987. output = strm.output;
  23988. left = strm.avail_out;
  23989. next = strm.next_in;
  23990. input = strm.input;
  23991. have = strm.avail_in;
  23992. hold = state.hold;
  23993. bits = state.bits;
  23994. //---
  23995. if (state.mode === TYPE) {
  23996. state.back = -1;
  23997. }
  23998. break;
  23999. }
  24000. state.back = 0;
  24001. for (;;) {
  24002. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  24003. here_bits = here >>> 24;
  24004. here_op = (here >>> 16) & 0xff;
  24005. here_val = here & 0xffff;
  24006. if (here_bits <= bits) { break; }
  24007. //--- PULLBYTE() ---//
  24008. if (have === 0) { break inf_leave; }
  24009. have--;
  24010. hold += input[next++] << bits;
  24011. bits += 8;
  24012. //---//
  24013. }
  24014. if (here_op && (here_op & 0xf0) === 0) {
  24015. last_bits = here_bits;
  24016. last_op = here_op;
  24017. last_val = here_val;
  24018. for (;;) {
  24019. here = state.lencode[last_val +
  24020. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  24021. here_bits = here >>> 24;
  24022. here_op = (here >>> 16) & 0xff;
  24023. here_val = here & 0xffff;
  24024. if ((last_bits + here_bits) <= bits) { break; }
  24025. //--- PULLBYTE() ---//
  24026. if (have === 0) { break inf_leave; }
  24027. have--;
  24028. hold += input[next++] << bits;
  24029. bits += 8;
  24030. //---//
  24031. }
  24032. //--- DROPBITS(last.bits) ---//
  24033. hold >>>= last_bits;
  24034. bits -= last_bits;
  24035. //---//
  24036. state.back += last_bits;
  24037. }
  24038. //--- DROPBITS(here.bits) ---//
  24039. hold >>>= here_bits;
  24040. bits -= here_bits;
  24041. //---//
  24042. state.back += here_bits;
  24043. state.length = here_val;
  24044. if (here_op === 0) {
  24045. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  24046. // "inflate: literal '%c'\n" :
  24047. // "inflate: literal 0x%02x\n", here.val));
  24048. state.mode = LIT;
  24049. break;
  24050. }
  24051. if (here_op & 32) {
  24052. //Tracevv((stderr, "inflate: end of block\n"));
  24053. state.back = -1;
  24054. state.mode = TYPE;
  24055. break;
  24056. }
  24057. if (here_op & 64) {
  24058. strm.msg = 'invalid literal/length code';
  24059. state.mode = BAD;
  24060. break;
  24061. }
  24062. state.extra = here_op & 15;
  24063. state.mode = LENEXT;
  24064. /* falls through */
  24065. case LENEXT:
  24066. if (state.extra) {
  24067. //=== NEEDBITS(state.extra);
  24068. n = state.extra;
  24069. while (bits < n) {
  24070. if (have === 0) { break inf_leave; }
  24071. have--;
  24072. hold += input[next++] << bits;
  24073. bits += 8;
  24074. }
  24075. //===//
  24076. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  24077. //--- DROPBITS(state.extra) ---//
  24078. hold >>>= state.extra;
  24079. bits -= state.extra;
  24080. //---//
  24081. state.back += state.extra;
  24082. }
  24083. //Tracevv((stderr, "inflate: length %u\n", state.length));
  24084. state.was = state.length;
  24085. state.mode = DIST;
  24086. /* falls through */
  24087. case DIST:
  24088. for (;;) {
  24089. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  24090. here_bits = here >>> 24;
  24091. here_op = (here >>> 16) & 0xff;
  24092. here_val = here & 0xffff;
  24093. if ((here_bits) <= bits) { break; }
  24094. //--- PULLBYTE() ---//
  24095. if (have === 0) { break inf_leave; }
  24096. have--;
  24097. hold += input[next++] << bits;
  24098. bits += 8;
  24099. //---//
  24100. }
  24101. if ((here_op & 0xf0) === 0) {
  24102. last_bits = here_bits;
  24103. last_op = here_op;
  24104. last_val = here_val;
  24105. for (;;) {
  24106. here = state.distcode[last_val +
  24107. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  24108. here_bits = here >>> 24;
  24109. here_op = (here >>> 16) & 0xff;
  24110. here_val = here & 0xffff;
  24111. if ((last_bits + here_bits) <= bits) { break; }
  24112. //--- PULLBYTE() ---//
  24113. if (have === 0) { break inf_leave; }
  24114. have--;
  24115. hold += input[next++] << bits;
  24116. bits += 8;
  24117. //---//
  24118. }
  24119. //--- DROPBITS(last.bits) ---//
  24120. hold >>>= last_bits;
  24121. bits -= last_bits;
  24122. //---//
  24123. state.back += last_bits;
  24124. }
  24125. //--- DROPBITS(here.bits) ---//
  24126. hold >>>= here_bits;
  24127. bits -= here_bits;
  24128. //---//
  24129. state.back += here_bits;
  24130. if (here_op & 64) {
  24131. strm.msg = 'invalid distance code';
  24132. state.mode = BAD;
  24133. break;
  24134. }
  24135. state.offset = here_val;
  24136. state.extra = (here_op) & 15;
  24137. state.mode = DISTEXT;
  24138. /* falls through */
  24139. case DISTEXT:
  24140. if (state.extra) {
  24141. //=== NEEDBITS(state.extra);
  24142. n = state.extra;
  24143. while (bits < n) {
  24144. if (have === 0) { break inf_leave; }
  24145. have--;
  24146. hold += input[next++] << bits;
  24147. bits += 8;
  24148. }
  24149. //===//
  24150. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  24151. //--- DROPBITS(state.extra) ---//
  24152. hold >>>= state.extra;
  24153. bits -= state.extra;
  24154. //---//
  24155. state.back += state.extra;
  24156. }
  24157. //#ifdef INFLATE_STRICT
  24158. if (state.offset > state.dmax) {
  24159. strm.msg = 'invalid distance too far back';
  24160. state.mode = BAD;
  24161. break;
  24162. }
  24163. //#endif
  24164. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  24165. state.mode = MATCH;
  24166. /* falls through */
  24167. case MATCH:
  24168. if (left === 0) { break inf_leave; }
  24169. copy = _out - left;
  24170. if (state.offset > copy) { /* copy from window */
  24171. copy = state.offset - copy;
  24172. if (copy > state.whave) {
  24173. if (state.sane) {
  24174. strm.msg = 'invalid distance too far back';
  24175. state.mode = BAD;
  24176. break;
  24177. }
  24178. // (!) This block is disabled in zlib defailts,
  24179. // don't enable it for binary compatibility
  24180. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  24181. // Trace((stderr, "inflate.c too far\n"));
  24182. // copy -= state.whave;
  24183. // if (copy > state.length) { copy = state.length; }
  24184. // if (copy > left) { copy = left; }
  24185. // left -= copy;
  24186. // state.length -= copy;
  24187. // do {
  24188. // output[put++] = 0;
  24189. // } while (--copy);
  24190. // if (state.length === 0) { state.mode = LEN; }
  24191. // break;
  24192. //#endif
  24193. }
  24194. if (copy > state.wnext) {
  24195. copy -= state.wnext;
  24196. from = state.wsize - copy;
  24197. }
  24198. else {
  24199. from = state.wnext - copy;
  24200. }
  24201. if (copy > state.length) { copy = state.length; }
  24202. from_source = state.window;
  24203. }
  24204. else { /* copy from output */
  24205. from_source = output;
  24206. from = put - state.offset;
  24207. copy = state.length;
  24208. }
  24209. if (copy > left) { copy = left; }
  24210. left -= copy;
  24211. state.length -= copy;
  24212. do {
  24213. output[put++] = from_source[from++];
  24214. } while (--copy);
  24215. if (state.length === 0) { state.mode = LEN; }
  24216. break;
  24217. case LIT:
  24218. if (left === 0) { break inf_leave; }
  24219. output[put++] = state.length;
  24220. left--;
  24221. state.mode = LEN;
  24222. break;
  24223. case CHECK:
  24224. if (state.wrap) {
  24225. //=== NEEDBITS(32);
  24226. while (bits < 32) {
  24227. if (have === 0) { break inf_leave; }
  24228. have--;
  24229. // Use '|' insdead of '+' to make sure that result is signed
  24230. hold |= input[next++] << bits;
  24231. bits += 8;
  24232. }
  24233. //===//
  24234. _out -= left;
  24235. strm.total_out += _out;
  24236. state.total += _out;
  24237. if (_out) {
  24238. strm.adler = state.check =
  24239. /*UPDATE(state.check, put - _out, _out);*/
  24240. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  24241. }
  24242. _out = left;
  24243. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  24244. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  24245. strm.msg = 'incorrect data check';
  24246. state.mode = BAD;
  24247. break;
  24248. }
  24249. //=== INITBITS();
  24250. hold = 0;
  24251. bits = 0;
  24252. //===//
  24253. //Tracev((stderr, "inflate: check matches trailer\n"));
  24254. }
  24255. state.mode = LENGTH;
  24256. /* falls through */
  24257. case LENGTH:
  24258. if (state.wrap && state.flags) {
  24259. //=== NEEDBITS(32);
  24260. while (bits < 32) {
  24261. if (have === 0) { break inf_leave; }
  24262. have--;
  24263. hold += input[next++] << bits;
  24264. bits += 8;
  24265. }
  24266. //===//
  24267. if (hold !== (state.total & 0xffffffff)) {
  24268. strm.msg = 'incorrect length check';
  24269. state.mode = BAD;
  24270. break;
  24271. }
  24272. //=== INITBITS();
  24273. hold = 0;
  24274. bits = 0;
  24275. //===//
  24276. //Tracev((stderr, "inflate: length matches trailer\n"));
  24277. }
  24278. state.mode = DONE;
  24279. /* falls through */
  24280. case DONE:
  24281. ret = Z_STREAM_END;
  24282. break inf_leave;
  24283. case BAD:
  24284. ret = Z_DATA_ERROR;
  24285. break inf_leave;
  24286. case MEM:
  24287. return Z_MEM_ERROR;
  24288. case SYNC:
  24289. /* falls through */
  24290. default:
  24291. return Z_STREAM_ERROR;
  24292. }
  24293. }
  24294. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  24295. /*
  24296. Return from inflate(), updating the total counts and the check value.
  24297. If there was no progress during the inflate() call, return a buffer
  24298. error. Call updatewindow() to create and/or update the window state.
  24299. Note: a memory error from inflate() is non-recoverable.
  24300. */
  24301. //--- RESTORE() ---
  24302. strm.next_out = put;
  24303. strm.avail_out = left;
  24304. strm.next_in = next;
  24305. strm.avail_in = have;
  24306. state.hold = hold;
  24307. state.bits = bits;
  24308. //---
  24309. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  24310. (state.mode < CHECK || flush !== Z_FINISH))) {
  24311. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  24312. state.mode = MEM;
  24313. return Z_MEM_ERROR;
  24314. }
  24315. }
  24316. _in -= strm.avail_in;
  24317. _out -= strm.avail_out;
  24318. strm.total_in += _in;
  24319. strm.total_out += _out;
  24320. state.total += _out;
  24321. if (state.wrap && _out) {
  24322. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  24323. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  24324. }
  24325. strm.data_type = state.bits + (state.last ? 64 : 0) +
  24326. (state.mode === TYPE ? 128 : 0) +
  24327. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  24328. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  24329. ret = Z_BUF_ERROR;
  24330. }
  24331. return ret;
  24332. }
  24333. function inflateEnd(strm) {
  24334. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  24335. return Z_STREAM_ERROR;
  24336. }
  24337. var state = strm.state;
  24338. if (state.window) {
  24339. state.window = null;
  24340. }
  24341. strm.state = null;
  24342. return Z_OK;
  24343. }
  24344. function inflateGetHeader(strm, head) {
  24345. var state;
  24346. /* check state */
  24347. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  24348. state = strm.state;
  24349. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  24350. /* save header structure */
  24351. state.head = head;
  24352. head.done = false;
  24353. return Z_OK;
  24354. }
  24355. exports.inflateReset = inflateReset;
  24356. exports.inflateReset2 = inflateReset2;
  24357. exports.inflateResetKeep = inflateResetKeep;
  24358. exports.inflateInit = inflateInit;
  24359. exports.inflateInit2 = inflateInit2;
  24360. exports.inflate = inflate;
  24361. exports.inflateEnd = inflateEnd;
  24362. exports.inflateGetHeader = inflateGetHeader;
  24363. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  24364. /* Not implemented
  24365. exports.inflateCopy = inflateCopy;
  24366. exports.inflateGetDictionary = inflateGetDictionary;
  24367. exports.inflateMark = inflateMark;
  24368. exports.inflatePrime = inflatePrime;
  24369. exports.inflateSetDictionary = inflateSetDictionary;
  24370. exports.inflateSync = inflateSync;
  24371. exports.inflateSyncPoint = inflateSyncPoint;
  24372. exports.inflateUndermine = inflateUndermine;
  24373. */
  24374. },{"../utils/common":76,"./adler32":78,"./crc32":80,"./inffast":83,"./inftrees":85}],85:[function(require,module,exports){
  24375. 'use strict';
  24376. var utils = require('../utils/common');
  24377. var MAXBITS = 15;
  24378. var ENOUGH_LENS = 852;
  24379. var ENOUGH_DISTS = 592;
  24380. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  24381. var CODES = 0;
  24382. var LENS = 1;
  24383. var DISTS = 2;
  24384. var lbase = [ /* Length codes 257..285 base */
  24385. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  24386. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  24387. ];
  24388. var lext = [ /* Length codes 257..285 extra */
  24389. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  24390. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  24391. ];
  24392. var dbase = [ /* Distance codes 0..29 base */
  24393. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  24394. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  24395. 8193, 12289, 16385, 24577, 0, 0
  24396. ];
  24397. var dext = [ /* Distance codes 0..29 extra */
  24398. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  24399. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  24400. 28, 28, 29, 29, 64, 64
  24401. ];
  24402. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  24403. {
  24404. var bits = opts.bits;
  24405. //here = opts.here; /* table entry for duplication */
  24406. var len = 0; /* a code's length in bits */
  24407. var sym = 0; /* index of code symbols */
  24408. var min = 0, max = 0; /* minimum and maximum code lengths */
  24409. var root = 0; /* number of index bits for root table */
  24410. var curr = 0; /* number of index bits for current table */
  24411. var drop = 0; /* code bits to drop for sub-table */
  24412. var left = 0; /* number of prefix codes available */
  24413. var used = 0; /* code entries in table used */
  24414. var huff = 0; /* Huffman code */
  24415. var incr; /* for incrementing code, index */
  24416. var fill; /* index for replicating entries */
  24417. var low; /* low bits for current root entry */
  24418. var mask; /* mask for low root bits */
  24419. var next; /* next available space in table */
  24420. var base = null; /* base value table to use */
  24421. var base_index = 0;
  24422. // var shoextra; /* extra bits table to use */
  24423. var end; /* use base and extra for symbol > end */
  24424. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  24425. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  24426. var extra = null;
  24427. var extra_index = 0;
  24428. var here_bits, here_op, here_val;
  24429. /*
  24430. Process a set of code lengths to create a canonical Huffman code. The
  24431. code lengths are lens[0..codes-1]. Each length corresponds to the
  24432. symbols 0..codes-1. The Huffman code is generated by first sorting the
  24433. symbols by length from short to long, and retaining the symbol order
  24434. for codes with equal lengths. Then the code starts with all zero bits
  24435. for the first code of the shortest length, and the codes are integer
  24436. increments for the same length, and zeros are appended as the length
  24437. increases. For the deflate format, these bits are stored backwards
  24438. from their more natural integer increment ordering, and so when the
  24439. decoding tables are built in the large loop below, the integer codes
  24440. are incremented backwards.
  24441. This routine assumes, but does not check, that all of the entries in
  24442. lens[] are in the range 0..MAXBITS. The caller must assure this.
  24443. 1..MAXBITS is interpreted as that code length. zero means that that
  24444. symbol does not occur in this code.
  24445. The codes are sorted by computing a count of codes for each length,
  24446. creating from that a table of starting indices for each length in the
  24447. sorted table, and then entering the symbols in order in the sorted
  24448. table. The sorted table is work[], with that space being provided by
  24449. the caller.
  24450. The length counts are used for other purposes as well, i.e. finding
  24451. the minimum and maximum length codes, determining if there are any
  24452. codes at all, checking for a valid set of lengths, and looking ahead
  24453. at length counts to determine sub-table sizes when building the
  24454. decoding tables.
  24455. */
  24456. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  24457. for (len = 0; len <= MAXBITS; len++) {
  24458. count[len] = 0;
  24459. }
  24460. for (sym = 0; sym < codes; sym++) {
  24461. count[lens[lens_index + sym]]++;
  24462. }
  24463. /* bound code lengths, force root to be within code lengths */
  24464. root = bits;
  24465. for (max = MAXBITS; max >= 1; max--) {
  24466. if (count[max] !== 0) { break; }
  24467. }
  24468. if (root > max) {
  24469. root = max;
  24470. }
  24471. if (max === 0) { /* no symbols to code at all */
  24472. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  24473. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  24474. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  24475. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24476. //table.op[opts.table_index] = 64;
  24477. //table.bits[opts.table_index] = 1;
  24478. //table.val[opts.table_index++] = 0;
  24479. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24480. opts.bits = 1;
  24481. return 0; /* no symbols, but wait for decoding to report error */
  24482. }
  24483. for (min = 1; min < max; min++) {
  24484. if (count[min] !== 0) { break; }
  24485. }
  24486. if (root < min) {
  24487. root = min;
  24488. }
  24489. /* check for an over-subscribed or incomplete set of lengths */
  24490. left = 1;
  24491. for (len = 1; len <= MAXBITS; len++) {
  24492. left <<= 1;
  24493. left -= count[len];
  24494. if (left < 0) {
  24495. return -1;
  24496. } /* over-subscribed */
  24497. }
  24498. if (left > 0 && (type === CODES || max !== 1)) {
  24499. return -1; /* incomplete set */
  24500. }
  24501. /* generate offsets into symbol table for each length for sorting */
  24502. offs[1] = 0;
  24503. for (len = 1; len < MAXBITS; len++) {
  24504. offs[len + 1] = offs[len] + count[len];
  24505. }
  24506. /* sort symbols by length, by symbol order within each length */
  24507. for (sym = 0; sym < codes; sym++) {
  24508. if (lens[lens_index + sym] !== 0) {
  24509. work[offs[lens[lens_index + sym]]++] = sym;
  24510. }
  24511. }
  24512. /*
  24513. Create and fill in decoding tables. In this loop, the table being
  24514. filled is at next and has curr index bits. The code being used is huff
  24515. with length len. That code is converted to an index by dropping drop
  24516. bits off of the bottom. For codes where len is less than drop + curr,
  24517. those top drop + curr - len bits are incremented through all values to
  24518. fill the table with replicated entries.
  24519. root is the number of index bits for the root table. When len exceeds
  24520. root, sub-tables are created pointed to by the root entry with an index
  24521. of the low root bits of huff. This is saved in low to check for when a
  24522. new sub-table should be started. drop is zero when the root table is
  24523. being filled, and drop is root when sub-tables are being filled.
  24524. When a new sub-table is needed, it is necessary to look ahead in the
  24525. code lengths to determine what size sub-table is needed. The length
  24526. counts are used for this, and so count[] is decremented as codes are
  24527. entered in the tables.
  24528. used keeps track of how many table entries have been allocated from the
  24529. provided *table space. It is checked for LENS and DIST tables against
  24530. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24531. the initial root table size constants. See the comments in inftrees.h
  24532. for more information.
  24533. sym increments through all symbols, and the loop terminates when
  24534. all codes of length max, i.e. all codes, have been processed. This
  24535. routine permits incomplete codes, so another loop after this one fills
  24536. in the rest of the decoding tables with invalid code markers.
  24537. */
  24538. /* set up for code type */
  24539. // poor man optimization - use if-else instead of switch,
  24540. // to avoid deopts in old v8
  24541. if (type === CODES) {
  24542. base = extra = work; /* dummy value--not used */
  24543. end = 19;
  24544. } else if (type === LENS) {
  24545. base = lbase;
  24546. base_index -= 257;
  24547. extra = lext;
  24548. extra_index -= 257;
  24549. end = 256;
  24550. } else { /* DISTS */
  24551. base = dbase;
  24552. extra = dext;
  24553. end = -1;
  24554. }
  24555. /* initialize opts for loop */
  24556. huff = 0; /* starting code */
  24557. sym = 0; /* starting code symbol */
  24558. len = min; /* starting code length */
  24559. next = table_index; /* current table to fill in */
  24560. curr = root; /* current table index bits */
  24561. drop = 0; /* current bits to drop from code for index */
  24562. low = -1; /* trigger new sub-table when len > root */
  24563. used = 1 << root; /* use root table entries */
  24564. mask = used - 1; /* mask for comparing low */
  24565. /* check available table space */
  24566. if ((type === LENS && used > ENOUGH_LENS) ||
  24567. (type === DISTS && used > ENOUGH_DISTS)) {
  24568. return 1;
  24569. }
  24570. var i=0;
  24571. /* process all codes and make table entries */
  24572. for (;;) {
  24573. i++;
  24574. /* create table entry */
  24575. here_bits = len - drop;
  24576. if (work[sym] < end) {
  24577. here_op = 0;
  24578. here_val = work[sym];
  24579. }
  24580. else if (work[sym] > end) {
  24581. here_op = extra[extra_index + work[sym]];
  24582. here_val = base[base_index + work[sym]];
  24583. }
  24584. else {
  24585. here_op = 32 + 64; /* end of block */
  24586. here_val = 0;
  24587. }
  24588. /* replicate for those indices with low len bits equal to huff */
  24589. incr = 1 << (len - drop);
  24590. fill = 1 << curr;
  24591. min = fill; /* save offset to next table */
  24592. do {
  24593. fill -= incr;
  24594. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24595. } while (fill !== 0);
  24596. /* backwards increment the len-bit code huff */
  24597. incr = 1 << (len - 1);
  24598. while (huff & incr) {
  24599. incr >>= 1;
  24600. }
  24601. if (incr !== 0) {
  24602. huff &= incr - 1;
  24603. huff += incr;
  24604. } else {
  24605. huff = 0;
  24606. }
  24607. /* go to next symbol, update count, len */
  24608. sym++;
  24609. if (--count[len] === 0) {
  24610. if (len === max) { break; }
  24611. len = lens[lens_index + work[sym]];
  24612. }
  24613. /* create new sub-table if needed */
  24614. if (len > root && (huff & mask) !== low) {
  24615. /* if first time, transition to sub-tables */
  24616. if (drop === 0) {
  24617. drop = root;
  24618. }
  24619. /* increment past last table */
  24620. next += min; /* here min is 1 << curr */
  24621. /* determine length of next table */
  24622. curr = len - drop;
  24623. left = 1 << curr;
  24624. while (curr + drop < max) {
  24625. left -= count[curr + drop];
  24626. if (left <= 0) { break; }
  24627. curr++;
  24628. left <<= 1;
  24629. }
  24630. /* check for enough space */
  24631. used += 1 << curr;
  24632. if ((type === LENS && used > ENOUGH_LENS) ||
  24633. (type === DISTS && used > ENOUGH_DISTS)) {
  24634. return 1;
  24635. }
  24636. /* point entry in root table to sub-table */
  24637. low = huff & mask;
  24638. /*table.op[low] = curr;
  24639. table.bits[low] = root;
  24640. table.val[low] = next - opts.table_index;*/
  24641. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24642. }
  24643. }
  24644. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24645. at most one remaining entry, since if the code is incomplete, the
  24646. maximum code length that was allowed to get this far is one bit) */
  24647. if (huff !== 0) {
  24648. //table.op[next + huff] = 64; /* invalid code marker */
  24649. //table.bits[next + huff] = len - drop;
  24650. //table.val[next + huff] = 0;
  24651. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24652. }
  24653. /* set return parameters */
  24654. //opts.table_index += used;
  24655. opts.bits = root;
  24656. return 0;
  24657. };
  24658. },{"../utils/common":76}],86:[function(require,module,exports){
  24659. 'use strict';
  24660. module.exports = {
  24661. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24662. '1': 'stream end', /* Z_STREAM_END 1 */
  24663. '0': '', /* Z_OK 0 */
  24664. '-1': 'file error', /* Z_ERRNO (-1) */
  24665. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24666. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24667. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24668. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24669. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24670. };
  24671. },{}],87:[function(require,module,exports){
  24672. 'use strict';
  24673. var utils = require('../utils/common');
  24674. /* Public constants ==========================================================*/
  24675. /* ===========================================================================*/
  24676. //var Z_FILTERED = 1;
  24677. //var Z_HUFFMAN_ONLY = 2;
  24678. //var Z_RLE = 3;
  24679. var Z_FIXED = 4;
  24680. //var Z_DEFAULT_STRATEGY = 0;
  24681. /* Possible values of the data_type field (though see inflate()) */
  24682. var Z_BINARY = 0;
  24683. var Z_TEXT = 1;
  24684. //var Z_ASCII = 1; // = Z_TEXT
  24685. var Z_UNKNOWN = 2;
  24686. /*============================================================================*/
  24687. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24688. // From zutil.h
  24689. var STORED_BLOCK = 0;
  24690. var STATIC_TREES = 1;
  24691. var DYN_TREES = 2;
  24692. /* The three kinds of block type */
  24693. var MIN_MATCH = 3;
  24694. var MAX_MATCH = 258;
  24695. /* The minimum and maximum match lengths */
  24696. // From deflate.h
  24697. /* ===========================================================================
  24698. * Internal compression state.
  24699. */
  24700. var LENGTH_CODES = 29;
  24701. /* number of length codes, not counting the special END_BLOCK code */
  24702. var LITERALS = 256;
  24703. /* number of literal bytes 0..255 */
  24704. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24705. /* number of Literal or Length codes, including the END_BLOCK code */
  24706. var D_CODES = 30;
  24707. /* number of distance codes */
  24708. var BL_CODES = 19;
  24709. /* number of codes used to transfer the bit lengths */
  24710. var HEAP_SIZE = 2*L_CODES + 1;
  24711. /* maximum heap size */
  24712. var MAX_BITS = 15;
  24713. /* All codes must not exceed MAX_BITS bits */
  24714. var Buf_size = 16;
  24715. /* size of bit buffer in bi_buf */
  24716. /* ===========================================================================
  24717. * Constants
  24718. */
  24719. var MAX_BL_BITS = 7;
  24720. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24721. var END_BLOCK = 256;
  24722. /* end of block literal code */
  24723. var REP_3_6 = 16;
  24724. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24725. var REPZ_3_10 = 17;
  24726. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24727. var REPZ_11_138 = 18;
  24728. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24729. var extra_lbits = /* extra bits for each length code */
  24730. [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];
  24731. var extra_dbits = /* extra bits for each distance code */
  24732. [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];
  24733. var extra_blbits = /* extra bits for each bit length code */
  24734. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24735. var bl_order =
  24736. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24737. /* The lengths of the bit length codes are sent in order of decreasing
  24738. * probability, to avoid transmitting the lengths for unused bit length codes.
  24739. */
  24740. /* ===========================================================================
  24741. * Local data. These are initialized only once.
  24742. */
  24743. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24744. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24745. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24746. var static_ltree = new Array((L_CODES+2) * 2);
  24747. zero(static_ltree);
  24748. /* The static literal tree. Since the bit lengths are imposed, there is no
  24749. * need for the L_CODES extra codes used during heap construction. However
  24750. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24751. * below).
  24752. */
  24753. var static_dtree = new Array(D_CODES * 2);
  24754. zero(static_dtree);
  24755. /* The static distance tree. (Actually a trivial tree since all codes use
  24756. * 5 bits.)
  24757. */
  24758. var _dist_code = new Array(DIST_CODE_LEN);
  24759. zero(_dist_code);
  24760. /* Distance codes. The first 256 values correspond to the distances
  24761. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24762. * the 15 bit distances.
  24763. */
  24764. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24765. zero(_length_code);
  24766. /* length code for each normalized match length (0 == MIN_MATCH) */
  24767. var base_length = new Array(LENGTH_CODES);
  24768. zero(base_length);
  24769. /* First normalized length for each code (0 = MIN_MATCH) */
  24770. var base_dist = new Array(D_CODES);
  24771. zero(base_dist);
  24772. /* First normalized distance for each code (0 = distance of 1) */
  24773. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24774. this.static_tree = static_tree; /* static tree or NULL */
  24775. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24776. this.extra_base = extra_base; /* base index for extra_bits */
  24777. this.elems = elems; /* max number of elements in the tree */
  24778. this.max_length = max_length; /* max bit length for the codes */
  24779. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24780. this.has_stree = static_tree && static_tree.length;
  24781. };
  24782. var static_l_desc;
  24783. var static_d_desc;
  24784. var static_bl_desc;
  24785. var TreeDesc = function(dyn_tree, stat_desc) {
  24786. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24787. this.max_code = 0; /* largest code with non zero frequency */
  24788. this.stat_desc = stat_desc; /* the corresponding static tree */
  24789. };
  24790. function d_code(dist) {
  24791. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24792. }
  24793. /* ===========================================================================
  24794. * Output a short LSB first on the stream.
  24795. * IN assertion: there is enough room in pendingBuf.
  24796. */
  24797. function put_short (s, w) {
  24798. // put_byte(s, (uch)((w) & 0xff));
  24799. // put_byte(s, (uch)((ush)(w) >> 8));
  24800. s.pending_buf[s.pending++] = (w) & 0xff;
  24801. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24802. }
  24803. /* ===========================================================================
  24804. * Send a value on a given number of bits.
  24805. * IN assertion: length <= 16 and value fits in length bits.
  24806. */
  24807. function send_bits(s, value, length) {
  24808. if (s.bi_valid > (Buf_size - length)) {
  24809. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24810. put_short(s, s.bi_buf);
  24811. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24812. s.bi_valid += length - Buf_size;
  24813. } else {
  24814. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24815. s.bi_valid += length;
  24816. }
  24817. }
  24818. function send_code(s, c, tree) {
  24819. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24820. }
  24821. /* ===========================================================================
  24822. * Reverse the first len bits of a code, using straightforward code (a faster
  24823. * method would use a table)
  24824. * IN assertion: 1 <= len <= 15
  24825. */
  24826. function bi_reverse(code, len) {
  24827. var res = 0;
  24828. do {
  24829. res |= code & 1;
  24830. code >>>= 1;
  24831. res <<= 1;
  24832. } while (--len > 0);
  24833. return res >>> 1;
  24834. }
  24835. /* ===========================================================================
  24836. * Flush the bit buffer, keeping at most 7 bits in it.
  24837. */
  24838. function bi_flush(s) {
  24839. if (s.bi_valid === 16) {
  24840. put_short(s, s.bi_buf);
  24841. s.bi_buf = 0;
  24842. s.bi_valid = 0;
  24843. } else if (s.bi_valid >= 8) {
  24844. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24845. s.bi_buf >>= 8;
  24846. s.bi_valid -= 8;
  24847. }
  24848. }
  24849. /* ===========================================================================
  24850. * Compute the optimal bit lengths for a tree and update the total bit length
  24851. * for the current block.
  24852. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24853. * above are the tree nodes sorted by increasing frequency.
  24854. * OUT assertions: the field len is set to the optimal bit length, the
  24855. * array bl_count contains the frequencies for each bit length.
  24856. * The length opt_len is updated; static_len is also updated if stree is
  24857. * not null.
  24858. */
  24859. function gen_bitlen(s, desc)
  24860. // deflate_state *s;
  24861. // tree_desc *desc; /* the tree descriptor */
  24862. {
  24863. var tree = desc.dyn_tree;
  24864. var max_code = desc.max_code;
  24865. var stree = desc.stat_desc.static_tree;
  24866. var has_stree = desc.stat_desc.has_stree;
  24867. var extra = desc.stat_desc.extra_bits;
  24868. var base = desc.stat_desc.extra_base;
  24869. var max_length = desc.stat_desc.max_length;
  24870. var h; /* heap index */
  24871. var n, m; /* iterate over the tree elements */
  24872. var bits; /* bit length */
  24873. var xbits; /* extra bits */
  24874. var f; /* frequency */
  24875. var overflow = 0; /* number of elements with bit length too large */
  24876. for (bits = 0; bits <= MAX_BITS; bits++) {
  24877. s.bl_count[bits] = 0;
  24878. }
  24879. /* In a first pass, compute the optimal bit lengths (which may
  24880. * overflow in the case of the bit length tree).
  24881. */
  24882. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24883. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24884. n = s.heap[h];
  24885. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24886. if (bits > max_length) {
  24887. bits = max_length;
  24888. overflow++;
  24889. }
  24890. tree[n*2 + 1]/*.Len*/ = bits;
  24891. /* We overwrite tree[n].Dad which is no longer needed */
  24892. if (n > max_code) { continue; } /* not a leaf node */
  24893. s.bl_count[bits]++;
  24894. xbits = 0;
  24895. if (n >= base) {
  24896. xbits = extra[n-base];
  24897. }
  24898. f = tree[n * 2]/*.Freq*/;
  24899. s.opt_len += f * (bits + xbits);
  24900. if (has_stree) {
  24901. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24902. }
  24903. }
  24904. if (overflow === 0) { return; }
  24905. // Trace((stderr,"\nbit length overflow\n"));
  24906. /* This happens for example on obj2 and pic of the Calgary corpus */
  24907. /* Find the first bit length which could increase: */
  24908. do {
  24909. bits = max_length-1;
  24910. while (s.bl_count[bits] === 0) { bits--; }
  24911. s.bl_count[bits]--; /* move one leaf down the tree */
  24912. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24913. s.bl_count[max_length]--;
  24914. /* The brother of the overflow item also moves one step up,
  24915. * but this does not affect bl_count[max_length]
  24916. */
  24917. overflow -= 2;
  24918. } while (overflow > 0);
  24919. /* Now recompute all bit lengths, scanning in increasing frequency.
  24920. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24921. * lengths instead of fixing only the wrong ones. This idea is taken
  24922. * from 'ar' written by Haruhiko Okumura.)
  24923. */
  24924. for (bits = max_length; bits !== 0; bits--) {
  24925. n = s.bl_count[bits];
  24926. while (n !== 0) {
  24927. m = s.heap[--h];
  24928. if (m > max_code) { continue; }
  24929. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24930. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24931. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24932. tree[m*2 + 1]/*.Len*/ = bits;
  24933. }
  24934. n--;
  24935. }
  24936. }
  24937. }
  24938. /* ===========================================================================
  24939. * Generate the codes for a given tree and bit counts (which need not be
  24940. * optimal).
  24941. * IN assertion: the array bl_count contains the bit length statistics for
  24942. * the given tree and the field len is set for all tree elements.
  24943. * OUT assertion: the field code is set for all tree elements of non
  24944. * zero code length.
  24945. */
  24946. function gen_codes(tree, max_code, bl_count)
  24947. // ct_data *tree; /* the tree to decorate */
  24948. // int max_code; /* largest code with non zero frequency */
  24949. // ushf *bl_count; /* number of codes at each bit length */
  24950. {
  24951. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24952. var code = 0; /* running code value */
  24953. var bits; /* bit index */
  24954. var n; /* code index */
  24955. /* The distribution counts are first used to generate the code values
  24956. * without bit reversal.
  24957. */
  24958. for (bits = 1; bits <= MAX_BITS; bits++) {
  24959. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24960. }
  24961. /* Check that the bit counts in bl_count are consistent. The last code
  24962. * must be all ones.
  24963. */
  24964. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24965. // "inconsistent bit counts");
  24966. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24967. for (n = 0; n <= max_code; n++) {
  24968. var len = tree[n*2 + 1]/*.Len*/;
  24969. if (len === 0) { continue; }
  24970. /* Now reverse the bits */
  24971. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24972. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24973. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24974. }
  24975. }
  24976. /* ===========================================================================
  24977. * Initialize the various 'constant' tables.
  24978. */
  24979. function tr_static_init() {
  24980. var n; /* iterates over tree elements */
  24981. var bits; /* bit counter */
  24982. var length; /* length value */
  24983. var code; /* code value */
  24984. var dist; /* distance index */
  24985. var bl_count = new Array(MAX_BITS+1);
  24986. /* number of codes at each bit length for an optimal tree */
  24987. // do check in _tr_init()
  24988. //if (static_init_done) return;
  24989. /* For some embedded targets, global variables are not initialized: */
  24990. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24991. static_l_desc.static_tree = static_ltree;
  24992. static_l_desc.extra_bits = extra_lbits;
  24993. static_d_desc.static_tree = static_dtree;
  24994. static_d_desc.extra_bits = extra_dbits;
  24995. static_bl_desc.extra_bits = extra_blbits;
  24996. #endif*/
  24997. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24998. length = 0;
  24999. for (code = 0; code < LENGTH_CODES-1; code++) {
  25000. base_length[code] = length;
  25001. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  25002. _length_code[length++] = code;
  25003. }
  25004. }
  25005. //Assert (length == 256, "tr_static_init: length != 256");
  25006. /* Note that the length 255 (match length 258) can be represented
  25007. * in two different ways: code 284 + 5 bits or code 285, so we
  25008. * overwrite length_code[255] to use the best encoding:
  25009. */
  25010. _length_code[length-1] = code;
  25011. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  25012. dist = 0;
  25013. for (code = 0 ; code < 16; code++) {
  25014. base_dist[code] = dist;
  25015. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  25016. _dist_code[dist++] = code;
  25017. }
  25018. }
  25019. //Assert (dist == 256, "tr_static_init: dist != 256");
  25020. dist >>= 7; /* from now on, all distances are divided by 128 */
  25021. for (; code < D_CODES; code++) {
  25022. base_dist[code] = dist << 7;
  25023. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  25024. _dist_code[256 + dist++] = code;
  25025. }
  25026. }
  25027. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  25028. /* Construct the codes of the static literal tree */
  25029. for (bits = 0; bits <= MAX_BITS; bits++) {
  25030. bl_count[bits] = 0;
  25031. }
  25032. n = 0;
  25033. while (n <= 143) {
  25034. static_ltree[n*2 + 1]/*.Len*/ = 8;
  25035. n++;
  25036. bl_count[8]++;
  25037. }
  25038. while (n <= 255) {
  25039. static_ltree[n*2 + 1]/*.Len*/ = 9;
  25040. n++;
  25041. bl_count[9]++;
  25042. }
  25043. while (n <= 279) {
  25044. static_ltree[n*2 + 1]/*.Len*/ = 7;
  25045. n++;
  25046. bl_count[7]++;
  25047. }
  25048. while (n <= 287) {
  25049. static_ltree[n*2 + 1]/*.Len*/ = 8;
  25050. n++;
  25051. bl_count[8]++;
  25052. }
  25053. /* Codes 286 and 287 do not exist, but we must include them in the
  25054. * tree construction to get a canonical Huffman tree (longest code
  25055. * all ones)
  25056. */
  25057. gen_codes(static_ltree, L_CODES+1, bl_count);
  25058. /* The static distance tree is trivial: */
  25059. for (n = 0; n < D_CODES; n++) {
  25060. static_dtree[n*2 + 1]/*.Len*/ = 5;
  25061. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  25062. }
  25063. // Now data ready and we can init static trees
  25064. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  25065. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  25066. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  25067. //static_init_done = true;
  25068. }
  25069. /* ===========================================================================
  25070. * Initialize a new block.
  25071. */
  25072. function init_block(s) {
  25073. var n; /* iterates over tree elements */
  25074. /* Initialize the trees. */
  25075. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  25076. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  25077. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  25078. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  25079. s.opt_len = s.static_len = 0;
  25080. s.last_lit = s.matches = 0;
  25081. }
  25082. /* ===========================================================================
  25083. * Flush the bit buffer and align the output on a byte boundary
  25084. */
  25085. function bi_windup(s)
  25086. {
  25087. if (s.bi_valid > 8) {
  25088. put_short(s, s.bi_buf);
  25089. } else if (s.bi_valid > 0) {
  25090. //put_byte(s, (Byte)s->bi_buf);
  25091. s.pending_buf[s.pending++] = s.bi_buf;
  25092. }
  25093. s.bi_buf = 0;
  25094. s.bi_valid = 0;
  25095. }
  25096. /* ===========================================================================
  25097. * Copy a stored block, storing first the length and its
  25098. * one's complement if requested.
  25099. */
  25100. function copy_block(s, buf, len, header)
  25101. //DeflateState *s;
  25102. //charf *buf; /* the input data */
  25103. //unsigned len; /* its length */
  25104. //int header; /* true if block header must be written */
  25105. {
  25106. bi_windup(s); /* align on byte boundary */
  25107. if (header) {
  25108. put_short(s, len);
  25109. put_short(s, ~len);
  25110. }
  25111. // while (len--) {
  25112. // put_byte(s, *buf++);
  25113. // }
  25114. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  25115. s.pending += len;
  25116. }
  25117. /* ===========================================================================
  25118. * Compares to subtrees, using the tree depth as tie breaker when
  25119. * the subtrees have equal frequency. This minimizes the worst case length.
  25120. */
  25121. function smaller(tree, n, m, depth) {
  25122. var _n2 = n*2;
  25123. var _m2 = m*2;
  25124. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  25125. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  25126. }
  25127. /* ===========================================================================
  25128. * Restore the heap property by moving down the tree starting at node k,
  25129. * exchanging a node with the smallest of its two sons if necessary, stopping
  25130. * when the heap property is re-established (each father smaller than its
  25131. * two sons).
  25132. */
  25133. function pqdownheap(s, tree, k)
  25134. // deflate_state *s;
  25135. // ct_data *tree; /* the tree to restore */
  25136. // int k; /* node to move down */
  25137. {
  25138. var v = s.heap[k];
  25139. var j = k << 1; /* left son of k */
  25140. while (j <= s.heap_len) {
  25141. /* Set j to the smallest of the two sons: */
  25142. if (j < s.heap_len &&
  25143. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  25144. j++;
  25145. }
  25146. /* Exit if v is smaller than both sons */
  25147. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  25148. /* Exchange v with the smallest son */
  25149. s.heap[k] = s.heap[j];
  25150. k = j;
  25151. /* And continue down the tree, setting j to the left son of k */
  25152. j <<= 1;
  25153. }
  25154. s.heap[k] = v;
  25155. }
  25156. // inlined manually
  25157. // var SMALLEST = 1;
  25158. /* ===========================================================================
  25159. * Send the block data compressed using the given Huffman trees
  25160. */
  25161. function compress_block(s, ltree, dtree)
  25162. // deflate_state *s;
  25163. // const ct_data *ltree; /* literal tree */
  25164. // const ct_data *dtree; /* distance tree */
  25165. {
  25166. var dist; /* distance of matched string */
  25167. var lc; /* match length or unmatched char (if dist == 0) */
  25168. var lx = 0; /* running index in l_buf */
  25169. var code; /* the code to send */
  25170. var extra; /* number of extra bits to send */
  25171. if (s.last_lit !== 0) {
  25172. do {
  25173. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  25174. lc = s.pending_buf[s.l_buf + lx];
  25175. lx++;
  25176. if (dist === 0) {
  25177. send_code(s, lc, ltree); /* send a literal byte */
  25178. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  25179. } else {
  25180. /* Here, lc is the match length - MIN_MATCH */
  25181. code = _length_code[lc];
  25182. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  25183. extra = extra_lbits[code];
  25184. if (extra !== 0) {
  25185. lc -= base_length[code];
  25186. send_bits(s, lc, extra); /* send the extra length bits */
  25187. }
  25188. dist--; /* dist is now the match distance - 1 */
  25189. code = d_code(dist);
  25190. //Assert (code < D_CODES, "bad d_code");
  25191. send_code(s, code, dtree); /* send the distance code */
  25192. extra = extra_dbits[code];
  25193. if (extra !== 0) {
  25194. dist -= base_dist[code];
  25195. send_bits(s, dist, extra); /* send the extra distance bits */
  25196. }
  25197. } /* literal or match pair ? */
  25198. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  25199. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  25200. // "pendingBuf overflow");
  25201. } while (lx < s.last_lit);
  25202. }
  25203. send_code(s, END_BLOCK, ltree);
  25204. }
  25205. /* ===========================================================================
  25206. * Construct one Huffman tree and assigns the code bit strings and lengths.
  25207. * Update the total bit length for the current block.
  25208. * IN assertion: the field freq is set for all tree elements.
  25209. * OUT assertions: the fields len and code are set to the optimal bit length
  25210. * and corresponding code. The length opt_len is updated; static_len is
  25211. * also updated if stree is not null. The field max_code is set.
  25212. */
  25213. function build_tree(s, desc)
  25214. // deflate_state *s;
  25215. // tree_desc *desc; /* the tree descriptor */
  25216. {
  25217. var tree = desc.dyn_tree;
  25218. var stree = desc.stat_desc.static_tree;
  25219. var has_stree = desc.stat_desc.has_stree;
  25220. var elems = desc.stat_desc.elems;
  25221. var n, m; /* iterate over heap elements */
  25222. var max_code = -1; /* largest code with non zero frequency */
  25223. var node; /* new node being created */
  25224. /* Construct the initial heap, with least frequent element in
  25225. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  25226. * heap[0] is not used.
  25227. */
  25228. s.heap_len = 0;
  25229. s.heap_max = HEAP_SIZE;
  25230. for (n = 0; n < elems; n++) {
  25231. if (tree[n * 2]/*.Freq*/ !== 0) {
  25232. s.heap[++s.heap_len] = max_code = n;
  25233. s.depth[n] = 0;
  25234. } else {
  25235. tree[n*2 + 1]/*.Len*/ = 0;
  25236. }
  25237. }
  25238. /* The pkzip format requires that at least one distance code exists,
  25239. * and that at least one bit should be sent even if there is only one
  25240. * possible code. So to avoid special checks later on we force at least
  25241. * two codes of non zero frequency.
  25242. */
  25243. while (s.heap_len < 2) {
  25244. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  25245. tree[node * 2]/*.Freq*/ = 1;
  25246. s.depth[node] = 0;
  25247. s.opt_len--;
  25248. if (has_stree) {
  25249. s.static_len -= stree[node*2 + 1]/*.Len*/;
  25250. }
  25251. /* node is 0 or 1 so it does not have extra bits */
  25252. }
  25253. desc.max_code = max_code;
  25254. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  25255. * establish sub-heaps of increasing lengths:
  25256. */
  25257. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  25258. /* Construct the Huffman tree by repeatedly combining the least two
  25259. * frequent nodes.
  25260. */
  25261. node = elems; /* next internal node of the tree */
  25262. do {
  25263. //pqremove(s, tree, n); /* n = node of least frequency */
  25264. /*** pqremove ***/
  25265. n = s.heap[1/*SMALLEST*/];
  25266. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  25267. pqdownheap(s, tree, 1/*SMALLEST*/);
  25268. /***/
  25269. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  25270. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  25271. s.heap[--s.heap_max] = m;
  25272. /* Create a new node father of n and m */
  25273. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  25274. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  25275. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  25276. /* and insert the new node in the heap */
  25277. s.heap[1/*SMALLEST*/] = node++;
  25278. pqdownheap(s, tree, 1/*SMALLEST*/);
  25279. } while (s.heap_len >= 2);
  25280. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  25281. /* At this point, the fields freq and dad are set. We can now
  25282. * generate the bit lengths.
  25283. */
  25284. gen_bitlen(s, desc);
  25285. /* The field len is now set, we can generate the bit codes */
  25286. gen_codes(tree, max_code, s.bl_count);
  25287. }
  25288. /* ===========================================================================
  25289. * Scan a literal or distance tree to determine the frequencies of the codes
  25290. * in the bit length tree.
  25291. */
  25292. function scan_tree(s, tree, max_code)
  25293. // deflate_state *s;
  25294. // ct_data *tree; /* the tree to be scanned */
  25295. // int max_code; /* and its largest code of non zero frequency */
  25296. {
  25297. var n; /* iterates over all tree elements */
  25298. var prevlen = -1; /* last emitted length */
  25299. var curlen; /* length of current code */
  25300. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25301. var count = 0; /* repeat count of the current code */
  25302. var max_count = 7; /* max repeat count */
  25303. var min_count = 4; /* min repeat count */
  25304. if (nextlen === 0) {
  25305. max_count = 138;
  25306. min_count = 3;
  25307. }
  25308. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  25309. for (n = 0; n <= max_code; n++) {
  25310. curlen = nextlen;
  25311. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25312. if (++count < max_count && curlen === nextlen) {
  25313. continue;
  25314. } else if (count < min_count) {
  25315. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  25316. } else if (curlen !== 0) {
  25317. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  25318. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  25319. } else if (count <= 10) {
  25320. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  25321. } else {
  25322. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  25323. }
  25324. count = 0;
  25325. prevlen = curlen;
  25326. if (nextlen === 0) {
  25327. max_count = 138;
  25328. min_count = 3;
  25329. } else if (curlen === nextlen) {
  25330. max_count = 6;
  25331. min_count = 3;
  25332. } else {
  25333. max_count = 7;
  25334. min_count = 4;
  25335. }
  25336. }
  25337. }
  25338. /* ===========================================================================
  25339. * Send a literal or distance tree in compressed form, using the codes in
  25340. * bl_tree.
  25341. */
  25342. function send_tree(s, tree, max_code)
  25343. // deflate_state *s;
  25344. // ct_data *tree; /* the tree to be scanned */
  25345. // int max_code; /* and its largest code of non zero frequency */
  25346. {
  25347. var n; /* iterates over all tree elements */
  25348. var prevlen = -1; /* last emitted length */
  25349. var curlen; /* length of current code */
  25350. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25351. var count = 0; /* repeat count of the current code */
  25352. var max_count = 7; /* max repeat count */
  25353. var min_count = 4; /* min repeat count */
  25354. /* tree[max_code+1].Len = -1; */ /* guard already set */
  25355. if (nextlen === 0) {
  25356. max_count = 138;
  25357. min_count = 3;
  25358. }
  25359. for (n = 0; n <= max_code; n++) {
  25360. curlen = nextlen;
  25361. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25362. if (++count < max_count && curlen === nextlen) {
  25363. continue;
  25364. } else if (count < min_count) {
  25365. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  25366. } else if (curlen !== 0) {
  25367. if (curlen !== prevlen) {
  25368. send_code(s, curlen, s.bl_tree);
  25369. count--;
  25370. }
  25371. //Assert(count >= 3 && count <= 6, " 3_6?");
  25372. send_code(s, REP_3_6, s.bl_tree);
  25373. send_bits(s, count-3, 2);
  25374. } else if (count <= 10) {
  25375. send_code(s, REPZ_3_10, s.bl_tree);
  25376. send_bits(s, count-3, 3);
  25377. } else {
  25378. send_code(s, REPZ_11_138, s.bl_tree);
  25379. send_bits(s, count-11, 7);
  25380. }
  25381. count = 0;
  25382. prevlen = curlen;
  25383. if (nextlen === 0) {
  25384. max_count = 138;
  25385. min_count = 3;
  25386. } else if (curlen === nextlen) {
  25387. max_count = 6;
  25388. min_count = 3;
  25389. } else {
  25390. max_count = 7;
  25391. min_count = 4;
  25392. }
  25393. }
  25394. }
  25395. /* ===========================================================================
  25396. * Construct the Huffman tree for the bit lengths and return the index in
  25397. * bl_order of the last bit length code to send.
  25398. */
  25399. function build_bl_tree(s) {
  25400. var max_blindex; /* index of last bit length code of non zero freq */
  25401. /* Determine the bit length frequencies for literal and distance trees */
  25402. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  25403. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  25404. /* Build the bit length tree: */
  25405. build_tree(s, s.bl_desc);
  25406. /* opt_len now includes the length of the tree representations, except
  25407. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  25408. */
  25409. /* Determine the number of bit length codes to send. The pkzip format
  25410. * requires that at least 4 bit length codes be sent. (appnote.txt says
  25411. * 3 but the actual value used is 4.)
  25412. */
  25413. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  25414. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  25415. break;
  25416. }
  25417. }
  25418. /* Update opt_len to include the bit length tree and counts */
  25419. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  25420. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  25421. // s->opt_len, s->static_len));
  25422. return max_blindex;
  25423. }
  25424. /* ===========================================================================
  25425. * Send the header for a block using dynamic Huffman trees: the counts, the
  25426. * lengths of the bit length codes, the literal tree and the distance tree.
  25427. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  25428. */
  25429. function send_all_trees(s, lcodes, dcodes, blcodes)
  25430. // deflate_state *s;
  25431. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  25432. {
  25433. var rank; /* index in bl_order */
  25434. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  25435. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  25436. // "too many codes");
  25437. //Tracev((stderr, "\nbl counts: "));
  25438. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  25439. send_bits(s, dcodes-1, 5);
  25440. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  25441. for (rank = 0; rank < blcodes; rank++) {
  25442. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  25443. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  25444. }
  25445. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  25446. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  25447. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  25448. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  25449. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  25450. }
  25451. /* ===========================================================================
  25452. * Check if the data type is TEXT or BINARY, using the following algorithm:
  25453. * - TEXT if the two conditions below are satisfied:
  25454. * a) There are no non-portable control characters belonging to the
  25455. * "black list" (0..6, 14..25, 28..31).
  25456. * b) There is at least one printable character belonging to the
  25457. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  25458. * - BINARY otherwise.
  25459. * - The following partially-portable control characters form a
  25460. * "gray list" that is ignored in this detection algorithm:
  25461. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  25462. * IN assertion: the fields Freq of dyn_ltree are set.
  25463. */
  25464. function detect_data_type(s) {
  25465. /* black_mask is the bit mask of black-listed bytes
  25466. * set bits 0..6, 14..25, and 28..31
  25467. * 0xf3ffc07f = binary 11110011111111111100000001111111
  25468. */
  25469. var black_mask = 0xf3ffc07f;
  25470. var n;
  25471. /* Check for non-textual ("black-listed") bytes. */
  25472. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  25473. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  25474. return Z_BINARY;
  25475. }
  25476. }
  25477. /* Check for textual ("white-listed") bytes. */
  25478. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  25479. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  25480. return Z_TEXT;
  25481. }
  25482. for (n = 32; n < LITERALS; n++) {
  25483. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  25484. return Z_TEXT;
  25485. }
  25486. }
  25487. /* There are no "black-listed" or "white-listed" bytes:
  25488. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  25489. */
  25490. return Z_BINARY;
  25491. }
  25492. var static_init_done = false;
  25493. /* ===========================================================================
  25494. * Initialize the tree data structures for a new zlib stream.
  25495. */
  25496. function _tr_init(s)
  25497. {
  25498. if (!static_init_done) {
  25499. tr_static_init();
  25500. static_init_done = true;
  25501. }
  25502. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  25503. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  25504. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  25505. s.bi_buf = 0;
  25506. s.bi_valid = 0;
  25507. /* Initialize the first block of the first file: */
  25508. init_block(s);
  25509. }
  25510. /* ===========================================================================
  25511. * Send a stored block
  25512. */
  25513. function _tr_stored_block(s, buf, stored_len, last)
  25514. //DeflateState *s;
  25515. //charf *buf; /* input block */
  25516. //ulg stored_len; /* length of input block */
  25517. //int last; /* one if this is the last block for a file */
  25518. {
  25519. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  25520. copy_block(s, buf, stored_len, true); /* with header */
  25521. }
  25522. /* ===========================================================================
  25523. * Send one empty static block to give enough lookahead for inflate.
  25524. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25525. */
  25526. function _tr_align(s) {
  25527. send_bits(s, STATIC_TREES<<1, 3);
  25528. send_code(s, END_BLOCK, static_ltree);
  25529. bi_flush(s);
  25530. }
  25531. /* ===========================================================================
  25532. * Determine the best encoding for the current block: dynamic trees, static
  25533. * trees or store, and output the encoded block to the zip file.
  25534. */
  25535. function _tr_flush_block(s, buf, stored_len, last)
  25536. //DeflateState *s;
  25537. //charf *buf; /* input block, or NULL if too old */
  25538. //ulg stored_len; /* length of input block */
  25539. //int last; /* one if this is the last block for a file */
  25540. {
  25541. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25542. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25543. /* Build the Huffman trees unless a stored block is forced */
  25544. if (s.level > 0) {
  25545. /* Check if the file is binary or text */
  25546. if (s.strm.data_type === Z_UNKNOWN) {
  25547. s.strm.data_type = detect_data_type(s);
  25548. }
  25549. /* Construct the literal and distance trees */
  25550. build_tree(s, s.l_desc);
  25551. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25552. // s->static_len));
  25553. build_tree(s, s.d_desc);
  25554. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25555. // s->static_len));
  25556. /* At this point, opt_len and static_len are the total bit lengths of
  25557. * the compressed block data, excluding the tree representations.
  25558. */
  25559. /* Build the bit length tree for the above two trees, and get the index
  25560. * in bl_order of the last bit length code to send.
  25561. */
  25562. max_blindex = build_bl_tree(s);
  25563. /* Determine the best encoding. Compute the block lengths in bytes. */
  25564. opt_lenb = (s.opt_len+3+7) >>> 3;
  25565. static_lenb = (s.static_len+3+7) >>> 3;
  25566. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25567. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25568. // s->last_lit));
  25569. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25570. } else {
  25571. // Assert(buf != (char*)0, "lost buf");
  25572. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25573. }
  25574. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25575. /* 4: two words for the lengths */
  25576. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25577. * Otherwise we can't have processed more than WSIZE input bytes since
  25578. * the last block flush, because compression would have been
  25579. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25580. * transform a block into a stored block.
  25581. */
  25582. _tr_stored_block(s, buf, stored_len, last);
  25583. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25584. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25585. compress_block(s, static_ltree, static_dtree);
  25586. } else {
  25587. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25588. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25589. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25590. }
  25591. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25592. /* The above check is made mod 2^32, for files larger than 512 MB
  25593. * and uLong implemented on 32 bits.
  25594. */
  25595. init_block(s);
  25596. if (last) {
  25597. bi_windup(s);
  25598. }
  25599. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25600. // s->compressed_len-7*last));
  25601. }
  25602. /* ===========================================================================
  25603. * Save the match info and tally the frequency counts. Return true if
  25604. * the current block must be flushed.
  25605. */
  25606. function _tr_tally(s, dist, lc)
  25607. // deflate_state *s;
  25608. // unsigned dist; /* distance of matched string */
  25609. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25610. {
  25611. //var out_length, in_length, dcode;
  25612. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25613. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25614. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25615. s.last_lit++;
  25616. if (dist === 0) {
  25617. /* lc is the unmatched char */
  25618. s.dyn_ltree[lc*2]/*.Freq*/++;
  25619. } else {
  25620. s.matches++;
  25621. /* Here, lc is the match length - MIN_MATCH */
  25622. dist--; /* dist = match distance - 1 */
  25623. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25624. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25625. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25626. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25627. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25628. }
  25629. // (!) This block is disabled in zlib defailts,
  25630. // don't enable it for binary compatibility
  25631. //#ifdef TRUNCATE_BLOCK
  25632. // /* Try to guess if it is profitable to stop the current block here */
  25633. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25634. // /* Compute an upper bound for the compressed length */
  25635. // out_length = s.last_lit*8;
  25636. // in_length = s.strstart - s.block_start;
  25637. //
  25638. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25639. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25640. // }
  25641. // out_length >>>= 3;
  25642. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25643. // // s->last_lit, in_length, out_length,
  25644. // // 100L - out_length*100L/in_length));
  25645. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25646. // return true;
  25647. // }
  25648. // }
  25649. //#endif
  25650. return (s.last_lit === s.lit_bufsize-1);
  25651. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25652. * on 16 bit machines and because stored blocks are restricted to
  25653. * 64K-1 bytes.
  25654. */
  25655. }
  25656. exports._tr_init = _tr_init;
  25657. exports._tr_stored_block = _tr_stored_block;
  25658. exports._tr_flush_block = _tr_flush_block;
  25659. exports._tr_tally = _tr_tally;
  25660. exports._tr_align = _tr_align;
  25661. },{"../utils/common":76}],88:[function(require,module,exports){
  25662. 'use strict';
  25663. function ZStream() {
  25664. /* next input byte */
  25665. this.input = null; // JS specific, because we have no pointers
  25666. this.next_in = 0;
  25667. /* number of bytes available at input */
  25668. this.avail_in = 0;
  25669. /* total number of input bytes read so far */
  25670. this.total_in = 0;
  25671. /* next output byte should be put there */
  25672. this.output = null; // JS specific, because we have no pointers
  25673. this.next_out = 0;
  25674. /* remaining free space at output */
  25675. this.avail_out = 0;
  25676. /* total number of bytes output so far */
  25677. this.total_out = 0;
  25678. /* last error message, NULL if no error */
  25679. this.msg = ''/*Z_NULL*/;
  25680. /* not visible by applications */
  25681. this.state = null;
  25682. /* best guess about the data type: binary or text */
  25683. this.data_type = 2/*Z_UNKNOWN*/;
  25684. /* adler32 value of the uncompressed data */
  25685. this.adler = 0;
  25686. }
  25687. module.exports = ZStream;
  25688. },{}],89:[function(require,module,exports){
  25689. module.exports = require('./lib/retry');
  25690. },{"./lib/retry":90}],90:[function(require,module,exports){
  25691. var RetryOperation = require('./retry_operation');
  25692. exports.operation = function(options) {
  25693. var timeouts = exports.timeouts(options);
  25694. return new RetryOperation(timeouts);
  25695. };
  25696. exports.timeouts = function(options) {
  25697. if (options instanceof Array) {
  25698. return [].concat(options);
  25699. }
  25700. var opts = {
  25701. retries: 10,
  25702. factor: 2,
  25703. minTimeout: 1 * 1000,
  25704. maxTimeout: Infinity,
  25705. randomize: false
  25706. };
  25707. for (var key in options) {
  25708. opts[key] = options[key];
  25709. }
  25710. if (opts.minTimeout > opts.maxTimeout) {
  25711. throw new Error('minTimeout is greater than maxTimeout');
  25712. }
  25713. var timeouts = [];
  25714. for (var i = 0; i < opts.retries; i++) {
  25715. timeouts.push(this._createTimeout(i, opts));
  25716. }
  25717. // sort the array numerically ascending
  25718. timeouts.sort(function(a,b) {
  25719. return a - b;
  25720. });
  25721. return timeouts;
  25722. };
  25723. exports._createTimeout = function(attempt, opts) {
  25724. var random = (opts.randomize)
  25725. ? (Math.random() + 1)
  25726. : 1;
  25727. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25728. timeout = Math.min(timeout, opts.maxTimeout);
  25729. return timeout;
  25730. };
  25731. },{"./retry_operation":91}],91:[function(require,module,exports){
  25732. function RetryOperation(timeouts) {
  25733. this._timeouts = timeouts;
  25734. this._fn = null;
  25735. this._errors = [];
  25736. this._attempts = 1;
  25737. this._operationTimeout = null;
  25738. this._operationTimeoutCb = null;
  25739. this._timeout = null;
  25740. }
  25741. module.exports = RetryOperation;
  25742. RetryOperation.prototype.retry = function(err) {
  25743. if (this._timeout) {
  25744. clearTimeout(this._timeout);
  25745. }
  25746. if (!err) {
  25747. return false;
  25748. }
  25749. this._errors.push(err);
  25750. var timeout = this._timeouts.shift();
  25751. if (timeout === undefined) {
  25752. return false;
  25753. }
  25754. this._attempts++;
  25755. var self = this;
  25756. setTimeout(function() {
  25757. self._fn(self._attempts);
  25758. if (self._operationTimeoutCb) {
  25759. self._timeout = setTimeout(function() {
  25760. self._operationTimeoutCb(self._attempts);
  25761. }, self._operationTimeout);
  25762. }
  25763. }, timeout);
  25764. return true;
  25765. };
  25766. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25767. this._fn = fn;
  25768. if (timeoutOps) {
  25769. if (timeoutOps.timeout) {
  25770. this._operationTimeout = timeoutOps.timeout;
  25771. }
  25772. if (timeoutOps.cb) {
  25773. this._operationTimeoutCb = timeoutOps.cb;
  25774. }
  25775. }
  25776. this._fn(this._attempts);
  25777. var self = this;
  25778. if (this._operationTimeoutCb) {
  25779. this._timeout = setTimeout(function() {
  25780. self._operationTimeoutCb();
  25781. }, self._operationTimeout);
  25782. }
  25783. };
  25784. RetryOperation.prototype.try = function(fn) {
  25785. console.log('Using RetryOperation.try() is deprecated');
  25786. this.attempt(fn);
  25787. };
  25788. RetryOperation.prototype.start = function(fn) {
  25789. console.log('Using RetryOperation.start() is deprecated');
  25790. this.attempt(fn);
  25791. };
  25792. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25793. RetryOperation.prototype.errors = function() {
  25794. return this._errors;
  25795. };
  25796. RetryOperation.prototype.attempts = function() {
  25797. return this._attempts;
  25798. };
  25799. RetryOperation.prototype.mainError = function() {
  25800. if (this._errors.length === 0) {
  25801. return null;
  25802. }
  25803. var counts = {};
  25804. var mainError = null;
  25805. var mainErrorCount = 0;
  25806. for (var i = 0; i < this._errors.length; i++) {
  25807. var error = this._errors[i];
  25808. var message = error.message;
  25809. var count = (counts[message] || 0) + 1;
  25810. counts[message] = count;
  25811. if (count >= mainErrorCount) {
  25812. mainError = error;
  25813. mainErrorCount = count;
  25814. }
  25815. }
  25816. return mainError;
  25817. };
  25818. },{}],92:[function(require,module,exports){
  25819. module.exports = function arrayEquals(array) {
  25820. // if the other array is a falsy value, return
  25821. if (!array)
  25822. return false;
  25823. // compare lengths - can save a lot of time
  25824. if (this.length != array.length)
  25825. return false;
  25826. for (var i = 0, l = this.length; i < l; i++) {
  25827. // Check if we have nested arrays
  25828. if (this[i] instanceof Array && array[i] instanceof Array) {
  25829. // recurse into the nested arrays
  25830. if (!arrayEquals.apply(this[i], [array[i]]))
  25831. return false;
  25832. } else if (this[i] != array[i]) {
  25833. // Warning - two different object instances will never be equal:
  25834. // {x:20} != {x:20}
  25835. return false;
  25836. }
  25837. }
  25838. return true;
  25839. }
  25840. },{}],93:[function(require,module,exports){
  25841. exports.Interop = require('./interop');
  25842. },{"./interop":94}],94:[function(require,module,exports){
  25843. "use strict";
  25844. var transform = require('./transform');
  25845. var arrayEquals = require('./array-equals');
  25846. function Interop() {
  25847. /**
  25848. * This map holds the most recent Unified Plan offer/answer SDP that was
  25849. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25850. * the SDP string as values.
  25851. *
  25852. * @type {{}}
  25853. */
  25854. this.cache = {};
  25855. }
  25856. module.exports = Interop;
  25857. /**
  25858. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25859. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25860. * application.
  25861. *
  25862. * @param desc
  25863. * @returns {*}
  25864. */
  25865. Interop.prototype.toPlanB = function(desc) {
  25866. //#region Preliminary input validation.
  25867. if (typeof desc !== 'object' || desc === null ||
  25868. typeof desc.sdp !== 'string') {
  25869. console.warn('An empty description was passed as an argument.');
  25870. return desc;
  25871. }
  25872. // Objectify the SDP for easier manipulation.
  25873. var session = transform.parse(desc.sdp);
  25874. // If the SDP contains no media, there's nothing to transform.
  25875. if (typeof session.media === 'undefined' ||
  25876. !Array.isArray(session.media) || session.media.length === 0) {
  25877. console.warn('The description has no media.');
  25878. return desc;
  25879. }
  25880. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25881. // SDP has a video, an audio and a data "channel" at most.
  25882. if (session.media.length <= 3 && session.media.every(function(m) {
  25883. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25884. })) {
  25885. console.warn('This description does not look like Unified Plan.');
  25886. return desc;
  25887. }
  25888. //#endregion
  25889. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25890. // -> Unified Plan transformation.
  25891. this.cache[desc.type] = desc.sdp;
  25892. //#region Convert from Unified Plan to Plan B.
  25893. // We rebuild the session.media array.
  25894. var media = session.media;
  25895. session.media = [];
  25896. // Associative array that maps channel types to channel objects for fast
  25897. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25898. // obj.
  25899. var type2bl = {};
  25900. // Used to build the group:BUNDLE value after the channels construction
  25901. // loop.
  25902. var types = [];
  25903. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25904. media.forEach(function(unifiedLine) {
  25905. // rtcp-mux is required in the Plan B SDP.
  25906. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25907. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25908. unifiedLine.direction !== 'inactive') {
  25909. throw new Error('Cannot convert to Plan B because m-lines ' +
  25910. 'without the rtcp-mux attribute were found.');
  25911. }
  25912. if (unifiedLine.type === 'application') {
  25913. session.media.push(unifiedLine);
  25914. types.push(unifiedLine.mid);
  25915. return;
  25916. }
  25917. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25918. // as the channel basis.
  25919. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25920. type2bl[unifiedLine.type] = unifiedLine;
  25921. }
  25922. // Add sources to the channel and handle a=msid.
  25923. if (typeof unifiedLine.sources === 'object') {
  25924. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25925. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25926. type2bl[unifiedLine.type].sources = {};
  25927. // Assign the sources to the channel.
  25928. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25929. if (typeof unifiedLine.msid !== 'undefined') {
  25930. // In Plan B the msid is an SSRC attribute. Also, we don't
  25931. // care about the obsolete label and mslabel attributes.
  25932. //
  25933. // Note that it is not guaranteed that the unifiedLine will have
  25934. // an msid. recvonly channels in particular don't have one.
  25935. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25936. }
  25937. // NOTE ssrcs in ssrc groups will share msids, as
  25938. // draft-uberti-rtcweb-plan-00 mandates.
  25939. });
  25940. }
  25941. // Add ssrc groups to the channel.
  25942. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25943. Array.isArray(unifiedLine.ssrcGroups)) {
  25944. // Create the ssrcGroups array, if it's not defined.
  25945. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25946. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25947. type2bl[unifiedLine.type].ssrcGroups = [];
  25948. }
  25949. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25950. }
  25951. if (type2bl[unifiedLine.type] === unifiedLine) {
  25952. // Copy ICE related stuff from the principal media line.
  25953. unifiedLine.candidates = media[0].candidates;
  25954. unifiedLine.iceUfrag = media[0].iceUfrag;
  25955. unifiedLine.icePwd = media[0].icePwd;
  25956. unifiedLine.fingerprint = media[0].fingerprint;
  25957. // Plan B mids are in ['audio', 'video', 'data']
  25958. unifiedLine.mid = unifiedLine.type;
  25959. // Plan B doesn't support/need the bundle-only attribute.
  25960. delete unifiedLine.bundleOnly;
  25961. // In Plan B the msid is an SSRC attribute.
  25962. delete unifiedLine.msid;
  25963. // Used to build the group:BUNDLE value after this loop.
  25964. types.push(unifiedLine.type);
  25965. // Add the channel to the new media array.
  25966. session.media.push(unifiedLine);
  25967. }
  25968. });
  25969. // We regenerate the BUNDLE group with the new mids.
  25970. session.groups.some(function(group) {
  25971. if (group.type === 'BUNDLE') {
  25972. group.mids = types.join(' ');
  25973. return true;
  25974. }
  25975. });
  25976. // msid semantic
  25977. session.msidSemantic = {
  25978. semantic: 'WMS',
  25979. token: '*'
  25980. };
  25981. var resStr = transform.write(session);
  25982. return new RTCSessionDescription({
  25983. type: desc.type,
  25984. sdp: resStr
  25985. });
  25986. //#endregion
  25987. };
  25988. /**
  25989. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25990. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25991. * to FF.
  25992. *
  25993. * @param desc
  25994. * @returns {*}
  25995. */
  25996. Interop.prototype.toUnifiedPlan = function(desc) {
  25997. //#region Preliminary input validation.
  25998. if (typeof desc !== 'object' || desc === null ||
  25999. typeof desc.sdp !== 'string') {
  26000. console.warn('An empty description was passed as an argument.');
  26001. return desc;
  26002. }
  26003. var session = transform.parse(desc.sdp);
  26004. // If the SDP contains no media, there's nothing to transform.
  26005. if (typeof session.media === 'undefined' ||
  26006. !Array.isArray(session.media) || session.media.length === 0) {
  26007. console.warn('The description has no media.');
  26008. return desc;
  26009. }
  26010. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  26011. // a video, an audio and a data "channel" at most.
  26012. if (session.media.length > 3 || !session.media.every(function(m) {
  26013. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  26014. })) {
  26015. console.warn('This description does not look like Plan B.');
  26016. return desc;
  26017. }
  26018. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  26019. var mids = [];
  26020. session.media.forEach(function(m) {
  26021. mids.push(m.mid);
  26022. });
  26023. var hasBundle = false;
  26024. if (typeof session.groups !== 'undefined' &&
  26025. Array.isArray(session.groups)) {
  26026. hasBundle = session.groups.every(function(g) {
  26027. return g.type !== 'BUNDLE' ||
  26028. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  26029. });
  26030. }
  26031. if (!hasBundle) {
  26032. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  26033. " are not bundled were found.");
  26034. }
  26035. //#endregion
  26036. //#region Convert from Plan B to Unified Plan.
  26037. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  26038. // rebuild an equivalent Unified Plan offer/answer.
  26039. //
  26040. // For example, if this is a local answer (in Unified Plan style) that we
  26041. // convert to Plan B prior to handing it over to the application (the
  26042. // PeerConnection wrapper called us, for instance, after a successful
  26043. // createAnswer), we want to remember the m-line at which we've seen the
  26044. // (local) SSRC. That's because when the application wants to do call the
  26045. // SLD method, forcing us to do the inverse transformation (from Plan B to
  26046. // Unified Plan), we need to know to which m-line to assign the (local)
  26047. // SSRC. We also need to know all the other m-lines that the original
  26048. // answer had and include them in the transformed answer as well.
  26049. //
  26050. // Another example is if this is a remote offer that we convert to Plan B
  26051. // prior to giving it to the application, we want to remember the mid at
  26052. // which we've seen the (remote) SSRC.
  26053. //
  26054. // In the iteration that follows, we use the cached Unified Plan (if it
  26055. // exists) to assign mids to ssrcs.
  26056. var cached;
  26057. if (typeof this.cache[desc.type] !== 'undefined') {
  26058. cached = transform.parse(this.cache[desc.type]);
  26059. }
  26060. // A helper map that sends mids to m-line objects. We use it later to
  26061. // rebuild the Unified Plan style session.media array.
  26062. var mid2ul = {};
  26063. session.media.forEach(function(bLine) {
  26064. if ((typeof bLine.rtcpMux !== 'string' ||
  26065. bLine.rtcpMux !== 'rtcp-mux') &&
  26066. bLine.direction !== 'inactive') {
  26067. throw new Error("Cannot convert to Unified Plan because m-lines " +
  26068. "without the rtcp-mux attribute were found.");
  26069. }
  26070. if (bLine.type === 'application') {
  26071. mid2ul[bLine.mid] = bLine;
  26072. return;
  26073. }
  26074. // With rtcp-mux and bundle all the channels should have the same ICE
  26075. // stuff.
  26076. var sources = bLine.sources;
  26077. var ssrcGroups = bLine.ssrcGroups;
  26078. var candidates = bLine.candidates;
  26079. var iceUfrag = bLine.iceUfrag;
  26080. var icePwd = bLine.icePwd;
  26081. var fingerprint = bLine.fingerprint;
  26082. var port = bLine.port;
  26083. // We'll use the "bLine" object as a prototype for each new "mLine"
  26084. // that we create, but first we need to clean it up a bit.
  26085. delete bLine.sources;
  26086. delete bLine.ssrcGroups;
  26087. delete bLine.candidates;
  26088. delete bLine.iceUfrag;
  26089. delete bLine.icePwd;
  26090. delete bLine.fingerprint;
  26091. delete bLine.port;
  26092. delete bLine.mid;
  26093. // inverted ssrc group map
  26094. var ssrc2group = {};
  26095. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  26096. ssrcGroups.forEach(function (ssrcGroup) {
  26097. // TODO(gp) find out how to receive simulcast with FF. For the
  26098. // time being, hide it.
  26099. if (ssrcGroup.semantics === 'SIM') {
  26100. return;
  26101. }
  26102. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26103. Array.isArray(ssrcGroup.ssrcs)) {
  26104. ssrcGroup.ssrcs.forEach(function (ssrc) {
  26105. if (typeof ssrc2group[ssrc] === 'undefined') {
  26106. ssrc2group[ssrc] = [];
  26107. }
  26108. ssrc2group[ssrc].push(ssrcGroup);
  26109. });
  26110. }
  26111. });
  26112. }
  26113. // ssrc to m-line index.
  26114. var ssrc2ml = {};
  26115. if (typeof sources === 'object') {
  26116. // Explode the Plan B channel sources with one m-line per source.
  26117. Object.keys(sources).forEach(function(ssrc) {
  26118. // The (unified) m-line for this SSRC. We either create it from
  26119. // scratch or, if it's a grouped SSRC, we re-use a related
  26120. // mline. In other words, if the source is grouped with another
  26121. // source, put the two together in the same m-line.
  26122. var unifiedLine;
  26123. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  26124. Array.isArray(ssrc2group[ssrc])) {
  26125. ssrc2group[ssrc].some(function (ssrcGroup) {
  26126. // ssrcGroup.ssrcs *is* an Array, no need to check
  26127. // again here.
  26128. return ssrcGroup.ssrcs.some(function (related) {
  26129. if (typeof ssrc2ml[related] === 'object') {
  26130. unifiedLine = ssrc2ml[related];
  26131. return true;
  26132. }
  26133. });
  26134. });
  26135. }
  26136. if (typeof unifiedLine === 'object') {
  26137. // the m-line already exists. Just add the source.
  26138. unifiedLine.sources[ssrc] = sources[ssrc];
  26139. delete sources[ssrc].msid;
  26140. } else {
  26141. // Use the "bLine" as a prototype for the "unifiedLine".
  26142. unifiedLine = Object.create(bLine);
  26143. ssrc2ml[ssrc] = unifiedLine;
  26144. if (typeof sources[ssrc].msid !== 'undefined') {
  26145. // Assign the msid of the source to the m-line. Note
  26146. // that it is not guaranteed that the source will have
  26147. // msid. In particular "recvonly" sources don't have an
  26148. // msid. Note that "recvonly" is a term only defined
  26149. // for m-lines.
  26150. unifiedLine.msid = sources[ssrc].msid;
  26151. delete sources[ssrc].msid;
  26152. }
  26153. // We assign one SSRC per media line.
  26154. unifiedLine.sources = {};
  26155. unifiedLine.sources[ssrc] = sources[ssrc];
  26156. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  26157. // Use the cached Unified Plan SDP (if it exists) to assign
  26158. // SSRCs to mids.
  26159. if (typeof cached !== 'undefined' &&
  26160. typeof cached.media !== 'undefined' &&
  26161. Array.isArray(cached.media)) {
  26162. cached.media.forEach(function (m) {
  26163. if (typeof m.sources === 'object') {
  26164. Object.keys(m.sources).forEach(function (s) {
  26165. if (s === ssrc) {
  26166. unifiedLine.mid = m.mid;
  26167. }
  26168. });
  26169. }
  26170. });
  26171. }
  26172. if (typeof unifiedLine.mid === 'undefined') {
  26173. // If this is an SSRC that we see for the first time
  26174. // assign it a new mid. This is typically the case when
  26175. // this method is called to transform a remote
  26176. // description for the first time or when there is a
  26177. // new SSRC in the remote description because a new
  26178. // peer has joined the conference. Local SSRCs should
  26179. // have already been added to the map in the toPlanB
  26180. // method.
  26181. //
  26182. // Because FF generates answers in Unified Plan style,
  26183. // we MUST already have a cached answer with all the
  26184. // local SSRCs mapped to some m-line/mid.
  26185. if (desc.type === 'answer') {
  26186. throw new Error("An unmapped SSRC was found.");
  26187. }
  26188. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  26189. }
  26190. // Include the candidates in the 1st media line.
  26191. unifiedLine.candidates = candidates;
  26192. unifiedLine.iceUfrag = iceUfrag;
  26193. unifiedLine.icePwd = icePwd;
  26194. unifiedLine.fingerprint = fingerprint;
  26195. unifiedLine.port = port;
  26196. mid2ul[unifiedLine.mid] = unifiedLine;
  26197. }
  26198. });
  26199. }
  26200. });
  26201. // Rebuild the media array in the right order and add the missing mLines
  26202. // (missing from the Plan B SDP).
  26203. session.media = [];
  26204. mids = []; // reuse
  26205. if (desc.type === 'answer') {
  26206. // The media lines in the answer must match the media lines in the
  26207. // offer. The order is important too. Here we assume that Firefox is the
  26208. // answerer, so we merely have to use the reconstructed (unified) answer
  26209. // to update the cached (unified) answer accordingly.
  26210. //
  26211. // In the general case, one would have to use the cached (unified) offer
  26212. // to find the m-lines that are missing from the reconstructed answer,
  26213. // potentially grabbing them from the cached (unified) answer. One has
  26214. // to be carefull with this approach because inactive m-lines do not
  26215. // always have an mid, making it tricky (impossible?) to find where
  26216. // exactly and which m-lines are missing from the reconstructed answer.
  26217. for (var i = 0; i < cached.media.length; i++) {
  26218. var unifiedLine = cached.media[i];
  26219. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  26220. // The mid isn't in the reconstructed (unified) answer.
  26221. // This is either a (unified) m-line containing a remote
  26222. // track only, or a (unified) m-line containing a remote
  26223. // track and a local track that has been removed.
  26224. // In either case, it MUST exist in the cached
  26225. // (unified) answer.
  26226. //
  26227. // In case this is a removed local track, clean-up
  26228. // the (unified) m-line and make sure it's 'recvonly' or
  26229. // 'inactive'.
  26230. delete unifiedLine.msid;
  26231. delete unifiedLine.sources;
  26232. delete unifiedLine.ssrcGroups;
  26233. if (!unifiedLine.direction
  26234. || unifiedLine.direction === 'sendrecv')
  26235. unifiedLine.direction = 'recvonly';
  26236. if (!unifiedLine.direction
  26237. || unifiedLine.direction === 'sendonly')
  26238. unifiedLine.direction = 'inactive';
  26239. } else {
  26240. // This is an (unified) m-line/channel that contains a local
  26241. // track (sendrecv or sendonly channel) or it's a unified
  26242. // recvonly m-line/channel. In either case, since we're
  26243. // going from PlanB -> Unified Plan this m-line MUST
  26244. // exist in the cached answer.
  26245. }
  26246. session.media.push(unifiedLine);
  26247. if (typeof unifiedLine.mid === 'string') {
  26248. // inactive lines don't/may not have an mid.
  26249. mids.push(unifiedLine.mid);
  26250. }
  26251. }
  26252. } else {
  26253. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  26254. // under any circumstances. If we are no longer interested in sending a
  26255. // track, we just remove the msid and ssrc attributes and set it to
  26256. // either a=recvonly (as the reofferer, we must use recvonly if the
  26257. // other side was previously sending on the m-section, but we can also
  26258. // leave the possibility open if it wasn't previously in use), or
  26259. // a=inacive.
  26260. if (typeof cached !== 'undefined' &&
  26261. typeof cached.media !== 'undefined' &&
  26262. Array.isArray(cached.media)) {
  26263. cached.media.forEach(function(unifiedLine) {
  26264. mids.push(unifiedLine.mid);
  26265. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  26266. session.media.push(mid2ul[unifiedLine.mid]);
  26267. } else {
  26268. delete unifiedLine.msid;
  26269. delete unifiedLine.sources;
  26270. delete unifiedLine.ssrcGroups;
  26271. if (!unifiedLine.direction
  26272. || unifiedLine.direction === 'sendrecv')
  26273. unifiedLine.direction = 'recvonly';
  26274. if (!unifiedLine.direction
  26275. || unifiedLine.direction === 'sendonly')
  26276. unifiedLine.direction = 'inactive';
  26277. session.media.push(unifiedLine);
  26278. }
  26279. });
  26280. }
  26281. // Add all the remaining (new) m-lines of the transformed SDP.
  26282. Object.keys(mid2ul).forEach(function(mid) {
  26283. if (mids.indexOf(mid) === -1) {
  26284. mids.push(mid);
  26285. if (typeof mid2ul[mid].direction === 'recvonly') {
  26286. // This is a remote recvonly channel. Add its SSRC to the
  26287. // appropriate sendrecv or sendonly channel.
  26288. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  26289. session.media.some(function (unifiedLine) {
  26290. if ((unifiedLine.direction === 'sendrecv' ||
  26291. unifiedLine.direction === 'sendonly') &&
  26292. unifiedLine.type === mid2ul[mid].type) {
  26293. // mid2ul[mid] shouldn't have any ssrc-groups
  26294. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  26295. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  26296. });
  26297. return true;
  26298. }
  26299. });
  26300. } else {
  26301. session.media.push(mid2ul[mid]);
  26302. }
  26303. }
  26304. });
  26305. }
  26306. // We regenerate the BUNDLE group (since we regenerated the mids)
  26307. session.groups.some(function(group) {
  26308. if (group.type === 'BUNDLE') {
  26309. group.mids = mids.join(' ');
  26310. return true;
  26311. }
  26312. });
  26313. // msid semantic
  26314. session.msidSemantic = {
  26315. semantic: 'WMS',
  26316. token: '*'
  26317. };
  26318. var resStr = transform.write(session);
  26319. // Cache the transformed SDP (Unified Plan) for later re-use in this
  26320. // function.
  26321. this.cache[desc.type] = resStr;
  26322. return new RTCSessionDescription({
  26323. type: desc.type,
  26324. sdp: resStr
  26325. });
  26326. //#endregion
  26327. };
  26328. },{"./array-equals":92,"./transform":95}],95:[function(require,module,exports){
  26329. var transform = require('sdp-transform');
  26330. exports.write = function(session, opts) {
  26331. if (typeof session !== 'undefined' &&
  26332. typeof session.media !== 'undefined' &&
  26333. Array.isArray(session.media)) {
  26334. session.media.forEach(function (mLine) {
  26335. // expand sources to ssrcs
  26336. if (typeof mLine.sources !== 'undefined' &&
  26337. Object.keys(mLine.sources).length !== 0) {
  26338. mLine.ssrcs = [];
  26339. Object.keys(mLine.sources).forEach(function (ssrc) {
  26340. var source = mLine.sources[ssrc];
  26341. Object.keys(source).forEach(function (attribute) {
  26342. mLine.ssrcs.push({
  26343. id: ssrc,
  26344. attribute: attribute,
  26345. value: source[attribute]
  26346. });
  26347. });
  26348. });
  26349. delete mLine.sources;
  26350. }
  26351. // join ssrcs in ssrc groups
  26352. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26353. Array.isArray(mLine.ssrcGroups)) {
  26354. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26355. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26356. Array.isArray(ssrcGroup.ssrcs)) {
  26357. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  26358. }
  26359. });
  26360. }
  26361. });
  26362. }
  26363. // join group mids
  26364. if (typeof session !== 'undefined' &&
  26365. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26366. session.groups.forEach(function (g) {
  26367. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  26368. g.mids = g.mids.join(' ');
  26369. }
  26370. });
  26371. }
  26372. return transform.write(session, opts);
  26373. };
  26374. exports.parse = function(sdp) {
  26375. var session = transform.parse(sdp);
  26376. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  26377. Array.isArray(session.media)) {
  26378. session.media.forEach(function (mLine) {
  26379. // group sources attributes by ssrc
  26380. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26381. mLine.sources = {};
  26382. mLine.ssrcs.forEach(function (ssrc) {
  26383. if (!mLine.sources[ssrc.id])
  26384. mLine.sources[ssrc.id] = {};
  26385. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26386. });
  26387. delete mLine.ssrcs;
  26388. }
  26389. // split ssrcs in ssrc groups
  26390. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26391. Array.isArray(mLine.ssrcGroups)) {
  26392. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26393. if (typeof ssrcGroup.ssrcs === 'string') {
  26394. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  26395. }
  26396. });
  26397. }
  26398. });
  26399. }
  26400. // split group mids
  26401. if (typeof session !== 'undefined' &&
  26402. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26403. session.groups.forEach(function (g) {
  26404. if (typeof g.mids === 'string') {
  26405. g.mids = g.mids.split(' ');
  26406. }
  26407. });
  26408. }
  26409. return session;
  26410. };
  26411. },{"sdp-transform":97}],96:[function(require,module,exports){
  26412. var grammar = module.exports = {
  26413. v: [{
  26414. name: 'version',
  26415. reg: /^(\d*)$/
  26416. }],
  26417. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26418. // NB: sessionId will be a String in most cases because it is huge
  26419. name: 'origin',
  26420. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26421. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26422. format: "%s %s %d %s IP%d %s"
  26423. }],
  26424. // default parsing of these only (though some of these feel outdated)
  26425. s: [{ name: 'name' }],
  26426. i: [{ name: 'description' }],
  26427. u: [{ name: 'uri' }],
  26428. e: [{ name: 'email' }],
  26429. p: [{ name: 'phone' }],
  26430. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26431. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26432. //k: [{}], // outdated thing ignored
  26433. t: [{ //t=0 0
  26434. name: 'timing',
  26435. reg: /^(\d*) (\d*)/,
  26436. names: ['start', 'stop'],
  26437. format: "%d %d"
  26438. }],
  26439. c: [{ //c=IN IP4 10.47.197.26
  26440. name: 'connection',
  26441. reg: /^IN IP(\d) (\S*)/,
  26442. names: ['version', 'ip'],
  26443. format: "IN IP%d %s"
  26444. }],
  26445. b: [{ //b=AS:4000
  26446. push: 'bandwidth',
  26447. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26448. names: ['type', 'limit'],
  26449. format: "%s:%s"
  26450. }],
  26451. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26452. // NB: special - pushes to session
  26453. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26454. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26455. names: ['type', 'port', 'protocol', 'payloads'],
  26456. format: "%s %d %s %s"
  26457. }],
  26458. a: [
  26459. { //a=rtpmap:110 opus/48000/2
  26460. push: 'rtp',
  26461. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26462. names: ['payload', 'codec', 'rate', 'encoding'],
  26463. format: function (o) {
  26464. return (o.encoding) ?
  26465. "rtpmap:%d %s/%s/%s":
  26466. "rtpmap:%d %s/%s";
  26467. }
  26468. },
  26469. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26470. push: 'fmtp',
  26471. reg: /^fmtp:(\d*) (\S*)/,
  26472. names: ['payload', 'config'],
  26473. format: "fmtp:%d %s"
  26474. },
  26475. { //a=control:streamid=0
  26476. name: 'control',
  26477. reg: /^control:(.*)/,
  26478. format: "control:%s"
  26479. },
  26480. { //a=rtcp:65179 IN IP4 193.84.77.194
  26481. name: 'rtcp',
  26482. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26483. names: ['port', 'netType', 'ipVer', 'address'],
  26484. format: function (o) {
  26485. return (o.address != null) ?
  26486. "rtcp:%d %s IP%d %s":
  26487. "rtcp:%d";
  26488. }
  26489. },
  26490. { //a=rtcp-fb:98 trr-int 100
  26491. push: 'rtcpFbTrrInt',
  26492. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26493. names: ['payload', 'value'],
  26494. format: "rtcp-fb:%d trr-int %d"
  26495. },
  26496. { //a=rtcp-fb:98 nack rpsi
  26497. push: 'rtcpFb',
  26498. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26499. names: ['payload', 'type', 'subtype'],
  26500. format: function (o) {
  26501. return (o.subtype != null) ?
  26502. "rtcp-fb:%s %s %s":
  26503. "rtcp-fb:%s %s";
  26504. }
  26505. },
  26506. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26507. //a=extmap:1/recvonly URI-gps-string
  26508. push: 'ext',
  26509. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26510. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26511. format: function (o) {
  26512. return (o.config != null) ?
  26513. "extmap:%s %s %s":
  26514. "extmap:%s %s";
  26515. }
  26516. },
  26517. {
  26518. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26519. push: 'crypto',
  26520. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26521. names: ['id', 'suite', 'config', 'sessionConfig'],
  26522. format: function (o) {
  26523. return (o.sessionConfig != null) ?
  26524. "crypto:%d %s %s %s":
  26525. "crypto:%d %s %s";
  26526. }
  26527. },
  26528. { //a=setup:actpass
  26529. name: 'setup',
  26530. reg: /^setup:(\w*)/,
  26531. format: "setup:%s"
  26532. },
  26533. { //a=mid:1
  26534. name: 'mid',
  26535. reg: /^mid:([^\s]*)/,
  26536. format: "mid:%s"
  26537. },
  26538. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26539. name: 'msid',
  26540. reg: /^msid:(.*)/,
  26541. format: "msid:%s"
  26542. },
  26543. { //a=ptime:20
  26544. name: 'ptime',
  26545. reg: /^ptime:(\d*)/,
  26546. format: "ptime:%d"
  26547. },
  26548. { //a=maxptime:60
  26549. name: 'maxptime',
  26550. reg: /^maxptime:(\d*)/,
  26551. format: "maxptime:%d"
  26552. },
  26553. { //a=sendrecv
  26554. name: 'direction',
  26555. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26556. },
  26557. { //a=ice-lite
  26558. name: 'icelite',
  26559. reg: /^(ice-lite)/
  26560. },
  26561. { //a=ice-ufrag:F7gI
  26562. name: 'iceUfrag',
  26563. reg: /^ice-ufrag:(\S*)/,
  26564. format: "ice-ufrag:%s"
  26565. },
  26566. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26567. name: 'icePwd',
  26568. reg: /^ice-pwd:(\S*)/,
  26569. format: "ice-pwd:%s"
  26570. },
  26571. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26572. name: 'fingerprint',
  26573. reg: /^fingerprint:(\S*) (\S*)/,
  26574. names: ['type', 'hash'],
  26575. format: "fingerprint:%s %s"
  26576. },
  26577. {
  26578. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26579. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26580. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26581. push:'candidates',
  26582. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26583. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26584. format: function (o) {
  26585. var str = "candidate:%s %d %s %d %s %d typ %s";
  26586. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26587. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26588. if (o.generation != null) {
  26589. str += " generation %d";
  26590. }
  26591. return str;
  26592. }
  26593. },
  26594. { //a=end-of-candidates (keep after the candidates line for readability)
  26595. name: 'endOfCandidates',
  26596. reg: /^(end-of-candidates)/
  26597. },
  26598. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26599. name: 'remoteCandidates',
  26600. reg: /^remote-candidates:(.*)/,
  26601. format: "remote-candidates:%s"
  26602. },
  26603. { //a=ice-options:google-ice
  26604. name: 'iceOptions',
  26605. reg: /^ice-options:(\S*)/,
  26606. format: "ice-options:%s"
  26607. },
  26608. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26609. push: "ssrcs",
  26610. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26611. names: ['id', 'attribute', 'value'],
  26612. format: "ssrc:%d %s:%s"
  26613. },
  26614. { //a=ssrc-group:FEC 1 2
  26615. push: "ssrcGroups",
  26616. reg: /^ssrc-group:(\w*) (.*)/,
  26617. names: ['semantics', 'ssrcs'],
  26618. format: "ssrc-group:%s %s"
  26619. },
  26620. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26621. name: "msidSemantic",
  26622. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26623. names: ['semantic', 'token'],
  26624. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26625. },
  26626. { //a=group:BUNDLE audio video
  26627. push: 'groups',
  26628. reg: /^group:(\w*) (.*)/,
  26629. names: ['type', 'mids'],
  26630. format: "group:%s %s"
  26631. },
  26632. { //a=rtcp-mux
  26633. name: 'rtcpMux',
  26634. reg: /^(rtcp-mux)/
  26635. },
  26636. { //a=rtcp-rsize
  26637. name: 'rtcpRsize',
  26638. reg: /^(rtcp-rsize)/
  26639. },
  26640. { // any a= that we don't understand is kepts verbatim on media.invalid
  26641. push: 'invalid',
  26642. names: ["value"]
  26643. }
  26644. ]
  26645. };
  26646. // set sensible defaults to avoid polluting the grammar with boring details
  26647. Object.keys(grammar).forEach(function (key) {
  26648. var objs = grammar[key];
  26649. objs.forEach(function (obj) {
  26650. if (!obj.reg) {
  26651. obj.reg = /(.*)/;
  26652. }
  26653. if (!obj.format) {
  26654. obj.format = "%s";
  26655. }
  26656. });
  26657. });
  26658. },{}],97:[function(require,module,exports){
  26659. var parser = require('./parser');
  26660. var writer = require('./writer');
  26661. exports.write = writer;
  26662. exports.parse = parser.parse;
  26663. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26664. exports.parsePayloads = parser.parsePayloads;
  26665. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26666. },{"./parser":98,"./writer":99}],98:[function(require,module,exports){
  26667. var toIntIfInt = function (v) {
  26668. return String(Number(v)) === v ? Number(v) : v;
  26669. };
  26670. var attachProperties = function (match, location, names, rawName) {
  26671. if (rawName && !names) {
  26672. location[rawName] = toIntIfInt(match[1]);
  26673. }
  26674. else {
  26675. for (var i = 0; i < names.length; i += 1) {
  26676. if (match[i+1] != null) {
  26677. location[names[i]] = toIntIfInt(match[i+1]);
  26678. }
  26679. }
  26680. }
  26681. };
  26682. var parseReg = function (obj, location, content) {
  26683. var needsBlank = obj.name && obj.names;
  26684. if (obj.push && !location[obj.push]) {
  26685. location[obj.push] = [];
  26686. }
  26687. else if (needsBlank && !location[obj.name]) {
  26688. location[obj.name] = {};
  26689. }
  26690. var keyLocation = obj.push ?
  26691. {} : // blank object that will be pushed
  26692. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26693. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26694. if (obj.push) {
  26695. location[obj.push].push(keyLocation);
  26696. }
  26697. };
  26698. var grammar = require('./grammar');
  26699. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26700. exports.parse = function (sdp) {
  26701. var session = {}
  26702. , media = []
  26703. , location = session; // points at where properties go under (one of the above)
  26704. // parse lines we understand
  26705. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26706. var type = l[0];
  26707. var content = l.slice(2);
  26708. if (type === 'm') {
  26709. media.push({rtp: [], fmtp: []});
  26710. location = media[media.length-1]; // point at latest media line
  26711. }
  26712. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26713. var obj = grammar[type][j];
  26714. if (obj.reg.test(content)) {
  26715. return parseReg(obj, location, content);
  26716. }
  26717. }
  26718. });
  26719. session.media = media; // link it up
  26720. return session;
  26721. };
  26722. var fmtpReducer = function (acc, expr) {
  26723. var s = expr.split('=');
  26724. if (s.length === 2) {
  26725. acc[s[0]] = toIntIfInt(s[1]);
  26726. }
  26727. return acc;
  26728. };
  26729. exports.parseFmtpConfig = function (str) {
  26730. return str.split(';').reduce(fmtpReducer, {});
  26731. };
  26732. exports.parsePayloads = function (str) {
  26733. return str.split(' ').map(Number);
  26734. };
  26735. exports.parseRemoteCandidates = function (str) {
  26736. var candidates = [];
  26737. var parts = str.split(' ').map(toIntIfInt);
  26738. for (var i = 0; i < parts.length; i += 3) {
  26739. candidates.push({
  26740. component: parts[i],
  26741. ip: parts[i + 1],
  26742. port: parts[i + 2]
  26743. });
  26744. }
  26745. return candidates;
  26746. };
  26747. },{"./grammar":96}],99:[function(require,module,exports){
  26748. var grammar = require('./grammar');
  26749. // customized util.format - discards excess arguments and can void middle ones
  26750. var formatRegExp = /%[sdv%]/g;
  26751. var format = function (formatStr) {
  26752. var i = 1;
  26753. var args = arguments;
  26754. var len = args.length;
  26755. return formatStr.replace(formatRegExp, function (x) {
  26756. if (i >= len) {
  26757. return x; // missing argument
  26758. }
  26759. var arg = args[i];
  26760. i += 1;
  26761. switch (x) {
  26762. case '%%':
  26763. return '%';
  26764. case '%s':
  26765. return String(arg);
  26766. case '%d':
  26767. return Number(arg);
  26768. case '%v':
  26769. return '';
  26770. }
  26771. });
  26772. // NB: we discard excess arguments - they are typically undefined from makeLine
  26773. };
  26774. var makeLine = function (type, obj, location) {
  26775. var str = obj.format instanceof Function ?
  26776. (obj.format(obj.push ? location : location[obj.name])) :
  26777. obj.format;
  26778. var args = [type + '=' + str];
  26779. if (obj.names) {
  26780. for (var i = 0; i < obj.names.length; i += 1) {
  26781. var n = obj.names[i];
  26782. if (obj.name) {
  26783. args.push(location[obj.name][n]);
  26784. }
  26785. else { // for mLine and push attributes
  26786. args.push(location[obj.names[i]]);
  26787. }
  26788. }
  26789. }
  26790. else {
  26791. args.push(location[obj.name]);
  26792. }
  26793. return format.apply(null, args);
  26794. };
  26795. // RFC specified order
  26796. // TODO: extend this with all the rest
  26797. var defaultOuterOrder = [
  26798. 'v', 'o', 's', 'i',
  26799. 'u', 'e', 'p', 'c',
  26800. 'b', 't', 'r', 'z', 'a'
  26801. ];
  26802. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26803. module.exports = function (session, opts) {
  26804. opts = opts || {};
  26805. // ensure certain properties exist
  26806. if (session.version == null) {
  26807. session.version = 0; // "v=0" must be there (only defined version atm)
  26808. }
  26809. if (session.name == null) {
  26810. session.name = " "; // "s= " must be there if no meaningful name set
  26811. }
  26812. session.media.forEach(function (mLine) {
  26813. if (mLine.payloads == null) {
  26814. mLine.payloads = "";
  26815. }
  26816. });
  26817. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26818. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26819. var sdp = [];
  26820. // loop through outerOrder for matching properties on session
  26821. outerOrder.forEach(function (type) {
  26822. grammar[type].forEach(function (obj) {
  26823. if (obj.name in session && session[obj.name] != null) {
  26824. sdp.push(makeLine(type, obj, session));
  26825. }
  26826. else if (obj.push in session && session[obj.push] != null) {
  26827. session[obj.push].forEach(function (el) {
  26828. sdp.push(makeLine(type, obj, el));
  26829. });
  26830. }
  26831. });
  26832. });
  26833. // then for each media line, follow the innerOrder
  26834. session.media.forEach(function (mLine) {
  26835. sdp.push(makeLine('m', grammar.m[0], mLine));
  26836. innerOrder.forEach(function (type) {
  26837. grammar[type].forEach(function (obj) {
  26838. if (obj.name in mLine && mLine[obj.name] != null) {
  26839. sdp.push(makeLine(type, obj, mLine));
  26840. }
  26841. else if (obj.push in mLine && mLine[obj.push] != null) {
  26842. mLine[obj.push].forEach(function (el) {
  26843. sdp.push(makeLine(type, obj, el));
  26844. });
  26845. }
  26846. });
  26847. });
  26848. });
  26849. return sdp.join('\r\n') + '\r\n';
  26850. };
  26851. },{"./grammar":96}],100:[function(require,module,exports){
  26852. var transform = require('sdp-transform');
  26853. var transformUtils = require('./transform-utils');
  26854. var parseSsrcs = transformUtils.parseSsrcs;
  26855. var writeSsrcs = transformUtils.writeSsrcs;
  26856. //region Constants
  26857. var DEFAULT_NUM_OF_LAYERS = 3;
  26858. //endregion
  26859. //region Ctor
  26860. function Simulcast(options) {
  26861. this.options = options ? options : {};
  26862. if (!this.options.numOfLayers) {
  26863. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26864. }
  26865. this.layers = [];
  26866. }
  26867. //endregion
  26868. //region Stateless private utility functions
  26869. /**
  26870. * Returns a random integer between min (included) and max (excluded)
  26871. * Using Math.round() gives a non-uniform distribution!
  26872. * @returns {number}
  26873. */
  26874. function generateSSRC() {
  26875. var min = 0, max = 0xffffffff;
  26876. return Math.floor(Math.random() * (max - min)) + min;
  26877. };
  26878. function processVideo(session, action) {
  26879. if (session == null || !Array.isArray(session.media)) {
  26880. return;
  26881. }
  26882. session.media.forEach(function (mLine) {
  26883. if (mLine.type === 'video') {
  26884. action(mLine);
  26885. }
  26886. });
  26887. }
  26888. function validateDescription(desc)
  26889. {
  26890. return desc && desc != null
  26891. && desc.type && desc.type != ''
  26892. && desc.sdp && desc.sdp != '';
  26893. }
  26894. function explodeRemoteSimulcast(mLine) {
  26895. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26896. return;
  26897. }
  26898. var sources = parseSsrcs(mLine);
  26899. var order = [];
  26900. // Find the SIM group and explode its sources.
  26901. var j = mLine.ssrcGroups.length;
  26902. while (j--) {
  26903. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26904. continue;
  26905. }
  26906. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26907. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26908. var ssrc = simulcastSsrcs[i];
  26909. order.push(ssrc);
  26910. var parts = sources[ssrc].msid.split(' ');
  26911. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26912. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26913. // Remove all the groups that this SSRC participates in.
  26914. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26915. if (relatedGroup.semantics === 'SIM') {
  26916. return;
  26917. }
  26918. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26919. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26920. return;
  26921. }
  26922. // Nuke all the related SSRCs.
  26923. relatedSsrcs.forEach(function (relatedSSRC) {
  26924. sources[relatedSSRC].msid = sources[ssrc].msid;
  26925. sources[relatedSSRC].cname = sources[ssrc].cname;
  26926. if (relatedSSRC !== ssrc) {
  26927. order.push(relatedSSRC);
  26928. }
  26929. });
  26930. // Schedule the related group for nuking.
  26931. })
  26932. }
  26933. mLine.ssrcs = writeSsrcs(sources, order);
  26934. mLine.ssrcGroups.splice(j, 1);
  26935. };
  26936. }
  26937. function squeezeRemoteSimulcast(mLine) {
  26938. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26939. return;
  26940. }
  26941. var sources = parseSsrcs(mLine);
  26942. // Find the SIM group and nuke it.
  26943. mLine.ssrcGroups.some(function (simulcastGroup) {
  26944. if (simulcastGroup.semantics !== 'SIM') {
  26945. return false;
  26946. }
  26947. // Schedule the SIM group for nuking.
  26948. simulcastGroup.nuke = true;
  26949. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26950. // Nuke all the higher layer SSRCs.
  26951. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26952. var ssrc = simulcastSsrcs[i];
  26953. delete sources[ssrc];
  26954. // Remove all the groups that this SSRC participates in.
  26955. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26956. if (relatedGroup.semantics === 'SIM') {
  26957. return;
  26958. }
  26959. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26960. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26961. return;
  26962. }
  26963. // Nuke all the related SSRCs.
  26964. relatedSsrcs.forEach(function (relatedSSRC) {
  26965. delete sources[relatedSSRC];
  26966. });
  26967. // Schedule the related group for nuking.
  26968. relatedGroup.nuke = true;
  26969. })
  26970. }
  26971. return true;
  26972. });
  26973. mLine.ssrcs = writeSsrcs(sources);
  26974. // Nuke all the scheduled groups.
  26975. var i = mLine.ssrcGroups.length;
  26976. while (i--) {
  26977. if (mLine.ssrcGroups[i].nuke) {
  26978. mLine.ssrcGroups.splice(i, 1);
  26979. }
  26980. }
  26981. }
  26982. function removeGoogConference(mLine) {
  26983. if (!mLine || !Array.isArray(mLine.invalid)) {
  26984. return;
  26985. }
  26986. var i = mLine.invalid.length;
  26987. while (i--) {
  26988. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26989. mLine.invalid.splice(i, 1);
  26990. }
  26991. }
  26992. }
  26993. function assertGoogConference(mLine) {
  26994. if (!mLine) {
  26995. return;
  26996. }
  26997. if (!Array.isArray(mLine.invalid)) {
  26998. mLine.invalid = [];
  26999. }
  27000. if (!mLine.invalid.some(
  27001. function (i) { return i.value === 'x-google-flag:conference' })) {
  27002. mLine.invalid.push({'value': 'x-google-flag:conference'});
  27003. }
  27004. }
  27005. //endregion
  27006. //region "Private" functions
  27007. /**
  27008. *
  27009. * @param mLine
  27010. * @private
  27011. */
  27012. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  27013. if (!mLine || mLine.type !== 'video') {
  27014. return;
  27015. }
  27016. var sources = parseSsrcs(mLine);
  27017. if (Object.keys(sources).length === 0) {
  27018. // no sources, disable simulcast.
  27019. if (this.layers.length !== 0) {
  27020. this.layers = [];
  27021. }
  27022. return;
  27023. }
  27024. // find the base layer (we'll reuse its msid and cname).
  27025. var baseLayerSSRC = Object.keys(sources)[0];
  27026. var baseLayer = sources[baseLayerSSRC];
  27027. // todo(gp) handle screen sharing.
  27028. // check if base CNAME has changed and reinitialise layers.
  27029. if (this.layers.length > 0
  27030. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  27031. this.layers = [];
  27032. }
  27033. // (re)initialise layers
  27034. if (this.layers.length < 1) {
  27035. // first push the base layer.
  27036. this.layers.push({
  27037. ssrc: baseLayerSSRC,
  27038. msid: baseLayer.msid,
  27039. cname: baseLayer.cname
  27040. });
  27041. var rtx = false; // RFC 4588
  27042. if (Array.isArray(mLine.rtp)) {
  27043. rtx = mLine.rtp.some(
  27044. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  27045. }
  27046. if (rtx) {
  27047. this.layers[0].rtx = generateSSRC();
  27048. }
  27049. // now push additional layers.
  27050. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  27051. var layer = { ssrc: generateSSRC() };
  27052. if (rtx) {
  27053. layer.rtx = generateSSRC();
  27054. }
  27055. this.layers.push(layer);
  27056. }
  27057. }
  27058. };
  27059. /**
  27060. *
  27061. * @param mLine
  27062. * @private
  27063. */
  27064. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  27065. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  27066. var sources = {};
  27067. var msid = this.layers[0].msid;
  27068. var cname = this.layers[0].cname;
  27069. var simulcastSsrcs = [];
  27070. var ssrcGroups = [];
  27071. for (var i = 0; i < this.layers.length; i++) {
  27072. var layer = this.layers[i];
  27073. sources[layer.ssrc] = { msid: msid, cname: cname };
  27074. simulcastSsrcs.push(layer.ssrc);
  27075. if (layer.rtx) {
  27076. sources[layer.rtx] = {
  27077. msid: msid,
  27078. cname: cname
  27079. }
  27080. ssrcGroups.push({
  27081. semantics: 'FID',
  27082. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  27083. });
  27084. }
  27085. }
  27086. ssrcGroups.push({
  27087. semantics: 'SIM',
  27088. ssrcs: simulcastSsrcs.join(' ')
  27089. });
  27090. mLine.ssrcGroups = ssrcGroups;
  27091. mLine.ssrcs = writeSsrcs(sources);
  27092. }
  27093. }
  27094. //endregion
  27095. //region "Public" functions
  27096. Simulcast.prototype.isSupported = function () {
  27097. return window.chrome;
  27098. // TODO this needs improvements. For example I doubt that Chrome in Android
  27099. // has simulcast support. Also, only recent versions of Chromium have native
  27100. // simulcast support.
  27101. }
  27102. /**
  27103. *
  27104. * @param desc
  27105. * @returns {RTCSessionDescription}
  27106. */
  27107. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  27108. if (!validateDescription(desc)) {
  27109. return desc;
  27110. }
  27111. var session = transform.parse(desc.sdp);
  27112. var self = this;
  27113. processVideo(session, function (mLine) {
  27114. // Handle simulcast reception.
  27115. if (self.options.explodeRemoteSimulcast) {
  27116. explodeRemoteSimulcast(mLine);
  27117. } else {
  27118. squeezeRemoteSimulcast(mLine);
  27119. }
  27120. // If native simulcast is enabled, we must append the x-goog-conference
  27121. // attribute to the SDP.
  27122. if (self.layers.length < 1) {
  27123. removeGoogConference(mLine);
  27124. } else {
  27125. assertGoogConference(mLine);
  27126. }
  27127. });
  27128. return new RTCSessionDescription({
  27129. type: desc.type,
  27130. sdp: transform.write(session)
  27131. });
  27132. };
  27133. /**
  27134. *
  27135. * @param desc
  27136. * @returns {RTCSessionDescription}
  27137. */
  27138. Simulcast.prototype.mungeLocalDescription = function (desc) {
  27139. if (!validateDescription(desc) || !this.isSupported()) {
  27140. return desc;
  27141. }
  27142. var session = transform.parse(desc.sdp);
  27143. var self = this;
  27144. processVideo(session, function (mLine) {
  27145. // Initialize native simulcast layers, if not already done.
  27146. self._maybeInitializeLayers(mLine);
  27147. // Update the SDP with the simulcast layers.
  27148. self._restoreSimulcastView(mLine);
  27149. });
  27150. return new RTCSessionDescription({
  27151. type: desc.type,
  27152. sdp: transform.write(session)
  27153. });
  27154. };
  27155. //endregion
  27156. module.exports = Simulcast;
  27157. },{"./transform-utils":101,"sdp-transform":103}],101:[function(require,module,exports){
  27158. exports.writeSsrcs = function(sources, order) {
  27159. var ssrcs = [];
  27160. // expand sources to ssrcs
  27161. if (typeof sources !== 'undefined' &&
  27162. Object.keys(sources).length !== 0) {
  27163. if (Array.isArray(order)) {
  27164. for (var i = 0; i < order.length; i++) {
  27165. var ssrc = order[i];
  27166. var source = sources[ssrc];
  27167. Object.keys(source).forEach(function (attribute) {
  27168. ssrcs.push({
  27169. id: ssrc,
  27170. attribute: attribute,
  27171. value: source[attribute]
  27172. });
  27173. });
  27174. }
  27175. } else {
  27176. Object.keys(sources).forEach(function (ssrc) {
  27177. var source = sources[ssrc];
  27178. Object.keys(source).forEach(function (attribute) {
  27179. ssrcs.push({
  27180. id: ssrc,
  27181. attribute: attribute,
  27182. value: source[attribute]
  27183. });
  27184. });
  27185. });
  27186. }
  27187. }
  27188. return ssrcs;
  27189. };
  27190. exports.parseSsrcs = function (mLine) {
  27191. var sources = {};
  27192. // group sources attributes by ssrc.
  27193. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  27194. mLine.ssrcs.forEach(function (ssrc) {
  27195. if (!sources[ssrc.id])
  27196. sources[ssrc.id] = {};
  27197. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  27198. });
  27199. }
  27200. return sources;
  27201. };
  27202. },{}],102:[function(require,module,exports){
  27203. arguments[4][96][0].apply(exports,arguments)
  27204. },{"dup":96}],103:[function(require,module,exports){
  27205. arguments[4][97][0].apply(exports,arguments)
  27206. },{"./parser":104,"./writer":105,"dup":97}],104:[function(require,module,exports){
  27207. arguments[4][98][0].apply(exports,arguments)
  27208. },{"./grammar":102,"dup":98}],105:[function(require,module,exports){
  27209. arguments[4][99][0].apply(exports,arguments)
  27210. },{"./grammar":102,"dup":99}],106:[function(require,module,exports){
  27211. arguments[4][96][0].apply(exports,arguments)
  27212. },{"dup":96}],107:[function(require,module,exports){
  27213. arguments[4][97][0].apply(exports,arguments)
  27214. },{"./parser":108,"./writer":109,"dup":97}],108:[function(require,module,exports){
  27215. arguments[4][98][0].apply(exports,arguments)
  27216. },{"./grammar":106,"dup":98}],109:[function(require,module,exports){
  27217. arguments[4][99][0].apply(exports,arguments)
  27218. },{"./grammar":106,"dup":99}],110:[function(require,module,exports){
  27219. var MediaStreamType = {
  27220. VIDEO_TYPE: "Video",
  27221. AUDIO_TYPE: "Audio"
  27222. };
  27223. module.exports = MediaStreamType;
  27224. },{}],111:[function(require,module,exports){
  27225. var RTCEvents = {
  27226. RTC_READY: "rtc.ready",
  27227. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  27228. LASTN_CHANGED: "rtc.lastn_changed",
  27229. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  27230. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  27231. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  27232. AUDIO_MUTE: "rtc.audio_mute",
  27233. VIDEO_MUTE: "rtc.video_mute"
  27234. };
  27235. module.exports = RTCEvents;
  27236. },{}],112:[function(require,module,exports){
  27237. var Resolutions = {
  27238. "1080": {
  27239. width: 1920,
  27240. height: 1080,
  27241. order: 7
  27242. },
  27243. "fullhd": {
  27244. width: 1920,
  27245. height: 1080,
  27246. order: 7
  27247. },
  27248. "720": {
  27249. width: 1280,
  27250. height: 720,
  27251. order: 6
  27252. },
  27253. "hd": {
  27254. width: 1280,
  27255. height: 720,
  27256. order: 6
  27257. },
  27258. "960": {
  27259. width: 960,
  27260. height: 720,
  27261. order: 5
  27262. },
  27263. "640": {
  27264. width: 640,
  27265. height: 480,
  27266. order: 4
  27267. },
  27268. "vga": {
  27269. width: 640,
  27270. height: 480,
  27271. order: 4
  27272. },
  27273. "360": {
  27274. width: 640,
  27275. height: 360,
  27276. order: 3
  27277. },
  27278. "320": {
  27279. width: 320,
  27280. height: 240,
  27281. order: 2
  27282. },
  27283. "180": {
  27284. width: 320,
  27285. height: 180,
  27286. order: 1
  27287. }
  27288. };
  27289. module.exports = Resolutions;
  27290. },{}],113:[function(require,module,exports){
  27291. var StreamEventTypes = {
  27292. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  27293. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  27294. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  27295. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  27296. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  27297. };
  27298. module.exports = StreamEventTypes;
  27299. },{}],114:[function(require,module,exports){
  27300. var UIEvents = {
  27301. NICKNAME_CHANGED: "UI.nickname_changed",
  27302. SELECTED_ENDPOINT: "UI.selected_endpoint",
  27303. PINNED_ENDPOINT: "UI.pinned_endpoint",
  27304. LARGEVIDEO_INIT: "UI.largevideo_init"
  27305. };
  27306. module.exports = UIEvents;
  27307. },{}],115:[function(require,module,exports){
  27308. var AuthenticationEvents = {
  27309. /**
  27310. * Event callback arguments:
  27311. * function(authenticationEnabled, userIdentity)
  27312. * authenticationEnabled - indicates whether authentication has been enabled
  27313. * in this session
  27314. * userIdentity - if user has been logged in then it contains user name. If
  27315. * contains 'null' or 'undefined' then user is not logged in.
  27316. */
  27317. IDENTITY_UPDATED: "authentication.identity_updated"
  27318. };
  27319. module.exports = AuthenticationEvents;
  27320. },{}],116:[function(require,module,exports){
  27321. var CQEvents = {
  27322. LOCALSTATS_UPDATED: "cq.localstats_updated",
  27323. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  27324. STOP: "cq.stop"
  27325. };
  27326. module.exports = CQEvents;
  27327. },{}],117:[function(require,module,exports){
  27328. var DesktopSharingEventTypes = {
  27329. INIT: "ds.init",
  27330. SWITCHING_DONE: "ds.switching_done",
  27331. NEW_STREAM_CREATED: "ds.new_stream_created"
  27332. };
  27333. module.exports = DesktopSharingEventTypes;
  27334. },{}],118:[function(require,module,exports){
  27335. var Events = {
  27336. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  27337. };
  27338. module.exports = Events;
  27339. },{}],119:[function(require,module,exports){
  27340. module.exports = {
  27341. getLanguages : function () {
  27342. var languages = [];
  27343. for(var lang in this)
  27344. {
  27345. if(typeof this[lang] === "string")
  27346. languages.push(this[lang]);
  27347. }
  27348. return languages;
  27349. },
  27350. EN: "en",
  27351. BG: "bg",
  27352. DE: "de",
  27353. TR: "tr",
  27354. FR: "fr"
  27355. }
  27356. },{}],120:[function(require,module,exports){
  27357. var XMPPEvents = {
  27358. CONNECTION_FAILED: "xmpp.connection.failed",
  27359. // Indicates an interrupted connection event.
  27360. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  27361. // Indicates a restored connection event.
  27362. CONNECTION_RESTORED: "xmpp.connection.restored",
  27363. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  27364. CALL_INCOMING: "xmpp.callincoming.jingle",
  27365. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  27366. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  27367. KICKED: "xmpp.kicked",
  27368. BRIDGE_DOWN: "xmpp.bridge_down",
  27369. USER_ID_CHANGED: "xmpp.user_id_changed",
  27370. // We joined the MUC
  27371. MUC_JOINED: "xmpp.muc_joined",
  27372. // A member joined the MUC
  27373. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  27374. // A member left the MUC
  27375. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  27376. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  27377. MUC_DESTROYED: "xmpp.muc_destroyed",
  27378. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  27379. REMOTE_STATS: "xmpp.remote_stats",
  27380. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  27381. PRESENCE_STATUS: "xmpp.presence_status",
  27382. RESERVATION_ERROR: "xmpp.room_reservation_error",
  27383. SUBJECT_CHANGED: "xmpp.subject_changed",
  27384. MESSAGE_RECEIVED: "xmpp.message_received",
  27385. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27386. PASSWORD_REQUIRED: "xmpp.password_required",
  27387. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27388. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27389. ETHERPAD: "xmpp.etherpad",
  27390. DEVICE_AVAILABLE: "xmpp.device_available",
  27391. VIDEO_TYPE: "xmpp.video_type",
  27392. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27393. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27394. AUDIO_MUTED: "xmpp.audio_muted",
  27395. VIDEO_MUTED: "xmpp.video_muted",
  27396. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27397. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  27398. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27399. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27400. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27401. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27402. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27403. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27404. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27405. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27406. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27407. // xmpp is connected and obtained user media
  27408. READY_TO_JOIN: 'xmpp.ready_to_join'
  27409. };
  27410. module.exports = XMPPEvents;
  27411. },{}]},{},[3])(3)
  27412. });