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

app.bundle.js 1.2MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  13. this.xmpp = require("./modules/xmpp/xmpp");
  14. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  15. this.translation = require("./modules/translation/translation");
  16. this.settings = require("./modules/settings/Settings");
  17. this.DTMF = require("./modules/DTMF/DTMF");
  18. this.members = require("./modules/members/MemberList");
  19. }
  20. };
  21. function init() {
  22. APP.desktopsharing.init();
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. APP.keyboardshortcut.init();
  28. APP.members.start();
  29. }
  30. $(document).ready(function () {
  31. var URLProcessor = require("./modules/URLProcessor/URLProcessor");
  32. URLProcessor.setConfigParametersFromUrl();
  33. APP.init();
  34. APP.translation.init();
  35. if(APP.API.isEnabled())
  36. APP.API.init();
  37. APP.UI.start(init);
  38. });
  39. $(window).bind('beforeunload', function () {
  40. if(APP.API.isEnabled())
  41. APP.API.dispose();
  42. });
  43. module.exports = APP;
  44. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":11,"./modules/URLProcessor/URLProcessor":42,"./modules/connectionquality/connectionquality":43,"./modules/desktopsharing/desktopsharing":44,"./modules/keyboardshortcut/keyboardshortcut":45,"./modules/members/MemberList":46,"./modules/settings/Settings":47,"./modules/statistics/statistics":51,"./modules/translation/translation":52,"./modules/xmpp/xmpp":68}],2:[function(require,module,exports){
  45. /* global APP */
  46. /**
  47. * Implements API class that communicates with external api class
  48. * and provides interface to access Jitsi Meet features by external
  49. * applications that embed Jitsi Meet
  50. */
  51. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  52. /**
  53. * List of the available commands.
  54. * @type {{
  55. * displayName: inputDisplayNameHandler,
  56. * toggleAudio: toggleAudio,
  57. * toggleVideo: toggleVideo,
  58. * toggleFilmStrip: toggleFilmStrip,
  59. * toggleChat: toggleChat,
  60. * toggleContactList: toggleContactList
  61. * }}
  62. */
  63. var commands = {};
  64. function initCommands() {
  65. commands = {
  66. displayName: APP.UI.inputDisplayNameHandler,
  67. toggleAudio: APP.UI.toggleAudio,
  68. toggleVideo: APP.UI.toggleVideo,
  69. toggleFilmStrip: APP.UI.toggleFilmStrip,
  70. toggleChat: APP.UI.toggleChat,
  71. toggleContactList: APP.UI.toggleContactList
  72. };
  73. }
  74. /**
  75. * Maps the supported events and their status
  76. * (true it the event is enabled and false if it is disabled)
  77. * @type {{
  78. * incomingMessage: boolean,
  79. * outgoingMessage: boolean,
  80. * displayNameChange: boolean,
  81. * participantJoined: boolean,
  82. * participantLeft: boolean
  83. * }}
  84. */
  85. var events = {
  86. incomingMessage: false,
  87. outgoingMessage:false,
  88. displayNameChange: false,
  89. participantJoined: false,
  90. participantLeft: false
  91. };
  92. var displayName = {};
  93. /**
  94. * Processes commands from external application.
  95. * @param message the object with the command
  96. */
  97. function processCommand(message) {
  98. if (message.action != "execute") {
  99. console.error("Unknown action of the message");
  100. return;
  101. }
  102. for (var key in message) {
  103. if(commands[key])
  104. commands[key].apply(null, message[key]);
  105. }
  106. }
  107. /**
  108. * Processes events objects from external applications
  109. * @param event the event
  110. */
  111. function processEvent(event) {
  112. if (!event.action) {
  113. console.error("Event with no action is received.");
  114. return;
  115. }
  116. var i = 0;
  117. switch(event.action) {
  118. case "add":
  119. for (; i < event.events.length; i++) {
  120. events[event.events[i]] = true;
  121. }
  122. break;
  123. case "remove":
  124. for (; i < event.events.length; i++) {
  125. events[event.events[i]] = false;
  126. }
  127. break;
  128. default:
  129. console.error("Unknown action for event.");
  130. }
  131. }
  132. /**
  133. * Sends message to the external application.
  134. * @param object
  135. */
  136. function sendMessage(object) {
  137. window.parent.postMessage(JSON.stringify(object), "*");
  138. }
  139. /**
  140. * Processes a message event from the external application
  141. * @param event the message event
  142. */
  143. function processMessage(event) {
  144. var message;
  145. try {
  146. message = JSON.parse(event.data);
  147. } catch (e) {}
  148. if(!message.type)
  149. return;
  150. switch (message.type) {
  151. case "command":
  152. processCommand(message);
  153. break;
  154. case "event":
  155. processEvent(message);
  156. break;
  157. default:
  158. console.error("Unknown type of the message");
  159. return;
  160. }
  161. }
  162. function setupListeners() {
  163. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  164. API.triggerEvent("participantJoined", {jid: from});
  165. });
  166. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  167. if (from != myjid)
  168. API.triggerEvent("incomingMessage",
  169. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  170. });
  171. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  172. API.triggerEvent("participantLeft", {jid: jid});
  173. });
  174. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  175. var name = displayName[jid];
  176. if(!name || name != newDisplayName) {
  177. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  178. displayName[jid] = newDisplayName;
  179. }
  180. });
  181. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  182. APP.API.triggerEvent("outgoingMessage", {"message": body});
  183. });
  184. }
  185. var API = {
  186. /**
  187. * Check whether the API should be enabled or not.
  188. * @returns {boolean}
  189. */
  190. isEnabled: function () {
  191. var hash = location.hash;
  192. if (hash && hash.indexOf("external") > -1 && window.postMessage)
  193. return true;
  194. return false;
  195. },
  196. /**
  197. * Initializes the APIConnector. Setups message event listeners that will
  198. * receive information from external applications that embed Jitsi Meet.
  199. * It also sends a message to the external application that APIConnector
  200. * is initialized.
  201. */
  202. init: function () {
  203. initCommands();
  204. if (window.addEventListener) {
  205. window.addEventListener('message',
  206. processMessage, false);
  207. }
  208. else {
  209. window.attachEvent('onmessage', processMessage);
  210. }
  211. sendMessage({type: "system", loaded: true});
  212. setupListeners();
  213. },
  214. /**
  215. * Checks whether the event is enabled ot not.
  216. * @param name the name of the event.
  217. * @returns {*}
  218. */
  219. isEventEnabled: function (name) {
  220. return events[name];
  221. },
  222. /**
  223. * Sends event object to the external application that has been subscribed
  224. * for that event.
  225. * @param name the name event
  226. * @param object data associated with the event
  227. */
  228. triggerEvent: function (name, object) {
  229. if(this.isEnabled() && this.isEventEnabled(name))
  230. sendMessage({
  231. type: "event", action: "result", event: name, result: object});
  232. },
  233. /**
  234. * Removes the listeners.
  235. */
  236. dispose: function () {
  237. if(window.removeEventListener) {
  238. window.removeEventListener("message",
  239. processMessage, false);
  240. }
  241. else {
  242. window.detachEvent('onmessage', processMessage);
  243. }
  244. }
  245. };
  246. module.exports = API;
  247. },{"../../service/xmpp/XMPPEvents":161}],3:[function(require,module,exports){
  248. /* global APP */
  249. /**
  250. * A module for sending DTMF tones.
  251. */
  252. var DTMFSender;
  253. var initDtmfSender = function() {
  254. // TODO: This needs to reset this if the peerconnection changes
  255. // (e.g. the call is re-made)
  256. if (DTMFSender)
  257. return;
  258. var localAudio = APP.RTC.localAudio;
  259. if (localAudio && localAudio.getTracks().length > 0)
  260. {
  261. var peerconnection
  262. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  263. if (peerconnection) {
  264. DTMFSender =
  265. peerconnection.peerconnection
  266. .createDTMFSender(localAudio.getTracks()[0]);
  267. console.log("Initialized DTMFSender");
  268. }
  269. else {
  270. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  271. }
  272. }
  273. else {
  274. console.log("Failed to initialize DTMFSender: no audio track.");
  275. }
  276. };
  277. var DTMF = {
  278. sendTones: function (tones, duration, pause) {
  279. if (!DTMFSender)
  280. initDtmfSender();
  281. if (DTMFSender){
  282. DTMFSender.insertDTMF(tones,
  283. (duration || 200),
  284. (pause || 200));
  285. }
  286. }
  287. };
  288. module.exports = DTMF;
  289. },{}],4:[function(require,module,exports){
  290. /* global config, APP, Strophe */
  291. // cache datachannels to avoid garbage collection
  292. // https://code.google.com/p/chromium/issues/detail?id=405545
  293. var RTCEvents = require("../../service/RTC/RTCEvents");
  294. var _dataChannels = [];
  295. var eventEmitter = null;
  296. var DataChannels = {
  297. /**
  298. * Callback triggered by PeerConnection when new data channel is opened
  299. * on the bridge.
  300. * @param event the event info object.
  301. */
  302. onDataChannel: function (event) {
  303. var dataChannel = event.channel;
  304. dataChannel.onopen = function () {
  305. console.info("Data channel opened by the Videobridge!", dataChannel);
  306. // Code sample for sending string and/or binary data
  307. // Sends String message to the bridge
  308. //dataChannel.send("Hello bridge!");
  309. // Sends 12 bytes binary message to the bridge
  310. //dataChannel.send(new ArrayBuffer(12));
  311. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  312. };
  313. dataChannel.onerror = function (error) {
  314. console.error("Data Channel Error:", error, dataChannel);
  315. };
  316. dataChannel.onmessage = function (event) {
  317. var data = event.data;
  318. // JSON
  319. var obj;
  320. try {
  321. obj = JSON.parse(data);
  322. }
  323. catch (e) {
  324. console.error(
  325. "Failed to parse data channel message as JSON: ",
  326. data,
  327. dataChannel);
  328. }
  329. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  330. var colibriClass = obj.colibriClass;
  331. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  332. // Endpoint ID from the Videobridge.
  333. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  334. console.info(
  335. "Data channel new dominant speaker event: ",
  336. dominantSpeakerEndpoint);
  337. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  338. }
  339. else if ("InLastNChangeEvent" === colibriClass) {
  340. var oldValue = obj.oldValue;
  341. var newValue = obj.newValue;
  342. // Make sure that oldValue and newValue are of type boolean.
  343. var type;
  344. if ((type = typeof oldValue) !== 'boolean') {
  345. if (type === 'string') {
  346. oldValue = (oldValue == "true");
  347. } else {
  348. oldValue = new Boolean(oldValue).valueOf();
  349. }
  350. }
  351. if ((type = typeof newValue) !== 'boolean') {
  352. if (type === 'string') {
  353. newValue = (newValue == "true");
  354. } else {
  355. newValue = new Boolean(newValue).valueOf();
  356. }
  357. }
  358. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  359. }
  360. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  361. // The new/latest list of last-n endpoint IDs.
  362. var lastNEndpoints = obj.lastNEndpoints;
  363. // The list of endpoint IDs which are entering the list of
  364. // last-n at this time i.e. were not in the old list of last-n
  365. // endpoint IDs.
  366. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  367. console.log(
  368. "Data channel new last-n event: ",
  369. lastNEndpoints, endpointsEnteringLastN, obj);
  370. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  371. lastNEndpoints, endpointsEnteringLastN, obj);
  372. }
  373. else {
  374. console.debug("Data channel JSON-formatted message: ", obj);
  375. }
  376. }
  377. };
  378. dataChannel.onclose = function () {
  379. console.info("The Data Channel closed", dataChannel);
  380. var idx = _dataChannels.indexOf(dataChannel);
  381. if (idx > -1)
  382. _dataChannels = _dataChannels.splice(idx, 1);
  383. };
  384. _dataChannels.push(dataChannel);
  385. },
  386. /**
  387. * Binds "ondatachannel" event listener to given PeerConnection instance.
  388. * @param peerConnection WebRTC peer connection instance.
  389. */
  390. init: function (peerConnection, emitter) {
  391. if(!config.openSctp)
  392. return;
  393. peerConnection.ondatachannel = this.onDataChannel;
  394. eventEmitter = emitter;
  395. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  396. // Although it's not a requirement to open separate channels from both bridge
  397. // and peer as single channel can be used for sending and receiving data.
  398. // So either channel opened by the bridge or the one opened here is enough
  399. // for communication with the bridge.
  400. /*var dataChannelOptions =
  401. {
  402. reliable: true
  403. };
  404. var dataChannel
  405. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  406. // Can be used only when is in open state
  407. dataChannel.onopen = function ()
  408. {
  409. dataChannel.send("My channel !!!");
  410. };
  411. dataChannel.onmessage = function (event)
  412. {
  413. var msgData = event.data;
  414. console.info("Got My Data Channel Message:", msgData, dataChannel);
  415. };*/
  416. },
  417. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  418. handlePinnedEndpointEvent: onPinnedEndpointChanged
  419. };
  420. function onSelectedEndpointChanged(userResource) {
  421. console.log('selected endpoint changed: ', userResource);
  422. if (_dataChannels && _dataChannels.length != 0) {
  423. _dataChannels.some(function (dataChannel) {
  424. if (dataChannel.readyState == 'open') {
  425. console.log('sending selected endpoint changed ' +
  426. 'notification to the bridge: ', userResource);
  427. dataChannel.send(JSON.stringify({
  428. 'colibriClass': 'SelectedEndpointChangedEvent',
  429. 'selectedEndpoint':
  430. (!userResource || userResource === null)?
  431. null : userResource
  432. }));
  433. return true;
  434. }
  435. });
  436. }
  437. }
  438. function onPinnedEndpointChanged(userResource) {
  439. console.log('pinned endpoint changed: ', userResource);
  440. if (_dataChannels && _dataChannels.length != 0) {
  441. _dataChannels.some(function (dataChannel) {
  442. if (dataChannel.readyState == 'open') {
  443. dataChannel.send(JSON.stringify({
  444. 'colibriClass': 'PinnedEndpointChangedEvent',
  445. 'pinnedEndpoint':
  446. (!userResource || userResource == null)?
  447. null : userResource
  448. }));
  449. return true;
  450. }
  451. });
  452. }
  453. }
  454. module.exports = DataChannels;
  455. },{"../../service/RTC/RTCEvents":152}],5:[function(require,module,exports){
  456. /* global APP */
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. var RTCEvents = require("../../service/RTC/RTCEvents");
  459. var RTCBrowserType = require("./RTCBrowserType");
  460. /**
  461. * This implements 'onended' callback normally fired by WebRTC after the stream
  462. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  463. * @param stream original WebRTC stream object to which 'onended' handling
  464. * will be added.
  465. */
  466. function implementOnEndedHandling(stream) {
  467. var originalStop = stream.stop;
  468. stream.stop = function () {
  469. originalStop.apply(stream);
  470. if (!stream.ended) {
  471. stream.ended = true;
  472. stream.onended();
  473. }
  474. };
  475. }
  476. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  477. this.stream = stream;
  478. this.eventEmitter = eventEmitter;
  479. this.type = type;
  480. this.videoType = videoType;
  481. this.isGUMStream = true;
  482. if(isGUMStream === false)
  483. this.isGUMStream = isGUMStream;
  484. var self = this;
  485. if(type == "audio") {
  486. this.getTracks = function () {
  487. return self.stream.getAudioTracks();
  488. };
  489. } else {
  490. this.getTracks = function () {
  491. return self.stream.getVideoTracks();
  492. };
  493. }
  494. this.stream.onended = function () {
  495. self.streamEnded();
  496. };
  497. if (RTCBrowserType.isFirefox()) {
  498. implementOnEndedHandling(this.stream);
  499. }
  500. }
  501. LocalStream.prototype.streamEnded = function () {
  502. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  503. };
  504. LocalStream.prototype.getOriginalStream = function()
  505. {
  506. return this.stream;
  507. };
  508. LocalStream.prototype.isAudioStream = function () {
  509. return this.type === "audio";
  510. };
  511. LocalStream.prototype.setMute = function (mute)
  512. {
  513. var isAudio = this.isAudioStream();
  514. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  515. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  516. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  517. // FIXME FF does not support 'removeStream' method used to mute
  518. RTCBrowserType.isFirefox()) {
  519. var tracks = this.getTracks();
  520. for (var idx = 0; idx < tracks.length; idx++) {
  521. tracks[idx].enabled = !mute;
  522. }
  523. this.eventEmitter.emit(eventType, mute);
  524. } else {
  525. if (mute) {
  526. APP.xmpp.removeStream(this.stream);
  527. this.stream.stop();
  528. this.eventEmitter.emit(eventType, true);
  529. } else {
  530. var self = this;
  531. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  532. (this.isAudioStream() ? ["audio"] : ["video"]),
  533. function (stream) {
  534. if (isAudio) {
  535. APP.RTC.changeLocalAudio(stream,
  536. function () {
  537. self.eventEmitter.emit(eventType, false);
  538. });
  539. } else {
  540. APP.RTC.changeLocalVideo(stream, false,
  541. function () {
  542. self.eventEmitter.emit(eventType, false);
  543. });
  544. }
  545. });
  546. }
  547. }
  548. };
  549. LocalStream.prototype.isMuted = function () {
  550. var tracks = [];
  551. if (this.isAudioStream()) {
  552. tracks = this.stream.getAudioTracks();
  553. } else {
  554. if (this.stream.ended)
  555. return true;
  556. tracks = this.stream.getVideoTracks();
  557. }
  558. for (var idx = 0; idx < tracks.length; idx++) {
  559. if(tracks[idx].enabled)
  560. return false;
  561. }
  562. return true;
  563. };
  564. LocalStream.prototype.getId = function () {
  565. return this.stream.getTracks()[0].id;
  566. };
  567. module.exports = LocalStream;
  568. },{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes.js":154,"./RTCBrowserType":8}],6:[function(require,module,exports){
  569. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  570. /**
  571. * Creates a MediaStream object for the given data, session id and ssrc.
  572. * It is a wrapper class for the MediaStream.
  573. *
  574. * @param data the data object from which we obtain the stream,
  575. * the peerjid, etc.
  576. * @param sid the session id
  577. * @param ssrc the ssrc corresponding to this MediaStream
  578. *
  579. * @constructor
  580. */
  581. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  582. // XXX(gp) to minimize headaches in the future, we should build our
  583. // abstractions around tracks and not streams. ORTC is track based API.
  584. // Mozilla expects m-lines to represent media tracks.
  585. //
  586. // Practically, what I'm saying is that we should have a MediaTrack class
  587. // and not a MediaStream class.
  588. //
  589. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  590. // a track might have an associated RTX and FEC sources.
  591. this.sid = sid;
  592. this.stream = data.stream;
  593. this.peerjid = data.peerjid;
  594. this.videoType = data.videoType;
  595. this.ssrc = ssrc;
  596. this.type = (this.stream.getVideoTracks().length > 0)?
  597. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  598. this.muted = false;
  599. this.eventEmitter = eventEmitter;
  600. }
  601. MediaStream.prototype.getOriginalStream = function() {
  602. return this.stream;
  603. };
  604. MediaStream.prototype.setMute = function (value) {
  605. this.stream.muted = value;
  606. this.muted = value;
  607. };
  608. module.exports = MediaStream;
  609. },{"../../service/RTC/MediaStreamTypes":151}],7:[function(require,module,exports){
  610. /* global APP */
  611. var EventEmitter = require("events");
  612. var RTCBrowserType = require("./RTCBrowserType");
  613. var RTCUtils = require("./RTCUtils.js");
  614. var LocalStream = require("./LocalStream.js");
  615. var DataChannels = require("./DataChannels");
  616. var MediaStream = require("./MediaStream.js");
  617. var DesktopSharingEventTypes
  618. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  619. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  620. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  621. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  622. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  623. var UIEvents = require("../../service/UI/UIEvents");
  624. var eventEmitter = new EventEmitter();
  625. function getMediaStreamUsage()
  626. {
  627. var result = {
  628. audio: true,
  629. video: true
  630. };
  631. /** There are some issues with the desktop sharing
  632. * when this property is enabled.
  633. * WARNING: We must change the implementation to start video/audio if we
  634. * receive from the focus that the peer is not muted.
  635. var isSecureConnection = window.location.protocol == "https:";
  636. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  637. {
  638. result = {
  639. audio: false,
  640. video: false
  641. };
  642. }
  643. **/
  644. return result;
  645. }
  646. var RTC = {
  647. rtcUtils: null,
  648. devices: {
  649. audio: true,
  650. video: true
  651. },
  652. localStreams: [],
  653. remoteStreams: {},
  654. localAudio: null,
  655. localVideo: null,
  656. addStreamListener: function (listener, eventType) {
  657. eventEmitter.on(eventType, listener);
  658. },
  659. addListener: function (type, listener) {
  660. eventEmitter.on(type, listener);
  661. },
  662. removeStreamListener: function (listener, eventType) {
  663. if(!(eventType instanceof StreamEventTypes))
  664. throw "Illegal argument";
  665. eventEmitter.removeListener(eventType, listener);
  666. },
  667. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  668. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  669. //in firefox we have only one stream object
  670. if(this.localStreams.length == 0 ||
  671. this.localStreams[0].getOriginalStream() != stream)
  672. this.localStreams.push(localStream);
  673. if(isMuted === true)
  674. localStream.setMute(true);
  675. if(type == "audio") {
  676. this.localAudio = localStream;
  677. } else {
  678. this.localVideo = localStream;
  679. }
  680. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  681. if(change)
  682. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  683. eventEmitter.emit(eventType, localStream, isMuted);
  684. return localStream;
  685. },
  686. removeLocalStream: function (stream) {
  687. for(var i = 0; i < this.localStreams.length; i++) {
  688. if(this.localStreams[i].getOriginalStream() === stream) {
  689. delete this.localStreams[i];
  690. return;
  691. }
  692. }
  693. },
  694. createRemoteStream: function (data, sid, thessrc) {
  695. var remoteStream = new MediaStream(data, sid, thessrc,
  696. RTCBrowserType.getBrowserType(), eventEmitter);
  697. var jid = data.peerjid || APP.xmpp.myJid();
  698. if(!this.remoteStreams[jid]) {
  699. this.remoteStreams[jid] = {};
  700. }
  701. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  702. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  703. return remoteStream;
  704. },
  705. getPCConstraints: function () {
  706. return this.rtcUtils.pc_constraints;
  707. },
  708. getUserMediaWithConstraints:function(um, success_callback,
  709. failure_callback, resolution,
  710. bandwidth, fps, desktopStream)
  711. {
  712. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  713. failure_callback, resolution, bandwidth, fps, desktopStream);
  714. },
  715. attachMediaStream: function (elSelector, stream) {
  716. this.rtcUtils.attachMediaStream(elSelector, stream);
  717. },
  718. getStreamID: function (stream) {
  719. return this.rtcUtils.getStreamID(stream);
  720. },
  721. getVideoSrc: function (element) {
  722. return this.rtcUtils.getVideoSrc(element);
  723. },
  724. setVideoSrc: function (element, src) {
  725. this.rtcUtils.setVideoSrc(element, src);
  726. },
  727. getVideoElementName: function () {
  728. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  729. },
  730. dispose: function() {
  731. if (this.rtcUtils) {
  732. this.rtcUtils = null;
  733. }
  734. },
  735. stop: function () {
  736. this.dispose();
  737. },
  738. start: function () {
  739. var self = this;
  740. APP.desktopsharing.addListener(
  741. function (stream, isUsingScreenStream, callback) {
  742. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  743. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  744. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  745. DataChannels.init(event.peerconnection, eventEmitter);
  746. });
  747. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  748. DataChannels.handleSelectedEndpointEvent);
  749. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  750. DataChannels.handlePinnedEndpointEvent);
  751. // In case of IE we continue from 'onReady' callback
  752. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  753. // once it is initialized.
  754. var onReady = function () {
  755. eventEmitter.emit(RTCEvents.RTC_READY, true);
  756. self.rtcUtils.obtainAudioAndVideoPermissions(
  757. null, null, getMediaStreamUsage());
  758. };
  759. this.rtcUtils = new RTCUtils(this, onReady);
  760. // Call onReady() if Temasys plugin is not used
  761. if (!RTCBrowserType.isTemasysPluginUsed()) {
  762. onReady();
  763. }
  764. },
  765. muteRemoteVideoStream: function (jid, value) {
  766. var stream;
  767. if(this.remoteStreams[jid] &&
  768. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  769. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  770. }
  771. if(!stream)
  772. return true;
  773. if (value != stream.muted) {
  774. stream.setMute(value);
  775. return true;
  776. }
  777. return false;
  778. },
  779. switchVideoStreams: function (new_stream) {
  780. this.localVideo.stream = new_stream;
  781. this.localStreams = [];
  782. //in firefox we have only one stream object
  783. if (this.localAudio.getOriginalStream() != new_stream)
  784. this.localStreams.push(this.localAudio);
  785. this.localStreams.push(this.localVideo);
  786. },
  787. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  788. var oldStream = this.localVideo.getOriginalStream();
  789. var type = (isUsingScreenStream ? "screen" : "camera");
  790. var localCallback = callback;
  791. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  792. localCallback = function() {
  793. APP.xmpp.setVideoMute(false, function(mute) {
  794. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  795. });
  796. callback();
  797. };
  798. }
  799. // FIXME: Workaround for FF/IE/Safari
  800. if (stream && stream.videoStream) {
  801. stream = stream.videoStream;
  802. }
  803. var videoStream = this.rtcUtils.createStream(stream, true);
  804. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  805. // Stop the stream to trigger onended event for old stream
  806. oldStream.stop();
  807. this.switchVideoStreams(videoStream, oldStream);
  808. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  809. },
  810. changeLocalAudio: function (stream, callback) {
  811. var oldStream = this.localAudio.getOriginalStream();
  812. var newStream = this.rtcUtils.createStream(stream);
  813. this.localAudio = this.createLocalStream(newStream, "audio", true);
  814. // Stop the stream to trigger onended event for old stream
  815. oldStream.stop();
  816. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  817. },
  818. isVideoMuted: function (jid) {
  819. if (jid === APP.xmpp.myJid()) {
  820. var localVideo = APP.RTC.localVideo;
  821. return (!localVideo || localVideo.isMuted());
  822. } else {
  823. if (!APP.RTC.remoteStreams[jid] ||
  824. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  825. return null;
  826. }
  827. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  828. }
  829. },
  830. setVideoMute: function (mute, callback, options) {
  831. if (!this.localVideo)
  832. return;
  833. if (mute == APP.RTC.localVideo.isMuted())
  834. {
  835. APP.xmpp.sendVideoInfoPresence(mute);
  836. if (callback)
  837. callback(mute);
  838. }
  839. else
  840. {
  841. APP.RTC.localVideo.setMute(mute);
  842. APP.xmpp.setVideoMute(
  843. mute,
  844. callback,
  845. options);
  846. }
  847. },
  848. setDeviceAvailability: function (devices) {
  849. if(!devices)
  850. return;
  851. if(devices.audio === true || devices.audio === false)
  852. this.devices.audio = devices.audio;
  853. if(devices.video === true || devices.video === false)
  854. this.devices.video = devices.video;
  855. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  856. }
  857. };
  858. module.exports = RTC;
  859. },{"../../service/RTC/MediaStreamTypes":151,"../../service/RTC/RTCEvents.js":152,"../../service/RTC/StreamEventTypes.js":154,"../../service/UI/UIEvents":155,"../../service/desktopsharing/DesktopSharingEventTypes":158,"../../service/xmpp/XMPPEvents":161,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":162}],8:[function(require,module,exports){
  860. var currentBrowser;
  861. var browserVersion;
  862. var RTCBrowserType = {
  863. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  864. RTC_BROWSER_OPERA: "rtc_browser.opera",
  865. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  866. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  867. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  868. getBrowserType: function () {
  869. return currentBrowser;
  870. },
  871. isChrome: function () {
  872. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  873. },
  874. isOpera: function () {
  875. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  876. },
  877. isFirefox: function () {
  878. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  879. },
  880. isIExplorer: function () {
  881. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  882. },
  883. isSafari: function () {
  884. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  885. },
  886. isTemasysPluginUsed: function () {
  887. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  888. },
  889. getFirefoxVersion: function () {
  890. return RTCBrowserType.isFirefox() ? browserVersion : null;
  891. },
  892. getChromeVersion: function () {
  893. return RTCBrowserType.isChrome() ? browserVersion : null;
  894. },
  895. usesPlanB: function() {
  896. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  897. RTCBrowserType.isTemasysPluginUsed();
  898. },
  899. usesUnifiedPlan: function() {
  900. return RTCBrowserType.isFirefox();
  901. }
  902. // Add version getters for other browsers when needed
  903. };
  904. // detectOpera() must be called before detectChrome() !!!
  905. // otherwise Opera wil be detected as Chrome
  906. function detectChrome() {
  907. if (navigator.webkitGetUserMedia) {
  908. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  909. var userAgent = navigator.userAgent.toLowerCase();
  910. // We can assume that user agent is chrome, because it's
  911. // enforced when 'ext' streaming method is set
  912. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  913. console.log("This appears to be Chrome, ver: " + ver);
  914. return ver;
  915. }
  916. return null;
  917. }
  918. function detectOpera() {
  919. var userAgent = navigator.userAgent;
  920. if (userAgent.match(/Opera|OPR/)) {
  921. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  922. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  923. console.info("This appears to be Opera, ver: " + version);
  924. return version;
  925. }
  926. return null;
  927. }
  928. function detectFirefox() {
  929. if (navigator.mozGetUserMedia) {
  930. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  931. var version = parseInt(
  932. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  933. console.log('This appears to be Firefox, ver: ' + version);
  934. return version;
  935. }
  936. return null;
  937. }
  938. function detectSafari() {
  939. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  940. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  941. console.info("This appears to be Safari");
  942. // FIXME detect Safari version when needed
  943. return 1;
  944. }
  945. return null;
  946. }
  947. function detectIE() {
  948. var version;
  949. var ua = window.navigator.userAgent;
  950. var msie = ua.indexOf('MSIE ');
  951. if (msie > 0) {
  952. // IE 10 or older => return version number
  953. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  954. }
  955. var trident = ua.indexOf('Trident/');
  956. if (!version && trident > 0) {
  957. // IE 11 => return version number
  958. var rv = ua.indexOf('rv:');
  959. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  960. }
  961. var edge = ua.indexOf('Edge/');
  962. if (!version && edge > 0) {
  963. // IE 12 => return version number
  964. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  965. }
  966. if (version) {
  967. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  968. console.info("This appears to be IExplorer, ver: " + version);
  969. }
  970. return version;
  971. }
  972. function detectBrowser() {
  973. var version;
  974. var detectors = [
  975. detectOpera,
  976. detectChrome,
  977. detectFirefox,
  978. detectIE,
  979. detectSafari
  980. ];
  981. // Try all browser detectors
  982. for (var i = 0; i < detectors.length; i++) {
  983. version = detectors[i]();
  984. if (version)
  985. return version;
  986. }
  987. console.error("Failed to detect browser type");
  988. return undefined;
  989. }
  990. browserVersion = detectBrowser();
  991. module.exports = RTCBrowserType;
  992. },{}],9:[function(require,module,exports){
  993. /* global config, require, attachMediaStream, getUserMedia */
  994. var RTCBrowserType = require("./RTCBrowserType");
  995. var Resolutions = require("../../service/RTC/Resolutions");
  996. var AdapterJS = require("./adapter.screenshare");
  997. var SDPUtil = require("../xmpp/SDPUtil");
  998. var currentResolution = null;
  999. function getPreviousResolution(resolution) {
  1000. if(!Resolutions[resolution])
  1001. return null;
  1002. var order = Resolutions[resolution].order;
  1003. var res = null;
  1004. var resName = null;
  1005. for(var i in Resolutions) {
  1006. var tmp = Resolutions[i];
  1007. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1008. resName = i;
  1009. res = tmp;
  1010. }
  1011. }
  1012. return resName;
  1013. }
  1014. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1015. if (Resolutions[resolution]) {
  1016. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1017. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1018. }
  1019. else if (isAndroid) {
  1020. // FIXME can't remember if the purpose of this was to always request
  1021. // low resolution on Android ? if yes it should be moved up front
  1022. constraints.video.mandatory.minWidth = 320;
  1023. constraints.video.mandatory.minHeight = 240;
  1024. constraints.video.mandatory.maxFrameRate = 15;
  1025. }
  1026. if (constraints.video.mandatory.minWidth)
  1027. constraints.video.mandatory.maxWidth =
  1028. constraints.video.mandatory.minWidth;
  1029. if (constraints.video.mandatory.minHeight)
  1030. constraints.video.mandatory.maxHeight =
  1031. constraints.video.mandatory.minHeight;
  1032. }
  1033. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1034. {
  1035. var constraints = {audio: false, video: false};
  1036. if (um.indexOf('video') >= 0) {
  1037. // same behaviour as true
  1038. constraints.video = { mandatory: {}, optional: [] };
  1039. constraints.video.optional.push({ googLeakyBucket: true });
  1040. setResolutionConstraints(constraints, resolution, isAndroid);
  1041. }
  1042. if (um.indexOf('audio') >= 0) {
  1043. if (!RTCBrowserType.isFirefox()) {
  1044. // same behaviour as true
  1045. constraints.audio = { mandatory: {}, optional: []};
  1046. // if it is good enough for hangouts...
  1047. constraints.audio.optional.push(
  1048. {googEchoCancellation: true},
  1049. {googAutoGainControl: true},
  1050. {googNoiseSupression: true},
  1051. {googHighpassFilter: true},
  1052. {googNoisesuppression2: true},
  1053. {googEchoCancellation2: true},
  1054. {googAutoGainControl2: true}
  1055. );
  1056. } else {
  1057. constraints.audio = true;
  1058. }
  1059. }
  1060. if (um.indexOf('screen') >= 0) {
  1061. if (RTCBrowserType.isChrome()) {
  1062. constraints.video = {
  1063. mandatory: {
  1064. chromeMediaSource: "screen",
  1065. googLeakyBucket: true,
  1066. maxWidth: window.screen.width,
  1067. maxHeight: window.screen.height,
  1068. maxFrameRate: 3
  1069. },
  1070. optional: []
  1071. };
  1072. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1073. constraints.video = {
  1074. optional: [
  1075. {
  1076. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1077. }
  1078. ]
  1079. };
  1080. } else {
  1081. console.error(
  1082. "'screen' WebRTC media source is supported only in Chrome" +
  1083. " and with Temasys plugin");
  1084. }
  1085. }
  1086. if (um.indexOf('desktop') >= 0) {
  1087. constraints.video = {
  1088. mandatory: {
  1089. chromeMediaSource: "desktop",
  1090. chromeMediaSourceId: desktopStream,
  1091. googLeakyBucket: true,
  1092. maxWidth: window.screen.width,
  1093. maxHeight: window.screen.height,
  1094. maxFrameRate: 3
  1095. },
  1096. optional: []
  1097. };
  1098. }
  1099. if (bandwidth) {
  1100. if (!constraints.video) {
  1101. //same behaviour as true
  1102. constraints.video = {mandatory: {}, optional: []};
  1103. }
  1104. constraints.video.optional.push({bandwidth: bandwidth});
  1105. }
  1106. if (fps) {
  1107. // for some cameras it might be necessary to request 30fps
  1108. // so they choose 30fps mjpg over 10fps yuy2
  1109. if (!constraints.video) {
  1110. // same behaviour as true;
  1111. constraints.video = {mandatory: {}, optional: []};
  1112. }
  1113. constraints.video.mandatory.minFrameRate = fps;
  1114. }
  1115. return constraints;
  1116. }
  1117. function RTCUtils(RTCService, onTemasysPluginReady)
  1118. {
  1119. var self = this;
  1120. this.service = RTCService;
  1121. if (RTCBrowserType.isFirefox()) {
  1122. var FFversion = RTCBrowserType.getFirefoxVersion();
  1123. if (FFversion >= 40) {
  1124. this.peerconnection = mozRTCPeerConnection;
  1125. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1126. this.pc_constraints = {};
  1127. this.attachMediaStream = function (element, stream) {
  1128. // srcObject is being standardized and FF will eventually
  1129. // support that unprefixed. FF also supports the
  1130. // "element.src = URL.createObjectURL(...)" combo, but that
  1131. // will be deprecated in favour of srcObject.
  1132. //
  1133. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1134. // https://github.com/webrtc/samples/issues/302
  1135. if(!element[0])
  1136. return;
  1137. element[0].mozSrcObject = stream;
  1138. element[0].play();
  1139. };
  1140. this.getStreamID = function (stream) {
  1141. var id = stream.id;
  1142. if (!id) {
  1143. var tracks = stream.getVideoTracks();
  1144. if (!tracks || tracks.length === 0) {
  1145. tracks = stream.getAudioTracks();
  1146. }
  1147. id = tracks[0].id;
  1148. }
  1149. return SDPUtil.filter_special_chars(id);
  1150. };
  1151. this.getVideoSrc = function (element) {
  1152. if(!element)
  1153. return null;
  1154. return element.mozSrcObject;
  1155. };
  1156. this.setVideoSrc = function (element, src) {
  1157. if(element)
  1158. element.mozSrcObject = src;
  1159. };
  1160. RTCSessionDescription = mozRTCSessionDescription;
  1161. RTCIceCandidate = mozRTCIceCandidate;
  1162. } else {
  1163. console.error(
  1164. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1165. window.location.href = 'unsupported_browser.html';
  1166. return;
  1167. }
  1168. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1169. this.peerconnection = webkitRTCPeerConnection;
  1170. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1171. this.attachMediaStream = function (element, stream) {
  1172. element.attr('src', webkitURL.createObjectURL(stream));
  1173. };
  1174. this.getStreamID = function (stream) {
  1175. // streams from FF endpoints have the characters '{' and '}'
  1176. // that make jQuery choke.
  1177. return SDPUtil.filter_special_chars(stream.id);
  1178. };
  1179. this.getVideoSrc = function (element) {
  1180. if(!element)
  1181. return null;
  1182. return element.getAttribute("src");
  1183. };
  1184. this.setVideoSrc = function (element, src) {
  1185. if(element)
  1186. element.setAttribute("src", src);
  1187. };
  1188. // DTLS should now be enabled by default but..
  1189. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1190. if (navigator.userAgent.indexOf('Android') != -1) {
  1191. this.pc_constraints = {}; // disable DTLS on Android
  1192. }
  1193. if (!webkitMediaStream.prototype.getVideoTracks) {
  1194. webkitMediaStream.prototype.getVideoTracks = function () {
  1195. return this.videoTracks;
  1196. };
  1197. }
  1198. if (!webkitMediaStream.prototype.getAudioTracks) {
  1199. webkitMediaStream.prototype.getAudioTracks = function () {
  1200. return this.audioTracks;
  1201. };
  1202. }
  1203. }
  1204. // Detect IE/Safari
  1205. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1206. //AdapterJS.WebRTCPlugin.setLogLevel(
  1207. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1208. AdapterJS.webRTCReady(function (isPlugin) {
  1209. self.peerconnection = RTCPeerConnection;
  1210. self.getUserMedia = getUserMedia;
  1211. self.attachMediaStream = function (elSel, stream) {
  1212. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1213. return;
  1214. }
  1215. attachMediaStream(elSel[0], stream);
  1216. };
  1217. self.getStreamID = function (stream) {
  1218. var id = SDPUtil.filter_special_chars(stream.label);
  1219. return id;
  1220. };
  1221. self.getVideoSrc = function (element) {
  1222. if (!element) {
  1223. console.warn("Attempt to get video SRC of null element");
  1224. return null;
  1225. }
  1226. var children = element.children;
  1227. for (var i = 0; i !== children.length; ++i) {
  1228. if (children[i].name === 'streamId') {
  1229. return children[i].value;
  1230. }
  1231. }
  1232. //console.info(element.id + " SRC: " + src);
  1233. return null;
  1234. };
  1235. self.setVideoSrc = function (element, src) {
  1236. //console.info("Set video src: ", element, src);
  1237. if (!src) {
  1238. console.warn("Not attaching video stream, 'src' is null");
  1239. return;
  1240. }
  1241. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1242. var stream = AdapterJS.WebRTCPlugin.plugin
  1243. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1244. attachMediaStream(element, stream);
  1245. };
  1246. onTemasysPluginReady(isPlugin);
  1247. });
  1248. } else {
  1249. try {
  1250. console.log('Browser does not appear to be WebRTC-capable');
  1251. } catch (e) { }
  1252. window.location.href = 'unsupported_browser.html';
  1253. }
  1254. }
  1255. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1256. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1257. desktopStream) {
  1258. currentResolution = resolution;
  1259. // Check if we are running on Android device
  1260. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1261. var constraints = getConstraints(
  1262. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1263. console.info("Get media constraints", constraints);
  1264. var self = this;
  1265. try {
  1266. this.getUserMedia(constraints,
  1267. function (stream) {
  1268. console.log('onUserMediaSuccess');
  1269. self.setAvailableDevices(um, true);
  1270. success_callback(stream);
  1271. },
  1272. function (error) {
  1273. self.setAvailableDevices(um, false);
  1274. console.warn('Failed to get access to local media. Error ',
  1275. error, constraints);
  1276. if (failure_callback) {
  1277. failure_callback(error);
  1278. }
  1279. });
  1280. } catch (e) {
  1281. console.error('GUM failed: ', e);
  1282. if(failure_callback) {
  1283. failure_callback(e);
  1284. }
  1285. }
  1286. };
  1287. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1288. var devices = {};
  1289. if(um.indexOf("video") != -1) {
  1290. devices.video = available;
  1291. }
  1292. if(um.indexOf("audio") != -1) {
  1293. devices.audio = available;
  1294. }
  1295. this.service.setDeviceAvailability(devices);
  1296. };
  1297. /**
  1298. * We ask for audio and video combined stream in order to get permissions and
  1299. * not to ask twice.
  1300. */
  1301. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1302. function(devices, callback, usageOptions)
  1303. {
  1304. var self = this;
  1305. // Get AV
  1306. var successCallback = function (stream) {
  1307. if(callback)
  1308. callback(stream, usageOptions);
  1309. else
  1310. self.successCallback(stream, usageOptions);
  1311. };
  1312. if(!devices)
  1313. devices = ['audio', 'video'];
  1314. var newDevices = [];
  1315. if(usageOptions)
  1316. for(var i = 0; i < devices.length; i++) {
  1317. var device = devices[i];
  1318. if(usageOptions[device] === true)
  1319. newDevices.push(device);
  1320. }
  1321. else
  1322. newDevices = devices;
  1323. if(newDevices.length === 0) {
  1324. successCallback();
  1325. return;
  1326. }
  1327. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1328. // With FF/IE we can't split the stream into audio and video because FF
  1329. // doesn't support media stream constructors. So, we need to get the
  1330. // audio stream separately from the video stream using two distinct GUM
  1331. // calls. Not very user friendly :-( but we don't have many other
  1332. // options neither.
  1333. //
  1334. // Note that we pack those 2 streams in a single object and pass it to
  1335. // the successCallback method.
  1336. var obtainVideo = function (audioStream) {
  1337. self.getUserMediaWithConstraints(
  1338. ['video'],
  1339. function (videoStream) {
  1340. return successCallback({
  1341. audioStream: audioStream,
  1342. videoStream: videoStream
  1343. });
  1344. },
  1345. function (error) {
  1346. console.error(
  1347. 'failed to obtain video stream - stop', error);
  1348. self.errorCallback(error);
  1349. },
  1350. config.resolution || '360');
  1351. };
  1352. var obtainAudio = function () {
  1353. self.getUserMediaWithConstraints(
  1354. ['audio'],
  1355. function (audioStream) {
  1356. if (newDevices.indexOf('video') !== -1)
  1357. obtainVideo(audioStream);
  1358. },
  1359. function (error) {
  1360. console.error(
  1361. 'failed to obtain audio stream - stop', error);
  1362. self.errorCallback(error);
  1363. }
  1364. );
  1365. };
  1366. if (newDevices.indexOf('audio') !== -1) {
  1367. obtainAudio();
  1368. } else {
  1369. obtainVideo(null);
  1370. }
  1371. } else {
  1372. this.getUserMediaWithConstraints(
  1373. newDevices,
  1374. function (stream) {
  1375. successCallback(stream);
  1376. },
  1377. function (error) {
  1378. self.errorCallback(error);
  1379. },
  1380. config.resolution || '360');
  1381. }
  1382. };
  1383. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1384. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1385. // it's an object with two properties: audioStream, videoStream.
  1386. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1387. console.log('got', stream, stream.getAudioTracks().length,
  1388. stream.getVideoTracks().length);
  1389. this.handleLocalStream(stream, usageOptions);
  1390. };
  1391. RTCUtils.prototype.errorCallback = function (error) {
  1392. var self = this;
  1393. console.error('failed to obtain audio/video stream - trying audio only', error);
  1394. var resolution = getPreviousResolution(currentResolution);
  1395. if(typeof error == "object" && error.constraintName && error.name
  1396. && (error.name == "ConstraintNotSatisfiedError" ||
  1397. error.name == "OverconstrainedError") &&
  1398. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1399. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1400. && resolution != null)
  1401. {
  1402. self.getUserMediaWithConstraints(['audio', 'video'],
  1403. function (stream) {
  1404. return self.successCallback(stream);
  1405. }, function (error) {
  1406. return self.errorCallback(error);
  1407. }, resolution);
  1408. }
  1409. else {
  1410. self.getUserMediaWithConstraints(
  1411. ['audio'],
  1412. function (stream) {
  1413. return self.successCallback(stream);
  1414. },
  1415. function (error) {
  1416. console.error('failed to obtain audio/video stream - stop',
  1417. error);
  1418. return self.successCallback(null);
  1419. }
  1420. );
  1421. }
  1422. };
  1423. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1424. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1425. // an object with two properties: audioStream, videoStream.
  1426. var audioStream, videoStream;
  1427. if(window.webkitMediaStream)
  1428. {
  1429. audioStream = new webkitMediaStream();
  1430. videoStream = new webkitMediaStream();
  1431. if(stream) {
  1432. var audioTracks = stream.getAudioTracks();
  1433. for (var i = 0; i < audioTracks.length; i++) {
  1434. audioStream.addTrack(audioTracks[i]);
  1435. }
  1436. var videoTracks = stream.getVideoTracks();
  1437. for (i = 0; i < videoTracks.length; i++) {
  1438. videoStream.addTrack(videoTracks[i]);
  1439. }
  1440. }
  1441. }
  1442. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1443. { // Firefox and Temasys plugin
  1444. if (stream && stream.audioStream)
  1445. audioStream = stream.audioStream;
  1446. else
  1447. audioStream = new DummyMediaStream("dummyAudio");
  1448. if (stream && stream.videoStream)
  1449. videoStream = stream.videoStream;
  1450. else
  1451. videoStream = new DummyMediaStream("dummyVideo");
  1452. }
  1453. var audioMuted = (usageOptions && usageOptions.audio === false),
  1454. videoMuted = (usageOptions && usageOptions.video === false);
  1455. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1456. videoGUM = (!usageOptions || usageOptions.video !== false);
  1457. this.service.createLocalStream(audioStream, "audio", null, null,
  1458. audioMuted, audioGUM);
  1459. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1460. videoMuted, videoGUM);
  1461. };
  1462. function DummyMediaStream(id) {
  1463. this.id = id;
  1464. this.label = id;
  1465. this.stop = function() { };
  1466. this.getAudioTracks = function() { return []; };
  1467. this.getVideoTracks = function() { return []; };
  1468. }
  1469. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1470. var newStream = null;
  1471. if (window.webkitMediaStream) {
  1472. newStream = new webkitMediaStream();
  1473. if (newStream) {
  1474. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1475. for (var i = 0; i < tracks.length; i++) {
  1476. newStream.addTrack(tracks[i]);
  1477. }
  1478. }
  1479. }
  1480. else {
  1481. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1482. if (stream) {
  1483. newStream = stream;
  1484. } else {
  1485. newStream =
  1486. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1487. }
  1488. }
  1489. return newStream;
  1490. };
  1491. module.exports = RTCUtils;
  1492. },{"../../service/RTC/Resolutions":153,"../xmpp/SDPUtil":58,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1493. /*! adapterjs - custom version from - 2015-08-12 */
  1494. // Adapter's interface.
  1495. var AdapterJS = AdapterJS || {};
  1496. // Browserify compatibility
  1497. if(typeof exports !== 'undefined') {
  1498. module.exports = AdapterJS;
  1499. }
  1500. AdapterJS.options = AdapterJS.options || {};
  1501. // uncomment to get virtual webcams
  1502. // AdapterJS.options.getAllCams = true;
  1503. // uncomment to prevent the install prompt when the plugin in not yet installed
  1504. // AdapterJS.options.hidePluginInstallPrompt = true;
  1505. // AdapterJS version
  1506. AdapterJS.VERSION = '0.11.1';
  1507. // This function will be called when the WebRTC API is ready to be used
  1508. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1509. // the plugin
  1510. // You may Override this function to synchronise the start of your application
  1511. // with the WebRTC API being ready.
  1512. // If you decide not to override use this synchronisation, it may result in
  1513. // an extensive CPU usage on the plugin start (once per tab loaded)
  1514. // Params:
  1515. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1516. //
  1517. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1518. // The WebRTC API is ready.
  1519. // Override me and do whatever you want here
  1520. };
  1521. // Sets a callback function to be called when the WebRTC interface is ready.
  1522. // The first argument is the function to callback.\
  1523. // Throws an error if the first argument is not a function
  1524. AdapterJS.webRTCReady = function (callback) {
  1525. if (typeof callback !== 'function') {
  1526. throw new Error('Callback provided is not a function');
  1527. }
  1528. if (true === AdapterJS.onwebrtcreadyDone) {
  1529. // All WebRTC interfaces are ready, just call the callback
  1530. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1531. } else {
  1532. // will be triggered automatically when your browser/plugin is ready.
  1533. AdapterJS.onwebrtcready = callback;
  1534. }
  1535. };
  1536. // Plugin namespace
  1537. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1538. // The object to store plugin information
  1539. AdapterJS.WebRTCPlugin.pluginInfo = {
  1540. prefix : 'Tem',
  1541. plugName : 'TemWebRTCPlugin',
  1542. pluginId : 'plugin0',
  1543. type : 'application/x-temwebrtcplugin',
  1544. onload : '__TemWebRTCReady0',
  1545. portalLink : 'http://skylink.io/plugin/',
  1546. downloadLink : null, //set below
  1547. companyName: 'Temasys'
  1548. };
  1549. if(!!navigator.platform.match(/^Mac/i)) {
  1550. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1551. }
  1552. else if(!!navigator.platform.match(/^Win/i)) {
  1553. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1554. }
  1555. // Unique identifier of each opened page
  1556. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1557. // Use this whenever you want to call the plugin.
  1558. AdapterJS.WebRTCPlugin.plugin = null;
  1559. // Set log level for the plugin once it is ready.
  1560. // The different values are
  1561. // This is an asynchronous function that will run when the plugin is ready
  1562. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1563. // Defines webrtc's JS interface according to the plugin's implementation.
  1564. // Define plugin Browsers as WebRTC Interface.
  1565. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1566. // This function detects whether or not a plugin is installed.
  1567. // Checks if Not IE (firefox, for example), else if it's IE,
  1568. // we're running IE and do something. If not it is not supported.
  1569. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1570. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1571. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1572. // Inject the HTML DOM object element into the page.
  1573. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1574. // States of readiness that the plugin goes through when
  1575. // being injected and stated
  1576. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1577. NONE : 0, // no plugin use
  1578. INITIALIZING : 1, // Detected need for plugin
  1579. INJECTING : 2, // Injecting plugin
  1580. INJECTED: 3, // Plugin element injected but not usable yet
  1581. READY: 4 // Plugin ready to be used
  1582. };
  1583. // Current state of the plugin. You cannot use the plugin before this is
  1584. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1585. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1586. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1587. // Used to make sure AdapterJS.onwebrtcready is only called once
  1588. AdapterJS.onwebrtcreadyDone = false;
  1589. // Log levels for the plugin.
  1590. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1591. /*
  1592. Log outputs are prefixed in some cases.
  1593. INFO: Information reported by the plugin.
  1594. ERROR: Errors originating from within the plugin.
  1595. WEBRTC: Error originating from within the libWebRTC library
  1596. */
  1597. // From the least verbose to the most verbose
  1598. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1599. NONE : 'NONE',
  1600. ERROR : 'ERROR',
  1601. WARNING : 'WARNING',
  1602. INFO: 'INFO',
  1603. VERBOSE: 'VERBOSE',
  1604. SENSITIVE: 'SENSITIVE'
  1605. };
  1606. // Does a waiting check before proceeding to load the plugin.
  1607. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1608. // This methid will use an interval to wait for the plugin to be ready.
  1609. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1610. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1611. // This function will be called when plugin is ready. It sends necessary
  1612. // details to the plugin.
  1613. // The function will wait for the document to be ready and the set the
  1614. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1615. // indicating that it can start being requested.
  1616. // This function is not in the IE/Safari condition brackets so that
  1617. // TemPluginLoaded function might be called on Chrome/Firefox.
  1618. // This function is the only private function that is not encapsulated to
  1619. // allow the plugin method to be called.
  1620. __TemWebRTCReady0 = function () {
  1621. if (document.readyState === 'complete') {
  1622. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1623. AdapterJS.maybeThroughWebRTCReady();
  1624. } else {
  1625. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1626. if (document.readyState === 'complete') {
  1627. // TODO: update comments, we wait for the document to be ready
  1628. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1629. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1630. AdapterJS.maybeThroughWebRTCReady();
  1631. }
  1632. }, 100);
  1633. }
  1634. };
  1635. AdapterJS.maybeThroughWebRTCReady = function() {
  1636. if (!AdapterJS.onwebrtcreadyDone) {
  1637. AdapterJS.onwebrtcreadyDone = true;
  1638. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1639. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1640. }
  1641. }
  1642. };
  1643. // Text namespace
  1644. AdapterJS.TEXT = {
  1645. PLUGIN: {
  1646. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1647. 'to work on this browser.',
  1648. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1649. BUTTON: 'Install Now'
  1650. },
  1651. REFRESH: {
  1652. REQUIRE_REFRESH: 'Please refresh page',
  1653. BUTTON: 'Refresh Page'
  1654. }
  1655. };
  1656. // The result of ice connection states.
  1657. // - starting: Ice connection is starting.
  1658. // - checking: Ice connection is checking.
  1659. // - connected Ice connection is connected.
  1660. // - completed Ice connection is connected.
  1661. // - done Ice connection has been completed.
  1662. // - disconnected Ice connection has been disconnected.
  1663. // - failed Ice connection has failed.
  1664. // - closed Ice connection is closed.
  1665. AdapterJS._iceConnectionStates = {
  1666. starting : 'starting',
  1667. checking : 'checking',
  1668. connected : 'connected',
  1669. completed : 'connected',
  1670. done : 'completed',
  1671. disconnected : 'disconnected',
  1672. failed : 'failed',
  1673. closed : 'closed'
  1674. };
  1675. //The IceConnection states that has been fired for each peer.
  1676. AdapterJS._iceConnectionFiredStates = [];
  1677. // Check if WebRTC Interface is defined.
  1678. AdapterJS.isDefined = null;
  1679. // This function helps to retrieve the webrtc detected browser information.
  1680. // This sets:
  1681. // - webrtcDetectedBrowser: The browser agent name.
  1682. // - webrtcDetectedVersion: The browser version.
  1683. // - webrtcDetectedType: The types of webRTC support.
  1684. // - 'moz': Mozilla implementation of webRTC.
  1685. // - 'webkit': WebKit implementation of webRTC.
  1686. // - 'plugin': Using the plugin implementation.
  1687. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1688. var hasMatch, checkMatch = navigator.userAgent.match(
  1689. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1690. if (/trident/i.test(checkMatch[1])) {
  1691. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1692. webrtcDetectedBrowser = 'IE';
  1693. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1694. } else if (checkMatch[1] === 'Chrome') {
  1695. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1696. if (hasMatch !== null) {
  1697. webrtcDetectedBrowser = 'opera';
  1698. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1699. }
  1700. }
  1701. if (navigator.userAgent.indexOf('Safari')) {
  1702. if (typeof InstallTrigger !== 'undefined') {
  1703. webrtcDetectedBrowser = 'firefox';
  1704. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1705. webrtcDetectedBrowser = 'IE';
  1706. } else if (
  1707. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1708. webrtcDetectedBrowser = 'safari';
  1709. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1710. webrtcDetectedBrowser = 'opera';
  1711. } else if (!!window.chrome) {
  1712. webrtcDetectedBrowser = 'chrome';
  1713. }
  1714. }
  1715. if (!webrtcDetectedBrowser) {
  1716. webrtcDetectedVersion = checkMatch[1];
  1717. }
  1718. if (!webrtcDetectedVersion) {
  1719. try {
  1720. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1721. [navigator.appName, navigator.appVersion, '-?'];
  1722. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1723. checkMatch.splice(1, 1, hasMatch[1]);
  1724. }
  1725. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1726. } catch (error) { }
  1727. }
  1728. };
  1729. // To fix configuration as some browsers does not support
  1730. // the 'urls' attribute.
  1731. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1732. if (pcConfig === null) {
  1733. return;
  1734. }
  1735. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1736. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1737. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1738. delete pcConfig.iceServers[i].urls;
  1739. }
  1740. }
  1741. };
  1742. AdapterJS.addEvent = function(elem, evnt, func) {
  1743. if (elem.addEventListener) { // W3C DOM
  1744. elem.addEventListener(evnt, func, false);
  1745. } else if (elem.attachEvent) {// OLD IE DOM
  1746. elem.attachEvent('on'+evnt, func);
  1747. } else { // No much to do
  1748. elem[evnt] = func;
  1749. }
  1750. };
  1751. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1752. // only inject once the page is ready
  1753. if (document.readyState !== 'complete') {
  1754. return;
  1755. }
  1756. var w = window;
  1757. var i = document.createElement('iframe');
  1758. i.style.position = 'fixed';
  1759. i.style.top = '-41px';
  1760. i.style.left = 0;
  1761. i.style.right = 0;
  1762. i.style.width = '100%';
  1763. i.style.height = '40px';
  1764. i.style.backgroundColor = '#ffffe1';
  1765. i.style.border = 'none';
  1766. i.style.borderBottom = '1px solid #888888';
  1767. i.style.zIndex = '9999999';
  1768. if(typeof i.style.webkitTransition === 'string') {
  1769. i.style.webkitTransition = 'all .5s ease-out';
  1770. } else if(typeof i.style.transition === 'string') {
  1771. i.style.transition = 'all .5s ease-out';
  1772. }
  1773. document.body.appendChild(i);
  1774. c = (i.contentWindow) ? i.contentWindow :
  1775. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1776. c.document.open();
  1777. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1778. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1779. 'middle; cursor: default;">' + text + '</span>');
  1780. if(buttonText && buttonLink) {
  1781. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1782. c.document.close();
  1783. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1784. if (!!displayRefreshBar) {
  1785. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1786. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1787. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1788. }
  1789. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1790. e.preventDefault();
  1791. try {
  1792. event.cancelBubble = true;
  1793. } catch(error) { }
  1794. var pluginInstallInterval = setInterval(function(){
  1795. if(! isIE) {
  1796. navigator.plugins.refresh(false);
  1797. }
  1798. AdapterJS.WebRTCPlugin.isPluginInstalled(
  1799. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  1800. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  1801. function() {
  1802. clearInterval(pluginInstallInterval);
  1803. AdapterJS.WebRTCPlugin.defineWebRTCInterface()
  1804. },
  1805. function() { //Does nothing because not used here
  1806. });
  1807. } , 500);
  1808. });
  1809. }else {
  1810. c.document.close();
  1811. }
  1812. AdapterJS.addEvent(c.document, 'click', function() {
  1813. w.document.body.removeChild(i);
  1814. });
  1815. setTimeout(function() {
  1816. if(typeof i.style.webkitTransform === 'string') {
  1817. i.style.webkitTransform = 'translateY(40px)';
  1818. } else if(typeof i.style.transform === 'string') {
  1819. i.style.transform = 'translateY(40px)';
  1820. } else {
  1821. i.style.top = '0px';
  1822. }
  1823. }, 300);
  1824. };
  1825. // -----------------------------------------------------------
  1826. // Detected webrtc implementation. Types are:
  1827. // - 'moz': Mozilla implementation of webRTC.
  1828. // - 'webkit': WebKit implementation of webRTC.
  1829. // - 'plugin': Using the plugin implementation.
  1830. webrtcDetectedType = null;
  1831. // Detected webrtc datachannel support. Types are:
  1832. // - 'SCTP': SCTP datachannel support.
  1833. // - 'RTP': RTP datachannel support.
  1834. webrtcDetectedDCSupport = null;
  1835. // Set the settings for creating DataChannels, MediaStream for
  1836. // Cross-browser compability.
  1837. // - This is only for SCTP based support browsers.
  1838. // the 'urls' attribute.
  1839. checkMediaDataChannelSettings =
  1840. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1841. if (typeof callback !== 'function') {
  1842. return;
  1843. }
  1844. var beOfferer = true;
  1845. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1846. // Nightly version does not require MozDontOfferDataChannel for interop
  1847. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1848. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1849. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1850. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1851. // Resends an updated version of constraints for MozDataChannel to work
  1852. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1853. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1854. try {
  1855. delete constraints.mandatory.MozDontOfferDataChannel;
  1856. } catch (error) {
  1857. console.error('Failed deleting MozDontOfferDataChannel');
  1858. console.error(error);
  1859. }
  1860. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1861. constraints.mandatory.MozDontOfferDataChannel = true;
  1862. }
  1863. if (!isLocalFirefox) {
  1864. // temporary measure to remove Moz* constraints in non Firefox browsers
  1865. for (var prop in constraints.mandatory) {
  1866. if (constraints.mandatory.hasOwnProperty(prop)) {
  1867. if (prop.indexOf('Moz') !== -1) {
  1868. delete constraints.mandatory[prop];
  1869. }
  1870. }
  1871. }
  1872. }
  1873. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1874. // interopability of the media stream
  1875. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1876. beOfferer = false;
  1877. }
  1878. callback(beOfferer, constraints);
  1879. };
  1880. // Handles the differences for all browsers ice connection state output.
  1881. // - Tested outcomes are:
  1882. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1883. // - Chrome (answerer) : 'checking' > 'connected'
  1884. // - Firefox (offerer) : 'checking' > 'connected'
  1885. // - Firefox (answerer): 'checking' > 'connected'
  1886. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1887. if (typeof callback !== 'function') {
  1888. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1889. return;
  1890. }
  1891. peerId = (peerId) ? peerId : 'peer';
  1892. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1893. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1894. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1895. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1896. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1897. }
  1898. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1899. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1900. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1901. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1902. setTimeout(function () {
  1903. AdapterJS._iceConnectionFiredStates[peerId]
  1904. .push(AdapterJS._iceConnectionStates.done);
  1905. callback(AdapterJS._iceConnectionStates.done);
  1906. }, 1000);
  1907. }
  1908. callback(iceConnectionState);
  1909. }
  1910. return;
  1911. };
  1912. // Firefox:
  1913. // - Creates iceServer from the url for Firefox.
  1914. // - Create iceServer with stun url.
  1915. // - Create iceServer with turn url.
  1916. // - Ignore the transport parameter from TURN url for FF version <=27.
  1917. // - Return null for createIceServer if transport=tcp.
  1918. // - FF 27 and above supports transport parameters in TURN url,
  1919. // - So passing in the full url to create iceServer.
  1920. // Chrome:
  1921. // - Creates iceServer from the url for Chrome M33 and earlier.
  1922. // - Create iceServer with stun url.
  1923. // - Chrome M28 & above uses below TURN format.
  1924. // Plugin:
  1925. // - Creates Ice Server for Plugin Browsers
  1926. // - If Stun - Create iceServer with stun url.
  1927. // - Else - Create iceServer with turn url
  1928. // - This is a WebRTC Function
  1929. createIceServer = null;
  1930. // Firefox:
  1931. // - Creates IceServers for Firefox
  1932. // - Use .url for FireFox.
  1933. // - Multiple Urls support
  1934. // Chrome:
  1935. // - Creates iceServers from the urls for Chrome M34 and above.
  1936. // - .urls is supported since Chrome M34.
  1937. // - Multiple Urls support
  1938. // Plugin:
  1939. // - Creates Ice Servers for Plugin Browsers
  1940. // - Multiple Urls support
  1941. // - This is a WebRTC Function
  1942. createIceServers = null;
  1943. //------------------------------------------------------------
  1944. //The RTCPeerConnection object.
  1945. RTCPeerConnection = null;
  1946. // Creates RTCSessionDescription object for Plugin Browsers
  1947. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  1948. RTCSessionDescription : null;
  1949. // Creates RTCIceCandidate object for Plugin Browsers
  1950. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  1951. RTCIceCandidate : null;
  1952. // Get UserMedia (only difference is the prefix).
  1953. // Code from Adam Barth.
  1954. getUserMedia = null;
  1955. // Attach a media stream to an element.
  1956. attachMediaStream = null;
  1957. // Re-attach a media stream to an element.
  1958. reattachMediaStream = null;
  1959. // Detected browser agent name. Types are:
  1960. // - 'firefox': Firefox browser.
  1961. // - 'chrome': Chrome browser.
  1962. // - 'opera': Opera browser.
  1963. // - 'safari': Safari browser.
  1964. // - 'IE' - Internet Explorer browser.
  1965. webrtcDetectedBrowser = null;
  1966. // Detected browser version.
  1967. webrtcDetectedVersion = null;
  1968. // Check for browser types and react accordingly
  1969. if (navigator.mozGetUserMedia) {
  1970. webrtcDetectedBrowser = 'firefox';
  1971. webrtcDetectedVersion = parseInt(navigator
  1972. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1973. webrtcDetectedType = 'moz';
  1974. webrtcDetectedDCSupport = 'SCTP';
  1975. RTCPeerConnection = function (pcConfig, pcConstraints) {
  1976. AdapterJS.maybeFixConfiguration(pcConfig);
  1977. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  1978. };
  1979. // The RTCSessionDescription object.
  1980. RTCSessionDescription = mozRTCSessionDescription;
  1981. window.RTCSessionDescription = RTCSessionDescription;
  1982. // The RTCIceCandidate object.
  1983. RTCIceCandidate = mozRTCIceCandidate;
  1984. window.RTCIceCandidate = RTCIceCandidate;
  1985. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1986. navigator.getUserMedia = window.getUserMedia;
  1987. // Shim for MediaStreamTrack.getSources.
  1988. MediaStreamTrack.getSources = function(successCb) {
  1989. setTimeout(function() {
  1990. var infos = [
  1991. { kind: 'audio', id: 'default', label:'', facing:'' },
  1992. { kind: 'video', id: 'default', label:'', facing:'' }
  1993. ];
  1994. successCb(infos);
  1995. }, 0);
  1996. };
  1997. createIceServer = function (url, username, password) {
  1998. var iceServer = null;
  1999. var url_parts = url.split(':');
  2000. if (url_parts[0].indexOf('stun') === 0) {
  2001. iceServer = { url : url };
  2002. } else if (url_parts[0].indexOf('turn') === 0) {
  2003. if (webrtcDetectedVersion < 27) {
  2004. var turn_url_parts = url.split('?');
  2005. if (turn_url_parts.length === 1 ||
  2006. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2007. iceServer = {
  2008. url : turn_url_parts[0],
  2009. credential : password,
  2010. username : username
  2011. };
  2012. }
  2013. } else {
  2014. iceServer = {
  2015. url : url,
  2016. credential : password,
  2017. username : username
  2018. };
  2019. }
  2020. }
  2021. return iceServer;
  2022. };
  2023. createIceServers = function (urls, username, password) {
  2024. var iceServers = [];
  2025. for (i = 0; i < urls.length; i++) {
  2026. var iceServer = createIceServer(urls[i], username, password);
  2027. if (iceServer !== null) {
  2028. iceServers.push(iceServer);
  2029. }
  2030. }
  2031. return iceServers;
  2032. };
  2033. attachMediaStream = function (element, stream) {
  2034. element.mozSrcObject = stream;
  2035. if (stream !== null)
  2036. element.play();
  2037. return element;
  2038. };
  2039. reattachMediaStream = function (to, from) {
  2040. to.mozSrcObject = from.mozSrcObject;
  2041. to.play();
  2042. return to;
  2043. };
  2044. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2045. if (!callback) {
  2046. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2047. ': 1 argument required, but only 0 present.');
  2048. }
  2049. return callback([]);
  2050. };
  2051. // Fake get{Video,Audio}Tracks
  2052. if (!MediaStream.prototype.getVideoTracks) {
  2053. MediaStream.prototype.getVideoTracks = function () {
  2054. return [];
  2055. };
  2056. }
  2057. if (!MediaStream.prototype.getAudioTracks) {
  2058. MediaStream.prototype.getAudioTracks = function () {
  2059. return [];
  2060. };
  2061. }
  2062. AdapterJS.maybeThroughWebRTCReady();
  2063. } else if (navigator.webkitGetUserMedia) {
  2064. webrtcDetectedBrowser = 'chrome';
  2065. webrtcDetectedType = 'webkit';
  2066. webrtcDetectedVersion = parseInt(navigator
  2067. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2068. // check if browser is opera 20+
  2069. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2070. if (checkIfOpera !== null) {
  2071. webrtcDetectedBrowser = 'opera';
  2072. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2073. }
  2074. // check browser datachannel support
  2075. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2076. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2077. webrtcDetectedDCSupport = 'SCTP';
  2078. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2079. webrtcDetectedVersion > 24) {
  2080. webrtcDetectedDCSupport = 'RTP';
  2081. } else {
  2082. webrtcDetectedDCSupport = '';
  2083. }
  2084. createIceServer = function (url, username, password) {
  2085. var iceServer = null;
  2086. var url_parts = url.split(':');
  2087. if (url_parts[0].indexOf('stun') === 0) {
  2088. iceServer = { 'url' : url };
  2089. } else if (url_parts[0].indexOf('turn') === 0) {
  2090. iceServer = {
  2091. 'url' : url,
  2092. 'credential' : password,
  2093. 'username' : username
  2094. };
  2095. }
  2096. return iceServer;
  2097. };
  2098. createIceServers = function (urls, username, password) {
  2099. var iceServers = [];
  2100. if (webrtcDetectedVersion >= 34) {
  2101. iceServers = {
  2102. 'urls' : urls,
  2103. 'credential' : password,
  2104. 'username' : username
  2105. };
  2106. } else {
  2107. for (i = 0; i < urls.length; i++) {
  2108. var iceServer = createIceServer(urls[i], username, password);
  2109. if (iceServer !== null) {
  2110. iceServers.push(iceServer);
  2111. }
  2112. }
  2113. }
  2114. return iceServers;
  2115. };
  2116. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2117. if (webrtcDetectedVersion < 34) {
  2118. AdapterJS.maybeFixConfiguration(pcConfig);
  2119. }
  2120. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2121. };
  2122. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2123. navigator.getUserMedia = window.getUserMedia;
  2124. attachMediaStream = function (element, stream) {
  2125. if (typeof element.srcObject !== 'undefined') {
  2126. element.srcObject = stream;
  2127. } else if (typeof element.mozSrcObject !== 'undefined') {
  2128. element.mozSrcObject = stream;
  2129. } else if (typeof element.src !== 'undefined') {
  2130. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2131. } else {
  2132. console.log('Error attaching stream to element.');
  2133. }
  2134. return element;
  2135. };
  2136. reattachMediaStream = function (to, from) {
  2137. to.src = from.src;
  2138. return to;
  2139. };
  2140. AdapterJS.maybeThroughWebRTCReady();
  2141. } else { // TRY TO USE PLUGIN
  2142. // IE 9 is not offering an implementation of console.log until you open a console
  2143. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2144. /* jshint -W020 */
  2145. console = {} || console;
  2146. // Implemented based on console specs from MDN
  2147. // You may override these functions
  2148. console.log = function (arg) {};
  2149. console.info = function (arg) {};
  2150. console.error = function (arg) {};
  2151. console.dir = function (arg) {};
  2152. console.exception = function (arg) {};
  2153. console.trace = function (arg) {};
  2154. console.warn = function (arg) {};
  2155. console.count = function (arg) {};
  2156. console.debug = function (arg) {};
  2157. console.count = function (arg) {};
  2158. console.time = function (arg) {};
  2159. console.timeEnd = function (arg) {};
  2160. console.group = function (arg) {};
  2161. console.groupCollapsed = function (arg) {};
  2162. console.groupEnd = function (arg) {};
  2163. /* jshint +W020 */
  2164. }
  2165. webrtcDetectedType = 'plugin';
  2166. webrtcDetectedDCSupport = 'plugin';
  2167. AdapterJS.parseWebrtcDetectedBrowser();
  2168. isIE = webrtcDetectedBrowser === 'IE';
  2169. /* jshint -W035 */
  2170. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2171. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2172. /* empty because it needs to prevent the function from running. */
  2173. }
  2174. };
  2175. /* jshint +W035 */
  2176. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2177. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2178. // Call immediately if possible
  2179. // Once the plugin is set, the code will always take this path
  2180. callback();
  2181. } else {
  2182. // otherwise start a 100ms interval
  2183. var checkPluginReadyState = setInterval(function () {
  2184. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2185. clearInterval(checkPluginReadyState);
  2186. callback();
  2187. }
  2188. }, 100);
  2189. }
  2190. };
  2191. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2192. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2193. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2194. });
  2195. };
  2196. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2197. // only inject once the page is ready
  2198. if (document.readyState !== 'complete') {
  2199. return;
  2200. }
  2201. // Prevent multiple injections
  2202. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2203. return;
  2204. }
  2205. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2206. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2207. var frag = document.createDocumentFragment();
  2208. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2209. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2210. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2211. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2212. '<param name="pluginId" value="' +
  2213. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2214. '<param name="windowless" value="false" /> ' +
  2215. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2216. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2217. '" />' +
  2218. // uncomment to be able to use virtual cams
  2219. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2220. '</object>';
  2221. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2222. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2223. }
  2224. document.body.appendChild(frag);
  2225. // Need to re-fetch the plugin
  2226. AdapterJS.WebRTCPlugin.plugin =
  2227. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2228. } else {
  2229. // Load Plugin
  2230. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2231. AdapterJS.WebRTCPlugin.plugin.id =
  2232. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2233. // IE will only start the plugin if it's ACTUALLY visible
  2234. if (isIE) {
  2235. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2236. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2237. } else { // The size of the plugin on Safari should be 0x0px
  2238. // so that the autorisation prompt is at the top
  2239. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2240. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2241. }
  2242. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2243. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2244. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2245. '<param name="pluginId" value="' +
  2246. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2247. '<param name="windowless" value="false" /> ' +
  2248. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2249. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2250. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2251. }
  2252. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2253. };
  2254. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2255. function (comName, plugName, installedCb, notInstalledCb) {
  2256. if (!isIE) {
  2257. var pluginArray = navigator.plugins;
  2258. for (var i = 0; i < pluginArray.length; i++) {
  2259. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2260. installedCb();
  2261. return;
  2262. }
  2263. }
  2264. notInstalledCb();
  2265. } else {
  2266. try {
  2267. var axo = new ActiveXObject(comName + '.' + plugName);
  2268. } catch (e) {
  2269. notInstalledCb();
  2270. return;
  2271. }
  2272. installedCb();
  2273. }
  2274. };
  2275. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2276. if (AdapterJS.WebRTCPlugin.pluginState ===
  2277. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2278. console.error("WebRTC interface has been defined already");
  2279. return;
  2280. }
  2281. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2282. AdapterJS.isDefined = function (variable) {
  2283. return variable !== null && variable !== undefined;
  2284. };
  2285. createIceServer = function (url, username, password) {
  2286. var iceServer = null;
  2287. var url_parts = url.split(':');
  2288. if (url_parts[0].indexOf('stun') === 0) {
  2289. iceServer = {
  2290. 'url' : url,
  2291. 'hasCredentials' : false
  2292. };
  2293. } else if (url_parts[0].indexOf('turn') === 0) {
  2294. iceServer = {
  2295. 'url' : url,
  2296. 'hasCredentials' : true,
  2297. 'credential' : password,
  2298. 'username' : username
  2299. };
  2300. }
  2301. return iceServer;
  2302. };
  2303. createIceServers = function (urls, username, password) {
  2304. var iceServers = [];
  2305. for (var i = 0; i < urls.length; ++i) {
  2306. iceServers.push(createIceServer(urls[i], username, password));
  2307. }
  2308. return iceServers;
  2309. };
  2310. RTCSessionDescription = function (info) {
  2311. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2312. return AdapterJS.WebRTCPlugin.plugin.
  2313. ConstructSessionDescription(info.type, info.sdp);
  2314. };
  2315. RTCPeerConnection = function (servers, constraints) {
  2316. var iceServers = null;
  2317. if (servers) {
  2318. iceServers = servers.iceServers;
  2319. for (var i = 0; i < iceServers.length; i++) {
  2320. if (iceServers[i].urls && !iceServers[i].url) {
  2321. iceServers[i].url = iceServers[i].urls;
  2322. }
  2323. iceServers[i].hasCredentials = AdapterJS.
  2324. isDefined(iceServers[i].username) &&
  2325. AdapterJS.isDefined(iceServers[i].credential);
  2326. }
  2327. }
  2328. var mandatory = (constraints && constraints.mandatory) ?
  2329. constraints.mandatory : null;
  2330. var optional = (constraints && constraints.optional) ?
  2331. constraints.optional : null;
  2332. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2333. return AdapterJS.WebRTCPlugin.plugin.
  2334. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2335. iceServers, mandatory, optional);
  2336. };
  2337. MediaStreamTrack = {};
  2338. MediaStreamTrack.getSources = function (callback) {
  2339. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2340. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2341. });
  2342. };
  2343. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2344. constraints.audio = constraints.audio || false;
  2345. constraints.video = constraints.video || false;
  2346. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2347. AdapterJS.WebRTCPlugin.plugin.
  2348. getUserMedia(constraints, successCallback, failureCallback);
  2349. });
  2350. };
  2351. window.navigator.getUserMedia = window.getUserMedia;
  2352. attachMediaStream = function (element, stream) {
  2353. if (!element || !element.parentNode) {
  2354. return;
  2355. }
  2356. var streamId
  2357. if (stream === null) {
  2358. streamId = '';
  2359. }
  2360. else {
  2361. stream.enableSoundTracks(true);
  2362. streamId = stream.id;
  2363. }
  2364. if (element.nodeName.toLowerCase() !== 'audio') {
  2365. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2366. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2367. var frag = document.createDocumentFragment();
  2368. var temp = document.createElement('div');
  2369. var classHTML = '';
  2370. if (element.className) {
  2371. classHTML = 'class="' + element.className + '" ';
  2372. } else if (element.attributes && element.attributes['class']) {
  2373. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2374. }
  2375. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2376. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2377. '<param name="pluginId" value="' + elementId + '" /> ' +
  2378. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2379. '<param name="windowless" value="true" /> ' +
  2380. '<param name="streamId" value="' + streamId + '" /> ' +
  2381. '</object>';
  2382. while (temp.firstChild) {
  2383. frag.appendChild(temp.firstChild);
  2384. }
  2385. var height = '';
  2386. var width = '';
  2387. if (element.getBoundingClientRect) {
  2388. var rectObject = element.getBoundingClientRect();
  2389. width = rectObject.width + 'px';
  2390. height = rectObject.height + 'px';
  2391. }
  2392. else if (element.width) {
  2393. width = element.width;
  2394. height = element.height;
  2395. } else {
  2396. // TODO: What scenario could bring us here?
  2397. }
  2398. element.parentNode.insertBefore(frag, element);
  2399. frag = document.getElementById(elementId);
  2400. frag.width = width;
  2401. frag.height = height;
  2402. element.parentNode.removeChild(element);
  2403. } else {
  2404. var children = element.children;
  2405. for (var i = 0; i !== children.length; ++i) {
  2406. if (children[i].name === 'streamId') {
  2407. children[i].value = streamId;
  2408. break;
  2409. }
  2410. }
  2411. element.setStreamId(streamId);
  2412. }
  2413. var newElement = document.getElementById(elementId);
  2414. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2415. if (isIE) { // on IE the event needs to be plugged manually
  2416. newElement.attachEvent('onplaying', newElement.onplaying);
  2417. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2418. newElement._TemOnClick = function (id) {
  2419. var arg = {
  2420. srcElement : document.getElementById(id)
  2421. };
  2422. newElement.onclick(arg);
  2423. };
  2424. }
  2425. return newElement;
  2426. } else {
  2427. return element;
  2428. }
  2429. };
  2430. reattachMediaStream = function (to, from) {
  2431. var stream = null;
  2432. var children = from.children;
  2433. for (var i = 0; i !== children.length; ++i) {
  2434. if (children[i].name === 'streamId') {
  2435. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2436. stream = AdapterJS.WebRTCPlugin.plugin
  2437. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2438. break;
  2439. }
  2440. }
  2441. if (stream !== null) {
  2442. return attachMediaStream(to, stream);
  2443. } else {
  2444. console.log('Could not find the stream associated with this element');
  2445. }
  2446. };
  2447. RTCIceCandidate = function (candidate) {
  2448. if (!candidate.sdpMid) {
  2449. candidate.sdpMid = '';
  2450. }
  2451. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2452. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2453. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2454. );
  2455. };
  2456. // inject plugin
  2457. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2458. AdapterJS.WebRTCPlugin.injectPlugin();
  2459. };
  2460. // This function will be called if the plugin is needed (browser different
  2461. // from Chrome or Firefox), but the plugin is not installed.
  2462. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2463. function() {
  2464. AdapterJS.addEvent(document,
  2465. 'readystatechange',
  2466. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2467. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2468. };
  2469. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2470. if (AdapterJS.options.hidePluginInstallPrompt) {
  2471. return;
  2472. }
  2473. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2474. if(downloadLink) { // if download link
  2475. var popupString;
  2476. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2477. popupString = 'This website requires you to install the ' +
  2478. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2479. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2480. ' WebRTC Plugin</a>' +
  2481. ' to work on this browser.';
  2482. } else { // no portal link, just print a generic explanation
  2483. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2484. }
  2485. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2486. } else { // no download link, just print a generic explanation
  2487. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2488. }
  2489. };
  2490. // Try to detect the plugin and act accordingly
  2491. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2492. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2493. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2494. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2495. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2496. }
  2497. (function () {
  2498. 'use strict';
  2499. var baseGetUserMedia = null;
  2500. AdapterJS.TEXT.EXTENSION = {
  2501. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2502. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2503. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2504. BUTTON_FF: 'Install Now',
  2505. BUTTON_CHROME: 'Go to Chrome Web Store'
  2506. };
  2507. var clone = function(obj) {
  2508. if (null == obj || "object" != typeof obj) return obj;
  2509. var copy = obj.constructor();
  2510. for (var attr in obj) {
  2511. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2512. }
  2513. return copy;
  2514. };
  2515. if (window.navigator.mozGetUserMedia) {
  2516. baseGetUserMedia = window.navigator.getUserMedia;
  2517. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2518. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2519. // intercepting screensharing requests
  2520. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2521. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2522. }
  2523. var updatedConstraints = clone(constraints);
  2524. //constraints.video.mediaSource = constraints.video.mediaSource;
  2525. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2526. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2527. // strange but this works anyway
  2528. var checkIfReady = setInterval(function () {
  2529. if (document.readyState === 'complete') {
  2530. clearInterval(checkIfReady);
  2531. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2532. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2533. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2534. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2535. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2536. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2537. } else {
  2538. failureCb(error);
  2539. }
  2540. });
  2541. }
  2542. }, 1);
  2543. } else { // regular GetUserMediaRequest
  2544. baseGetUserMedia(constraints, successCb, failureCb);
  2545. }
  2546. };
  2547. getUserMedia = navigator.getUserMedia;
  2548. } else if (window.navigator.webkitGetUserMedia) {
  2549. baseGetUserMedia = window.navigator.getUserMedia;
  2550. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2551. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2552. if (window.webrtcDetectedBrowser !== 'chrome') {
  2553. throw new Error('Current browser does not support screensharing');
  2554. }
  2555. // would be fine since no methods
  2556. var updatedConstraints = clone(constraints);
  2557. var chromeCallback = function(error, sourceId) {
  2558. if(!error) {
  2559. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2560. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2561. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2562. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2563. if (sourceId) {
  2564. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2565. }
  2566. delete updatedConstraints.video.mediaSource;
  2567. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2568. } else {
  2569. if (error === 'permission-denied') {
  2570. throw new Error('Permission denied for screen retrieval');
  2571. } else {
  2572. throw new Error('Failed retrieving selected screen');
  2573. }
  2574. }
  2575. };
  2576. var onIFrameCallback = function (event) {
  2577. if (!event.data) {
  2578. return;
  2579. }
  2580. if (event.data.chromeMediaSourceId) {
  2581. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2582. chromeCallback('permission-denied');
  2583. } else {
  2584. chromeCallback(null, event.data.chromeMediaSourceId);
  2585. }
  2586. }
  2587. if (event.data.chromeExtensionStatus) {
  2588. if (event.data.chromeExtensionStatus === 'not-installed') {
  2589. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2590. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2591. event.data.data, true, true);
  2592. } else {
  2593. chromeCallback(event.data.chromeExtensionStatus, null);
  2594. }
  2595. }
  2596. // this event listener is no more needed
  2597. window.removeEventListener('message', onIFrameCallback);
  2598. };
  2599. window.addEventListener('message', onIFrameCallback);
  2600. postFrameMessage({
  2601. captureSourceId: true
  2602. });
  2603. } else {
  2604. baseGetUserMedia(constraints, successCb, failureCb);
  2605. }
  2606. };
  2607. getUserMedia = navigator.getUserMedia;
  2608. } else {
  2609. baseGetUserMedia = window.navigator.getUserMedia;
  2610. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2611. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2612. // would be fine since no methods
  2613. var updatedConstraints = clone(constraints);
  2614. // wait for plugin to be ready
  2615. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2616. // check if screensharing feature is available
  2617. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2618. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2619. // set the constraints
  2620. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2621. updatedConstraints.video.optional.push({
  2622. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2623. });
  2624. delete updatedConstraints.video.mediaSource;
  2625. } else {
  2626. throw new Error('Your WebRTC plugin does not support screensharing');
  2627. }
  2628. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2629. });
  2630. } else {
  2631. baseGetUserMedia(constraints, successCb, failureCb);
  2632. }
  2633. };
  2634. getUserMedia = window.navigator.getUserMedia;
  2635. }
  2636. if (window.webrtcDetectedBrowser === 'chrome') {
  2637. var iframe = document.createElement('iframe');
  2638. iframe.onload = function() {
  2639. iframe.isLoaded = true;
  2640. };
  2641. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2642. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2643. iframe.style.display = 'none';
  2644. (document.body || document.documentElement).appendChild(iframe);
  2645. var postFrameMessage = function (object) {
  2646. object = object || {};
  2647. if (!iframe.isLoaded) {
  2648. setTimeout(function () {
  2649. iframe.contentWindow.postMessage(object, '*');
  2650. }, 100);
  2651. return;
  2652. }
  2653. iframe.contentWindow.postMessage(object, '*');
  2654. };
  2655. }
  2656. })();
  2657. },{}],11:[function(require,module,exports){
  2658. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2659. var UI = {};
  2660. var VideoLayout = require("./videolayout/VideoLayout.js");
  2661. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2662. var Prezi = require("./prezi/Prezi.js");
  2663. var Etherpad = require("./etherpad/Etherpad.js");
  2664. var Chat = require("./side_pannels/chat/Chat.js");
  2665. var Toolbar = require("./toolbars/Toolbar");
  2666. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2667. var BottomToolbar = require("./toolbars/BottomToolbar");
  2668. var ContactList = require("./side_pannels/contactlist/ContactList");
  2669. var Avatar = require("./avatar/Avatar");
  2670. var EventEmitter = require("events");
  2671. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2672. var Settings = require("./../settings/Settings");
  2673. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2674. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2675. UI.messageHandler = require("./util/MessageHandler");
  2676. var messageHandler = UI.messageHandler;
  2677. var Authentication = require("./authentication/Authentication");
  2678. var UIUtil = require("./util/UIUtil");
  2679. var NicknameHandler = require("./util/NicknameHandler");
  2680. var JitsiPopover = require("./util/JitsiPopover");
  2681. var CQEvents = require("../../service/connectionquality/CQEvents");
  2682. var DesktopSharingEventTypes
  2683. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2684. var RTCEvents = require("../../service/RTC/RTCEvents");
  2685. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2686. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2687. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2688. var UIEvents = require("../../service/UI/UIEvents");
  2689. var MemberEvents = require("../../service/members/Events");
  2690. var eventEmitter = new EventEmitter();
  2691. var roomName = null;
  2692. function promptDisplayName() {
  2693. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2694. message += APP.translation.translateString(
  2695. "dialog.displayNameRequired");
  2696. message += '</h2>' +
  2697. '<input name="displayName" type="text" data-i18n=' +
  2698. '"[placeholder]defaultNickname" placeholder="' +
  2699. APP.translation.translateString(
  2700. "defaultNickname", {name: "Jane Pink"}) +
  2701. '" autofocus>';
  2702. var buttonTxt
  2703. = APP.translation.generateTranslationHTML("dialog.Ok");
  2704. var buttons = [];
  2705. buttons.push({title: buttonTxt, value: "ok"});
  2706. messageHandler.openDialog(null, message,
  2707. true,
  2708. buttons,
  2709. function (e, v, m, f) {
  2710. if (v == "ok") {
  2711. var displayName = f.displayName;
  2712. if (displayName) {
  2713. VideoLayout.inputDisplayNameHandler(displayName);
  2714. return true;
  2715. }
  2716. }
  2717. e.preventDefault();
  2718. },
  2719. function () {
  2720. var form = $.prompt.getPrompt();
  2721. var input = form.find("input[name='displayName']");
  2722. input.focus();
  2723. var button = form.find("button");
  2724. button.attr("disabled", "disabled");
  2725. input.keyup(function () {
  2726. if(!input.val())
  2727. button.attr("disabled", "disabled");
  2728. else
  2729. button.removeAttr("disabled");
  2730. });
  2731. }
  2732. );
  2733. }
  2734. function notifyForInitialMute() {
  2735. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2736. "notify.muted", null, {timeOut: 120000});
  2737. }
  2738. function setupPrezi() {
  2739. $("#reloadPresentationLink").click(function() {
  2740. Prezi.reloadPresentation();
  2741. });
  2742. }
  2743. function setupChat() {
  2744. Chat.init();
  2745. $("#toggle_smileys").click(function() {
  2746. Chat.toggleSmileys();
  2747. });
  2748. }
  2749. function setupToolbars() {
  2750. Toolbar.init(UI);
  2751. Toolbar.setupButtonsFromConfig();
  2752. BottomToolbar.init();
  2753. }
  2754. function streamHandler(stream, isMuted) {
  2755. switch (stream.type) {
  2756. case "audio":
  2757. VideoLayout.changeLocalAudio(stream, isMuted);
  2758. break;
  2759. case "video":
  2760. VideoLayout.changeLocalVideo(stream, isMuted);
  2761. break;
  2762. case "stream":
  2763. VideoLayout.changeLocalStream(stream, isMuted);
  2764. break;
  2765. }
  2766. }
  2767. function onXmppConnectionFailed(stropheErrorMsg) {
  2768. var title = APP.translation.generateTranslationHTML(
  2769. "dialog.error");
  2770. var message;
  2771. if (stropheErrorMsg) {
  2772. message = APP.translation.generateTranslationHTML(
  2773. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2774. } else {
  2775. message = APP.translation.generateTranslationHTML(
  2776. "dialog.connectError");
  2777. }
  2778. messageHandler.openDialog(
  2779. title, message, true, {}, function (e, v, m, f) { return false; });
  2780. }
  2781. function onDisposeConference(unload) {
  2782. Toolbar.showAuthenticateButton(false);
  2783. }
  2784. function onDisplayNameChanged(jid, displayName) {
  2785. ContactList.onDisplayNameChange(jid, displayName);
  2786. SettingsMenu.onDisplayNameChange(jid, displayName);
  2787. VideoLayout.onDisplayNameChanged(jid, displayName);
  2788. }
  2789. function registerListeners() {
  2790. APP.RTC.addStreamListener(streamHandler,
  2791. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2792. APP.RTC.addStreamListener(streamHandler,
  2793. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2794. APP.RTC.addStreamListener(function (stream) {
  2795. VideoLayout.onRemoteStreamAdded(stream);
  2796. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2797. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2798. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  2799. function (resourceJid) {
  2800. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2801. });
  2802. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2803. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2804. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2805. endpointsEnteringLastN, stream);
  2806. });
  2807. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2808. function (devices) {
  2809. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2810. });
  2811. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  2812. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function () {
  2813. // when the data channel becomes available, tell the bridge about video
  2814. // selections so that it can do adaptive simulcast,
  2815. // we want the notification to trigger even if userJid is undefined,
  2816. // or null.
  2817. var userResource = APP.UI.getLargeVideoResource();
  2818. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userResource);
  2819. });
  2820. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  2821. var resourceJid;
  2822. if(jid === APP.statistics.LOCAL_JID) {
  2823. resourceJid = AudioLevels.LOCAL_LEVEL;
  2824. if(APP.RTC.localAudio.isMuted()) {
  2825. audioLevel = 0;
  2826. }
  2827. } else {
  2828. resourceJid = Strophe.getResourceFromJid(jid);
  2829. }
  2830. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2831. UI.getLargeVideoResource());
  2832. });
  2833. APP.desktopsharing.addListener(function () {
  2834. ToolbarToggler.showDesktopSharingButton();
  2835. }, DesktopSharingEventTypes.INIT);
  2836. APP.desktopsharing.addListener(
  2837. Toolbar.changeDesktopSharingButtonState,
  2838. DesktopSharingEventTypes.SWITCHING_DONE);
  2839. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2840. VideoLayout.updateLocalConnectionStats);
  2841. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2842. VideoLayout.updateConnectionStats);
  2843. APP.connectionquality.addListener(CQEvents.STOP,
  2844. VideoLayout.onStatsStop);
  2845. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2846. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2847. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2848. messageHandler.openMessageDialog(
  2849. 'dialog.serviceUnavailable',
  2850. 'dialog.gracefulShutdown'
  2851. );
  2852. });
  2853. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2854. var title = APP.translation.generateTranslationHTML(
  2855. "dialog.reservationError");
  2856. var message = APP.translation.generateTranslationHTML(
  2857. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2858. messageHandler.openDialog(
  2859. title,
  2860. message,
  2861. true, {},
  2862. function (event, value, message, formVals) {
  2863. return false;
  2864. }
  2865. );
  2866. });
  2867. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2868. messageHandler.openMessageDialog("dialog.sessTerminated",
  2869. "dialog.kickMessage");
  2870. });
  2871. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2872. //FIXME: use Session Terminated from translation, but
  2873. // 'reason' text comes from XMPP packet and is not translated
  2874. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2875. messageHandler.openDialog(
  2876. title, reason, true, {},
  2877. function (event, value, message, formVals) {
  2878. return false;
  2879. }
  2880. );
  2881. });
  2882. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2883. messageHandler.showError("dialog.error",
  2884. "dialog.bridgeUnavailable");
  2885. });
  2886. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2887. Avatar.setUserAvatar(from, id);
  2888. });
  2889. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2890. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2891. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2892. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2893. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2894. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2895. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2896. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2897. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2898. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2899. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2900. onAuthenticationRequired);
  2901. APP.xmpp.addListener(XMPPEvents.VIDEO_TYPE, onPeerVideoTypeChanged);
  2902. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2903. function (resource, devices) {
  2904. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2905. });
  2906. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  2907. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  2908. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function (doMuteAudio) {
  2909. UI.setAudioMuted(doMuteAudio);
  2910. });
  2911. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2912. onDtmfSupportChanged);
  2913. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  2914. SettingsMenu.setStartMuted(audio, video);
  2915. });
  2916. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  2917. UI.setInitialMuteFromFocus(audio, video);
  2918. });
  2919. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  2920. UI.messageHandler.showError("dialog.sorry",
  2921. "dialog.internalError");
  2922. });
  2923. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function () {
  2924. messageHandler.showError("dialog.error",
  2925. "dialog.SLDFailure");
  2926. });
  2927. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function () {
  2928. messageHandler.showError("dialog.error",
  2929. "dialog.SRDFailure");
  2930. });
  2931. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function () {
  2932. messageHandler.showError();
  2933. });
  2934. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function () {
  2935. // FIXME: re-use LoginDialog which supports retries
  2936. UI.showLoginPopup(connect);
  2937. });
  2938. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focusComponent, retrySec) {
  2939. UI.messageHandler.notify(
  2940. null, "notify.focus",
  2941. 'disconnected', "notify.focusFail",
  2942. {component: focusComponent, ms: retrySec});
  2943. });
  2944. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  2945. UI.messageHandler.openReportDialog(null,
  2946. "dialog.joinError", pres);
  2947. });
  2948. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  2949. UI.messageHandler.openReportDialog(null,
  2950. "dialog.connectError", pres);
  2951. });
  2952. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function () {
  2953. var roomName = UI.generateRoomName();
  2954. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  2955. });
  2956. //NicknameHandler emits this event
  2957. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  2958. APP.xmpp.addToPresence("displayName", nickname);
  2959. });
  2960. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  2961. AudioLevels.init();
  2962. });
  2963. if (!interfaceConfig.filmStripOnly) {
  2964. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2965. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2966. // Listens for video interruption events.
  2967. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  2968. // Listens for video restores events.
  2969. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  2970. }
  2971. }
  2972. /**
  2973. * Mutes/unmutes the local video.
  2974. *
  2975. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2976. * @param options an object which specifies optional arguments such as the
  2977. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2978. * specifies whether the method was initiated in response to a user command (in
  2979. * contrast to an automatic decision taken by the application logic)
  2980. */
  2981. function setVideoMute(mute, options) {
  2982. APP.RTC.setVideoMute(mute,
  2983. UI.setVideoMuteButtonsState,
  2984. options);
  2985. }
  2986. function onResize() {
  2987. Chat.resizeChat();
  2988. VideoLayout.resizeLargeVideoContainer();
  2989. }
  2990. function bindEvents() {
  2991. /**
  2992. * Resizes and repositions videos in full screen mode.
  2993. */
  2994. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  2995. onResize);
  2996. $(window).resize(onResize);
  2997. }
  2998. UI.start = function (init) {
  2999. document.title = interfaceConfig.APP_NAME;
  3000. var setupWelcomePage = null;
  3001. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3002. (!window.localStorage.welcomePageDisabled ||
  3003. window.localStorage.welcomePageDisabled == "false")) {
  3004. $("#videoconference_page").hide();
  3005. if (!setupWelcomePage)
  3006. setupWelcomePage = require("./welcome_page/WelcomePage");
  3007. setupWelcomePage();
  3008. return;
  3009. }
  3010. $("#welcome_page").hide();
  3011. // Set the defaults for prompt dialogs.
  3012. $.prompt.setDefaults({persistent: false});
  3013. registerListeners();
  3014. VideoLayout.init(eventEmitter);
  3015. NicknameHandler.init(eventEmitter);
  3016. bindEvents();
  3017. setupPrezi();
  3018. if (!interfaceConfig.filmStripOnly) {
  3019. $("#videospace").mousemove(function () {
  3020. return ToolbarToggler.showToolbar();
  3021. });
  3022. setupToolbars();
  3023. setupChat();
  3024. // Display notice message at the top of the toolbar
  3025. if (config.noticeMessage) {
  3026. $('#noticeText').text(config.noticeMessage);
  3027. $('#notice').css({display: 'block'});
  3028. }
  3029. $("#downloadlog").click(function (event) {
  3030. dump(event.target);
  3031. });
  3032. }
  3033. else
  3034. {
  3035. $("#header").css("display", "none");
  3036. $("#bottomToolbar").css("display", "none");
  3037. $("#downloadlog").css("display", "none");
  3038. $("#remoteVideos").css("padding", "0px 0px 18px 0px");
  3039. $("#remoteVideos").css("right", "0px");
  3040. messageHandler.disableNotifications();
  3041. $('body').popover("disable");
  3042. // $("[data-toggle=popover]").popover("disable");
  3043. JitsiPopover.enabled = false;
  3044. }
  3045. document.title = interfaceConfig.APP_NAME;
  3046. if(config.requireDisplayName) {
  3047. var currentSettings = Settings.getSettings();
  3048. if (!currentSettings.displayName) {
  3049. promptDisplayName();
  3050. }
  3051. }
  3052. init();
  3053. if (!interfaceConfig.filmStripOnly) {
  3054. toastr.options = {
  3055. "closeButton": true,
  3056. "debug": false,
  3057. "positionClass": "notification-bottom-right",
  3058. "onclick": null,
  3059. "showDuration": "300",
  3060. "hideDuration": "1000",
  3061. "timeOut": "2000",
  3062. "extendedTimeOut": "1000",
  3063. "showEasing": "swing",
  3064. "hideEasing": "linear",
  3065. "showMethod": "fadeIn",
  3066. "hideMethod": "fadeOut",
  3067. "reposition": function () {
  3068. if (PanelToggler.isVisible()) {
  3069. $("#toast-container").addClass("notification-bottom-right-center");
  3070. } else {
  3071. $("#toast-container").removeClass("notification-bottom-right-center");
  3072. }
  3073. },
  3074. "newestOnTop": false
  3075. };
  3076. SettingsMenu.init();
  3077. }
  3078. };
  3079. function chatAddError(errorMessage, originalText) {
  3080. return Chat.chatAddError(errorMessage, originalText);
  3081. }
  3082. function chatSetSubject(text) {
  3083. return Chat.chatSetSubject(text);
  3084. }
  3085. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3086. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3087. }
  3088. function onMucJoined(jid, info) {
  3089. Toolbar.updateRoomUrl(window.location.href);
  3090. var meHTML = APP.translation.generateTranslationHTML("me");
  3091. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3092. var settings = Settings.getSettings();
  3093. // Make sure we configure our avatar id, before creating avatar for us
  3094. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3095. // Add myself to the contact list.
  3096. ContactList.addContact(jid);
  3097. // Once we've joined the muc show the toolbar
  3098. ToolbarToggler.showToolbar();
  3099. var displayName =
  3100. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3101. if (displayName)
  3102. onDisplayNameChanged('localVideoContainer', displayName);
  3103. VideoLayout.mucJoined();
  3104. }
  3105. function initEtherpad(name) {
  3106. Etherpad.init(name);
  3107. }
  3108. function onMucMemberLeft(jid) {
  3109. console.log('left.muc', jid);
  3110. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3111. '>.displayname').html();
  3112. messageHandler.notify(displayName,'notify.somebody',
  3113. 'disconnected',
  3114. 'notify.disconnected');
  3115. if (!config.startAudioMuted ||
  3116. config.startAudioMuted > APP.members.size()) {
  3117. UIUtil.playSoundNotification('userLeft');
  3118. }
  3119. ContactList.removeContact(jid);
  3120. VideoLayout.participantLeft(jid);
  3121. }
  3122. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3123. console.info("My role changed, new role: " + info.role);
  3124. onModeratorStatusChanged(isModerator);
  3125. VideoLayout.showModeratorIndicator();
  3126. SettingsMenu.onRoleChanged();
  3127. if (isModerator) {
  3128. Authentication.closeAuthenticationWindow();
  3129. messageHandler.notify(null, "notify.me",
  3130. 'connected', "notify.moderator");
  3131. Toolbar.checkAutoRecord();
  3132. }
  3133. }
  3134. function onModeratorStatusChanged(isModerator) {
  3135. Toolbar.showSipCallButton(isModerator);
  3136. Toolbar.showRecordingButton(
  3137. isModerator); //&&
  3138. // FIXME:
  3139. // Recording visible if
  3140. // there are at least 2(+ 1 focus) participants
  3141. //Object.keys(connection.emuc.members).length >= 3);
  3142. }
  3143. function onPasswordRequired(callback) {
  3144. // password is required
  3145. Toolbar.lockLockButton();
  3146. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3147. message += APP.translation.translateString(
  3148. "dialog.passwordRequired");
  3149. message += '</h2>' +
  3150. '<input name="lockKey" type="text" data-i18n=' +
  3151. '"[placeholder]dialog.password" placeholder="' +
  3152. APP.translation.translateString("dialog.password") +
  3153. '" autofocus>';
  3154. messageHandler.openTwoButtonDialog(null, null, null, message,
  3155. true,
  3156. "dialog.Ok",
  3157. function (e, v, m, f) {},
  3158. null,
  3159. function (e, v, m, f) {
  3160. if (v) {
  3161. var lockKey = f.lockKey;
  3162. if (lockKey) {
  3163. Toolbar.setSharedKey(lockKey);
  3164. callback(lockKey);
  3165. }
  3166. }
  3167. },
  3168. ':input:first'
  3169. );
  3170. }
  3171. /**
  3172. * The dialpad button is shown iff there is at least one member that supports
  3173. * DTMF (e.g. jigasi).
  3174. */
  3175. function onDtmfSupportChanged(dtmfSupport) {
  3176. //TODO: enable when the UI is ready
  3177. //Toolbar.showDialPadButton(dtmfSupport);
  3178. }
  3179. function onMucMemberJoined(jid, id, displayName) {
  3180. messageHandler.notify(displayName,'notify.somebody',
  3181. 'connected',
  3182. 'notify.connected');
  3183. if (!config.startAudioMuted ||
  3184. config.startAudioMuted > APP.members.size())
  3185. UIUtil.playSoundNotification('userJoined');
  3186. // Configure avatar
  3187. Avatar.setUserAvatar(jid, id);
  3188. // Add Peer's container
  3189. VideoLayout.ensurePeerContainerExists(jid);
  3190. }
  3191. function onMucPresenceStatus(jid, info) {
  3192. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3193. }
  3194. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3195. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3196. }
  3197. function onMucRoleChanged(role, displayName) {
  3198. VideoLayout.showModeratorIndicator();
  3199. if (role === 'moderator') {
  3200. var messageKey, messageOptions = {};
  3201. if (!displayName) {
  3202. messageKey = "notify.grantedToUnknown";
  3203. }
  3204. else {
  3205. messageKey = "notify.grantedTo";
  3206. messageOptions = {to: displayName};
  3207. }
  3208. messageHandler.notify(
  3209. displayName,'notify.somebody',
  3210. 'connected', messageKey,
  3211. messageOptions);
  3212. }
  3213. }
  3214. function onAuthenticationRequired(intervalCallback) {
  3215. Authentication.openAuthenticationDialog(
  3216. roomName, intervalCallback, function () {
  3217. Toolbar.authenticateClicked();
  3218. });
  3219. }
  3220. function onLastNChanged(oldValue, newValue) {
  3221. if (config.muteLocalVideoIfNotInLastN) {
  3222. setVideoMute(!newValue, { 'byUser': false });
  3223. }
  3224. }
  3225. UI.toggleSmileys = function () {
  3226. Chat.toggleSmileys();
  3227. };
  3228. UI.getSettings = function () {
  3229. return Settings.getSettings();
  3230. };
  3231. UI.toggleFilmStrip = function () {
  3232. return BottomToolbar.toggleFilmStrip();
  3233. };
  3234. UI.toggleChat = function () {
  3235. return BottomToolbar.toggleChat();
  3236. };
  3237. UI.toggleContactList = function () {
  3238. return BottomToolbar.toggleContactList();
  3239. };
  3240. UI.inputDisplayNameHandler = function (value) {
  3241. VideoLayout.inputDisplayNameHandler(value);
  3242. };
  3243. UI.getLargeVideoResource = function () {
  3244. return VideoLayout.getLargeVideoResource();
  3245. };
  3246. UI.generateRoomName = function() {
  3247. if(roomName)
  3248. return roomName;
  3249. var roomnode = null;
  3250. var path = window.location.pathname;
  3251. // determinde the room node from the url
  3252. // TODO: just the roomnode or the whole bare jid?
  3253. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3254. // custom function might be responsible for doing the pushstate
  3255. roomnode = config.getroomnode(path);
  3256. } else {
  3257. /* fall back to default strategy
  3258. * this is making assumptions about how the URL->room mapping happens.
  3259. * It currently assumes deployment at root, with a rewrite like the
  3260. * following one (for nginx):
  3261. location ~ ^/([a-zA-Z0-9]+)$ {
  3262. rewrite ^/(.*)$ / break;
  3263. }
  3264. */
  3265. if (path.length > 1) {
  3266. roomnode = path.substr(1).toLowerCase();
  3267. } else {
  3268. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3269. roomnode = word.toLowerCase();
  3270. window.history.pushState('VideoChat',
  3271. 'Room: ' + word, window.location.pathname + word);
  3272. }
  3273. }
  3274. roomName = roomnode + '@' + config.hosts.muc;
  3275. return roomName;
  3276. };
  3277. UI.connectionIndicatorShowMore = function(jid) {
  3278. return VideoLayout.showMore(jid);
  3279. };
  3280. UI.showLoginPopup = function(callback) {
  3281. console.log('password is required');
  3282. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3283. message += APP.translation.translateString(
  3284. "dialog.passwordRequired");
  3285. message += '</h2>' +
  3286. '<input name="username" type="text" ' +
  3287. 'placeholder="user@domain.net" autofocus>' +
  3288. '<input name="password" ' +
  3289. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3290. ' placeholder="user password">';
  3291. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3292. true,
  3293. "dialog.Ok",
  3294. function (e, v, m, f) {
  3295. if (v) {
  3296. if (f.username !== null && f.password != null) {
  3297. callback(f.username, f.password);
  3298. }
  3299. }
  3300. },
  3301. null, null, ':input:first'
  3302. );
  3303. };
  3304. UI.checkForNicknameAndJoin = function () {
  3305. Authentication.closeAuthenticationDialog();
  3306. Authentication.stopInterval();
  3307. var nick = null;
  3308. if (config.useNicks) {
  3309. nick = window.prompt('Your nickname (optional)');
  3310. }
  3311. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3312. };
  3313. function dump(elem, filename) {
  3314. elem = elem.parentNode;
  3315. elem.download = filename || 'meetlog.json';
  3316. elem.href = 'data:application/json;charset=utf-8,\n';
  3317. var data = APP.xmpp.getJingleLog();
  3318. var metadata = {};
  3319. metadata.time = new Date();
  3320. metadata.url = window.location.href;
  3321. metadata.ua = navigator.userAgent;
  3322. var log = APP.xmpp.getXmppLog();
  3323. if (log) {
  3324. metadata.xmpp = log;
  3325. }
  3326. data.metadata = metadata;
  3327. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3328. return false;
  3329. }
  3330. UI.getRoomName = function () {
  3331. return roomName;
  3332. };
  3333. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3334. if (muteAudio || muteVideo)
  3335. notifyForInitialMute();
  3336. if (muteAudio)
  3337. UI.setAudioMuted(true);
  3338. if (muteVideo)
  3339. UI.setVideoMute(true);
  3340. };
  3341. /**
  3342. * Mutes/unmutes the local video.
  3343. */
  3344. UI.toggleVideo = function () {
  3345. setVideoMute(!APP.RTC.localVideo.isMuted());
  3346. };
  3347. /**
  3348. * Mutes / unmutes audio for the local participant.
  3349. */
  3350. UI.toggleAudio = function() {
  3351. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3352. };
  3353. /**
  3354. * Sets muted audio state for the local participant.
  3355. */
  3356. UI.setAudioMuted = function (mute, earlyMute) {
  3357. var audioMute = null;
  3358. if (earlyMute)
  3359. audioMute = function (mute, cb) {
  3360. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3361. };
  3362. else
  3363. audioMute = function (mute, cb) {
  3364. return APP.xmpp.setAudioMute(mute, cb);
  3365. };
  3366. if (!audioMute(mute, function () {
  3367. VideoLayout.showLocalAudioIndicator(mute);
  3368. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3369. })) {
  3370. // We still click the button.
  3371. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3372. return;
  3373. }
  3374. };
  3375. UI.addListener = function (type, listener) {
  3376. eventEmitter.on(type, listener);
  3377. };
  3378. UI.clickOnVideo = function (videoNumber) {
  3379. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3380. if (remoteVideos.length > videoNumber) {
  3381. remoteVideos[videoNumber].click();
  3382. }
  3383. };
  3384. //Used by torture
  3385. UI.showToolbar = function () {
  3386. return ToolbarToggler.showToolbar();
  3387. };
  3388. //Used by torture
  3389. UI.dockToolbar = function (isDock) {
  3390. return ToolbarToggler.dockToolbar(isDock);
  3391. };
  3392. UI.setVideoMuteButtonsState = function (mute) {
  3393. var video = $('#toolbar_button_camera');
  3394. var communicativeClass = "icon-camera";
  3395. var muteClass = "icon-camera icon-camera-disabled";
  3396. if (mute) {
  3397. video.removeClass(communicativeClass);
  3398. video.addClass(muteClass);
  3399. } else {
  3400. video.removeClass(muteClass);
  3401. video.addClass(communicativeClass);
  3402. }
  3403. };
  3404. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3405. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3406. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3407. if(resourceJid === APP.xmpp.myResource())
  3408. SettingsMenu.changeAvatar(thumbUrl);
  3409. };
  3410. UI.setVideoMute = setVideoMute;
  3411. module.exports = UI;
  3412. },{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes":154,"../../service/UI/UIEvents":155,"../../service/connectionquality/CQEvents":157,"../../service/desktopsharing/DesktopSharingEventTypes":158,"../../service/members/Events":159,"../../service/xmpp/XMPPEvents":161,"../RTC/RTCBrowserType":8,"./../settings/Settings":47,"./audio_levels/AudioLevels.js":12,"./authentication/Authentication":14,"./avatar/Avatar":16,"./etherpad/Etherpad.js":17,"./prezi/Prezi.js":18,"./side_pannels/SidePanelToggler":20,"./side_pannels/chat/Chat.js":21,"./side_pannels/contactlist/ContactList":25,"./side_pannels/settings/SettingsMenu":26,"./toolbars/BottomToolbar":27,"./toolbars/Toolbar":28,"./toolbars/ToolbarToggler":29,"./util/JitsiPopover":30,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":162}],12:[function(require,module,exports){
  3413. /* global APP, interfaceConfig, $, Strophe */
  3414. var CanvasUtil = require("./CanvasUtils");
  3415. var ASDrawContext = null;
  3416. function initActiveSpeakerAudioLevels() {
  3417. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3418. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3419. // Draw a circle.
  3420. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3421. // Add a shadow around the circle
  3422. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3423. ASDrawContext.shadowOffsetX = 0;
  3424. ASDrawContext.shadowOffsetY = 0;
  3425. }
  3426. /**
  3427. * The audio Levels plugin.
  3428. */
  3429. var AudioLevels = (function(my) {
  3430. var audioLevelCanvasCache = {};
  3431. my.LOCAL_LEVEL = 'local';
  3432. my.init = function () {
  3433. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3434. initActiveSpeakerAudioLevels();
  3435. };
  3436. /**
  3437. * Updates the audio level canvas for the given peerJid. If the canvas
  3438. * didn't exist we create it.
  3439. */
  3440. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3441. var resourceJid = null;
  3442. var videoSpanId = null;
  3443. if (!peerJid)
  3444. videoSpanId = 'localVideoContainer';
  3445. else {
  3446. resourceJid = Strophe.getResourceFromJid(peerJid);
  3447. videoSpanId = 'participant_' + resourceJid;
  3448. }
  3449. var videoSpan = document.getElementById(videoSpanId);
  3450. if (!videoSpan) {
  3451. if (resourceJid)
  3452. console.error("No video element for jid", resourceJid);
  3453. else
  3454. console.error("No video element for local video.");
  3455. return;
  3456. }
  3457. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3458. var videoSpaceWidth = $('#remoteVideos').width();
  3459. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3460. var thumbnailWidth = thumbnailSize[0];
  3461. var thumbnailHeight = thumbnailSize[1];
  3462. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3463. audioLevelCanvas = document.createElement('canvas');
  3464. audioLevelCanvas.className = "audiolevel";
  3465. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3466. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3467. resizeAudioLevelCanvas( audioLevelCanvas,
  3468. thumbnailWidth,
  3469. thumbnailHeight);
  3470. videoSpan.appendChild(audioLevelCanvas);
  3471. } else {
  3472. audioLevelCanvas = audioLevelCanvas.get(0);
  3473. resizeAudioLevelCanvas( audioLevelCanvas,
  3474. thumbnailWidth,
  3475. thumbnailHeight);
  3476. }
  3477. };
  3478. /**
  3479. * Updates the audio level UI for the given resourceJid.
  3480. *
  3481. * @param resourceJid the resource jid indicating the video element for
  3482. * which we draw the audio level
  3483. * @param audioLevel the newAudio level to render
  3484. */
  3485. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3486. drawAudioLevelCanvas(resourceJid, audioLevel);
  3487. var videoSpanId = getVideoSpanId(resourceJid);
  3488. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3489. if (!audioLevelCanvas)
  3490. return;
  3491. var drawContext = audioLevelCanvas.getContext('2d');
  3492. var canvasCache = audioLevelCanvasCache[resourceJid];
  3493. drawContext.clearRect (0, 0,
  3494. audioLevelCanvas.width, audioLevelCanvas.height);
  3495. drawContext.drawImage(canvasCache, 0, 0);
  3496. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3497. if(!APP.xmpp.myJid()) {
  3498. return;
  3499. }
  3500. resourceJid = APP.xmpp.myResource();
  3501. }
  3502. if(resourceJid === largeVideoResourceJid) {
  3503. window.requestAnimationFrame(function () {
  3504. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3505. });
  3506. }
  3507. };
  3508. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3509. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3510. return;
  3511. ASDrawContext.clearRect(0, 0, 300, 300);
  3512. if(audioLevel == 0)
  3513. return;
  3514. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3515. // Fill the shape.
  3516. ASDrawContext.fill();
  3517. };
  3518. /**
  3519. * Resizes the given audio level canvas to match the given thumbnail size.
  3520. */
  3521. function resizeAudioLevelCanvas(audioLevelCanvas,
  3522. thumbnailWidth,
  3523. thumbnailHeight) {
  3524. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3525. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3526. }
  3527. /**
  3528. * Draws the audio level canvas into the cached canvas object.
  3529. *
  3530. * @param resourceJid the resource jid indicating the video element for
  3531. * which we draw the audio level
  3532. * @param audioLevel the newAudio level to render
  3533. */
  3534. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3535. if (!audioLevelCanvasCache[resourceJid]) {
  3536. var videoSpanId = getVideoSpanId(resourceJid);
  3537. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3538. /*
  3539. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3540. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3541. * error. Since audio levels are frequently updated, the errors have
  3542. * been observed to pile into the console, strain the CPU.
  3543. */
  3544. if (audioLevelCanvasOrig) {
  3545. audioLevelCanvasCache[resourceJid] =
  3546. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3547. }
  3548. }
  3549. var canvas = audioLevelCanvasCache[resourceJid];
  3550. if (!canvas)
  3551. return;
  3552. var drawContext = canvas.getContext('2d');
  3553. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3554. var shadowLevel = getShadowLevel(audioLevel);
  3555. if (shadowLevel > 0) {
  3556. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3557. CanvasUtil.drawRoundRectGlow(drawContext,
  3558. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3559. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3560. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3561. interfaceConfig.CANVAS_RADIUS,
  3562. interfaceConfig.SHADOW_COLOR,
  3563. shadowLevel);
  3564. }
  3565. }
  3566. /**
  3567. * Returns the shadow/glow level for the given audio level.
  3568. *
  3569. * @param audioLevel the audio level from which we determine the shadow
  3570. * level
  3571. */
  3572. function getShadowLevel (audioLevel) {
  3573. var shadowLevel = 0;
  3574. if (audioLevel <= 0.3) {
  3575. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3576. }
  3577. else if (audioLevel <= 0.6) {
  3578. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3579. }
  3580. else {
  3581. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3582. }
  3583. return shadowLevel;
  3584. }
  3585. /**
  3586. * Returns the video span id corresponding to the given resourceJid or local
  3587. * user.
  3588. */
  3589. function getVideoSpanId(resourceJid) {
  3590. var videoSpanId = null;
  3591. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3592. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3593. videoSpanId = 'localVideoContainer';
  3594. else
  3595. videoSpanId = 'participant_' + resourceJid;
  3596. return videoSpanId;
  3597. }
  3598. /**
  3599. * Indicates that the remote video has been resized.
  3600. */
  3601. $(document).bind('remotevideo.resized', function (event, width, height) {
  3602. var resized = false;
  3603. $('#remoteVideos>span>canvas').each(function() {
  3604. var canvas = $(this).get(0);
  3605. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3606. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3607. resized = true;
  3608. }
  3609. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3610. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3611. resized = true;
  3612. }
  3613. });
  3614. if (resized)
  3615. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3616. audioLevelCanvasCache[resourceJid].width =
  3617. width + interfaceConfig.CANVAS_EXTRA;
  3618. audioLevelCanvasCache[resourceJid].height =
  3619. height + interfaceConfig.CANVAS_EXTRA;
  3620. });
  3621. });
  3622. return my;
  3623. })(AudioLevels || {});
  3624. module.exports = AudioLevels;
  3625. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3626. /**
  3627. * Utility class for drawing canvas shapes.
  3628. */
  3629. var CanvasUtil = (function(my) {
  3630. /**
  3631. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3632. * of the glow.
  3633. *
  3634. * @param drawContext the context of the canvas to draw to
  3635. * @param x the x coordinate of the round rectangle
  3636. * @param y the y coordinate of the round rectangle
  3637. * @param w the width of the round rectangle
  3638. * @param h the height of the round rectangle
  3639. * @param glowColor the color of the glow
  3640. * @param glowWidth the width of the glow
  3641. */
  3642. my.drawRoundRectGlow
  3643. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3644. // Save the previous state of the context.
  3645. drawContext.save();
  3646. if (w < 2 * r) r = w / 2;
  3647. if (h < 2 * r) r = h / 2;
  3648. // Draw a round rectangle.
  3649. drawContext.beginPath();
  3650. drawContext.moveTo(x+r, y);
  3651. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3652. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3653. drawContext.arcTo(x, y+h, x, y, r);
  3654. drawContext.arcTo(x, y, x+w, y, r);
  3655. drawContext.closePath();
  3656. // Add a shadow around the rectangle
  3657. drawContext.shadowColor = glowColor;
  3658. drawContext.shadowBlur = glowWidth;
  3659. drawContext.shadowOffsetX = 0;
  3660. drawContext.shadowOffsetY = 0;
  3661. // Fill the shape.
  3662. drawContext.fill();
  3663. drawContext.save();
  3664. drawContext.restore();
  3665. // 1) Uncomment this line to use Composite Operation, which is doing the
  3666. // same as the clip function below and is also antialiasing the round
  3667. // border, but is said to be less fast performance wise.
  3668. // drawContext.globalCompositeOperation='destination-out';
  3669. drawContext.beginPath();
  3670. drawContext.moveTo(x+r, y);
  3671. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3672. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3673. drawContext.arcTo(x, y+h, x, y, r);
  3674. drawContext.arcTo(x, y, x+w, y, r);
  3675. drawContext.closePath();
  3676. // 2) Uncomment this line to use Composite Operation, which is doing the
  3677. // same as the clip function below and is also antialiasing the round
  3678. // border, but is said to be less fast performance wise.
  3679. // drawContext.fill();
  3680. // Comment these two lines if choosing to do the same with composite
  3681. // operation above 1 and 2.
  3682. drawContext.clip();
  3683. drawContext.clearRect(0, 0, 277, 200);
  3684. // Restore the previous context state.
  3685. drawContext.restore();
  3686. };
  3687. /**
  3688. * Clones the given canvas.
  3689. *
  3690. * @return the new cloned canvas.
  3691. */
  3692. my.cloneCanvas = function (oldCanvas) {
  3693. /*
  3694. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3695. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3696. * levels are frequently updated, the errors have been observed to pile
  3697. * into the console, strain the CPU.
  3698. */
  3699. if (!oldCanvas)
  3700. return oldCanvas;
  3701. //create a new canvas
  3702. var newCanvas = document.createElement('canvas');
  3703. var context = newCanvas.getContext('2d');
  3704. //set dimensions
  3705. newCanvas.width = oldCanvas.width;
  3706. newCanvas.height = oldCanvas.height;
  3707. //apply the old canvas to the new one
  3708. context.drawImage(oldCanvas, 0, 0);
  3709. //return the new canvas
  3710. return newCanvas;
  3711. };
  3712. return my;
  3713. })(CanvasUtil || {});
  3714. module.exports = CanvasUtil;
  3715. },{}],14:[function(require,module,exports){
  3716. /* global $, APP*/
  3717. var LoginDialog = require('./LoginDialog');
  3718. var Moderator = require('../../xmpp/moderator');
  3719. /* Initial "authentication required" dialog */
  3720. var authDialog = null;
  3721. /* Loop retry ID that wits for other user to create the room */
  3722. var authRetryId = null;
  3723. var authenticationWindow = null;
  3724. var Authentication = {
  3725. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3726. // This is the loop that will wait for the room to be created by
  3727. // someone else. 'auth_required.moderator' will bring us back here.
  3728. authRetryId = window.setTimeout(intervalCallback, 5000);
  3729. // Show prompt only if it's not open
  3730. if (authDialog !== null) {
  3731. return;
  3732. }
  3733. // extract room name from 'room@muc.server.net'
  3734. var room = roomName.substr(0, roomName.indexOf('@'));
  3735. var title
  3736. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3737. var msg
  3738. = APP.translation.generateTranslationHTML(
  3739. "dialog.WaitForHostMsg", {room: room});
  3740. var buttonTxt
  3741. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3742. var buttons = [];
  3743. buttons.push({title: buttonTxt, value: "authNow"});
  3744. authDialog = APP.UI.messageHandler.openDialog(
  3745. title,
  3746. msg,
  3747. true,
  3748. buttons,
  3749. function (onSubmitEvent, submitValue) {
  3750. // Do not close the dialog yet
  3751. onSubmitEvent.preventDefault();
  3752. // Open login popup
  3753. if (submitValue === 'authNow') {
  3754. callback();
  3755. }
  3756. }
  3757. );
  3758. },
  3759. closeAuthenticationWindow: function () {
  3760. if (authenticationWindow) {
  3761. authenticationWindow.close();
  3762. authenticationWindow = null;
  3763. }
  3764. },
  3765. xmppAuthenticate: function () {
  3766. var loginDialog = LoginDialog.show(
  3767. function (connection, state) {
  3768. if (!state) {
  3769. // User cancelled
  3770. loginDialog.close();
  3771. return;
  3772. } else if (state == APP.xmpp.Status.CONNECTED) {
  3773. loginDialog.close();
  3774. Authentication.stopInterval();
  3775. Authentication.closeAuthenticationDialog();
  3776. // Close the connection as anonymous one will be used
  3777. // to create the conference. Session-id will authorize
  3778. // the request.
  3779. connection.disconnect();
  3780. var roomName = APP.UI.generateRoomName();
  3781. Moderator.allocateConferenceFocus(roomName, function () {
  3782. // If it's not "on the fly" authentication now join
  3783. // the conference room
  3784. if (!APP.xmpp.isMUCJoined()) {
  3785. APP.UI.checkForNicknameAndJoin();
  3786. }
  3787. });
  3788. }
  3789. }, true);
  3790. },
  3791. focusAuthenticationWindow: function () {
  3792. // If auth window exists just bring it to the front
  3793. if (authenticationWindow) {
  3794. authenticationWindow.focus();
  3795. return;
  3796. }
  3797. },
  3798. closeAuthenticationDialog: function () {
  3799. // Close authentication dialog if opened
  3800. if (authDialog) {
  3801. authDialog.close();
  3802. authDialog = null;
  3803. }
  3804. },
  3805. createAuthenticationWindow: function (callback, url) {
  3806. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3807. url, 910, 660,
  3808. // On closed
  3809. function () {
  3810. // Close authentication dialog if opened
  3811. Authentication.closeAuthenticationDialog();
  3812. callback();
  3813. authenticationWindow = null;
  3814. });
  3815. return authenticationWindow;
  3816. },
  3817. stopInterval: function () {
  3818. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3819. if (authRetryId) {
  3820. window.clearTimeout(authRetryId);
  3821. authRetryId = null;
  3822. }
  3823. }
  3824. };
  3825. module.exports = Authentication;
  3826. },{"../../xmpp/moderator":60,"./LoginDialog":15}],15:[function(require,module,exports){
  3827. /* global $, APP, config*/
  3828. var XMPP = require('../../xmpp/xmpp');
  3829. var Moderator = require('../../xmpp/moderator');
  3830. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3831. // anonymous domain is not enabled
  3832. /**
  3833. * Creates new <tt>Dialog</tt> instance.
  3834. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3835. * when we either fail to connect or succeed(check Strophe.Status).
  3836. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3837. * in order to create session-id after the connection is established.
  3838. * @constructor
  3839. */
  3840. function Dialog(callback, obtainSession) {
  3841. var self = this;
  3842. var stop = false;
  3843. var connection = APP.xmpp.createConnection();
  3844. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3845. message += APP.translation.translateString("dialog.passwordRequired");
  3846. message += '</h2>' +
  3847. '<input name="username" type="text" ' +
  3848. 'placeholder="user@domain.net" autofocus>' +
  3849. '<input name="password" ' +
  3850. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3851. ' placeholder="user password">';
  3852. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3853. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3854. var states = {
  3855. login: {
  3856. html: message,
  3857. buttons: [
  3858. { title: okButton, value: true},
  3859. { title: cancelButton, value: false}
  3860. ],
  3861. focus: ':input:first',
  3862. submit: function (e, v, m, f) {
  3863. e.preventDefault();
  3864. if (v) {
  3865. var jid = f.username;
  3866. var password = f.password;
  3867. if (jid && password) {
  3868. stop = false;
  3869. connection.reset();
  3870. connDialog.goToState('connecting');
  3871. connection.connect(jid, password, stateHandler);
  3872. }
  3873. } else {
  3874. // User cancelled
  3875. stop = true;
  3876. callback();
  3877. }
  3878. }
  3879. },
  3880. connecting: {
  3881. title: APP.translation.translateString('dialog.connecting'),
  3882. html: '<div id="connectionStatus"></div>',
  3883. buttons: [],
  3884. defaultButton: 0
  3885. },
  3886. finished: {
  3887. title: APP.translation.translateString('dialog.error'),
  3888. html: '<div id="errorMessage"></div>',
  3889. buttons: [
  3890. {
  3891. title: APP.translation.translateString('dialog.retry'),
  3892. value: 'retry'
  3893. },
  3894. {
  3895. title: APP.translation.translateString('dialog.Cancel'),
  3896. value: 'cancel'
  3897. },
  3898. ],
  3899. defaultButton: 0,
  3900. submit: function (e, v, m, f) {
  3901. e.preventDefault();
  3902. if (v === 'retry')
  3903. connDialog.goToState('login');
  3904. else
  3905. callback();
  3906. }
  3907. }
  3908. };
  3909. var connDialog
  3910. = APP.UI.messageHandler.openDialogWithStates(states,
  3911. { persistent: true, closeText: '' }, null);
  3912. var stateHandler = function (status, message) {
  3913. if (stop) {
  3914. return;
  3915. }
  3916. var translateKey = "connection." + XMPP.getStatusString(status);
  3917. var statusStr = APP.translation.translateString(translateKey);
  3918. // Display current state
  3919. var connectionStatus =
  3920. connDialog.getState('connecting').find('#connectionStatus');
  3921. connectionStatus.text(statusStr);
  3922. switch (status) {
  3923. case XMPP.Status.CONNECTED:
  3924. stop = true;
  3925. if (!obtainSession) {
  3926. callback(connection, status);
  3927. return;
  3928. }
  3929. // Obtaining session-id status
  3930. connectionStatus.text(
  3931. APP.translation.translateString(
  3932. 'connection.FETCH_SESSION_ID'));
  3933. // Authenticate with Jicofo and obtain session-id
  3934. var roomName = APP.UI.generateRoomName();
  3935. // Jicofo will return new session-id when connected
  3936. // from authenticated domain
  3937. connection.sendIQ(
  3938. Moderator.createConferenceIq(roomName),
  3939. function (result) {
  3940. connectionStatus.text(
  3941. APP.translation.translateString(
  3942. 'connection.GOT_SESSION_ID'));
  3943. stop = true;
  3944. // Parse session-id
  3945. Moderator.parseSessionId(result);
  3946. callback(connection, status);
  3947. },
  3948. function (error) {
  3949. console.error("Auth on the fly failed", error);
  3950. stop = true;
  3951. var errorMsg =
  3952. APP.translation.translateString(
  3953. 'connection.GET_SESSION_ID_ERROR') +
  3954. $(error).find('>error').attr('code');
  3955. self.displayError(errorMsg);
  3956. connection.disconnect();
  3957. });
  3958. break;
  3959. case XMPP.Status.AUTHFAIL:
  3960. case XMPP.Status.CONNFAIL:
  3961. case XMPP.Status.DISCONNECTED:
  3962. stop = true;
  3963. callback(connection, status);
  3964. var errorMessage = statusStr;
  3965. if (message)
  3966. {
  3967. errorMessage += ': ' + message;
  3968. }
  3969. self.displayError(errorMessage);
  3970. break;
  3971. default:
  3972. break;
  3973. }
  3974. };
  3975. /**
  3976. * Displays error message in 'finished' state which allows either to cancel
  3977. * or retry.
  3978. * @param message the final message to be displayed.
  3979. */
  3980. this.displayError = function (message) {
  3981. var finishedState = connDialog.getState('finished');
  3982. var errorMessageElem = finishedState.find('#errorMessage');
  3983. errorMessageElem.text(message);
  3984. connDialog.goToState('finished');
  3985. };
  3986. /**
  3987. * Closes LoginDialog.
  3988. */
  3989. this.close = function () {
  3990. stop = true;
  3991. connDialog.close();
  3992. };
  3993. }
  3994. var LoginDialog = {
  3995. /**
  3996. * Displays login prompt used to establish new XMPP connection. Given
  3997. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  3998. * called when we connect successfully(status === CONNECTED) or when we fail
  3999. * to do so. On connection failure program can call Dialog.close() method in
  4000. * order to cancel or do nothing to let the user retry.
  4001. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4002. * called when we either fail to connect or succeed(check
  4003. * Strophe.Status).
  4004. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4005. * Jicofo in order to create session-id after the connection is
  4006. * established.
  4007. * @returns {Dialog}
  4008. */
  4009. show: function (callback, obtainSession) {
  4010. return new Dialog(callback, obtainSession);
  4011. }
  4012. };
  4013. module.exports = LoginDialog;
  4014. },{"../../xmpp/moderator":60,"../../xmpp/xmpp":68}],16:[function(require,module,exports){
  4015. var Settings = require("../../settings/Settings");
  4016. var users = {};
  4017. var Avatar = {
  4018. /**
  4019. * Sets the user's avatar in the settings menu(if local user), contact list
  4020. * and thumbnail
  4021. * @param jid jid of the user
  4022. * @param id email or userID to be used as a hash
  4023. */
  4024. setUserAvatar: function (jid, id) {
  4025. if (id) {
  4026. if (users[jid] === id) {
  4027. return;
  4028. }
  4029. users[jid] = id;
  4030. }
  4031. var thumbUrl = this.getThumbUrl(jid);
  4032. var contactListUrl = this.getContactListUrl(jid);
  4033. var resourceJid = Strophe.getResourceFromJid(jid);
  4034. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4035. },
  4036. /**
  4037. * Returns image URL for the avatar to be displayed on large video area
  4038. * where current active speaker is presented.
  4039. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4040. */
  4041. getActiveSpeakerUrl: function (jid) {
  4042. return this.getGravatarUrl(jid, 100);
  4043. },
  4044. /**
  4045. * Returns image URL for the avatar to be displayed on small video thumbnail
  4046. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4047. */
  4048. getThumbUrl: function (jid) {
  4049. return this.getGravatarUrl(jid, 100);
  4050. },
  4051. /**
  4052. * Returns the URL for the avatar to be displayed as contactlist item
  4053. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4054. */
  4055. getContactListUrl: function (jid) {
  4056. return this.getGravatarUrl(jid, 30);
  4057. },
  4058. getGravatarUrl: function (jid, size) {
  4059. if (!jid) {
  4060. console.error("Get gravatar - jid is undefined");
  4061. return null;
  4062. }
  4063. var id = users[jid];
  4064. if (!id) {
  4065. console.warn(
  4066. "No avatar stored yet for " + jid + " - using JID as ID");
  4067. id = jid;
  4068. }
  4069. return 'https://www.gravatar.com/avatar/' +
  4070. MD5.hexdigest(id.trim().toLowerCase()) +
  4071. "?d=wavatar&size=" + (size || "30");
  4072. }
  4073. };
  4074. module.exports = Avatar;
  4075. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4076. /* global $, config,
  4077. setLargeVideoVisible, Util */
  4078. var VideoLayout = require("../videolayout/VideoLayout");
  4079. var Prezi = require("../prezi/Prezi");
  4080. var UIUtil = require("../util/UIUtil");
  4081. var etherpadName = null;
  4082. var etherpadIFrame = null;
  4083. var domain = null;
  4084. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4085. /**
  4086. * Resizes the etherpad.
  4087. */
  4088. function resize() {
  4089. if ($('#etherpad>iframe').length) {
  4090. var remoteVideos = $('#remoteVideos');
  4091. var availableHeight
  4092. = window.innerHeight - remoteVideos.outerHeight();
  4093. var availableWidth = UIUtil.getAvailableVideoWidth();
  4094. $('#etherpad>iframe').width(availableWidth);
  4095. $('#etherpad>iframe').height(availableHeight);
  4096. }
  4097. }
  4098. /**
  4099. * Creates the Etherpad button and adds it to the toolbar.
  4100. */
  4101. function enableEtherpadButton() {
  4102. if (!$('#toolbar_button_etherpad').is(":visible"))
  4103. $('#toolbar_button_etherpad').css({display: 'inline-block'});
  4104. }
  4105. /**
  4106. * Creates the IFrame for the etherpad.
  4107. */
  4108. function createIFrame() {
  4109. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4110. domain + etherpadName + options, function() {
  4111. document.domain = document.domain;
  4112. bubbleIframeMouseMove(etherpadIFrame);
  4113. setTimeout(function() {
  4114. // the iframes inside of the etherpad are
  4115. // not yet loaded when the etherpad iframe is loaded
  4116. var outer = etherpadIFrame.
  4117. contentDocument.getElementsByName("ace_outer")[0];
  4118. bubbleIframeMouseMove(outer);
  4119. var inner = outer.
  4120. contentDocument.getElementsByName("ace_inner")[0];
  4121. bubbleIframeMouseMove(inner);
  4122. }, 2000);
  4123. });
  4124. }
  4125. function bubbleIframeMouseMove(iframe){
  4126. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4127. iframe.contentWindow.onmousemove = function(e){
  4128. if(existingOnMouseMove) existingOnMouseMove(e);
  4129. var evt = document.createEvent("MouseEvents");
  4130. var boundingClientRect = iframe.getBoundingClientRect();
  4131. evt.initMouseEvent(
  4132. "mousemove",
  4133. true, // bubbles
  4134. false, // not cancelable
  4135. window,
  4136. e.detail,
  4137. e.screenX,
  4138. e.screenY,
  4139. e.clientX + boundingClientRect.left,
  4140. e.clientY + boundingClientRect.top,
  4141. e.ctrlKey,
  4142. e.altKey,
  4143. e.shiftKey,
  4144. e.metaKey,
  4145. e.button,
  4146. null // no related element
  4147. );
  4148. iframe.dispatchEvent(evt);
  4149. };
  4150. }
  4151. var Etherpad = {
  4152. /**
  4153. * Initializes the etherpad.
  4154. */
  4155. init: function (name) {
  4156. if (config.etherpad_base && !etherpadName && name) {
  4157. domain = config.etherpad_base;
  4158. etherpadName = name;
  4159. enableEtherpadButton();
  4160. /**
  4161. * Resizes the etherpad, when the window is resized.
  4162. */
  4163. $(window).resize(function () {
  4164. resize();
  4165. });
  4166. }
  4167. },
  4168. /**
  4169. * Opens/hides the Etherpad.
  4170. */
  4171. toggleEtherpad: function (isPresentation) {
  4172. if (!etherpadIFrame)
  4173. createIFrame();
  4174. if(VideoLayout.getLargeVideoState() === "etherpad")
  4175. {
  4176. VideoLayout.setLargeVideoState("video");
  4177. }
  4178. else
  4179. {
  4180. VideoLayout.setLargeVideoState("etherpad");
  4181. }
  4182. resize();
  4183. }
  4184. };
  4185. module.exports = Etherpad;
  4186. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4187. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4188. var UIUtil = require("../util/UIUtil");
  4189. var VideoLayout = require("../videolayout/VideoLayout");
  4190. var messageHandler = require("../util/MessageHandler");
  4191. var PreziPlayer = require("./PreziPlayer");
  4192. var preziPlayer = null;
  4193. /**
  4194. * Shows/hides a presentation.
  4195. */
  4196. function setPresentationVisible(visible) {
  4197. if (visible) {
  4198. VideoLayout.setLargeVideoState("prezi");
  4199. }
  4200. else {
  4201. VideoLayout.setLargeVideoState("video");
  4202. }
  4203. }
  4204. var Prezi = {
  4205. /**
  4206. * Reloads the current presentation.
  4207. */
  4208. reloadPresentation: function() {
  4209. var iframe = document.getElementById(preziPlayer.options.preziId);
  4210. iframe.src = iframe.src;
  4211. },
  4212. /**
  4213. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4214. * otherwise.
  4215. */
  4216. isPresentationVisible: function () {
  4217. return ($('#presentation>iframe') != null
  4218. && $('#presentation>iframe').css('opacity') == 1);
  4219. },
  4220. /**
  4221. * Opens the Prezi dialog, from which the user could choose a presentation
  4222. * to load.
  4223. */
  4224. openPreziDialog: function() {
  4225. var myprezi = APP.xmpp.getPrezi();
  4226. if (myprezi) {
  4227. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4228. null,
  4229. "dialog.removePreziMsg",
  4230. null,
  4231. false,
  4232. "dialog.Remove",
  4233. function(e,v,m,f) {
  4234. if(v) {
  4235. APP.xmpp.removePreziFromPresence();
  4236. }
  4237. }
  4238. );
  4239. }
  4240. else if (preziPlayer != null) {
  4241. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4242. null, "dialog.sharePreziMsg",
  4243. null,
  4244. false,
  4245. "dialog.Ok",
  4246. function(e,v,m,f) {
  4247. $.prompt.close();
  4248. }
  4249. );
  4250. }
  4251. else {
  4252. var html = APP.translation.generateTranslationHTML(
  4253. "dialog.sharePreziTitle");
  4254. var cancelButton = APP.translation.generateTranslationHTML(
  4255. "dialog.Cancel");
  4256. var shareButton = APP.translation.generateTranslationHTML(
  4257. "dialog.Share");
  4258. var backButton = APP.translation.generateTranslationHTML(
  4259. "dialog.Back");
  4260. var buttons = [];
  4261. var buttons1 = [];
  4262. // Cancel button to both states
  4263. buttons.push({title: cancelButton, value: false});
  4264. buttons1.push({title: cancelButton, value: false});
  4265. // Share button
  4266. buttons.push({title: shareButton, value: true});
  4267. // Back button
  4268. buttons1.push({title: backButton, value: true});
  4269. var linkError = APP.translation.generateTranslationHTML(
  4270. "dialog.preziLinkError");
  4271. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4272. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4273. var openPreziState = {
  4274. state0: {
  4275. html: '<h2>' + html + '</h2>' +
  4276. '<input name="preziUrl" type="text" ' +
  4277. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4278. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4279. '\' placeholder="' + defaultUrl + '" autofocus>',
  4280. persistent: false,
  4281. buttons: buttons,
  4282. focus: ':input:first',
  4283. defaultButton: 0,
  4284. submit: function (e, v, m, f) {
  4285. e.preventDefault();
  4286. if(v)
  4287. {
  4288. var preziUrl = f.preziUrl;
  4289. if (preziUrl)
  4290. {
  4291. var urlValue
  4292. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4293. if (urlValue.indexOf('http://prezi.com/') != 0
  4294. && urlValue.indexOf('https://prezi.com/') != 0)
  4295. {
  4296. $.prompt.goToState('state1');
  4297. return false;
  4298. }
  4299. else {
  4300. var presIdTmp = urlValue.substring(
  4301. urlValue.indexOf("prezi.com/") + 10);
  4302. if (!isAlphanumeric(presIdTmp)
  4303. || presIdTmp.indexOf('/') < 2) {
  4304. $.prompt.goToState('state1');
  4305. return false;
  4306. }
  4307. else {
  4308. APP.xmpp.addToPresence("prezi", urlValue);
  4309. $.prompt.close();
  4310. }
  4311. }
  4312. }
  4313. }
  4314. else
  4315. $.prompt.close();
  4316. }
  4317. },
  4318. state1: {
  4319. html: '<h2>' + html + '</h2>' +
  4320. linkError,
  4321. persistent: false,
  4322. buttons: buttons1,
  4323. focus: ':input:first',
  4324. defaultButton: 1,
  4325. submit: function (e, v, m, f) {
  4326. e.preventDefault();
  4327. if (v === 0)
  4328. $.prompt.close();
  4329. else
  4330. $.prompt.goToState('state0');
  4331. }
  4332. }
  4333. };
  4334. messageHandler.openDialogWithStates(openPreziState);
  4335. }
  4336. }
  4337. };
  4338. /**
  4339. * A new presentation has been added.
  4340. *
  4341. * @param event the event indicating the add of a presentation
  4342. * @param jid the jid from which the presentation was added
  4343. * @param presUrl url of the presentation
  4344. * @param currentSlide the current slide to which we should move
  4345. */
  4346. function presentationAdded(event, jid, presUrl, currentSlide) {
  4347. console.log("presentation added", presUrl);
  4348. var presId = getPresentationId(presUrl);
  4349. var elementId = 'participant_'
  4350. + Strophe.getResourceFromJid(jid)
  4351. + '_' + presId;
  4352. VideoLayout.addPreziContainer(elementId);
  4353. var controlsEnabled = false;
  4354. if (jid === APP.xmpp.myJid())
  4355. controlsEnabled = true;
  4356. setPresentationVisible(true);
  4357. VideoLayout.setLargeVideoHover(
  4358. function (event) {
  4359. if (Prezi.isPresentationVisible()) {
  4360. var reloadButtonRight = window.innerWidth
  4361. - $('#presentation>iframe').offset().left
  4362. - $('#presentation>iframe').width();
  4363. $('#reloadPresentation').css({ right: reloadButtonRight,
  4364. display:'inline-block'});
  4365. }
  4366. },
  4367. function (event) {
  4368. if (!Prezi.isPresentationVisible())
  4369. $('#reloadPresentation').css({display:'none'});
  4370. else {
  4371. var e = event.toElement || event.relatedTarget;
  4372. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4373. $('#reloadPresentation').css({display:'none'});
  4374. }
  4375. });
  4376. preziPlayer = new PreziPlayer(
  4377. 'presentation',
  4378. {preziId: presId,
  4379. width: getPresentationWidth(),
  4380. height: getPresentationHeihgt(),
  4381. controls: controlsEnabled,
  4382. debug: true
  4383. });
  4384. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4385. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4386. console.log("prezi status", event.value);
  4387. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4388. if (jid != APP.xmpp.myJid())
  4389. preziPlayer.flyToStep(currentSlide);
  4390. }
  4391. });
  4392. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4393. console.log("event value", event.value);
  4394. APP.xmpp.addToPresence("preziSlide", event.value);
  4395. });
  4396. $("#" + elementId).css( 'background-image',
  4397. 'url(../images/avatarprezi.png)');
  4398. $("#" + elementId).click(
  4399. function () {
  4400. setPresentationVisible(true);
  4401. }
  4402. );
  4403. };
  4404. /**
  4405. * A presentation has been removed.
  4406. *
  4407. * @param event the event indicating the remove of a presentation
  4408. * @param jid the jid for which the presentation was removed
  4409. * @param the url of the presentation
  4410. */
  4411. function presentationRemoved(event, jid, presUrl) {
  4412. console.log('presentation removed', presUrl);
  4413. var presId = getPresentationId(presUrl);
  4414. setPresentationVisible(false);
  4415. $('#participant_'
  4416. + Strophe.getResourceFromJid(jid)
  4417. + '_' + presId).remove();
  4418. $('#presentation>iframe').remove();
  4419. if (preziPlayer != null) {
  4420. preziPlayer.destroy();
  4421. preziPlayer = null;
  4422. }
  4423. };
  4424. /**
  4425. * Indicates if the given string is an alphanumeric string.
  4426. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4427. * purpose of checking URIs.
  4428. */
  4429. function isAlphanumeric(unsafeText) {
  4430. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4431. return regex.test(unsafeText);
  4432. }
  4433. /**
  4434. * Returns the presentation id from the given url.
  4435. */
  4436. function getPresentationId (presUrl) {
  4437. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4438. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4439. }
  4440. /**
  4441. * Returns the presentation width.
  4442. */
  4443. function getPresentationWidth() {
  4444. var availableWidth = UIUtil.getAvailableVideoWidth();
  4445. var availableHeight = getPresentationHeihgt();
  4446. var aspectRatio = 16.0 / 9.0;
  4447. if (availableHeight < availableWidth / aspectRatio) {
  4448. availableWidth = Math.floor(availableHeight * aspectRatio);
  4449. }
  4450. return availableWidth;
  4451. }
  4452. /**
  4453. * Returns the presentation height.
  4454. */
  4455. function getPresentationHeihgt() {
  4456. var remoteVideos = $('#remoteVideos');
  4457. return window.innerHeight - remoteVideos.outerHeight();
  4458. }
  4459. /**
  4460. * Resizes the presentation iframe.
  4461. */
  4462. function resize() {
  4463. if ($('#presentation>iframe')) {
  4464. $('#presentation>iframe').width(getPresentationWidth());
  4465. $('#presentation>iframe').height(getPresentationHeihgt());
  4466. }
  4467. }
  4468. /**
  4469. * Presentation has been removed.
  4470. */
  4471. $(document).bind('presentationremoved.muc', presentationRemoved);
  4472. /**
  4473. * Presentation has been added.
  4474. */
  4475. $(document).bind('presentationadded.muc', presentationAdded);
  4476. /*
  4477. * Indicates presentation slide change.
  4478. */
  4479. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4480. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4481. preziPlayer.flyToStep(current);
  4482. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4483. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4484. preziPlayer.flyToStep(current, i);
  4485. }
  4486. }
  4487. });
  4488. $(window).resize(function () {
  4489. resize();
  4490. });
  4491. module.exports = Prezi;
  4492. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4493. (function() {
  4494. "use strict";
  4495. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4496. window.PreziPlayer = (function() {
  4497. PreziPlayer.API_VERSION = 1;
  4498. PreziPlayer.CURRENT_STEP = 'currentStep';
  4499. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4500. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4501. PreziPlayer.STATUS_LOADING = 'loading';
  4502. PreziPlayer.STATUS_READY = 'ready';
  4503. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4504. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4505. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4506. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4507. PreziPlayer.EVENT_STATUS = "statusChange";
  4508. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4509. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4510. PreziPlayer.domain = "https://prezi.com";
  4511. PreziPlayer.path = "/player/";
  4512. PreziPlayer.players = {};
  4513. PreziPlayer.binded_methods = ['changesHandler'];
  4514. PreziPlayer.createMultiplePlayers = function(optionArray){
  4515. for(var i=0; i<optionArray.length; i++) {
  4516. var optionSet = optionArray[i];
  4517. new PreziPlayer(optionSet.id, optionSet);
  4518. };
  4519. };
  4520. PreziPlayer.messageReceived = function(event){
  4521. var message, item, player;
  4522. try {
  4523. message = JSON.parse(event.data);
  4524. if (message.id && (player = PreziPlayer.players[message.id])) {
  4525. if (player.options.debug === true) {
  4526. if (console && console.log)
  4527. console.log('received', message);
  4528. }
  4529. if (message.type === "changes") {
  4530. player.changesHandler(message);
  4531. }
  4532. for (var i = 0; i < player.callbacks.length; i++) {
  4533. item = player.callbacks[i];
  4534. if (item && message.type === item.event) {
  4535. item.callback(message);
  4536. }
  4537. }
  4538. }
  4539. } catch (e) { }
  4540. };
  4541. function PreziPlayer(id, options) {
  4542. var params, paramString = "", _this = this;
  4543. if (PreziPlayer.players[id]){
  4544. PreziPlayer.players[id].destroy();
  4545. }
  4546. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4547. var method_name = PreziPlayer.binded_methods[i];
  4548. _this[method_name] = __bind(_this[method_name], _this);
  4549. };
  4550. options = options || {};
  4551. this.options = options;
  4552. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4553. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4554. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4555. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4556. this.callbacks = [];
  4557. this.id = id;
  4558. this.embedTo = document.getElementById(id);
  4559. if (!this.embedTo) {
  4560. throw "The element id is not available.";
  4561. }
  4562. this.iframe = document.createElement('iframe');
  4563. params = [
  4564. { name: 'oid', value: options.preziId },
  4565. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4566. { name: 'controls', value: options.controls ? 1 : 0 }
  4567. ];
  4568. for(var i=0; i<params.length; i++) {
  4569. var param = params[i];
  4570. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4571. };
  4572. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4573. this.iframe.frameBorder = 0;
  4574. this.iframe.scrolling = "no";
  4575. this.iframe.width = options.width || 640;
  4576. this.iframe.height = options.height || 480;
  4577. this.embedTo.innerHTML = '';
  4578. // JITSI: IN CASE SOMETHING GOES WRONG.
  4579. try {
  4580. this.embedTo.appendChild(this.iframe);
  4581. }
  4582. catch (err) {
  4583. console.log("CATCH ERROR");
  4584. }
  4585. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4586. // crashes for us.
  4587. this.initPollInterval = setInterval(function(){
  4588. _this.sendMessage({'action': 'init'});
  4589. }, 500);
  4590. PreziPlayer.players[id] = this;
  4591. }
  4592. PreziPlayer.prototype.changesHandler = function(message) {
  4593. var key, value, j, item;
  4594. if (this.initPollInterval) {
  4595. clearInterval(this.initPollInterval);
  4596. this.initPollInterval = false;
  4597. }
  4598. for (key in message.data) {
  4599. if (message.data.hasOwnProperty(key)){
  4600. value = message.data[key];
  4601. this.values[key] = value;
  4602. for (j=0; j<this.callbacks.length; j++) {
  4603. item = this.callbacks[j];
  4604. if (item && item.event === key + "Change"){
  4605. item.callback({type: item.event, value: value});
  4606. }
  4607. }
  4608. }
  4609. }
  4610. };
  4611. PreziPlayer.prototype.destroy = function() {
  4612. if (this.initPollInterval) {
  4613. clearInterval(this.initPollInterval);
  4614. this.initPollInterval = false;
  4615. }
  4616. this.embedTo.innerHTML = '';
  4617. };
  4618. PreziPlayer.prototype.sendMessage = function(message) {
  4619. if (this.options.debug === true) {
  4620. if (console && console.log) console.log('sent', message);
  4621. }
  4622. message.version = PreziPlayer.API_VERSION;
  4623. message.id = this.id;
  4624. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4625. };
  4626. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4627. PreziPlayer.prototype.flyToNextStep = function() {
  4628. return this.sendMessage({
  4629. 'action': 'present',
  4630. 'data': ['moveToNextStep']
  4631. });
  4632. };
  4633. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4634. PreziPlayer.prototype.flyToPreviousStep = function() {
  4635. return this.sendMessage({
  4636. 'action': 'present',
  4637. 'data': ['moveToPrevStep']
  4638. });
  4639. };
  4640. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4641. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4642. var obj = this;
  4643. // check animation_step
  4644. if (animation_step > 0 &&
  4645. obj.values.animationCountOnSteps &&
  4646. obj.values.animationCountOnSteps[step] <= animation_step) {
  4647. animation_step = obj.values.animationCountOnSteps[step];
  4648. }
  4649. // jump to animation steps by calling flyToNextStep()
  4650. function doAnimationSteps() {
  4651. if (obj.values.isMoving == true) {
  4652. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4653. return;
  4654. }
  4655. while (animation_step-- > 0) {
  4656. obj.flyToNextStep(); // do the animation steps
  4657. }
  4658. }
  4659. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4660. // jump to the step
  4661. return this.sendMessage({
  4662. 'action': 'present',
  4663. 'data': ['moveToStep', step]
  4664. });
  4665. };
  4666. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4667. PreziPlayer.prototype.flyToObject = function(objectId) {
  4668. return this.sendMessage({
  4669. 'action': 'present',
  4670. 'data': ['moveToObject', objectId]
  4671. });
  4672. };
  4673. PreziPlayer.prototype.play = function(defaultDelay) {
  4674. return this.sendMessage({
  4675. 'action': 'present',
  4676. 'data': ['startAutoPlay', defaultDelay]
  4677. });
  4678. };
  4679. PreziPlayer.prototype.stop = function() {
  4680. return this.sendMessage({
  4681. 'action': 'present',
  4682. 'data': ['stopAutoPlay']
  4683. });
  4684. };
  4685. PreziPlayer.prototype.pause = function(defaultDelay) {
  4686. return this.sendMessage({
  4687. 'action': 'present',
  4688. 'data': ['pauseAutoPlay', defaultDelay]
  4689. });
  4690. };
  4691. PreziPlayer.prototype.getCurrentStep = function() {
  4692. return this.values.currentStep;
  4693. };
  4694. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4695. return this.values.currentAnimationStep;
  4696. };
  4697. PreziPlayer.prototype.getCurrentObject = function() {
  4698. return this.values.currentObject;
  4699. };
  4700. PreziPlayer.prototype.getStatus = function() {
  4701. return this.values.status;
  4702. };
  4703. PreziPlayer.prototype.isPlaying = function() {
  4704. return this.values.isAutoPlaying;
  4705. };
  4706. PreziPlayer.prototype.getStepCount = function() {
  4707. return this.values.stepCount;
  4708. };
  4709. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4710. return this.values.animationCountOnSteps;
  4711. };
  4712. PreziPlayer.prototype.getTitle = function() {
  4713. return this.values.title;
  4714. };
  4715. PreziPlayer.prototype.setDimensions = function(dims) {
  4716. for (var parameter in dims) {
  4717. this.iframe[parameter] = dims[parameter];
  4718. }
  4719. }
  4720. PreziPlayer.prototype.getDimensions = function() {
  4721. return {
  4722. width: parseInt(this.iframe.width, 10),
  4723. height: parseInt(this.iframe.height, 10)
  4724. }
  4725. }
  4726. PreziPlayer.prototype.on = function(event, callback) {
  4727. this.callbacks.push({
  4728. event: event,
  4729. callback: callback
  4730. });
  4731. };
  4732. PreziPlayer.prototype.off = function(event, callback) {
  4733. var j, item;
  4734. if (event === undefined) {
  4735. this.callbacks = [];
  4736. }
  4737. j = this.callbacks.length;
  4738. while (j--) {
  4739. item = this.callbacks[j];
  4740. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4741. this.callbacks.splice(j, 1);
  4742. }
  4743. }
  4744. };
  4745. if (window.addEventListener) {
  4746. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4747. } else {
  4748. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4749. }
  4750. return PreziPlayer;
  4751. })();
  4752. })();
  4753. module.exports = PreziPlayer;
  4754. },{}],20:[function(require,module,exports){
  4755. /* global require, $ */
  4756. var Chat = require("./chat/Chat");
  4757. var ContactList = require("./contactlist/ContactList");
  4758. var Settings = require("./../../settings/Settings");
  4759. var SettingsMenu = require("./settings/SettingsMenu");
  4760. var VideoLayout = require("../videolayout/VideoLayout");
  4761. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4762. var UIUtil = require("../util/UIUtil");
  4763. var LargeVideo = require("../videolayout/LargeVideo");
  4764. /**
  4765. * Toggler for the chat, contact list, settings menu, etc..
  4766. */
  4767. var PanelToggler = (function(my) {
  4768. var currentlyOpen = null;
  4769. var buttons = {
  4770. '#chatspace': '#chatBottomButton',
  4771. '#contactlist': '#contactListButton',
  4772. '#settingsmenu': '#toolbar_button_settings'
  4773. };
  4774. /**
  4775. * Toggles the windows in the side panel
  4776. * @param object the window that should be shown
  4777. * @param selector the selector for the element containing the panel
  4778. * @param onOpenComplete function to be called when the panel is opened
  4779. * @param onOpen function to be called if the window is going to be opened
  4780. * @param onClose function to be called if the window is going to be closed
  4781. */
  4782. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4783. UIUtil.buttonClick(buttons[selector], "active");
  4784. if (object.isVisible()) {
  4785. $("#toast-container").animate({
  4786. right: '5px'
  4787. },
  4788. {
  4789. queue: false,
  4790. duration: 500
  4791. });
  4792. $(selector).hide("slide", {
  4793. direction: "right",
  4794. queue: false,
  4795. duration: 500
  4796. });
  4797. if(typeof onClose === "function") {
  4798. onClose();
  4799. }
  4800. currentlyOpen = null;
  4801. }
  4802. else {
  4803. // Undock the toolbar when the chat is shown and if we're in a
  4804. // video mode.
  4805. if (LargeVideo.isLargeVideoVisible()) {
  4806. ToolbarToggler.dockToolbar(false);
  4807. }
  4808. if(currentlyOpen) {
  4809. var current = $(currentlyOpen);
  4810. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4811. current.css('z-index', 4);
  4812. setTimeout(function () {
  4813. current.css('display', 'none');
  4814. current.css('z-index', 5);
  4815. }, 500);
  4816. }
  4817. $("#toast-container").animate({
  4818. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4819. },
  4820. {
  4821. queue: false,
  4822. duration: 500
  4823. });
  4824. $(selector).show("slide", {
  4825. direction: "right",
  4826. queue: false,
  4827. duration: 500,
  4828. complete: onOpenComplete
  4829. });
  4830. if(typeof onOpen === "function") {
  4831. onOpen();
  4832. }
  4833. currentlyOpen = selector;
  4834. }
  4835. };
  4836. /**
  4837. * Opens / closes the chat area.
  4838. */
  4839. my.toggleChat = function() {
  4840. var chatCompleteFunction = Chat.isVisible() ?
  4841. function() {} : function () {
  4842. Chat.scrollChatToBottom();
  4843. $('#chatspace').trigger('shown');
  4844. };
  4845. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4846. toggle(Chat,
  4847. '#chatspace',
  4848. function () {
  4849. // Request the focus in the nickname field or the chat input field.
  4850. if ($('#nickname').css('visibility') === 'visible') {
  4851. $('#nickinput').focus();
  4852. } else {
  4853. $('#usermsg').focus();
  4854. }
  4855. },
  4856. null,
  4857. Chat.resizeChat,
  4858. null);
  4859. };
  4860. /**
  4861. * Opens / closes the contact list area.
  4862. */
  4863. my.toggleContactList = function () {
  4864. var completeFunction = ContactList.isVisible() ?
  4865. function() {} : function () { $('#contactlist').trigger('shown');};
  4866. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4867. toggle(ContactList,
  4868. '#contactlist',
  4869. null,
  4870. function() {
  4871. ContactList.setVisualNotification(false);
  4872. },
  4873. null);
  4874. };
  4875. /**
  4876. * Opens / closes the settings menu
  4877. */
  4878. my.toggleSettingsMenu = function() {
  4879. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4880. toggle(SettingsMenu,
  4881. '#settingsmenu',
  4882. null,
  4883. function() {
  4884. var settings = Settings.getSettings();
  4885. $('#setDisplayName').get(0).value = settings.displayName;
  4886. $('#setEmail').get(0).value = settings.email;
  4887. },
  4888. null);
  4889. };
  4890. /**
  4891. * Returns the size of the side panel.
  4892. */
  4893. my.getPanelSize = function () {
  4894. var availableHeight = window.innerHeight;
  4895. var availableWidth = window.innerWidth;
  4896. var panelWidth = 200;
  4897. if (availableWidth * 0.2 < 200) {
  4898. panelWidth = availableWidth * 0.2;
  4899. }
  4900. return [panelWidth, availableHeight];
  4901. };
  4902. my.isVisible = function() {
  4903. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4904. };
  4905. return my;
  4906. }(PanelToggler || {}));
  4907. module.exports = PanelToggler;
  4908. },{"../toolbars/ToolbarToggler":29,"../util/UIUtil":33,"../videolayout/LargeVideo":35,"../videolayout/VideoLayout":39,"./../../settings/Settings":47,"./chat/Chat":21,"./contactlist/ContactList":25,"./settings/SettingsMenu":26}],21:[function(require,module,exports){
  4909. /* global APP, $, Util, nickname:true */
  4910. var Replacement = require("./Replacement");
  4911. var CommandsProcessor = require("./Commands");
  4912. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4913. var smileys = require("./smileys.json").smileys;
  4914. var NicknameHandler = require("../../util/NicknameHandler");
  4915. var UIUtil = require("../../util/UIUtil");
  4916. var UIEvents = require("../../../../service/UI/UIEvents");
  4917. var notificationInterval = false;
  4918. var unreadMessages = 0;
  4919. /**
  4920. * Shows/hides a visual notification, indicating that a message has arrived.
  4921. */
  4922. function setVisualNotification(show) {
  4923. var unreadMsgElement = document.getElementById('unreadMessages');
  4924. var unreadMsgBottomElement
  4925. = document.getElementById('bottomUnreadMessages');
  4926. var glower = $('#toolbar_button_chat');
  4927. var bottomGlower = $('#chatBottomButton');
  4928. if (unreadMessages) {
  4929. unreadMsgElement.innerHTML = unreadMessages.toString();
  4930. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4931. ToolbarToggler.dockToolbar(true);
  4932. var chatButtonElement
  4933. = document.getElementById('toolbar_button_chat');
  4934. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4935. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4936. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4937. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4938. unreadMsgElement.setAttribute(
  4939. 'style',
  4940. 'top:' + topIndent +
  4941. '; left:' + leftIndent + ';');
  4942. var chatBottomButtonElement
  4943. = document.getElementById('chatBottomButton').parentNode;
  4944. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4945. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4946. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4947. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  4948. unreadMsgBottomElement.setAttribute(
  4949. 'style',
  4950. 'top:' + bottomTopIndent +
  4951. '; left:' + bottomLeftIndent + ';');
  4952. if (!glower.hasClass('icon-chat-simple')) {
  4953. glower.removeClass('icon-chat');
  4954. glower.addClass('icon-chat-simple');
  4955. }
  4956. }
  4957. else {
  4958. unreadMsgElement.innerHTML = '';
  4959. unreadMsgBottomElement.innerHTML = '';
  4960. glower.removeClass('icon-chat-simple');
  4961. glower.addClass('icon-chat');
  4962. }
  4963. if (show && !notificationInterval) {
  4964. notificationInterval = window.setInterval(function () {
  4965. glower.toggleClass('active');
  4966. bottomGlower.toggleClass('active glowing');
  4967. }, 800);
  4968. }
  4969. else if (!show && notificationInterval) {
  4970. window.clearInterval(notificationInterval);
  4971. notificationInterval = false;
  4972. glower.removeClass('active');
  4973. bottomGlower.removeClass('glowing');
  4974. bottomGlower.addClass('active');
  4975. }
  4976. }
  4977. /**
  4978. * Returns the current time in the format it is shown to the user
  4979. * @returns {string}
  4980. */
  4981. function getCurrentTime(stamp) {
  4982. var now = (stamp? new Date(stamp): new Date());
  4983. var hour = now.getHours();
  4984. var minute = now.getMinutes();
  4985. var second = now.getSeconds();
  4986. if(hour.toString().length === 1) {
  4987. hour = '0'+hour;
  4988. }
  4989. if(minute.toString().length === 1) {
  4990. minute = '0'+minute;
  4991. }
  4992. if(second.toString().length === 1) {
  4993. second = '0'+second;
  4994. }
  4995. return hour+':'+minute+':'+second;
  4996. }
  4997. function toggleSmileys() {
  4998. var smileys = $('#smileysContainer');
  4999. if(!smileys.is(':visible')) {
  5000. smileys.show("slide", { direction: "down", duration: 300});
  5001. } else {
  5002. smileys.hide("slide", { direction: "down", duration: 300});
  5003. }
  5004. $('#usermsg').focus();
  5005. }
  5006. function addClickFunction(smiley, number) {
  5007. smiley.onclick = function addSmileyToMessage() {
  5008. var usermsg = $('#usermsg');
  5009. var message = usermsg.val();
  5010. message += smileys['smiley' + number];
  5011. usermsg.val(message);
  5012. usermsg.get(0).setSelectionRange(message.length, message.length);
  5013. toggleSmileys();
  5014. usermsg.focus();
  5015. };
  5016. }
  5017. /**
  5018. * Adds the smileys container to the chat
  5019. */
  5020. function addSmileys() {
  5021. var smileysContainer = document.createElement('div');
  5022. smileysContainer.id = 'smileysContainer';
  5023. for(var i = 1; i <= 21; i++) {
  5024. var smileyContainer = document.createElement('div');
  5025. smileyContainer.id = 'smiley' + i;
  5026. smileyContainer.className = 'smileyContainer';
  5027. var smiley = document.createElement('img');
  5028. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5029. smiley.className = 'smiley';
  5030. addClickFunction(smiley, i);
  5031. smileyContainer.appendChild(smiley);
  5032. smileysContainer.appendChild(smileyContainer);
  5033. }
  5034. $("#chatspace").append(smileysContainer);
  5035. }
  5036. /**
  5037. * Resizes the chat conversation.
  5038. */
  5039. function resizeChatConversation() {
  5040. var msgareaHeight = $('#usermsg').outerHeight();
  5041. var chatspace = $('#chatspace');
  5042. var width = chatspace.width();
  5043. var chat = $('#chatconversation');
  5044. var smileys = $('#smileysarea');
  5045. smileys.height(msgareaHeight);
  5046. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5047. $('#smileysContainer').css('bottom', msgareaHeight);
  5048. chat.width(width - 10);
  5049. chat.height(window.innerHeight - 15 - msgareaHeight);
  5050. }
  5051. /**
  5052. * Chat related user interface.
  5053. */
  5054. var Chat = (function (my) {
  5055. /**
  5056. * Initializes chat related interface.
  5057. */
  5058. my.init = function () {
  5059. if(NicknameHandler.getNickname())
  5060. Chat.setChatConversationMode(true);
  5061. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5062. function (nickname) {
  5063. Chat.setChatConversationMode(true);
  5064. });
  5065. $('#nickinput').keydown(function (event) {
  5066. if (event.keyCode === 13) {
  5067. event.preventDefault();
  5068. var val = UIUtil.escapeHtml(this.value);
  5069. this.value = '';
  5070. if (!NicknameHandler.getNickname()) {
  5071. NicknameHandler.setNickname(val);
  5072. return;
  5073. }
  5074. }
  5075. });
  5076. var usermsg = $('#usermsg');
  5077. usermsg.keydown(function (event) {
  5078. if (event.keyCode === 13) {
  5079. event.preventDefault();
  5080. var value = this.value;
  5081. usermsg.val('').trigger('autosize.resize');
  5082. this.focus();
  5083. var command = new CommandsProcessor(value);
  5084. if(command.isCommand()) {
  5085. command.processCommand();
  5086. }
  5087. else {
  5088. var message = UIUtil.escapeHtml(value);
  5089. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5090. }
  5091. }
  5092. });
  5093. var onTextAreaResize = function () {
  5094. resizeChatConversation();
  5095. Chat.scrollChatToBottom();
  5096. };
  5097. usermsg.autosize({callback: onTextAreaResize});
  5098. $("#chatspace").bind("shown",
  5099. function () {
  5100. unreadMessages = 0;
  5101. setVisualNotification(false);
  5102. });
  5103. addSmileys();
  5104. };
  5105. /**
  5106. * Appends the given message to the chat conversation.
  5107. */
  5108. my.updateChatConversation =
  5109. function (from, displayName, message, myjid, stamp) {
  5110. var divClassName = '';
  5111. if (APP.xmpp.myJid() === from) {
  5112. divClassName = "localuser";
  5113. }
  5114. else {
  5115. divClassName = "remoteuser";
  5116. if (!Chat.isVisible()) {
  5117. unreadMessages++;
  5118. UIUtil.playSoundNotification('chatNotification');
  5119. setVisualNotification(true);
  5120. }
  5121. }
  5122. // replace links and smileys
  5123. // Strophe already escapes special symbols on sending,
  5124. // so we escape here only tags to avoid double &amp;
  5125. var escMessage = message.replace(/</g, '&lt;').
  5126. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5127. var escDisplayName = UIUtil.escapeHtml(displayName);
  5128. message = Replacement.processReplacements(escMessage);
  5129. var messageContainer =
  5130. '<div class="chatmessage">'+
  5131. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5132. '<div class="username ' + divClassName +'">' + escDisplayName +
  5133. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5134. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5135. '</div>';
  5136. $('#chatconversation').append(messageContainer);
  5137. $('#chatconversation').animate(
  5138. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5139. };
  5140. /**
  5141. * Appends error message to the conversation
  5142. * @param errorMessage the received error message.
  5143. * @param originalText the original message.
  5144. */
  5145. my.chatAddError = function(errorMessage, originalText) {
  5146. errorMessage = UIUtil.escapeHtml(errorMessage);
  5147. originalText = UIUtil.escapeHtml(originalText);
  5148. $('#chatconversation').append(
  5149. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5150. (originalText? (' \"'+ originalText + '\"') : "") +
  5151. ' was not sent.' +
  5152. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5153. $('#chatconversation').animate(
  5154. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5155. };
  5156. /**
  5157. * Sets the subject to the UI
  5158. * @param subject the subject
  5159. */
  5160. my.chatSetSubject = function(subject) {
  5161. if (subject)
  5162. subject = subject.trim();
  5163. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5164. if(subject === "") {
  5165. $("#subject").css({display: "none"});
  5166. }
  5167. else {
  5168. $("#subject").css({display: "block"});
  5169. }
  5170. };
  5171. /**
  5172. * Sets the chat conversation mode.
  5173. */
  5174. my.setChatConversationMode = function (isConversationMode) {
  5175. if (isConversationMode) {
  5176. $('#nickname').css({visibility: 'hidden'});
  5177. $('#chatconversation').css({visibility: 'visible'});
  5178. $('#usermsg').css({visibility: 'visible'});
  5179. $('#smileysarea').css({visibility: 'visible'});
  5180. $('#usermsg').focus();
  5181. }
  5182. };
  5183. /**
  5184. * Resizes the chat area.
  5185. */
  5186. my.resizeChat = function () {
  5187. var chatSize = require("../SidePanelToggler").getPanelSize();
  5188. $('#chatspace').width(chatSize[0]);
  5189. $('#chatspace').height(chatSize[1]);
  5190. resizeChatConversation();
  5191. };
  5192. /**
  5193. * Indicates if the chat is currently visible.
  5194. */
  5195. my.isVisible = function () {
  5196. return $('#chatspace').is(":visible");
  5197. };
  5198. /**
  5199. * Shows and hides the window with the smileys
  5200. */
  5201. my.toggleSmileys = toggleSmileys;
  5202. /**
  5203. * Scrolls chat to the bottom.
  5204. */
  5205. my.scrollChatToBottom = function() {
  5206. setTimeout(function () {
  5207. $('#chatconversation').scrollTop(
  5208. $('#chatconversation')[0].scrollHeight);
  5209. }, 5);
  5210. };
  5211. return my;
  5212. }(Chat || {}));
  5213. module.exports = Chat;
  5214. },{"../../../../service/UI/UIEvents":155,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5215. /* global APP, require */
  5216. var UIUtil = require("../../util/UIUtil");
  5217. /**
  5218. * List with supported commands. The keys are the names of the commands and
  5219. * the value is the function that processes the message.
  5220. * @type {{String: function}}
  5221. */
  5222. var commands = {
  5223. "topic" : processTopic
  5224. };
  5225. /**
  5226. * Extracts the command from the message.
  5227. * @param message the received message
  5228. * @returns {string} the command
  5229. */
  5230. function getCommand(message) {
  5231. if(message) {
  5232. for(var command in commands) {
  5233. if(message.indexOf("/" + command) == 0)
  5234. return command;
  5235. }
  5236. }
  5237. return "";
  5238. }
  5239. /**
  5240. * Processes the data for topic command.
  5241. * @param commandArguments the arguments of the topic command.
  5242. */
  5243. function processTopic(commandArguments) {
  5244. var topic = UIUtil.escapeHtml(commandArguments);
  5245. APP.xmpp.setSubject(topic);
  5246. }
  5247. /**
  5248. * Constructs a new CommandProccessor instance from a message that
  5249. * handles commands received via chat messages.
  5250. * @param message the message
  5251. * @constructor
  5252. */
  5253. function CommandsProcessor(message) {
  5254. var command = getCommand(message);
  5255. /**
  5256. * Returns the name of the command.
  5257. * @returns {String} the command
  5258. */
  5259. this.getCommand = function() {
  5260. return command;
  5261. };
  5262. var messageArgument = message.substr(command.length + 2);
  5263. /**
  5264. * Returns the arguments of the command.
  5265. * @returns {string}
  5266. */
  5267. this.getArgument = function() {
  5268. return messageArgument;
  5269. };
  5270. }
  5271. /**
  5272. * Checks whether this instance is valid command or not.
  5273. * @returns {boolean}
  5274. */
  5275. CommandsProcessor.prototype.isCommand = function() {
  5276. if (this.getCommand())
  5277. return true;
  5278. return false;
  5279. };
  5280. /**
  5281. * Processes the command.
  5282. */
  5283. CommandsProcessor.prototype.processCommand = function() {
  5284. if(!this.isCommand())
  5285. return;
  5286. commands[this.getCommand()](this.getArgument());
  5287. };
  5288. module.exports = CommandsProcessor;
  5289. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5290. var Smileys = require("./smileys.json");
  5291. /**
  5292. * Processes links and smileys in "body"
  5293. */
  5294. function processReplacements(body)
  5295. {
  5296. //make links clickable
  5297. body = linkify(body);
  5298. //add smileys
  5299. body = smilify(body);
  5300. return body;
  5301. }
  5302. /**
  5303. * Finds and replaces all links in the links in "body"
  5304. * with their <a href=""></a>
  5305. */
  5306. function linkify(inputText)
  5307. {
  5308. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5309. //URLs starting with http://, https://, or ftp://
  5310. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5311. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5312. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5313. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5314. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5315. //Change email addresses to mailto:: links.
  5316. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5317. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5318. return replacedText;
  5319. }
  5320. /**
  5321. * Replaces common smiley strings with images
  5322. */
  5323. function smilify(body)
  5324. {
  5325. if(!body) {
  5326. return body;
  5327. }
  5328. var regexs = Smileys["regexs"];
  5329. for(var smiley in regexs) {
  5330. if(regexs.hasOwnProperty(smiley)) {
  5331. body = body.replace(regexs[smiley],
  5332. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5333. }
  5334. }
  5335. return body;
  5336. }
  5337. module.exports = {
  5338. processReplacements: processReplacements,
  5339. linkify: linkify
  5340. };
  5341. },{"./smileys.json":24}],24:[function(require,module,exports){
  5342. module.exports={
  5343. "smileys": {
  5344. "smiley1": ":)",
  5345. "smiley2": ":(",
  5346. "smiley3": ":D",
  5347. "smiley4": "(y)",
  5348. "smiley5": " :P",
  5349. "smiley6": "(wave)",
  5350. "smiley7": "(blush)",
  5351. "smiley8": "(chuckle)",
  5352. "smiley9": "(shocked)",
  5353. "smiley10": ":*",
  5354. "smiley11": "(n)",
  5355. "smiley12": "(search)",
  5356. "smiley13": " <3",
  5357. "smiley14": "(oops)",
  5358. "smiley15": "(angry)",
  5359. "smiley16": "(angel)",
  5360. "smiley17": "(sick)",
  5361. "smiley18": ";(",
  5362. "smiley19": "(bomb)",
  5363. "smiley20": "(clap)",
  5364. "smiley21": " ;)"
  5365. },
  5366. "regexs": {
  5367. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5368. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5369. "smiley1": /(:-\)|:\))/gi,
  5370. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5371. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5372. "smiley6": /(\(wave\))/gi,
  5373. "smiley7": /(\(blush\))/gi,
  5374. "smiley8": /(\(chuckle\))/gi,
  5375. "smiley9": /(:-0|\(shocked\))/gi,
  5376. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5377. "smiley11": /(\(n\))/gi,
  5378. "smiley12": /(\(search\))/g,
  5379. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5380. "smiley14": /(\(oops\))/gi,
  5381. "smiley15": /(\(angry\))/gi,
  5382. "smiley16": /(\(angel\))/gi,
  5383. "smiley17": /(\(sick\))/gi,
  5384. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5385. "smiley19": /(\(bomb\))/gi,
  5386. "smiley20": /(\(clap\))/gi,
  5387. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5388. }
  5389. }
  5390. },{}],25:[function(require,module,exports){
  5391. /* global $, APP, Strophe */
  5392. var Avatar = require('../../avatar/Avatar');
  5393. var numberOfContacts = 0;
  5394. var notificationInterval;
  5395. /**
  5396. * Updates the number of participants in the contact list button and sets
  5397. * the glow
  5398. * @param delta indicates whether a new user has joined (1) or someone has
  5399. * left(-1)
  5400. */
  5401. function updateNumberOfParticipants(delta) {
  5402. numberOfContacts += delta;
  5403. if (numberOfContacts === 1) {
  5404. // when the user is alone we don't show the number of participants
  5405. $("#numberOfParticipants").text('');
  5406. ContactList.setVisualNotification(false);
  5407. } else if (numberOfContacts > 1) {
  5408. ContactList.setVisualNotification(!ContactList.isVisible());
  5409. $("#numberOfParticipants").text(numberOfContacts);
  5410. } else {
  5411. console.error("Invalid number of participants: " + numberOfContacts);
  5412. }
  5413. }
  5414. /**
  5415. * Creates the avatar element.
  5416. *
  5417. * @return {object} the newly created avatar element
  5418. */
  5419. function createAvatar(jid) {
  5420. var avatar = document.createElement('img');
  5421. avatar.className = "icon-avatar avatar";
  5422. avatar.src = Avatar.getContactListUrl(jid);
  5423. return avatar;
  5424. }
  5425. /**
  5426. * Creates the display name paragraph.
  5427. *
  5428. * @param displayName the display name to set
  5429. */
  5430. function createDisplayNameParagraph(key, displayName) {
  5431. var p = document.createElement('p');
  5432. if(displayName)
  5433. p.innerText = displayName;
  5434. else if(key) {
  5435. p.setAttribute("data-i18n",key);
  5436. p.innerText = APP.translation.translateString(key);
  5437. }
  5438. return p;
  5439. }
  5440. function stopGlowing(glower) {
  5441. window.clearInterval(notificationInterval);
  5442. notificationInterval = false;
  5443. glower.removeClass('glowing');
  5444. if (!ContactList.isVisible()) {
  5445. glower.removeClass('active');
  5446. }
  5447. }
  5448. /**
  5449. * Contact list.
  5450. */
  5451. var ContactList = {
  5452. /**
  5453. * Indicates if the chat is currently visible.
  5454. *
  5455. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5456. * otherwise
  5457. */
  5458. isVisible: function () {
  5459. return $('#contactlist').is(":visible");
  5460. },
  5461. /**
  5462. * Adds a contact for the given peerJid if such doesn't yet exist.
  5463. *
  5464. * @param peerJid the peerJid corresponding to the contact
  5465. */
  5466. ensureAddContact: function (peerJid) {
  5467. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5468. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5469. if (!contact || contact.length <= 0)
  5470. ContactList.addContact(peerJid);
  5471. },
  5472. /**
  5473. * Adds a contact for the given peer jid.
  5474. *
  5475. * @param peerJid the jid of the contact to add
  5476. */
  5477. addContact: function (peerJid) {
  5478. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5479. var contactlist = $('#contacts');
  5480. var newContact = document.createElement('li');
  5481. newContact.id = resourceJid;
  5482. newContact.className = "clickable";
  5483. newContact.onclick = function (event) {
  5484. if (event.currentTarget.className === "clickable") {
  5485. $(ContactList).trigger('contactclicked', [peerJid]);
  5486. }
  5487. };
  5488. newContact.appendChild(createAvatar(peerJid));
  5489. newContact.appendChild(createDisplayNameParagraph("participant"));
  5490. if (resourceJid === APP.xmpp.myResource()) {
  5491. contactlist.prepend(newContact);
  5492. }
  5493. else {
  5494. contactlist.append(newContact);
  5495. }
  5496. updateNumberOfParticipants(1);
  5497. },
  5498. /**
  5499. * Removes a contact for the given peer jid.
  5500. *
  5501. * @param peerJid the peerJid corresponding to the contact to remove
  5502. */
  5503. removeContact: function (peerJid) {
  5504. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5505. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5506. if (contact && contact.length > 0) {
  5507. var contactlist = $('#contactlist>ul');
  5508. contactlist.get(0).removeChild(contact.get(0));
  5509. updateNumberOfParticipants(-1);
  5510. }
  5511. },
  5512. setVisualNotification: function (show, stopGlowingIn) {
  5513. var glower = $('#contactListButton');
  5514. if (show && !notificationInterval) {
  5515. notificationInterval = window.setInterval(function () {
  5516. glower.toggleClass('active glowing');
  5517. }, 800);
  5518. }
  5519. else if (!show && notificationInterval) {
  5520. stopGlowing(glower);
  5521. }
  5522. if (stopGlowingIn) {
  5523. setTimeout(function () {
  5524. stopGlowing(glower);
  5525. }, stopGlowingIn);
  5526. }
  5527. },
  5528. setClickable: function (resourceJid, isClickable) {
  5529. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5530. if (isClickable) {
  5531. contact.addClass('clickable');
  5532. } else {
  5533. contact.removeClass('clickable');
  5534. }
  5535. },
  5536. onDisplayNameChange: function (peerJid, displayName) {
  5537. if (peerJid === 'localVideoContainer')
  5538. peerJid = APP.xmpp.myJid();
  5539. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5540. var contactName = $('#contacts #' + resourceJid + '>p');
  5541. if (contactName && displayName && displayName.length > 0)
  5542. contactName.html(displayName);
  5543. },
  5544. userAvatarChanged: function (resourceJid, contactListUrl) {
  5545. // set the avatar in the contact list
  5546. var contact = $('#' + resourceJid + '>img');
  5547. if (contact && contact.length > 0) {
  5548. contact.get(0).src = contactListUrl;
  5549. }
  5550. }
  5551. };
  5552. module.exports = ContactList;
  5553. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5554. /* global APP, $ */
  5555. var Avatar = require("../../avatar/Avatar");
  5556. var Settings = require("./../../../settings/Settings");
  5557. var UIUtil = require("../../util/UIUtil");
  5558. var languages = require("../../../../service/translation/languages");
  5559. function generateLanguagesSelectBox() {
  5560. var currentLang = APP.translation.getCurrentLanguage();
  5561. var html = "<select id=\"languages_selectbox\">";
  5562. var langArray = languages.getLanguages();
  5563. for(var i = 0; i < langArray.length; i++) {
  5564. var lang = langArray[i];
  5565. html += "<option ";
  5566. if(lang === currentLang)
  5567. html += "selected ";
  5568. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5569. html += "</option>";
  5570. }
  5571. return html + "</select>";
  5572. }
  5573. var SettingsMenu = {
  5574. init: function () {
  5575. var startMutedSelector = $("#startMutedOptions");
  5576. startMutedSelector.before(generateLanguagesSelectBox());
  5577. APP.translation.translateElement($("#languages_selectbox"));
  5578. $('#settingsmenu>input').keyup(function(event){
  5579. if(event.keyCode === 13) {//enter
  5580. SettingsMenu.update();
  5581. }
  5582. });
  5583. if (APP.xmpp.isModerator()) {
  5584. startMutedSelector.css("display", "block");
  5585. }
  5586. else {
  5587. startMutedSelector.css("display", "none");
  5588. }
  5589. $("#updateSettings").click(function () {
  5590. SettingsMenu.update();
  5591. });
  5592. },
  5593. onRoleChanged: function () {
  5594. if(APP.xmpp.isModerator()) {
  5595. $("#startMutedOptions").css("display", "block");
  5596. }
  5597. else {
  5598. $("#startMutedOptions").css("display", "none");
  5599. }
  5600. },
  5601. setStartMuted: function (audio, video) {
  5602. $("#startAudioMuted").attr("checked", audio);
  5603. $("#startVideoMuted").attr("checked", video);
  5604. },
  5605. update: function() {
  5606. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5607. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5608. if(newDisplayName) {
  5609. var displayName = Settings.setDisplayName(newDisplayName);
  5610. APP.xmpp.addToPresence("displayName", displayName, true);
  5611. }
  5612. var language = $("#languages_selectbox").val();
  5613. APP.translation.setLanguage(language);
  5614. Settings.setLanguage(language);
  5615. APP.xmpp.addToPresence("email", newEmail);
  5616. var email = Settings.setEmail(newEmail);
  5617. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5618. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5619. APP.xmpp.addToPresence("startMuted",
  5620. [startAudioMuted, startVideoMuted]);
  5621. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5622. },
  5623. isVisible: function() {
  5624. return $('#settingsmenu').is(':visible');
  5625. },
  5626. setDisplayName: function(newDisplayName) {
  5627. var displayName = Settings.setDisplayName(newDisplayName);
  5628. $('#setDisplayName').get(0).value = displayName;
  5629. },
  5630. onDisplayNameChange: function(peerJid, newDisplayName) {
  5631. if(peerJid === 'localVideoContainer' ||
  5632. peerJid === APP.xmpp.myJid()) {
  5633. this.setDisplayName(newDisplayName);
  5634. }
  5635. },
  5636. changeAvatar: function (thumbUrl) {
  5637. $('#avatar').get(0).src = thumbUrl;
  5638. }
  5639. };
  5640. module.exports = SettingsMenu;
  5641. },{"../../../../service/translation/languages":160,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5642. /* global $ */
  5643. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5644. var buttonHandlers = {
  5645. "bottom_toolbar_contact_list": function () {
  5646. BottomToolbar.toggleContactList();
  5647. },
  5648. "bottom_toolbar_film_strip": function () {
  5649. BottomToolbar.toggleFilmStrip();
  5650. },
  5651. "bottom_toolbar_chat": function () {
  5652. BottomToolbar.toggleChat();
  5653. }
  5654. };
  5655. var BottomToolbar = (function (my) {
  5656. my.init = function () {
  5657. for(var k in buttonHandlers)
  5658. $("#" + k).click(buttonHandlers[k]);
  5659. };
  5660. my.toggleChat = function() {
  5661. PanelToggler.toggleChat();
  5662. };
  5663. my.toggleContactList = function() {
  5664. PanelToggler.toggleContactList();
  5665. };
  5666. my.toggleFilmStrip = function() {
  5667. var filmstrip = $("#remoteVideos");
  5668. filmstrip.toggleClass("hidden");
  5669. };
  5670. $(document).bind("remotevideo.resized", function (event, width, height) {
  5671. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5672. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5673. });
  5674. return my;
  5675. }(BottomToolbar || {}));
  5676. module.exports = BottomToolbar;
  5677. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5678. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5679. Util */
  5680. var messageHandler = require("../util/MessageHandler");
  5681. var BottomToolbar = require("./BottomToolbar");
  5682. var Prezi = require("../prezi/Prezi");
  5683. var Etherpad = require("../etherpad/Etherpad");
  5684. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5685. var Authentication = require("../authentication/Authentication");
  5686. var UIUtil = require("../util/UIUtil");
  5687. var AuthenticationEvents
  5688. = require("../../../service/authentication/AuthenticationEvents");
  5689. var roomUrl = null;
  5690. var sharedKey = '';
  5691. var UI = null;
  5692. var recordingToaster = null;
  5693. var buttonHandlers = {
  5694. "toolbar_button_mute": function () {
  5695. return APP.UI.toggleAudio();
  5696. },
  5697. "toolbar_button_camera": function () {
  5698. return APP.UI.toggleVideo();
  5699. },
  5700. /*"toolbar_button_authentication": function () {
  5701. return Toolbar.authenticateClicked();
  5702. },*/
  5703. "toolbar_button_record": function () {
  5704. return toggleRecording();
  5705. },
  5706. "toolbar_button_security": function () {
  5707. return Toolbar.openLockDialog();
  5708. },
  5709. "toolbar_button_link": function () {
  5710. return Toolbar.openLinkDialog();
  5711. },
  5712. "toolbar_button_chat": function () {
  5713. return BottomToolbar.toggleChat();
  5714. },
  5715. "toolbar_button_prezi": function () {
  5716. return Prezi.openPreziDialog();
  5717. },
  5718. "toolbar_button_etherpad": function () {
  5719. return Etherpad.toggleEtherpad(0);
  5720. },
  5721. "toolbar_button_desktopsharing": function () {
  5722. return APP.desktopsharing.toggleScreenSharing();
  5723. },
  5724. "toolbar_button_fullScreen": function() {
  5725. UIUtil.buttonClick("#toolbar_button_fullScreen", "icon-full-screen icon-exit-full-screen");
  5726. return Toolbar.toggleFullScreen();
  5727. },
  5728. "toolbar_button_sip": function () {
  5729. return callSipButtonClicked();
  5730. },
  5731. "toolbar_button_dialpad": function () {
  5732. return dialpadButtonClicked();
  5733. },
  5734. "toolbar_button_settings": function () {
  5735. PanelToggler.toggleSettingsMenu();
  5736. },
  5737. "toolbar_button_hangup": function () {
  5738. return hangup();
  5739. },
  5740. "toolbar_button_login": function () {
  5741. Toolbar.authenticateClicked();
  5742. },
  5743. "toolbar_button_logout": function () {
  5744. // Ask for confirmation
  5745. messageHandler.openTwoButtonDialog(
  5746. "dialog.logoutTitle",
  5747. null,
  5748. "dialog.logoutQuestion",
  5749. null,
  5750. false,
  5751. "dialog.Yes",
  5752. function (evt, yes) {
  5753. if (yes) {
  5754. APP.xmpp.logout(function (url) {
  5755. if (url) {
  5756. window.location.href = url;
  5757. } else {
  5758. hangup();
  5759. }
  5760. });
  5761. }
  5762. });
  5763. }
  5764. };
  5765. function hangup() {
  5766. APP.xmpp.disposeConference();
  5767. if(config.enableWelcomePage) {
  5768. setTimeout(function() {
  5769. window.localStorage.welcomePageDisabled = false;
  5770. window.location.pathname = "/";
  5771. }, 10000);
  5772. }
  5773. var title = APP.translation.generateTranslationHTML(
  5774. "dialog.sessTerminated");
  5775. var msg = APP.translation.generateTranslationHTML(
  5776. "dialog.hungUp");
  5777. var button = APP.translation.generateTranslationHTML(
  5778. "dialog.joinAgain");
  5779. var buttons = [];
  5780. buttons.push({title: button, value: true});
  5781. UI.messageHandler.openDialog(
  5782. title,
  5783. msg,
  5784. true,
  5785. buttons,
  5786. function(event, value, message, formVals) {
  5787. window.location.reload();
  5788. return false;
  5789. }
  5790. );
  5791. }
  5792. /**
  5793. * Starts or stops the recording for the conference.
  5794. */
  5795. function toggleRecording(predefinedToken) {
  5796. APP.xmpp.toggleRecording(function (callback) {
  5797. if (predefinedToken) {
  5798. callback(UIUtil.escapeHtml(predefinedToken));
  5799. return;
  5800. }
  5801. var msg = APP.translation.generateTranslationHTML(
  5802. "dialog.recordingToken");
  5803. var token = APP.translation.translateString("dialog.token");
  5804. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5805. '<h2>' + msg + '</h2>' +
  5806. '<input name="recordingToken" type="text" ' +
  5807. ' data-i18n="[placeholder]dialog.token" ' +
  5808. 'placeholder="' + token + '" autofocus>',
  5809. false,
  5810. "dialog.Save",
  5811. function (e, v, m, f) {
  5812. if (v) {
  5813. var token = f.recordingToken;
  5814. if (token) {
  5815. callback(UIUtil.escapeHtml(token));
  5816. }
  5817. }
  5818. },
  5819. null,
  5820. function () { },
  5821. ':input:first'
  5822. );
  5823. }, Toolbar.setRecordingButtonState);
  5824. }
  5825. /**
  5826. * Locks / unlocks the room.
  5827. */
  5828. function lockRoom(lock) {
  5829. var currentSharedKey = '';
  5830. if (lock)
  5831. currentSharedKey = sharedKey;
  5832. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5833. // password is required
  5834. if (sharedKey) {
  5835. console.log('set room password');
  5836. Toolbar.lockLockButton();
  5837. }
  5838. else {
  5839. console.log('removed room password');
  5840. Toolbar.unlockLockButton();
  5841. }
  5842. }, function (err) {
  5843. console.warn('setting password failed', err);
  5844. messageHandler.showError("dialog.lockTitle",
  5845. "dialog.lockMessage");
  5846. Toolbar.setSharedKey('');
  5847. }, function () {
  5848. console.warn('room passwords not supported');
  5849. messageHandler.showError("dialog.warning",
  5850. "dialog.passwordNotSupported");
  5851. Toolbar.setSharedKey('');
  5852. });
  5853. }
  5854. /**
  5855. * Invite participants to conference.
  5856. */
  5857. function inviteParticipants() {
  5858. if (roomUrl === null)
  5859. return;
  5860. var sharedKeyText = "";
  5861. if (sharedKey && sharedKey.length > 0) {
  5862. sharedKeyText =
  5863. APP.translation.translateString("email.sharedKey",
  5864. {sharedKey: sharedKey});
  5865. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5866. }
  5867. var supportedBrowsers = "Chromium, Google Chrome " +
  5868. APP.translation.translateString("email.and") + " Opera";
  5869. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5870. var subject = APP.translation.translateString("email.subject",
  5871. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5872. var body = APP.translation.translateString("email.body",
  5873. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5874. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5875. body = body.replace(/\n/g, "%0D%0A");
  5876. if (window.localStorage.displayname) {
  5877. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5878. }
  5879. if (interfaceConfig.INVITATION_POWERED_BY) {
  5880. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5881. }
  5882. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5883. }
  5884. function dialpadButtonClicked() {
  5885. //TODO show the dialpad box
  5886. }
  5887. function callSipButtonClicked() {
  5888. var defaultNumber
  5889. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5890. var sipMsg = APP.translation.generateTranslationHTML(
  5891. "dialog.sipMsg");
  5892. messageHandler.openTwoButtonDialog(null, null, null,
  5893. '<h2>' + sipMsg + '</h2>' +
  5894. '<input name="sipNumber" type="text"' +
  5895. ' value="' + defaultNumber + '" autofocus>',
  5896. false,
  5897. "dialog.Dial",
  5898. function (e, v, m, f) {
  5899. if (v) {
  5900. var numberInput = f.sipNumber;
  5901. if (numberInput) {
  5902. APP.xmpp.dial(
  5903. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5904. }
  5905. }
  5906. },
  5907. null, null, ':input:first'
  5908. );
  5909. }
  5910. var Toolbar = (function (my) {
  5911. my.init = function (ui) {
  5912. for(var k in buttonHandlers)
  5913. $("#" + k).click(buttonHandlers[k]);
  5914. UI = ui;
  5915. // Update login info
  5916. APP.xmpp.addListener(
  5917. AuthenticationEvents.IDENTITY_UPDATED,
  5918. function (authenticationEnabled, userIdentity) {
  5919. var loggedIn = false;
  5920. if (userIdentity) {
  5921. loggedIn = true;
  5922. }
  5923. Toolbar.showAuthenticateButton(authenticationEnabled);
  5924. if (authenticationEnabled) {
  5925. Toolbar.setAuthenticatedIdentity(userIdentity);
  5926. Toolbar.showLoginButton(!loggedIn);
  5927. Toolbar.showLogoutButton(loggedIn);
  5928. }
  5929. }
  5930. );
  5931. };
  5932. /**
  5933. * Sets shared key
  5934. * @param sKey the shared key
  5935. */
  5936. my.setSharedKey = function (sKey) {
  5937. sharedKey = sKey;
  5938. };
  5939. my.authenticateClicked = function () {
  5940. Authentication.focusAuthenticationWindow();
  5941. if (!APP.xmpp.isExternalAuthEnabled()) {
  5942. Authentication.xmppAuthenticate();
  5943. return;
  5944. }
  5945. // Get authentication URL
  5946. if (!APP.xmpp.isMUCJoined()) {
  5947. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  5948. // If conference has not been started yet - redirect to login page
  5949. window.location.href = url;
  5950. });
  5951. } else {
  5952. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  5953. // Otherwise - open popup with authentication URL
  5954. var authenticationWindow = Authentication.createAuthenticationWindow(
  5955. function () {
  5956. // On popup closed - retry room allocation
  5957. APP.xmpp.allocateConferenceFocus(
  5958. APP.UI.getRoomName(),
  5959. function () { console.info("AUTH DONE"); }
  5960. );
  5961. }, url);
  5962. if (!authenticationWindow) {
  5963. messageHandler.openMessageDialog(
  5964. null, "dialog.popupError");
  5965. }
  5966. });
  5967. }
  5968. };
  5969. /**
  5970. * Updates the room invite url.
  5971. */
  5972. my.updateRoomUrl = function (newRoomUrl) {
  5973. roomUrl = newRoomUrl;
  5974. // If the invite dialog has been already opened we update the information.
  5975. var inviteLink = document.getElementById('inviteLinkRef');
  5976. if (inviteLink) {
  5977. inviteLink.value = roomUrl;
  5978. inviteLink.select();
  5979. $('#inviteLinkRef').parent()
  5980. .find('button[value=true]').prop('disabled', false);
  5981. }
  5982. };
  5983. /**
  5984. * Disables and enables some of the buttons.
  5985. */
  5986. my.setupButtonsFromConfig = function () {
  5987. if (config.disablePrezi) {
  5988. $("#toolbar_button_prezi").css({display: "none"});
  5989. }
  5990. };
  5991. /**
  5992. * Opens the lock room dialog.
  5993. */
  5994. my.openLockDialog = function () {
  5995. // Only the focus is able to set a shared key.
  5996. if (!APP.xmpp.isModerator()) {
  5997. if (sharedKey) {
  5998. messageHandler.openMessageDialog(null,
  5999. "dialog.passwordError");
  6000. } else {
  6001. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6002. }
  6003. } else {
  6004. if (sharedKey) {
  6005. messageHandler.openTwoButtonDialog(null, null,
  6006. "dialog.passwordCheck",
  6007. null,
  6008. false,
  6009. "dialog.Remove",
  6010. function (e, v) {
  6011. if (v) {
  6012. Toolbar.setSharedKey('');
  6013. lockRoom(false);
  6014. }
  6015. });
  6016. } else {
  6017. var msg = APP.translation.generateTranslationHTML(
  6018. "dialog.passwordMsg");
  6019. var yourPassword = APP.translation.translateString(
  6020. "dialog.yourPassword");
  6021. messageHandler.openTwoButtonDialog(null, null, null,
  6022. '<h2>' + msg + '</h2>' +
  6023. '<input name="lockKey" type="text"' +
  6024. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6025. 'placeholder="' + yourPassword + '" autofocus>',
  6026. false,
  6027. "dialog.Save",
  6028. function (e, v, m, f) {
  6029. if (v) {
  6030. var lockKey = f.lockKey;
  6031. if (lockKey) {
  6032. Toolbar.setSharedKey(
  6033. UIUtil.escapeHtml(lockKey));
  6034. lockRoom(true);
  6035. }
  6036. }
  6037. },
  6038. null, null, 'input:first'
  6039. );
  6040. }
  6041. }
  6042. };
  6043. /**
  6044. * Opens the invite link dialog.
  6045. */
  6046. my.openLinkDialog = function () {
  6047. var inviteAttreibutes;
  6048. if (roomUrl === null) {
  6049. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6050. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6051. } else {
  6052. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6053. }
  6054. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6055. null, null,
  6056. '<input id="inviteLinkRef" type="text" ' +
  6057. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6058. false,
  6059. "dialog.Invite",
  6060. function (e, v) {
  6061. if (v) {
  6062. if (roomUrl) {
  6063. inviteParticipants();
  6064. }
  6065. }
  6066. },
  6067. function (event) {
  6068. if (roomUrl) {
  6069. document.getElementById('inviteLinkRef').select();
  6070. } else {
  6071. if (event && event.target)
  6072. $(event.target)
  6073. .find('button[value=true]').prop('disabled', true);
  6074. }
  6075. }
  6076. );
  6077. };
  6078. /**
  6079. * Opens the settings dialog.
  6080. * FIXME: not used ?
  6081. */
  6082. my.openSettingsDialog = function () {
  6083. var settings1 = APP.translation.generateTranslationHTML(
  6084. "dialog.settings1");
  6085. var settings2 = APP.translation.generateTranslationHTML(
  6086. "dialog.settings2");
  6087. var settings3 = APP.translation.generateTranslationHTML(
  6088. "dialog.settings3");
  6089. var yourPassword = APP.translation.translateString(
  6090. "dialog.yourPassword");
  6091. messageHandler.openTwoButtonDialog(null,
  6092. '<h2>' + settings1 + '</h2>' +
  6093. '<input type="checkbox" id="initMuted">' +
  6094. settings2 + '<br/>' +
  6095. '<input type="checkbox" id="requireNicknames">' +
  6096. settings3 +
  6097. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6098. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6099. null,
  6100. null,
  6101. false,
  6102. "dialog.Save",
  6103. function () {
  6104. document.getElementById('lockKey').focus();
  6105. },
  6106. function (e, v) {
  6107. if (v) {
  6108. if ($('#initMuted').is(":checked")) {
  6109. // it is checked
  6110. }
  6111. if ($('#requireNicknames').is(":checked")) {
  6112. // it is checked
  6113. }
  6114. /*
  6115. var lockKey = document.getElementById('lockKey');
  6116. if (lockKey.value) {
  6117. setSharedKey(lockKey.value);
  6118. lockRoom(true);
  6119. }
  6120. */
  6121. }
  6122. }
  6123. );
  6124. };
  6125. /**
  6126. * Toggles the application in and out of full screen mode
  6127. * (a.k.a. presentation mode in Chrome).
  6128. */
  6129. my.toggleFullScreen = function () {
  6130. var fsElement = document.documentElement;
  6131. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6132. //Enter Full Screen
  6133. if (fsElement.mozRequestFullScreen) {
  6134. fsElement.mozRequestFullScreen();
  6135. }
  6136. else {
  6137. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6138. }
  6139. } else {
  6140. //Exit Full Screen
  6141. if (document.mozCancelFullScreen) {
  6142. document.mozCancelFullScreen();
  6143. } else {
  6144. document.webkitCancelFullScreen();
  6145. }
  6146. }
  6147. };
  6148. /**
  6149. * Unlocks the lock button state.
  6150. */
  6151. my.unlockLockButton = function () {
  6152. if ($("#toolbar_button_security").hasClass("icon-security-locked"))
  6153. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6154. };
  6155. /**
  6156. * Updates the lock button state to locked.
  6157. */
  6158. my.lockLockButton = function () {
  6159. if ($("#toolbar_button_security").hasClass("icon-security"))
  6160. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6161. };
  6162. /**
  6163. * Shows or hides authentication button
  6164. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6165. */
  6166. my.showAuthenticateButton = function (show) {
  6167. if (show) {
  6168. $('#authentication').css({display: "inline"});
  6169. }
  6170. else {
  6171. $('#authentication').css({display: "none"});
  6172. }
  6173. };
  6174. // Shows or hides the 'recording' button.
  6175. my.showRecordingButton = function (show) {
  6176. if (!config.enableRecording) {
  6177. return;
  6178. }
  6179. if (show) {
  6180. $('#toolbar_button_record').css({display: "inline-block"});
  6181. }
  6182. else {
  6183. $('#toolbar_button_record').css({display: "none"});
  6184. }
  6185. };
  6186. // Sets the state of the recording button
  6187. my.setRecordingButtonState = function (recordingState) {
  6188. var selector = $('#toolbar_button_record');
  6189. if (recordingState === 'on') {
  6190. selector.removeClass("icon-recEnable");
  6191. selector.addClass("icon-recEnable active");
  6192. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6193. var recordOnKey = "recording.on";
  6194. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6195. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6196. setTimeout(function(){
  6197. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6198. $('#videoConnectionMessage').css({display: "none"});
  6199. }, 1500);
  6200. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6201. null, null, {timeOut: 0, closeButton: null, tapToDismiss: false});
  6202. } else if (recordingState === 'off') {
  6203. selector.removeClass("icon-recEnable active");
  6204. selector.addClass("icon-recEnable");
  6205. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6206. $('#videoConnectionMessage').css({display: "none"});
  6207. if (recordingToaster)
  6208. messageHandler.remove(recordingToaster);
  6209. } else if (recordingState === 'pending') {
  6210. selector.removeClass("icon-recEnable active");
  6211. selector.addClass("icon-recEnable");
  6212. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6213. var recordPendingKey = "recording.pending";
  6214. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6215. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6216. $('#videoConnectionMessage').css({display: "block"});
  6217. }
  6218. };
  6219. // checks whether recording is enabled and whether we have params to start automatically recording
  6220. my.checkAutoRecord = function () {
  6221. if (config.enableRecording && config.autoRecord) {
  6222. toggleRecording(config.autoRecordToken);
  6223. }
  6224. }
  6225. // Shows or hides SIP calls button
  6226. my.showSipCallButton = function (show) {
  6227. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6228. $('#toolbar_button_sip').css({display: "inline-block"});
  6229. } else {
  6230. $('#toolbar_button_sip').css({display: "none"});
  6231. }
  6232. };
  6233. // Shows or hides the dialpad button
  6234. my.showDialPadButton = function (show) {
  6235. if (show) {
  6236. $('#toolbar_button_dialpad').css({display: "inline-block"});
  6237. } else {
  6238. $('#toolbar_button_dialpad').css({display: "none"});
  6239. }
  6240. };
  6241. /**
  6242. * Displays user authenticated identity name(login).
  6243. * @param authIdentity identity name to be displayed.
  6244. */
  6245. my.setAuthenticatedIdentity = function (authIdentity) {
  6246. if (authIdentity) {
  6247. var selector = $('#toolbar_auth_identity');
  6248. selector.css({display: "list-item"});
  6249. selector.text(authIdentity);
  6250. } else {
  6251. $('#toolbar_auth_identity').css({display: "none"});
  6252. }
  6253. };
  6254. /**
  6255. * Shows/hides login button.
  6256. * @param show <tt>true</tt> to show
  6257. */
  6258. my.showLoginButton = function (show) {
  6259. if (show) {
  6260. $('#toolbar_button_login').css({display: "list-item"});
  6261. } else {
  6262. $('#toolbar_button_login').css({display: "none"});
  6263. }
  6264. };
  6265. /**
  6266. * Shows/hides logout button.
  6267. * @param show <tt>true</tt> to show
  6268. */
  6269. my.showLogoutButton = function (show) {
  6270. if (show) {
  6271. $('#toolbar_button_logout').css({display: "list-item"});
  6272. } else {
  6273. $('#toolbar_button_logout').css({display: "none"});
  6274. }
  6275. };
  6276. /**
  6277. * Sets the state of the button. The button has blue glow if desktop
  6278. * streaming is active.
  6279. * @param active the state of the desktop streaming.
  6280. */
  6281. my.changeDesktopSharingButtonState = function (active) {
  6282. var button = $("#toolbar_button_desktopsharing");
  6283. if (active) {
  6284. button.addClass("glow");
  6285. } else {
  6286. button.removeClass("glow");
  6287. }
  6288. };
  6289. return my;
  6290. }(Toolbar || {}));
  6291. module.exports = Toolbar;
  6292. },{"../../../service/authentication/AuthenticationEvents":156,"../authentication/Authentication":14,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../side_pannels/SidePanelToggler":20,"../util/MessageHandler":31,"../util/UIUtil":33,"./BottomToolbar":27}],29:[function(require,module,exports){
  6293. /* global APP, config, $, interfaceConfig, Moderator,
  6294. DesktopStreaming.showDesktopSharingButton */
  6295. var toolbarTimeoutObject,
  6296. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6297. function showDesktopSharingButton() {
  6298. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6299. $('#toolbar_button_desktopsharing').css({display: "inline-block"});
  6300. } else {
  6301. $('#toolbar_button_desktopsharing').css({display: "none"});
  6302. }
  6303. }
  6304. /**
  6305. * Hides the toolbar.
  6306. */
  6307. function hideToolbar() {
  6308. if(config.alwaysVisibleToolbar)
  6309. return;
  6310. var header = $("#header"),
  6311. bottomToolbar = $("#bottomToolbar");
  6312. var isToolbarHover = false;
  6313. header.find('*').each(function () {
  6314. var id = $(this).attr('id');
  6315. if ($("#" + id + ":hover").length > 0) {
  6316. isToolbarHover = true;
  6317. }
  6318. });
  6319. if ($("#bottomToolbar:hover").length > 0) {
  6320. isToolbarHover = true;
  6321. }
  6322. clearTimeout(toolbarTimeoutObject);
  6323. toolbarTimeoutObject = null;
  6324. if (!isToolbarHover) {
  6325. header.hide("slide", { direction: "up", duration: 300});
  6326. $('#subject').animate({top: "-=40"}, 300);
  6327. if ($("#remoteVideos").hasClass("hidden")) {
  6328. bottomToolbar.hide(
  6329. "slide", {direction: "right", duration: 300});
  6330. }
  6331. }
  6332. else {
  6333. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6334. }
  6335. }
  6336. var ToolbarToggler = {
  6337. /**
  6338. * Shows the main toolbar.
  6339. */
  6340. showToolbar: function () {
  6341. if (interfaceConfig.filmStripOnly)
  6342. return;
  6343. var header = $("#header"),
  6344. bottomToolbar = $("#bottomToolbar");
  6345. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6346. header.show("slide", { direction: "up", duration: 300});
  6347. $('#subject').animate({top: "+=40"}, 300);
  6348. if (!bottomToolbar.is(":visible")) {
  6349. bottomToolbar.show(
  6350. "slide", {direction: "right", duration: 300});
  6351. }
  6352. if (toolbarTimeoutObject) {
  6353. clearTimeout(toolbarTimeoutObject);
  6354. toolbarTimeoutObject = null;
  6355. }
  6356. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6357. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6358. }
  6359. if (APP.xmpp.isModerator())
  6360. {
  6361. // TODO: Enable settings functionality.
  6362. // Need to uncomment the settings button in index.html.
  6363. // $('#settingsButton').css({visibility:"visible"});
  6364. }
  6365. // Show/hide desktop sharing button
  6366. showDesktopSharingButton();
  6367. },
  6368. /**
  6369. * Docks/undocks the toolbar.
  6370. *
  6371. * @param isDock indicates what operation to perform
  6372. */
  6373. dockToolbar: function (isDock) {
  6374. if (interfaceConfig.filmStripOnly)
  6375. return;
  6376. if (isDock) {
  6377. // First make sure the toolbar is shown.
  6378. if (!$('#header').is(':visible')) {
  6379. this.showToolbar();
  6380. }
  6381. // Then clear the time out, to dock the toolbar.
  6382. if (toolbarTimeoutObject) {
  6383. clearTimeout(toolbarTimeoutObject);
  6384. toolbarTimeoutObject = null;
  6385. }
  6386. }
  6387. else {
  6388. if (!$('#header').is(':visible')) {
  6389. this.showToolbar();
  6390. }
  6391. else {
  6392. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6393. }
  6394. }
  6395. },
  6396. showDesktopSharingButton: showDesktopSharingButton
  6397. };
  6398. module.exports = ToolbarToggler;
  6399. },{}],30:[function(require,module,exports){
  6400. /* global $ */
  6401. var JitsiPopover = (function () {
  6402. /**
  6403. * Constructs new JitsiPopover and attaches it to the element
  6404. * @param element jquery selector
  6405. * @param options the options for the popover.
  6406. * @constructor
  6407. */
  6408. function JitsiPopover(element, options)
  6409. {
  6410. this.options = {
  6411. skin: "white",
  6412. content: ""
  6413. };
  6414. if(options)
  6415. {
  6416. if(options.skin)
  6417. this.options.skin = options.skin;
  6418. if(options.content)
  6419. this.options.content = options.content;
  6420. }
  6421. this.elementIsHovered = false;
  6422. this.popoverIsHovered = false;
  6423. this.popoverShown = false;
  6424. element.data("jitsi_popover", this);
  6425. this.element = element;
  6426. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6427. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6428. '<div class="jitsiPopupmenuPadding"></div></div>';
  6429. var self = this;
  6430. this.element.on("mouseenter", function () {
  6431. self.elementIsHovered = true;
  6432. self.show();
  6433. }).on("mouseleave", function () {
  6434. self.elementIsHovered = false;
  6435. setTimeout(function () {
  6436. self.hide();
  6437. }, 10);
  6438. });
  6439. }
  6440. /**
  6441. * Shows the popover
  6442. */
  6443. JitsiPopover.prototype.show = function () {
  6444. if(!JitsiPopover.enabled)
  6445. return;
  6446. this.createPopover();
  6447. this.popoverShown = true;
  6448. };
  6449. /**
  6450. * Hides the popover
  6451. */
  6452. JitsiPopover.prototype.hide = function () {
  6453. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6454. this.popoverShown) {
  6455. this.forceHide();
  6456. }
  6457. };
  6458. /**
  6459. * Hides the popover.
  6460. */
  6461. JitsiPopover.prototype.forceHide = function () {
  6462. $(".jitsipopover").remove();
  6463. this.popoverShown = false;
  6464. };
  6465. /**
  6466. * Creates the popover html.
  6467. */
  6468. JitsiPopover.prototype.createPopover = function () {
  6469. $("body").append(this.template);
  6470. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6471. var self = this;
  6472. $(".jitsipopover").on("mouseenter", function () {
  6473. self.popoverIsHovered = true;
  6474. }).on("mouseleave", function () {
  6475. self.popoverIsHovered = false;
  6476. self.hide();
  6477. });
  6478. this.refreshPosition();
  6479. };
  6480. /**
  6481. * Refreshes the position of the popover.
  6482. */
  6483. JitsiPopover.prototype.refreshPosition = function () {
  6484. $(".jitsipopover").position({
  6485. my: "bottom",
  6486. at: "top",
  6487. collision: "fit",
  6488. of: this.element,
  6489. using: function (position, elements) {
  6490. var calcLeft = elements.target.left - elements.element.left +
  6491. elements.target.width/2;
  6492. $(".jitsipopover").css(
  6493. {top: position.top, left: position.left, display: "table"});
  6494. $(".jitsipopover > .arrow").css({left: calcLeft});
  6495. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6496. {left: calcLeft - 50});
  6497. }
  6498. });
  6499. };
  6500. /**
  6501. * Updates the content of popover.
  6502. * @param content new content
  6503. */
  6504. JitsiPopover.prototype.updateContent = function (content) {
  6505. this.options.content = content;
  6506. if(!this.popoverShown)
  6507. return;
  6508. $(".jitsipopover").remove();
  6509. this.createPopover();
  6510. };
  6511. JitsiPopover.enabled = true;
  6512. return JitsiPopover;
  6513. })();
  6514. module.exports = JitsiPopover;
  6515. },{}],31:[function(require,module,exports){
  6516. /* global $, APP, jQuery, toastr */
  6517. /**
  6518. * Flag for enable/disable of the notifications.
  6519. * @type {boolean}
  6520. */
  6521. var notificationsEnabled = true;
  6522. var messageHandler = (function(my) {
  6523. /**
  6524. * Shows a message to the user.
  6525. *
  6526. * @param titleKey the title of the message
  6527. * @param messageKey the text of the message
  6528. */
  6529. my.openMessageDialog = function(titleKey, messageKey) {
  6530. var title = null;
  6531. if(titleKey) {
  6532. title = APP.translation.generateTranslationHTML(titleKey);
  6533. }
  6534. var message = APP.translation.generateTranslationHTML(messageKey);
  6535. $.prompt(message,
  6536. {title: title, persistent: false}
  6537. );
  6538. };
  6539. /**
  6540. * Shows a message to the user with two buttons: first is given as a
  6541. * parameter and the second is Cancel.
  6542. *
  6543. * @param titleString the title of the message
  6544. * @param msgString the text of the message
  6545. * @param persistent boolean value which determines whether the message is
  6546. * persistent or not
  6547. * @param leftButton the fist button's text
  6548. * @param submitFunction function to be called on submit
  6549. * @param loadedFunction function to be called after the prompt is fully
  6550. * loaded
  6551. * @param closeFunction function to be called after the prompt is closed
  6552. * @param focus optional focus selector or button index to be focused after
  6553. * the dialog is opened
  6554. * @param defaultButton index of default button which will be activated when
  6555. * the user press 'enter'. Indexed from 0.
  6556. */
  6557. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6558. persistent, leftButtonKey, submitFunction, loadedFunction,
  6559. closeFunction, focus, defaultButton) {
  6560. var buttons = [];
  6561. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6562. buttons.push({ title: leftButton, value: true});
  6563. var cancelButton
  6564. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6565. buttons.push({title: cancelButton, value: false});
  6566. var message = msgString, title = titleString;
  6567. if (titleKey) {
  6568. title = APP.translation.generateTranslationHTML(titleKey);
  6569. }
  6570. if (msgKey) {
  6571. message = APP.translation.generateTranslationHTML(msgKey);
  6572. }
  6573. $.prompt(message, {
  6574. title: title,
  6575. persistent: false,
  6576. buttons: buttons,
  6577. defaultButton: defaultButton,
  6578. focus: focus,
  6579. loaded: loadedFunction,
  6580. submit: submitFunction,
  6581. close: closeFunction
  6582. });
  6583. };
  6584. /**
  6585. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6586. *
  6587. * @param titleString the title of the message
  6588. * @param msgString the text of the message
  6589. * @param persistent boolean value which determines whether the message is
  6590. * persistent or not
  6591. * @param buttons object with the buttons. The keys must be the name of the
  6592. * button and value is the value that will be passed to
  6593. * submitFunction
  6594. * @param submitFunction function to be called on submit
  6595. * @param loadedFunction function to be called after the prompt is fully
  6596. * loaded
  6597. */
  6598. my.openDialog = function (titleString, msgString, persistent, buttons,
  6599. submitFunction, loadedFunction) {
  6600. var args = {
  6601. title: titleString,
  6602. persistent: persistent,
  6603. buttons: buttons,
  6604. defaultButton: 1,
  6605. loaded: loadedFunction,
  6606. submit: submitFunction
  6607. };
  6608. if (persistent) {
  6609. args.closeText = '';
  6610. }
  6611. return new Impromptu(msgString, args);
  6612. };
  6613. /**
  6614. * Closes currently opened dialog.
  6615. */
  6616. my.closeDialog = function () {
  6617. $.prompt.close();
  6618. };
  6619. /**
  6620. * Shows a dialog with different states to the user.
  6621. *
  6622. * @param statesObject object containing all the states of the dialog.
  6623. */
  6624. my.openDialogWithStates = function (statesObject, options) {
  6625. return new Impromptu(statesObject, options);
  6626. };
  6627. /**
  6628. * Opens new popup window for given <tt>url</tt> centered over current
  6629. * window.
  6630. *
  6631. * @param url the URL to be displayed in the popup window
  6632. * @param w the width of the popup window
  6633. * @param h the height of the popup window
  6634. * @param onPopupClosed optional callback function called when popup window
  6635. * has been closed.
  6636. *
  6637. * @returns {object} popup window object if opened successfully or undefined
  6638. * in case we failed to open it(popup blocked)
  6639. */
  6640. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6641. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6642. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6643. var popup = window.open(
  6644. url, '_blank',
  6645. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6646. if (popup && onPopupClosed) {
  6647. var pollTimer = window.setInterval(function () {
  6648. if (popup.closed !== false) {
  6649. window.clearInterval(pollTimer);
  6650. onPopupClosed();
  6651. }
  6652. }, 200);
  6653. }
  6654. return popup;
  6655. };
  6656. /**
  6657. * Shows a dialog prompting the user to send an error report.
  6658. *
  6659. * @param titleKey the title of the message
  6660. * @param msgKey the text of the message
  6661. * @param error the error that is being reported
  6662. */
  6663. my.openReportDialog = function(titleKey, msgKey, error) {
  6664. my.openMessageDialog(titleKey, msgKey);
  6665. console.log(error);
  6666. //FIXME send the error to the server
  6667. };
  6668. /**
  6669. * Shows an error dialog to the user.
  6670. * @param titleKey the title of the message.
  6671. * @param msgKey the text of the message.
  6672. */
  6673. my.showError = function(titleKey, msgKey) {
  6674. if (!titleKey) {
  6675. titleKey = "dialog.oops";
  6676. }
  6677. if (!msgKey) {
  6678. msgKey = "dialog.defaultError";
  6679. }
  6680. messageHandler.openMessageDialog(titleKey, msgKey);
  6681. };
  6682. /**
  6683. * Displayes notification.
  6684. * @param displayName display name of the participant that is associated with the notification.
  6685. * @param displayNameKey the key from the language file for the display name.
  6686. * @param cls css class for the notification
  6687. * @param messageKey the key from the language file for the text of the message.
  6688. * @param messageArguments object with the arguments for the message.
  6689. * @param options object with language options.
  6690. */
  6691. my.notify = function(displayName, displayNameKey,
  6692. cls, messageKey, messageArguments, options) {
  6693. if(!notificationsEnabled)
  6694. return;
  6695. var displayNameSpan = '<span class="nickname" ';
  6696. if (displayName) {
  6697. displayNameSpan += ">" + displayName;
  6698. } else {
  6699. displayNameSpan += "data-i18n='" + displayNameKey +
  6700. "'>" + APP.translation.translateString(displayNameKey);
  6701. }
  6702. displayNameSpan += "</span>";
  6703. return toastr.info(
  6704. displayNameSpan + '<br>' +
  6705. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6706. (messageArguments?
  6707. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6708. : "") + ">" +
  6709. APP.translation.translateString(messageKey,
  6710. messageArguments) +
  6711. '</span>', null, options);
  6712. };
  6713. /**
  6714. * Removes the toaster.
  6715. * @param toasterElement
  6716. */
  6717. my.remove = function(toasterElement) {
  6718. toasterElement.remove();
  6719. };
  6720. /**
  6721. * Disables notifications.
  6722. */
  6723. my.disableNotifications = function () {
  6724. notificationsEnabled = false;
  6725. };
  6726. /**
  6727. * Enables notifications.
  6728. */
  6729. my.enableNotifications = function () {
  6730. notificationsEnabled = true;
  6731. };
  6732. return my;
  6733. }(messageHandler || {}));
  6734. module.exports = messageHandler;
  6735. },{}],32:[function(require,module,exports){
  6736. var UIEvents = require("../../../service/UI/UIEvents");
  6737. var nickname = null;
  6738. var eventEmitter = null;
  6739. var NicknameHandler = {
  6740. init: function (emitter) {
  6741. eventEmitter = emitter;
  6742. var storedDisplayName = window.localStorage.displayname;
  6743. if (storedDisplayName) {
  6744. nickname = storedDisplayName;
  6745. }
  6746. },
  6747. setNickname: function (newNickname) {
  6748. if (!newNickname || nickname === newNickname)
  6749. return;
  6750. nickname = newNickname;
  6751. window.localStorage.displayname = nickname;
  6752. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6753. },
  6754. getNickname: function () {
  6755. return nickname;
  6756. },
  6757. addListener: function (type, listener) {
  6758. eventEmitter.on(type, listener);
  6759. }
  6760. };
  6761. module.exports = NicknameHandler;
  6762. },{"../../../service/UI/UIEvents":155}],33:[function(require,module,exports){
  6763. /* global $ */
  6764. /**
  6765. * Created by hristo on 12/22/14.
  6766. */
  6767. module.exports = {
  6768. /**
  6769. * Returns the available video width.
  6770. */
  6771. getAvailableVideoWidth: function (isVisible) {
  6772. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6773. if(typeof isVisible === "undefined" || isVisible === null)
  6774. isVisible = PanelToggler.isVisible();
  6775. var rightPanelWidth
  6776. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6777. return window.innerWidth - rightPanelWidth;
  6778. },
  6779. /**
  6780. * Changes the style class of the element given by id.
  6781. */
  6782. buttonClick: function(id, classname) {
  6783. $(id).toggleClass(classname); // add the class to the clicked element
  6784. },
  6785. /**
  6786. * Returns the text width for the given element.
  6787. *
  6788. * @param el the element
  6789. */
  6790. getTextWidth: function (el) {
  6791. return (el.clientWidth + 1);
  6792. },
  6793. /**
  6794. * Returns the text height for the given element.
  6795. *
  6796. * @param el the element
  6797. */
  6798. getTextHeight: function (el) {
  6799. return (el.clientHeight + 1);
  6800. },
  6801. /**
  6802. * Plays the sound given by id.
  6803. *
  6804. * @param id the identifier of the audio element.
  6805. */
  6806. playSoundNotification: function (id) {
  6807. document.getElementById(id).play();
  6808. },
  6809. /**
  6810. * Escapes the given text.
  6811. */
  6812. escapeHtml: function (unsafeText) {
  6813. return $('<div/>').text(unsafeText).html();
  6814. },
  6815. imageToGrayScale: function (canvas) {
  6816. var context = canvas.getContext('2d');
  6817. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6818. var pixels = imgData.data;
  6819. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6820. var grayscale
  6821. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  6822. pixels[i ] = grayscale; // red
  6823. pixels[i+1] = grayscale; // green
  6824. pixels[i+2] = grayscale; // blue
  6825. // pixels[i+3] is alpha
  6826. }
  6827. // redraw the image in black & white
  6828. context.putImageData(imgData, 0, 0);
  6829. },
  6830. setTooltip: function (element, key, position) {
  6831. element.setAttribute("data-i18n", "[data-content]" + key);
  6832. element.setAttribute("data-toggle", "popover");
  6833. element.setAttribute("data-placement", position);
  6834. element.setAttribute("data-html", true);
  6835. element.setAttribute("data-container", "body");
  6836. },
  6837. /**
  6838. * Inserts given child element as the first one into the container.
  6839. * @param container the container to which new child element will be added
  6840. * @param newChild the new element that will be inserted into the container
  6841. */
  6842. prependChild: function (container, newChild) {
  6843. var firstChild = container.childNodes[0];
  6844. if (firstChild) {
  6845. container.insertBefore(newChild, firstChild);
  6846. } else {
  6847. container.appendChild(newChild);
  6848. }
  6849. }
  6850. };
  6851. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6852. /* global APP, $ */
  6853. var JitsiPopover = require("../util/JitsiPopover");
  6854. /**
  6855. * Constructs new connection indicator.
  6856. * @param videoContainer the video container associated with the indicator.
  6857. * @constructor
  6858. */
  6859. function ConnectionIndicator(videoContainer, jid) {
  6860. this.videoContainer = videoContainer;
  6861. this.bandwidth = null;
  6862. this.packetLoss = null;
  6863. this.bitrate = null;
  6864. this.showMoreValue = false;
  6865. this.resolution = null;
  6866. this.transport = [];
  6867. this.popover = null;
  6868. this.jid = jid;
  6869. this.create();
  6870. }
  6871. /**
  6872. * Values for the connection quality
  6873. * @type {{98: string,
  6874. * 81: string,
  6875. * 64: string,
  6876. * 47: string,
  6877. * 30: string,
  6878. * 0: string}}
  6879. */
  6880. ConnectionIndicator.connectionQualityValues = {
  6881. 98: "18px", //full
  6882. 81: "15px",//4 bars
  6883. 64: "11px",//3 bars
  6884. 47: "7px",//2 bars
  6885. 30: "3px",//1 bar
  6886. 0: "0px"//empty
  6887. };
  6888. ConnectionIndicator.getIP = function(value) {
  6889. return value.substring(0, value.lastIndexOf(":"));
  6890. };
  6891. ConnectionIndicator.getPort = function(value) {
  6892. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6893. };
  6894. ConnectionIndicator.getStringFromArray = function (array) {
  6895. var res = "";
  6896. for(var i = 0; i < array.length; i++) {
  6897. res += (i === 0? "" : ", ") + array[i];
  6898. }
  6899. return res;
  6900. };
  6901. /**
  6902. * Generates the html content.
  6903. * @returns {string} the html content.
  6904. */
  6905. ConnectionIndicator.prototype.generateText = function () {
  6906. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6907. var translate = APP.translation.translateString;
  6908. if(this.bitrate === null) {
  6909. downloadBitrate = "N/A";
  6910. uploadBitrate = "N/A";
  6911. }
  6912. else {
  6913. downloadBitrate =
  6914. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6915. uploadBitrate =
  6916. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6917. }
  6918. if(this.packetLoss === null) {
  6919. packetLoss = "N/A";
  6920. } else {
  6921. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6922. (this.packetLoss.download !== null ?
  6923. this.packetLoss.download : "N/A") +
  6924. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6925. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  6926. "%";
  6927. }
  6928. var resolutionValue = null;
  6929. if(this.resolution && this.jid != null) {
  6930. var keys = Object.keys(this.resolution);
  6931. for(var ssrc in this.resolution) {
  6932. resolutionValue = this.resolution[ssrc];
  6933. }
  6934. }
  6935. if(this.jid === null) {
  6936. resolution = "";
  6937. if(this.resolution === null || !Object.keys(this.resolution) ||
  6938. Object.keys(this.resolution).length === 0) {
  6939. resolution = "N/A";
  6940. } else {
  6941. for (i in this.resolution) {
  6942. resolutionValue = this.resolution[i];
  6943. if (resolutionValue) {
  6944. if (resolutionValue.height &&
  6945. resolutionValue.width) {
  6946. resolution += (resolution === "" ? "" : ", ") +
  6947. resolutionValue.width + "x" +
  6948. resolutionValue.height;
  6949. }
  6950. }
  6951. }
  6952. }
  6953. } else if(!resolutionValue ||
  6954. !resolutionValue.height ||
  6955. !resolutionValue.width) {
  6956. resolution = "N/A";
  6957. } else {
  6958. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6959. }
  6960. var result = "<table style='width:100%'>" +
  6961. "<tr>" +
  6962. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6963. translate("connectionindicator.bitrate") + "</span></td>" +
  6964. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6965. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6966. uploadBitrate + "</td>" +
  6967. "</tr><tr>" +
  6968. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6969. translate("connectionindicator.packetloss") + "</span></td>" +
  6970. "<td>" + packetLoss + "</td>" +
  6971. "</tr><tr>" +
  6972. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6973. translate("connectionindicator.resolution") + "</span></td>" +
  6974. "<td>" + resolution + "</td></tr></table>";
  6975. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6976. result += "<div class=\"jitsipopover_showmore\" " +
  6977. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6978. // FIXME: we do not know local jid when this text is generated
  6979. //this.jid + "')\" data-i18n='connectionindicator." +
  6980. "local')\" data-i18n='connectionindicator." +
  6981. (this.showMoreValue ? "less" : "more") + "'>" +
  6982. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6983. "</div><br />";
  6984. }
  6985. if (this.showMoreValue) {
  6986. var downloadBandwidth, uploadBandwidth, transport;
  6987. if (this.bandwidth === null) {
  6988. downloadBandwidth = "N/A";
  6989. uploadBandwidth = "N/A";
  6990. } else {
  6991. downloadBandwidth = this.bandwidth.download?
  6992. this.bandwidth.download + " Kbps" :
  6993. "N/A";
  6994. uploadBandwidth = this.bandwidth.upload?
  6995. this.bandwidth.upload + " Kbps" :
  6996. "N/A";
  6997. }
  6998. if (!this.transport || this.transport.length === 0) {
  6999. transport = "<tr>" +
  7000. "<td><span class='jitsipopover_blue' " +
  7001. "data-i18n='connectionindicator.address'>" +
  7002. translate("connectionindicator.address") + "</span></td>" +
  7003. "<td> N/A</td></tr>";
  7004. } else {
  7005. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7006. for(i = 0; i < this.transport.length; i++) {
  7007. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7008. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7009. var localIP =
  7010. ConnectionIndicator.getIP(this.transport[i].localip);
  7011. var localPort =
  7012. ConnectionIndicator.getPort(this.transport[i].localip);
  7013. if(data.remoteIP.indexOf(ip) == -1) {
  7014. data.remoteIP.push(ip);
  7015. }
  7016. if(data.remotePort.indexOf(port) == -1) {
  7017. data.remotePort.push(port);
  7018. }
  7019. if(data.localIP.indexOf(localIP) == -1) {
  7020. data.localIP.push(localIP);
  7021. }
  7022. if(data.localPort.indexOf(localPort) == -1) {
  7023. data.localPort.push(localPort);
  7024. }
  7025. }
  7026. var local_address_key = "connectionindicator.localaddress";
  7027. var remote_address_key = "connectionindicator.remoteaddress";
  7028. var localTransport =
  7029. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7030. local_address_key +"' data-i18n-options='" +
  7031. JSON.stringify({count: data.localIP.length}) + "'>" +
  7032. translate(local_address_key, {count: data.localIP.length}) +
  7033. "</span></td><td> " +
  7034. ConnectionIndicator.getStringFromArray(data.localIP) +
  7035. "</td></tr>";
  7036. transport =
  7037. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7038. remote_address_key + "' data-i18n-options='" +
  7039. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7040. translate(remote_address_key,
  7041. {count: data.remoteIP.length}) +
  7042. "</span></td><td> " +
  7043. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7044. "</td></tr>";
  7045. var key_remote = "connectionindicator.remoteport",
  7046. key_local = "connectionindicator.localport";
  7047. transport += "<tr>" +
  7048. "<td>" +
  7049. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7050. "' data-i18n-options='" +
  7051. JSON.stringify({count: this.transport.length}) + "'>" +
  7052. translate(key_remote, {count: this.transport.length}) +
  7053. "</span></td><td>";
  7054. localTransport += "<tr>" +
  7055. "<td>" +
  7056. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7057. "' data-i18n-options='" +
  7058. JSON.stringify({count: this.transport.length}) + "'>" +
  7059. translate(key_local, {count: this.transport.length}) +
  7060. "</span></td><td>";
  7061. transport +=
  7062. ConnectionIndicator.getStringFromArray(data.remotePort);
  7063. localTransport +=
  7064. ConnectionIndicator.getStringFromArray(data.localPort);
  7065. transport += "</td></tr>";
  7066. transport += localTransport + "</td></tr>";
  7067. transport +="<tr>" +
  7068. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7069. translate("connectionindicator.transport") + "</span></td>" +
  7070. "<td>" + this.transport[0].type + "</td></tr>";
  7071. }
  7072. result += "<table style='width:100%'>" +
  7073. "<tr>" +
  7074. "<td>" +
  7075. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7076. translate("connectionindicator.bandwidth") + "</span>" +
  7077. "</td><td>" +
  7078. "<span class='jitsipopover_green'>&darr;</span>" +
  7079. downloadBandwidth +
  7080. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7081. uploadBandwidth + "</td></tr>";
  7082. result += transport + "</table>";
  7083. }
  7084. return result;
  7085. };
  7086. /**
  7087. * Shows or hide the additional information.
  7088. */
  7089. ConnectionIndicator.prototype.showMore = function () {
  7090. this.showMoreValue = !this.showMoreValue;
  7091. this.updatePopoverData();
  7092. };
  7093. function createIcon(classes) {
  7094. var icon = document.createElement("span");
  7095. for(var i in classes) {
  7096. icon.classList.add(classes[i]);
  7097. }
  7098. icon.appendChild(
  7099. document.createElement("i")).classList.add("icon-connection");
  7100. return icon;
  7101. }
  7102. /**
  7103. * Creates the indicator
  7104. */
  7105. ConnectionIndicator.prototype.create = function () {
  7106. this.connectionIndicatorContainer = document.createElement("div");
  7107. this.connectionIndicatorContainer.className = "connectionindicator";
  7108. this.connectionIndicatorContainer.style.display = "none";
  7109. this.videoContainer.container.appendChild(
  7110. this.connectionIndicatorContainer);
  7111. this.popover = new JitsiPopover(
  7112. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7113. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7114. APP.translation.translateString("connectionindicator.na") + "</div>",
  7115. skin: "black"});
  7116. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7117. createIcon(["connection", "connection_empty"]));
  7118. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7119. createIcon(["connection", "connection_full"]));
  7120. };
  7121. /**
  7122. * Removes the indicator
  7123. */
  7124. ConnectionIndicator.prototype.remove = function() {
  7125. if (this.connectionIndicatorContainer.parentNode) {
  7126. this.connectionIndicatorContainer.parentNode.removeChild(
  7127. this.connectionIndicatorContainer);
  7128. }
  7129. this.popover.forceHide();
  7130. };
  7131. /**
  7132. * Updates the data of the indicator
  7133. * @param percent the percent of connection quality
  7134. * @param object the statistics data.
  7135. */
  7136. ConnectionIndicator.prototype.updateConnectionQuality =
  7137. function (percent, object) {
  7138. if (percent === null) {
  7139. this.connectionIndicatorContainer.style.display = "none";
  7140. this.popover.forceHide();
  7141. return;
  7142. } else {
  7143. if(this.connectionIndicatorContainer.style.display == "none") {
  7144. this.connectionIndicatorContainer.style.display = "block";
  7145. this.videoContainer.updateIconPositions();
  7146. }
  7147. }
  7148. this.bandwidth = object.bandwidth;
  7149. this.bitrate = object.bitrate;
  7150. this.packetLoss = object.packetLoss;
  7151. this.transport = object.transport;
  7152. if (object.resolution) {
  7153. this.resolution = object.resolution;
  7154. }
  7155. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7156. if (percent >= quality) {
  7157. this.fullIcon.style.width =
  7158. ConnectionIndicator.connectionQualityValues[quality];
  7159. }
  7160. }
  7161. this.updatePopoverData();
  7162. };
  7163. /**
  7164. * Updates the resolution
  7165. * @param resolution the new resolution
  7166. */
  7167. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7168. this.resolution = resolution;
  7169. this.updatePopoverData();
  7170. };
  7171. /**
  7172. * Updates the content of the popover
  7173. */
  7174. ConnectionIndicator.prototype.updatePopoverData = function () {
  7175. this.popover.updateContent(
  7176. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7177. APP.translation.translateElement($(".connection_info"));
  7178. };
  7179. /**
  7180. * Hides the popover
  7181. */
  7182. ConnectionIndicator.prototype.hide = function () {
  7183. this.popover.forceHide();
  7184. };
  7185. /**
  7186. * Hides the indicator
  7187. */
  7188. ConnectionIndicator.prototype.hideIndicator = function () {
  7189. this.connectionIndicatorContainer.style.display = "none";
  7190. if(this.popover)
  7191. this.popover.forceHide();
  7192. };
  7193. module.exports = ConnectionIndicator;
  7194. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7195. /* global $, APP, Strophe, interfaceConfig */
  7196. var Avatar = require("../avatar/Avatar");
  7197. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7198. var UIUtil = require("../util/UIUtil");
  7199. var UIEvents = require("../../../service/UI/UIEvents");
  7200. var xmpp = require("../../xmpp/xmpp");
  7201. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7202. // FIXME: With Temasys we have to re-select everytime
  7203. //var video = $('#largeVideo');
  7204. var currentVideoWidth = null;
  7205. var currentVideoHeight = null;
  7206. // By default we use camera
  7207. var getVideoSize = getCameraVideoSize;
  7208. var getVideoPosition = getCameraVideoPosition;
  7209. /**
  7210. * The small video instance that is displayed in the large video
  7211. * @type {SmallVideo}
  7212. */
  7213. var currentSmallVideo = null;
  7214. /**
  7215. * Indicates whether the large video is enabled.
  7216. * @type {boolean}
  7217. */
  7218. var isEnabled = true;
  7219. /**
  7220. * Current large video state.
  7221. * Possible values - video, prezi or etherpad.
  7222. * @type {string}
  7223. */
  7224. var state = "video";
  7225. /**
  7226. * Returns the html element associated with the passed state of large video
  7227. * @param state the state.
  7228. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7229. */
  7230. function getContainerByState(state)
  7231. {
  7232. var selector = null;
  7233. switch (state)
  7234. {
  7235. case "video":
  7236. selector = "#largeVideo";
  7237. break;
  7238. case "etherpad":
  7239. selector = "#etherpad>iframe";
  7240. break;
  7241. case "prezi":
  7242. selector = "#presentation>iframe";
  7243. break;
  7244. }
  7245. return (selector !== null)? $(selector) : null;
  7246. }
  7247. /**
  7248. * Sets the size and position of the given video element.
  7249. *
  7250. * @param video the video element to position
  7251. * @param width the desired video width
  7252. * @param height the desired video height
  7253. * @param horizontalIndent the left and right indent
  7254. * @param verticalIndent the top and bottom indent
  7255. */
  7256. function positionVideo(video,
  7257. width,
  7258. height,
  7259. horizontalIndent,
  7260. verticalIndent,
  7261. animate) {
  7262. if (animate) {
  7263. video.animate({
  7264. width: width,
  7265. height: height,
  7266. top: verticalIndent,
  7267. bottom: verticalIndent,
  7268. left: horizontalIndent,
  7269. right: horizontalIndent
  7270. },
  7271. {
  7272. queue: false,
  7273. duration: 500
  7274. });
  7275. } else {
  7276. video.width(width);
  7277. video.height(height);
  7278. video.css({ top: verticalIndent + 'px',
  7279. bottom: verticalIndent + 'px',
  7280. left: horizontalIndent + 'px',
  7281. right: horizontalIndent + 'px'});
  7282. }
  7283. }
  7284. /**
  7285. * Returns an array of the video dimensions, so that it keeps it's aspect
  7286. * ratio and fits available area with it's larger dimension. This method
  7287. * ensures that whole video will be visible and can leave empty areas.
  7288. *
  7289. * @return an array with 2 elements, the video width and the video height
  7290. */
  7291. function getDesktopVideoSize(videoWidth,
  7292. videoHeight,
  7293. videoSpaceWidth,
  7294. videoSpaceHeight) {
  7295. if (!videoWidth)
  7296. videoWidth = currentVideoWidth;
  7297. if (!videoHeight)
  7298. videoHeight = currentVideoHeight;
  7299. var aspectRatio = videoWidth / videoHeight;
  7300. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7301. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7302. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7303. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7304. {
  7305. availableHeight = videoSpaceHeight;
  7306. availableWidth = availableHeight * aspectRatio;
  7307. }
  7308. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7309. {
  7310. availableWidth = videoSpaceWidth;
  7311. availableHeight = availableWidth / aspectRatio;
  7312. }
  7313. return [availableWidth, availableHeight];
  7314. }
  7315. /**
  7316. * Returns an array of the video horizontal and vertical indents,
  7317. * so that if fits its parent.
  7318. *
  7319. * @return an array with 2 elements, the horizontal indent and the vertical
  7320. * indent
  7321. */
  7322. function getCameraVideoPosition(videoWidth,
  7323. videoHeight,
  7324. videoSpaceWidth,
  7325. videoSpaceHeight) {
  7326. // Parent height isn't completely calculated when we position the video in
  7327. // full screen mode and this is why we use the screen height in this case.
  7328. // Need to think it further at some point and implement it properly.
  7329. var isFullScreen = document.fullScreen ||
  7330. document.mozFullScreen ||
  7331. document.webkitIsFullScreen;
  7332. if (isFullScreen)
  7333. videoSpaceHeight = window.innerHeight;
  7334. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7335. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7336. return [horizontalIndent, verticalIndent];
  7337. }
  7338. /**
  7339. * Returns an array of the video horizontal and vertical indents.
  7340. * Centers horizontally and top aligns vertically.
  7341. *
  7342. * @return an array with 2 elements, the horizontal indent and the vertical
  7343. * indent
  7344. */
  7345. function getDesktopVideoPosition(videoWidth,
  7346. videoHeight,
  7347. videoSpaceWidth,
  7348. videoSpaceHeight) {
  7349. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7350. var verticalIndent = 0;// Top aligned
  7351. return [horizontalIndent, verticalIndent];
  7352. }
  7353. /**
  7354. * Returns an array of the video dimensions, so that it covers the screen.
  7355. * It leaves no empty areas, but some parts of the video might not be visible.
  7356. *
  7357. * @return an array with 2 elements, the video width and the video height
  7358. */
  7359. function getCameraVideoSize(videoWidth,
  7360. videoHeight,
  7361. videoSpaceWidth,
  7362. videoSpaceHeight) {
  7363. if (!videoWidth)
  7364. videoWidth = currentVideoWidth;
  7365. if (!videoHeight)
  7366. videoHeight = currentVideoHeight;
  7367. var aspectRatio = videoWidth / videoHeight;
  7368. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7369. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7370. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7371. availableHeight = videoSpaceHeight;
  7372. availableWidth = availableHeight * aspectRatio;
  7373. }
  7374. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7375. availableWidth = videoSpaceWidth;
  7376. availableHeight = availableWidth / aspectRatio;
  7377. }
  7378. return [availableWidth, availableHeight];
  7379. }
  7380. /**
  7381. * Updates the src of the active speaker avatar
  7382. * @param jid of the current active speaker
  7383. */
  7384. function updateActiveSpeakerAvatarSrc() {
  7385. var avatar = $("#activeSpeakerAvatar")[0];
  7386. var jid = currentSmallVideo.peerJid;
  7387. var url = Avatar.getActiveSpeakerUrl(jid);
  7388. if (avatar.src === url)
  7389. return;
  7390. if (jid) {
  7391. avatar.src = url;
  7392. currentSmallVideo.showAvatar();
  7393. }
  7394. }
  7395. /**
  7396. * Change the video source of the large video.
  7397. * @param isVisible
  7398. */
  7399. function changeVideo(isVisible) {
  7400. if (!currentSmallVideo) {
  7401. console.error("Unable to change large video - no 'currentSmallVideo'");
  7402. return;
  7403. }
  7404. updateActiveSpeakerAvatarSrc();
  7405. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7406. var videoTransform = document.getElementById('largeVideo')
  7407. .style.webkitTransform;
  7408. var flipX = currentSmallVideo.flipX;
  7409. if (flipX && videoTransform !== 'scaleX(-1)') {
  7410. document.getElementById('largeVideo').style.webkitTransform =
  7411. "scaleX(-1)";
  7412. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7413. document.getElementById('largeVideo').style.webkitTransform =
  7414. "none";
  7415. }
  7416. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7417. // Change the way we'll be measuring and positioning large video
  7418. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7419. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7420. getCameraVideoPosition;
  7421. // Only if the large video is currently visible.
  7422. if (isVisible) {
  7423. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7424. $('#largeVideo').fadeIn(300);
  7425. }
  7426. }
  7427. /**
  7428. * Creates the html elements for the large video.
  7429. */
  7430. function createLargeVideoHTML()
  7431. {
  7432. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7433. html += '<div id="presentation"></div>' +
  7434. '<div id="etherpad"></div>' +
  7435. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7436. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7437. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7438. '<span data-i18n="poweredby"></span> jitsi.org' +
  7439. '</a>'+
  7440. '<div id="activeSpeaker">' +
  7441. '<img id="activeSpeakerAvatar" src=""/>' +
  7442. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7443. '</div>' +
  7444. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7445. '<span id="videoConnectionMessage"></span>';
  7446. html += '</div>';
  7447. $(html).prependTo("#videospace");
  7448. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7449. var leftWatermarkDiv
  7450. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7451. leftWatermarkDiv.css({display: 'block'});
  7452. leftWatermarkDiv.parent().get(0).href
  7453. = interfaceConfig.JITSI_WATERMARK_LINK;
  7454. }
  7455. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7456. var rightWatermarkDiv
  7457. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7458. rightWatermarkDiv.css({display: 'block'});
  7459. rightWatermarkDiv.parent().get(0).href
  7460. = interfaceConfig.BRAND_WATERMARK_LINK;
  7461. rightWatermarkDiv.get(0).style.backgroundImage
  7462. = "url(images/rightwatermark.png)";
  7463. }
  7464. if (interfaceConfig.SHOW_POWERED_BY) {
  7465. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7466. }
  7467. if (!RTCBrowserType.isIExplorer()) {
  7468. $('#largeVideo').volume = 0;
  7469. }
  7470. }
  7471. var LargeVideo = {
  7472. init: function (VideoLayout, emitter) {
  7473. if(!isEnabled)
  7474. return;
  7475. createLargeVideoHTML();
  7476. this.VideoLayout = VideoLayout;
  7477. this.eventEmitter = emitter;
  7478. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7479. var self = this;
  7480. // Listen for large video size updates
  7481. var largeVideo = $('#largeVideo')[0];
  7482. var onplaying = function (arg1, arg2, arg3) {
  7483. // re-select
  7484. if (RTCBrowserType.isTemasysPluginUsed())
  7485. largeVideo = $('#largeVideo')[0];
  7486. currentVideoWidth = largeVideo.videoWidth;
  7487. currentVideoHeight = largeVideo.videoHeight;
  7488. self.position(currentVideoWidth, currentVideoHeight);
  7489. };
  7490. largeVideo.onplaying = onplaying;
  7491. },
  7492. /**
  7493. * Indicates if the large video is currently visible.
  7494. *
  7495. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7496. */
  7497. isLargeVideoVisible: function() {
  7498. return $('#largeVideo').is(':visible');
  7499. },
  7500. /**
  7501. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7502. */
  7503. isCurrentlyOnLarge: function (resourceJid) {
  7504. return currentSmallVideo && resourceJid &&
  7505. currentSmallVideo.getResourceJid() === resourceJid;
  7506. },
  7507. /**
  7508. * Updates the large video with the given new video source.
  7509. */
  7510. updateLargeVideo: function (resourceJid, forceUpdate) {
  7511. if(!isEnabled)
  7512. return;
  7513. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7514. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7515. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7516. $('#activeSpeaker').css('visibility', 'hidden');
  7517. var oldSmallVideo = null;
  7518. if (currentSmallVideo) {
  7519. oldSmallVideo = currentSmallVideo;
  7520. }
  7521. currentSmallVideo = newSmallVideo;
  7522. var oldJid = null;
  7523. if (oldSmallVideo)
  7524. oldJid = oldSmallVideo.peerJid;
  7525. if (oldJid !== resourceJid) {
  7526. // we want the notification to trigger even if userJid is undefined,
  7527. // or null.
  7528. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7529. }
  7530. if (RTCBrowserType.isSafari()) {
  7531. // FIXME In Safari fadeOut works only for the first time
  7532. changeVideo(this.isLargeVideoVisible());
  7533. } else {
  7534. $('#largeVideo').fadeOut(300,
  7535. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7536. }
  7537. } else {
  7538. if (currentSmallVideo) {
  7539. currentSmallVideo.showAvatar();
  7540. }
  7541. }
  7542. },
  7543. /**
  7544. * Shows/hides the large video.
  7545. */
  7546. setLargeVideoVisible: function(isVisible) {
  7547. if(!isEnabled)
  7548. return;
  7549. if (isVisible) {
  7550. $('#largeVideo').css({visibility: 'visible'});
  7551. $('.watermark').css({visibility: 'visible'});
  7552. if(currentSmallVideo)
  7553. currentSmallVideo.enableDominantSpeaker(true);
  7554. }
  7555. else {
  7556. $('#largeVideo').css({visibility: 'hidden'});
  7557. $('#activeSpeaker').css('visibility', 'hidden');
  7558. $('.watermark').css({visibility: 'hidden'});
  7559. if(currentSmallVideo)
  7560. currentSmallVideo.enableDominantSpeaker(false);
  7561. }
  7562. },
  7563. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7564. if (!isEnabled)
  7565. return;
  7566. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7567. {
  7568. var isDesktop = newVideoType === 'screen';
  7569. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7570. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7571. : getCameraVideoPosition;
  7572. this.position(null, null);
  7573. }
  7574. },
  7575. /**
  7576. * Positions the large video.
  7577. *
  7578. * @param videoWidth the stream video width
  7579. * @param videoHeight the stream video height
  7580. */
  7581. position: function (videoWidth, videoHeight,
  7582. videoSpaceWidth, videoSpaceHeight, animate) {
  7583. if(!isEnabled)
  7584. return;
  7585. if(!videoSpaceWidth)
  7586. videoSpaceWidth = $('#videospace').width();
  7587. if(!videoSpaceHeight)
  7588. videoSpaceHeight = window.innerHeight;
  7589. var videoSize = getVideoSize(videoWidth,
  7590. videoHeight,
  7591. videoSpaceWidth,
  7592. videoSpaceHeight);
  7593. var largeVideoWidth = videoSize[0];
  7594. var largeVideoHeight = videoSize[1];
  7595. var videoPosition = getVideoPosition(largeVideoWidth,
  7596. largeVideoHeight,
  7597. videoSpaceWidth,
  7598. videoSpaceHeight);
  7599. var horizontalIndent = videoPosition[0];
  7600. var verticalIndent = videoPosition[1];
  7601. positionVideo($('#largeVideo'),
  7602. largeVideoWidth,
  7603. largeVideoHeight,
  7604. horizontalIndent, verticalIndent, animate);
  7605. },
  7606. /**
  7607. * Resizes the large html elements.
  7608. * @param animate boolean property that indicates whether the resize should be animated or not.
  7609. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  7610. * If that parameter is null the method will check the chat pannel visibility.
  7611. * @param completeFunction a function to be called when the video space is resized
  7612. * @returns {*[]} array with the current width and height values of the largeVideo html element.
  7613. */
  7614. resize: function (animate, isVisible, completeFunction) {
  7615. if(!isEnabled)
  7616. return;
  7617. var availableHeight = window.innerHeight;
  7618. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7619. if (availableWidth < 0 || availableHeight < 0) return;
  7620. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7621. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7622. $('#activeSpeaker').css('top', top);
  7623. this.VideoLayout.resizeVideoSpace(animate, isVisible, completeFunction);
  7624. if(animate) {
  7625. $('#largeVideoContainer').animate({
  7626. width: availableWidth,
  7627. height: availableHeight
  7628. },
  7629. {
  7630. queue: false,
  7631. duration: 500
  7632. });
  7633. } else {
  7634. $('#largeVideoContainer').width(availableWidth);
  7635. $('#largeVideoContainer').height(availableHeight);
  7636. }
  7637. return [availableWidth, availableHeight];
  7638. },
  7639. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7640. if(!isEnabled)
  7641. return;
  7642. var size = this.resize(true, isVisible, completeFunction);
  7643. this.position(null, null, size[0], size[1], true);
  7644. },
  7645. getResourceJid: function () {
  7646. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7647. },
  7648. updateAvatar: function (resourceJid) {
  7649. if(!isEnabled)
  7650. return;
  7651. if (resourceJid === this.getResourceJid()) {
  7652. updateActiveSpeakerAvatarSrc();
  7653. }
  7654. },
  7655. showAvatar: function (resourceJid, show) {
  7656. if(!isEnabled)
  7657. return;
  7658. if(this.getResourceJid() === resourceJid && state === "video") {
  7659. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7660. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7661. return true;
  7662. }
  7663. return false;
  7664. },
  7665. /**
  7666. * Disables the large video
  7667. */
  7668. disable: function () {
  7669. isEnabled = false;
  7670. },
  7671. /**
  7672. * Enables the large video
  7673. */
  7674. enable: function () {
  7675. isEnabled = true;
  7676. },
  7677. /**
  7678. * Returns true if the video is enabled.
  7679. */
  7680. isEnabled: function () {
  7681. return isEnabled;
  7682. },
  7683. /**
  7684. * Creates the iframe used by the etherpad
  7685. * @param src the value for src attribute
  7686. * @param onloadHandler handler executed when the iframe loads it content
  7687. * @returns {HTMLElement} the iframe
  7688. */
  7689. createEtherpadIframe: function (src, onloadHandler) {
  7690. if(!isEnabled)
  7691. return;
  7692. var etherpadIFrame = document.createElement('iframe');
  7693. etherpadIFrame.src = src;
  7694. etherpadIFrame.frameBorder = 0;
  7695. etherpadIFrame.scrolling = "no";
  7696. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7697. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7698. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7699. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7700. etherpadIFrame.onload = onloadHandler;
  7701. return etherpadIFrame;
  7702. },
  7703. /**
  7704. * Changes the state of the large video.
  7705. * Possible values - video, prezi, etherpad.
  7706. * @param newState - the new state
  7707. */
  7708. setState: function (newState) {
  7709. if(state === newState)
  7710. return;
  7711. var currentContainer = getContainerByState(state);
  7712. if(!currentContainer)
  7713. return;
  7714. var self = this;
  7715. var oldState = state;
  7716. switch (newState)
  7717. {
  7718. case "etherpad":
  7719. $('#activeSpeaker').css('visibility', 'hidden');
  7720. currentContainer.fadeOut(300, function () {
  7721. if (oldState === "prezi") {
  7722. currentContainer.css({opacity: '0'});
  7723. $('#reloadPresentation').css({display: 'none'});
  7724. }
  7725. else {
  7726. self.setLargeVideoVisible(false);
  7727. }
  7728. });
  7729. $('#etherpad>iframe').fadeIn(300, function () {
  7730. document.body.style.background = '#eeeeee';
  7731. $('#etherpad>iframe').css({visibility: 'visible'});
  7732. $('#etherpad').css({zIndex: 2});
  7733. });
  7734. break;
  7735. case "prezi":
  7736. var prezi = $('#presentation>iframe');
  7737. currentContainer.fadeOut(300, function() {
  7738. document.body.style.background = 'black';
  7739. });
  7740. prezi.fadeIn(300, function() {
  7741. prezi.css({opacity:'1'});
  7742. ToolbarToggler.dockToolbar(true);//fix that
  7743. self.setLargeVideoVisible(false);
  7744. $('#etherpad>iframe').css({visibility: 'hidden'});
  7745. $('#etherpad').css({zIndex: 0});
  7746. });
  7747. $('#activeSpeaker').css('visibility', 'hidden');
  7748. break;
  7749. case "video":
  7750. currentContainer.fadeOut(300, function () {
  7751. $('#presentation>iframe').css({opacity:'0'});
  7752. $('#reloadPresentation').css({display:'none'});
  7753. $('#etherpad>iframe').css({visibility: 'hidden'});
  7754. $('#etherpad').css({zIndex: 0});
  7755. document.body.style.background = 'black';
  7756. ToolbarToggler.dockToolbar(false);//fix that
  7757. });
  7758. $('#largeVideo').fadeIn(300, function () {
  7759. self.setLargeVideoVisible(true);
  7760. });
  7761. break;
  7762. }
  7763. state = newState;
  7764. },
  7765. /**
  7766. * Returns the current state of the large video.
  7767. * @returns {string} the current state - video, prezi or etherpad.
  7768. */
  7769. getState: function () {
  7770. return state;
  7771. },
  7772. /**
  7773. * Sets hover handlers for the large video container div.
  7774. *
  7775. * @param inHandler
  7776. * @param outHandler
  7777. */
  7778. setHover: function(inHandler, outHandler)
  7779. {
  7780. $('#largeVideoContainer').hover(inHandler, outHandler);
  7781. },
  7782. /**
  7783. * Enables/disables the filter indicating a video problem to the user.
  7784. *
  7785. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  7786. */
  7787. enableVideoProblemFilter: function (enable) {
  7788. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  7789. }
  7790. };
  7791. module.exports = LargeVideo;
  7792. },{"../../../service/UI/UIEvents":155,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":68,"../avatar/Avatar":16,"../toolbars/ToolbarToggler":29,"../util/UIUtil":33}],36:[function(require,module,exports){
  7793. /* global $, interfaceConfig, APP */
  7794. var SmallVideo = require("./SmallVideo");
  7795. var ConnectionIndicator = require("./ConnectionIndicator");
  7796. var NicknameHandler = require("../util/NicknameHandler");
  7797. var UIUtil = require("../util/UIUtil");
  7798. var LargeVideo = require("./LargeVideo");
  7799. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7800. function LocalVideo(VideoLayout) {
  7801. this.videoSpanId = "localVideoContainer";
  7802. this.container = $("#localVideoContainer").get(0);
  7803. this.VideoLayout = VideoLayout;
  7804. this.flipX = true;
  7805. this.isLocal = true;
  7806. this.peerJid = null;
  7807. }
  7808. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7809. LocalVideo.prototype.constructor = LocalVideo;
  7810. /**
  7811. * Creates the edit display name button.
  7812. *
  7813. * @returns {object} the edit button
  7814. */
  7815. function createEditDisplayNameButton() {
  7816. var editButton = document.createElement('a');
  7817. editButton.className = 'displayname';
  7818. UIUtil.setTooltip(editButton,
  7819. "videothumbnail.editnickname",
  7820. "top");
  7821. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7822. return editButton;
  7823. }
  7824. /**
  7825. * Sets the display name for the given video span id.
  7826. */
  7827. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7828. if (!this.container) {
  7829. console.warn(
  7830. "Unable to set displayName - " + this.videoSpanId +
  7831. " does not exist");
  7832. return;
  7833. }
  7834. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7835. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7836. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7837. var meHTML;
  7838. // If we already have a display name for this video.
  7839. if (nameSpan.length > 0) {
  7840. if (nameSpan.text() !== displayName) {
  7841. if (displayName && displayName.length > 0) {
  7842. meHTML = APP.translation.generateTranslationHTML("me");
  7843. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7844. } else {
  7845. $('#localDisplayName').html(defaultLocalDisplayName);
  7846. }
  7847. }
  7848. } else {
  7849. var editButton = createEditDisplayNameButton();
  7850. nameSpan = document.createElement('span');
  7851. nameSpan.className = 'displayname';
  7852. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7853. if (displayName && displayName.length > 0) {
  7854. meHTML = APP.translation.generateTranslationHTML("me");
  7855. nameSpan.innerHTML = displayName + meHTML;
  7856. }
  7857. else {
  7858. nameSpan.innerHTML = defaultLocalDisplayName;
  7859. }
  7860. nameSpan.id = 'localDisplayName';
  7861. this.container.appendChild(editButton);
  7862. //translates popover of edit button
  7863. APP.translation.translateElement($("a.displayname"));
  7864. var editableText = document.createElement('input');
  7865. editableText.className = 'displayname';
  7866. editableText.type = 'text';
  7867. editableText.id = 'editDisplayName';
  7868. if (displayName && displayName.length) {
  7869. editableText.value = displayName;
  7870. }
  7871. var defaultNickname = APP.translation.translateString(
  7872. "defaultNickname", {name: "Jane Pink"});
  7873. editableText.setAttribute('style', 'display:none;');
  7874. editableText.setAttribute('data-18n',
  7875. '[placeholder]defaultNickname');
  7876. editableText.setAttribute("data-i18n-options",
  7877. JSON.stringify({name: "Jane Pink"}));
  7878. editableText.setAttribute("placeholder", defaultNickname);
  7879. this.container.appendChild(editableText);
  7880. var self = this;
  7881. $('#localVideoContainer .displayname')
  7882. .bind("click", function (e) {
  7883. var editDisplayName = $('#editDisplayName');
  7884. e.preventDefault();
  7885. e.stopPropagation();
  7886. $('#localDisplayName').hide();
  7887. editDisplayName.show();
  7888. editDisplayName.focus();
  7889. editDisplayName.select();
  7890. editDisplayName.one("focusout", function (e) {
  7891. self.VideoLayout.inputDisplayNameHandler(this.value);
  7892. });
  7893. editDisplayName.on('keydown', function (e) {
  7894. if (e.keyCode === 13) {
  7895. e.preventDefault();
  7896. self.VideoLayout.inputDisplayNameHandler(this.value);
  7897. }
  7898. });
  7899. });
  7900. }
  7901. };
  7902. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7903. NicknameHandler.setNickname(name);
  7904. var localDisplayName = $('#localDisplayName');
  7905. if (!localDisplayName.is(":visible")) {
  7906. if (NicknameHandler.getNickname()) {
  7907. var meHTML = APP.translation.generateTranslationHTML("me");
  7908. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  7909. meHTML + ")");
  7910. } else {
  7911. var defaultHTML = APP.translation.generateTranslationHTML(
  7912. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7913. localDisplayName .html(defaultHTML);
  7914. }
  7915. localDisplayName.show();
  7916. }
  7917. $('#editDisplayName').hide();
  7918. };
  7919. LocalVideo.prototype.createConnectionIndicator = function() {
  7920. if(this.connectionIndicator)
  7921. return;
  7922. this.connectionIndicator = new ConnectionIndicator(this, null);
  7923. };
  7924. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7925. var self = this;
  7926. function localVideoClick(event) {
  7927. // FIXME: with Temasys plugin event arg is not an event, but
  7928. // the clicked object itself, so we have to skip this call
  7929. if (event.stopPropagation) {
  7930. event.stopPropagation();
  7931. }
  7932. self.VideoLayout.handleVideoThumbClicked(
  7933. false,
  7934. APP.xmpp.myResource());
  7935. }
  7936. var localVideoContainerSelector = $('#localVideoContainer');
  7937. localVideoContainerSelector.off('click');
  7938. localVideoContainerSelector.on('click', localVideoClick);
  7939. // Add hover handler
  7940. localVideoContainerSelector.hover(
  7941. function() {
  7942. self.showDisplayName(true);
  7943. },
  7944. function() {
  7945. if (!LargeVideo.isLargeVideoVisible() ||
  7946. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  7947. self.showDisplayName(false);
  7948. }
  7949. }
  7950. );
  7951. if(isMuted) {
  7952. APP.UI.setVideoMute(true);
  7953. return;
  7954. }
  7955. this.flipX = stream.videoType != "screen";
  7956. var localVideo = document.createElement('video');
  7957. localVideo.id = 'localVideo_' +
  7958. APP.RTC.getStreamID(stream.getOriginalStream());
  7959. if (!RTCBrowserType.isIExplorer()) {
  7960. localVideo.autoplay = true;
  7961. localVideo.volume = 0; // is it required if audio is separated ?
  7962. }
  7963. localVideo.oncontextmenu = function () { return false; };
  7964. var localVideoContainer = document.getElementById('localVideoWrapper');
  7965. // Put the new video always in front
  7966. UIUtil.prependChild(localVideoContainer, localVideo);
  7967. var localVideoSelector = $('#' + localVideo.id);
  7968. // Add click handler to both video and video wrapper elements in case
  7969. // there's no video.
  7970. // onclick has to be used with Temasys plugin
  7971. localVideo.onclick = localVideoClick;
  7972. if (this.flipX) {
  7973. localVideoSelector.addClass("flipVideoX");
  7974. }
  7975. // Attach WebRTC stream
  7976. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7977. // Add stream ended handler
  7978. stream.getOriginalStream().onended = function () {
  7979. // We have to re-select after attach when Temasys plugin is used,
  7980. // because <video> element is replaced with <object>
  7981. localVideo = $('#' + localVideo.id)[0];
  7982. localVideoContainer.removeChild(localVideo);
  7983. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7984. };
  7985. };
  7986. LocalVideo.prototype.joined = function (jid) {
  7987. this.peerJid = jid;
  7988. };
  7989. LocalVideo.prototype.getResourceJid = function () {
  7990. var myResource = APP.xmpp.myResource();
  7991. if (!myResource) {
  7992. console.error("Requested local resource before we're in the MUC");
  7993. }
  7994. return myResource;
  7995. };
  7996. module.exports = LocalVideo;
  7997. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7998. /* global $, APP, require, Strophe, interfaceConfig */
  7999. var ConnectionIndicator = require("./ConnectionIndicator");
  8000. var SmallVideo = require("./SmallVideo");
  8001. var AudioLevels = require("../audio_levels/AudioLevels");
  8002. var LargeVideo = require("./LargeVideo");
  8003. var Avatar = require("../avatar/Avatar");
  8004. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8005. var UIUtils = require("../util/UIUtil");
  8006. function RemoteVideo(peerJid, VideoLayout) {
  8007. this.peerJid = peerJid;
  8008. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  8009. this.videoSpanId = 'participant_' + this.resourceJid;
  8010. this.VideoLayout = VideoLayout;
  8011. this.addRemoteVideoContainer();
  8012. this.connectionIndicator = new ConnectionIndicator(
  8013. this, this.peerJid);
  8014. this.setDisplayName();
  8015. var nickfield = document.createElement('span');
  8016. nickfield.className = "nick";
  8017. nickfield.appendChild(document.createTextNode(this.resourceJid));
  8018. this.container.appendChild(nickfield);
  8019. this.flipX = false;
  8020. this.isLocal = false;
  8021. }
  8022. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  8023. RemoteVideo.prototype.constructor = RemoteVideo;
  8024. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  8025. this.container = RemoteVideo.createContainer(this.videoSpanId);
  8026. if (APP.xmpp.isModerator())
  8027. this.addRemoteVideoMenu();
  8028. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  8029. return this.container;
  8030. };
  8031. /**
  8032. * Adds the remote video menu element for the given <tt>jid</tt> in the
  8033. * given <tt>parentElement</tt>.
  8034. *
  8035. * @param jid the jid indicating the video for which we're adding a menu.
  8036. * @param parentElement the parent element where this menu will be added
  8037. */
  8038. if (!interfaceConfig.filmStripOnly) {
  8039. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  8040. var spanElement = document.createElement('span');
  8041. spanElement.className = 'remotevideomenu';
  8042. this.container.appendChild(spanElement);
  8043. var menuElement = document.createElement('i');
  8044. menuElement.className = 'fa fa-angle-down';
  8045. menuElement.title = 'Remote user controls';
  8046. spanElement.appendChild(menuElement);
  8047. var popupmenuElement = document.createElement('ul');
  8048. popupmenuElement.className = 'popupmenu';
  8049. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  8050. spanElement.appendChild(popupmenuElement);
  8051. var muteMenuItem = document.createElement('li');
  8052. var muteLinkItem = document.createElement('a');
  8053. var mutedIndicator = "<i style='float:left;' " +
  8054. "class='icon-mic-disabled'></i>";
  8055. if (!this.isMuted) {
  8056. muteLinkItem.innerHTML = mutedIndicator +
  8057. " <div style='width: 90px;margin-left: 20px;' " +
  8058. "data-i18n='videothumbnail.domute'></div>";
  8059. muteLinkItem.className = 'mutelink';
  8060. }
  8061. else {
  8062. muteLinkItem.innerHTML = mutedIndicator +
  8063. " <div style='width: 90px;margin-left: 20px;' " +
  8064. "data-i18n='videothumbnail.muted'></div>";
  8065. muteLinkItem.className = 'mutelink disabled';
  8066. }
  8067. var self = this;
  8068. muteLinkItem.onclick = function(){
  8069. if ($(this).attr('disabled') != undefined) {
  8070. event.preventDefault();
  8071. }
  8072. var isMute = self.isMuted == true;
  8073. APP.xmpp.setMute(self.peerJid, !isMute);
  8074. popupmenuElement.setAttribute('style', 'display:none;');
  8075. if (isMute) {
  8076. this.innerHTML = mutedIndicator +
  8077. " <div style='width: 90px;margin-left: 20px;' " +
  8078. "data-i18n='videothumbnail.muted'></div>";
  8079. this.className = 'mutelink disabled';
  8080. }
  8081. else {
  8082. this.innerHTML = mutedIndicator +
  8083. " <div style='width: 90px;margin-left: 20px;' " +
  8084. "data-i18n='videothumbnail.domute'></div>";
  8085. this.className = 'mutelink';
  8086. }
  8087. };
  8088. muteMenuItem.appendChild(muteLinkItem);
  8089. popupmenuElement.appendChild(muteMenuItem);
  8090. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8091. var ejectMenuItem = document.createElement('li');
  8092. var ejectLinkItem = document.createElement('a');
  8093. var ejectText = "<div style='width: 90px;margin-left: 20px;' " +
  8094. "data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8095. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8096. ejectLinkItem.onclick = function(){
  8097. APP.xmpp.eject(self.peerJid);
  8098. popupmenuElement.setAttribute('style', 'display:none;');
  8099. };
  8100. ejectMenuItem.appendChild(ejectLinkItem);
  8101. popupmenuElement.appendChild(ejectMenuItem);
  8102. var paddingSpan = document.createElement('span');
  8103. paddingSpan.className = 'popupmenuPadding';
  8104. popupmenuElement.appendChild(paddingSpan);
  8105. APP.translation.translateElement(
  8106. $("#" + popupmenuElement.id + " > li > a > div"));
  8107. };
  8108. } else {
  8109. RemoteVideo.prototype.addRemoteVideoMenu = function() {}
  8110. }
  8111. /**
  8112. * Removes the remote stream element corresponding to the given stream and
  8113. * parent container.
  8114. *
  8115. * @param stream the stream
  8116. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8117. */
  8118. RemoteVideo.prototype.removeRemoteStreamElement =
  8119. function (stream, isVideo, id) {
  8120. if (!this.container)
  8121. return false;
  8122. var select = null;
  8123. if (isVideo) {
  8124. select = $('#' + id);
  8125. }
  8126. else
  8127. select = $('#' + this.videoSpanId + '>audio');
  8128. select.remove();
  8129. console.info((isVideo ? "Video" : "Audio") +
  8130. " removed " + this.getResourceJid(), select);
  8131. if (isVideo)
  8132. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8133. };
  8134. /**
  8135. * Removes RemoteVideo from the page.
  8136. */
  8137. RemoteVideo.prototype.remove = function () {
  8138. console.log("Remove thumbnail", this.peerJid);
  8139. this.removeConnectionIndicator();
  8140. // Remove whole container
  8141. if (this.container.parentNode)
  8142. this.container.parentNode.removeChild(this.container);
  8143. };
  8144. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8145. var isVideo = stream.getVideoTracks().length > 0;
  8146. if (!isVideo || stream.id === 'mixedmslabel') {
  8147. return;
  8148. }
  8149. var self = this;
  8150. var resourceJid = this.getResourceJid();
  8151. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8152. // when video playback starts
  8153. var onPlayingHandler = function () {
  8154. // FIXME: why do i have to do this for FF?
  8155. if (RTCBrowserType.isFirefox()) {
  8156. APP.RTC.attachMediaStream(sel, stream);
  8157. }
  8158. if (RTCBrowserType.isTemasysPluginUsed()) {
  8159. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8160. }
  8161. self.VideoLayout.videoactive(sel, resourceJid);
  8162. sel[0].onplaying = null;
  8163. if (RTCBrowserType.isTemasysPluginUsed()) {
  8164. // 'currentTime' is used to check if the video has started
  8165. // and the value is not set by the plugin, so we do it
  8166. sel[0].currentTime = 1;
  8167. }
  8168. };
  8169. sel[0].onplaying = onPlayingHandler;
  8170. };
  8171. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8172. if (!this.container)
  8173. return;
  8174. var self = this;
  8175. var isVideo = stream.getVideoTracks().length > 0;
  8176. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8177. var newElementId = streamElement.id;
  8178. // Put new stream element always in front
  8179. UIUtils.prependChild(this.container, streamElement);
  8180. var sel = $('#' + newElementId);
  8181. sel.hide();
  8182. // If the container is currently visible we attach the stream.
  8183. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8184. this.waitForPlayback(sel, stream);
  8185. APP.RTC.attachMediaStream(sel, stream);
  8186. }
  8187. stream.onended = function () {
  8188. console.log('stream ended', this);
  8189. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8190. };
  8191. // Name of video element name is different for IE/Safari
  8192. var videoElem = APP.RTC.getVideoElementName();
  8193. // Add click handler.
  8194. var onClickHandler = function (event) {
  8195. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8196. // On IE we need to populate this handler on video <object>
  8197. // and it does not give event instance as an argument,
  8198. // so we check here for methods.
  8199. if (event.stopPropagation && event.preventDefault) {
  8200. event.stopPropagation();
  8201. event.preventDefault();
  8202. }
  8203. return false;
  8204. };
  8205. this.container.onclick = onClickHandler;
  8206. // reselect
  8207. if (RTCBrowserType.isTemasysPluginUsed())
  8208. sel = $('#' + newElementId);
  8209. sel[0].onclick = onClickHandler;
  8210. //FIXME
  8211. // Add hover handler
  8212. $(this.container).hover(
  8213. function() {
  8214. self.showDisplayName(true);
  8215. },
  8216. function() {
  8217. // If the video has been "pinned" by the user we want to
  8218. // keep the display name on place.
  8219. if (!LargeVideo.isLargeVideoVisible() ||
  8220. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8221. self.showDisplayName(false);
  8222. }
  8223. );
  8224. },
  8225. /**
  8226. * Show/hide peer container for the given resourceJid.
  8227. */
  8228. RemoteVideo.prototype.showPeerContainer = function (state) {
  8229. if (!this.container)
  8230. return;
  8231. var isHide = state === 'hide';
  8232. var resizeThumbnails = false;
  8233. if (!isHide) {
  8234. if (!$(this.container).is(':visible')) {
  8235. resizeThumbnails = true;
  8236. $(this.container).show();
  8237. }
  8238. this.showAvatar(state !== 'show');
  8239. }
  8240. else if ($(this.container).is(':visible') && isHide)
  8241. {
  8242. resizeThumbnails = true;
  8243. $(this.container).hide();
  8244. if(this.connectionIndicator)
  8245. this.connectionIndicator.hide();
  8246. }
  8247. if (resizeThumbnails) {
  8248. this.VideoLayout.resizeThumbnails();
  8249. }
  8250. // We want to be able to pin a participant from the contact list, even
  8251. // if he's not in the lastN set!
  8252. // ContactList.setClickable(resourceJid, !isHide);
  8253. };
  8254. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8255. if (this.connectionIndicator)
  8256. this.connectionIndicator.remove();
  8257. };
  8258. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8259. if (this.connectionIndicator)
  8260. this.connectionIndicator.hide();
  8261. };
  8262. /**
  8263. * Updates the remote video menu.
  8264. *
  8265. * @param jid the jid indicating the video for which we're adding a menu.
  8266. * @param isMuted indicates the current mute state
  8267. */
  8268. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8269. var muteMenuItem
  8270. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8271. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8272. if (muteMenuItem.length) {
  8273. var muteLink = muteMenuItem.get(0);
  8274. if (isMuted === 'true') {
  8275. muteLink.innerHTML = mutedIndicator + ' Muted';
  8276. muteLink.className = 'mutelink disabled';
  8277. }
  8278. else {
  8279. muteLink.innerHTML = mutedIndicator + ' Mute';
  8280. muteLink.className = 'mutelink';
  8281. }
  8282. }
  8283. };
  8284. /**
  8285. * Sets the display name for the given video span id.
  8286. */
  8287. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8288. if (!this.container) {
  8289. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8290. " does not exist");
  8291. return;
  8292. }
  8293. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8294. // If we already have a display name for this video.
  8295. if (nameSpan.length > 0) {
  8296. if (displayName && displayName.length > 0) {
  8297. $('#' + this.videoSpanId + '_name').html(displayName);
  8298. }
  8299. else if (key && key.length > 0) {
  8300. var nameHtml = APP.translation.generateTranslationHTML(key);
  8301. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8302. }
  8303. else
  8304. $('#' + this.videoSpanId + '_name').text(
  8305. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8306. } else {
  8307. nameSpan = document.createElement('span');
  8308. nameSpan.className = 'displayname';
  8309. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8310. if (displayName && displayName.length > 0) {
  8311. nameSpan.innerText = displayName;
  8312. }
  8313. else
  8314. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8315. nameSpan.id = this.videoSpanId + '_name';
  8316. }
  8317. };
  8318. /**
  8319. * Removes remote video menu element from video element identified by
  8320. * given <tt>videoElementId</tt>.
  8321. *
  8322. * @param videoElementId the id of local or remote video element.
  8323. */
  8324. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8325. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8326. if (menuSpan.length) {
  8327. menuSpan.remove();
  8328. }
  8329. };
  8330. RemoteVideo.prototype.getResourceJid = function () {
  8331. if (!this.resourceJid) {
  8332. console.error("Undefined resource jid");
  8333. }
  8334. return this.resourceJid;
  8335. };
  8336. RemoteVideo.createContainer = function (spanId) {
  8337. var container = document.createElement('span');
  8338. container.id = spanId;
  8339. container.className = 'videocontainer';
  8340. var remotes = document.getElementById('remoteVideos');
  8341. return remotes.appendChild(container);
  8342. };
  8343. module.exports = RemoteVideo;
  8344. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8345. /* global $, APP, require */
  8346. var Avatar = require("../avatar/Avatar");
  8347. var UIUtil = require("../util/UIUtil");
  8348. var LargeVideo = require("./LargeVideo");
  8349. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8350. function SmallVideo() {
  8351. this.isMuted = false;
  8352. this.hasAvatar = false;
  8353. }
  8354. function setVisibility(selector, show) {
  8355. if (selector && selector.length > 0) {
  8356. selector.css("visibility", show ? "visible" : "hidden");
  8357. }
  8358. }
  8359. SmallVideo.prototype.showDisplayName = function(isShow) {
  8360. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8361. if (isShow) {
  8362. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8363. nameSpan.setAttribute("style", "display:inline-block;");
  8364. }
  8365. else {
  8366. if (nameSpan)
  8367. nameSpan.setAttribute("style", "display:none;");
  8368. }
  8369. };
  8370. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8371. if(!this.container)
  8372. return;
  8373. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8374. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8375. noMic.remove();
  8376. noVideo.remove();
  8377. if (!devices.audio) {
  8378. this.container.appendChild(
  8379. document.createElement("div")).setAttribute("class", "noMic");
  8380. }
  8381. if (!devices.video) {
  8382. this.container.appendChild(
  8383. document.createElement("div")).setAttribute("class", "noVideo");
  8384. }
  8385. if (!devices.audio && !devices.video) {
  8386. noMic.css("background-position", "75%");
  8387. noVideo.css("background-position", "25%");
  8388. noVideo.css("background-color", "transparent");
  8389. }
  8390. };
  8391. /**
  8392. * Sets the type of the video displayed by this instance.
  8393. * @param videoType 'camera' or 'screen'
  8394. */
  8395. SmallVideo.prototype.setVideoType = function (videoType) {
  8396. this.videoType = videoType;
  8397. };
  8398. /**
  8399. * Returns the type of the video displayed by this instance.
  8400. * @returns {String} 'camera', 'screen' or undefined.
  8401. */
  8402. SmallVideo.prototype.getVideoType = function () {
  8403. return this.videoType;
  8404. };
  8405. /**
  8406. * Shows the presence status message for the given video.
  8407. */
  8408. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8409. if (!this.container) {
  8410. // No container
  8411. return;
  8412. }
  8413. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8414. if (!statusSpan.length) {
  8415. //Add status span
  8416. statusSpan = document.createElement('span');
  8417. statusSpan.className = 'status';
  8418. statusSpan.id = this.videoSpanId + '_status';
  8419. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8420. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8421. }
  8422. // Display status
  8423. if (statusMsg && statusMsg.length) {
  8424. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8425. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8426. }
  8427. else {
  8428. // Hide
  8429. statusSpan.get(0).setAttribute("style", "display:none;");
  8430. }
  8431. };
  8432. /**
  8433. * Creates an audio or video stream element.
  8434. */
  8435. SmallVideo.createStreamElement = function (sid, stream) {
  8436. var isVideo = stream.getVideoTracks().length > 0;
  8437. var element = isVideo ? document.createElement('video')
  8438. : document.createElement('audio');
  8439. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8440. APP.RTC.getStreamID(stream);
  8441. element.id = id;
  8442. if (!RTCBrowserType.isIExplorer()) {
  8443. element.autoplay = true;
  8444. }
  8445. element.oncontextmenu = function () { return false; };
  8446. return element;
  8447. };
  8448. /**
  8449. * Updates the data for the indicator
  8450. * @param id the id of the indicator
  8451. * @param percent the percent for connection quality
  8452. * @param object the data
  8453. */
  8454. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8455. if(this.connectionIndicator)
  8456. this.connectionIndicator.updateConnectionQuality(percent, object);
  8457. };
  8458. SmallVideo.prototype.hideIndicator = function () {
  8459. if(this.connectionIndicator)
  8460. this.connectionIndicator.hideIndicator();
  8461. };
  8462. /**
  8463. * Shows audio muted indicator over small videos.
  8464. * @param {string} isMuted
  8465. */
  8466. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8467. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8468. if (!isMuted) {
  8469. if (audioMutedSpan.length > 0) {
  8470. audioMutedSpan.popover('hide');
  8471. audioMutedSpan.remove();
  8472. }
  8473. }
  8474. else {
  8475. if(audioMutedSpan.length == 0 ) {
  8476. audioMutedSpan = document.createElement('span');
  8477. audioMutedSpan.className = 'audioMuted';
  8478. UIUtil.setTooltip(audioMutedSpan,
  8479. "videothumbnail.mute",
  8480. "top");
  8481. this.container.appendChild(audioMutedSpan);
  8482. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8483. var mutedIndicator = document.createElement('i');
  8484. mutedIndicator.className = 'icon-mic-disabled';
  8485. audioMutedSpan.appendChild(mutedIndicator);
  8486. }
  8487. this.updateIconPositions();
  8488. }
  8489. this.isMuted = isMuted;
  8490. };
  8491. /**
  8492. * Shows video muted indicator over small videos.
  8493. */
  8494. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8495. this.showAvatar(isMuted);
  8496. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8497. if (isMuted === false) {
  8498. if (videoMutedSpan.length > 0) {
  8499. videoMutedSpan.remove();
  8500. }
  8501. }
  8502. else {
  8503. if(videoMutedSpan.length == 0) {
  8504. videoMutedSpan = document.createElement('span');
  8505. videoMutedSpan.className = 'videoMuted';
  8506. this.container.appendChild(videoMutedSpan);
  8507. var mutedIndicator = document.createElement('i');
  8508. mutedIndicator.className = 'icon-camera-disabled';
  8509. UIUtil.setTooltip(mutedIndicator,
  8510. "videothumbnail.videomute",
  8511. "top");
  8512. videoMutedSpan.appendChild(mutedIndicator);
  8513. //translate texts for muted indicator
  8514. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8515. }
  8516. this.updateIconPositions();
  8517. }
  8518. };
  8519. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8520. var resourceJid = this.getResourceJid();
  8521. var displayName = resourceJid;
  8522. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8523. if (nameSpan.length > 0)
  8524. displayName = nameSpan.html();
  8525. console.log("UI enable dominant speaker",
  8526. displayName,
  8527. resourceJid,
  8528. isEnable);
  8529. if (!this.container) {
  8530. return;
  8531. }
  8532. if (isEnable) {
  8533. this.showDisplayName(LargeVideo.getState() === "video");
  8534. if (!this.container.classList.contains("dominantspeaker"))
  8535. this.container.classList.add("dominantspeaker");
  8536. }
  8537. else {
  8538. this.showDisplayName(false);
  8539. if (this.container.classList.contains("dominantspeaker"))
  8540. this.container.classList.remove("dominantspeaker");
  8541. }
  8542. this.showAvatar();
  8543. };
  8544. SmallVideo.prototype.updateIconPositions = function () {
  8545. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8546. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8547. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8548. if(connectionIndicator.length > 0 &&
  8549. connectionIndicator[0].style.display != "none") {
  8550. audioMutedSpan.css({right: "23px"});
  8551. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8552. } else {
  8553. audioMutedSpan.css({right: "0px"});
  8554. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8555. }
  8556. };
  8557. /**
  8558. * Creates the element indicating the moderator(owner) of the conference.
  8559. *
  8560. * @param parentElement the parent element where the owner indicator will
  8561. * be added
  8562. */
  8563. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8564. // Show moderator indicator
  8565. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8566. if (!indicatorSpan || indicatorSpan.length === 0) {
  8567. indicatorSpan = document.createElement('span');
  8568. indicatorSpan.className = 'focusindicator';
  8569. this.container.appendChild(indicatorSpan);
  8570. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8571. }
  8572. if (indicatorSpan.children().length !== 0)
  8573. return;
  8574. var moderatorIndicator = document.createElement('i');
  8575. moderatorIndicator.className = 'fa fa-star';
  8576. indicatorSpan[0].appendChild(moderatorIndicator);
  8577. UIUtil.setTooltip(indicatorSpan[0],
  8578. "videothumbnail.moderator",
  8579. "top");
  8580. //translates text in focus indicators
  8581. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8582. };
  8583. SmallVideo.prototype.getSrc = function () {
  8584. var videoElement = APP.RTC.getVideoElementName();
  8585. return APP.RTC.getVideoSrc(
  8586. $('#' + this.videoSpanId).find(videoElement).get(0));
  8587. };
  8588. SmallVideo.prototype.focus = function(isFocused) {
  8589. if(!isFocused) {
  8590. this.container.classList.remove("videoContainerFocused");
  8591. } else {
  8592. this.container.classList.add("videoContainerFocused");
  8593. }
  8594. };
  8595. SmallVideo.prototype.hasVideo = function () {
  8596. return $("#" + this.videoSpanId).find(
  8597. APP.RTC.getVideoElementName()).length !== 0;
  8598. };
  8599. /**
  8600. * Hides or shows the user's avatar
  8601. * @param show whether we should show the avatar or not
  8602. * video because there is no dominant speaker and no focused speaker
  8603. */
  8604. SmallVideo.prototype.showAvatar = function (show) {
  8605. if (!this.hasAvatar) {
  8606. if (this.peerJid) {
  8607. // Init avatar
  8608. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8609. } else {
  8610. console.error("Unable to init avatar - no peerjid", this);
  8611. return;
  8612. }
  8613. }
  8614. var resourceJid = this.getResourceJid();
  8615. var videoElem = APP.RTC.getVideoElementName();
  8616. var video = $('#' + this.videoSpanId).find(videoElem);
  8617. var avatar = $('#avatar_' + resourceJid);
  8618. if (show === undefined || show === null) {
  8619. if (!this.isLocal &&
  8620. !this.VideoLayout.isInLastN(resourceJid)) {
  8621. show = true;
  8622. } else {
  8623. // We want to show the avatar when the video is muted or not exists
  8624. // that is when 'true' or 'null' is returned
  8625. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8626. }
  8627. }
  8628. if (LargeVideo.showAvatar(resourceJid, show)) {
  8629. setVisibility(avatar, false);
  8630. setVisibility(video, false);
  8631. } else {
  8632. if (video && video.length > 0) {
  8633. setVisibility(video, !show);
  8634. }
  8635. setVisibility(avatar, show);
  8636. }
  8637. };
  8638. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8639. var thumbnail = $('#' + this.videoSpanId);
  8640. var resourceJid = this.getResourceJid();
  8641. var avatar = $('#avatar_' + resourceJid);
  8642. this.hasAvatar = true;
  8643. // set the avatar in the thumbnail
  8644. if (avatar && avatar.length > 0) {
  8645. avatar[0].src = thumbUrl;
  8646. } else {
  8647. if (thumbnail && thumbnail.length > 0) {
  8648. avatar = document.createElement('img');
  8649. avatar.id = 'avatar_' + resourceJid;
  8650. avatar.className = 'userAvatar';
  8651. avatar.src = thumbUrl;
  8652. thumbnail.append(avatar);
  8653. }
  8654. }
  8655. };
  8656. module.exports = SmallVideo;
  8657. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8658. /* global config, APP, $, Strophe, require, interfaceConfig */
  8659. var AudioLevels = require("../audio_levels/AudioLevels");
  8660. var ContactList = require("../side_pannels/contactlist/ContactList");
  8661. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8662. var UIEvents = require("../../../service/UI/UIEvents");
  8663. var UIUtil = require("../util/UIUtil");
  8664. var RTC = require("../../RTC/RTC");
  8665. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8666. var RemoteVideo = require("./RemoteVideo");
  8667. var LargeVideo = require("./LargeVideo");
  8668. var LocalVideo = require("./LocalVideo");
  8669. var remoteVideos = {};
  8670. var remoteVideoTypes = {};
  8671. var localVideoThumbnail = null;
  8672. var currentDominantSpeaker = null;
  8673. var lastNCount = config.channelLastN;
  8674. var localLastNCount = config.channelLastN;
  8675. var localLastNSet = [];
  8676. var lastNEndpointsCache = [];
  8677. var lastNPickupJid = null;
  8678. var eventEmitter = null;
  8679. /**
  8680. * Currently focused video jid
  8681. * @type {String}
  8682. */
  8683. var focusedVideoResourceJid = null;
  8684. var VideoLayout = (function (my) {
  8685. my.init = function (emitter) {
  8686. eventEmitter = emitter;
  8687. localVideoThumbnail = new LocalVideo(VideoLayout);
  8688. if (interfaceConfig.filmStripOnly) {
  8689. LargeVideo.disable();
  8690. } else {
  8691. LargeVideo.init(VideoLayout, emitter);
  8692. }
  8693. VideoLayout.resizeLargeVideoContainer();
  8694. };
  8695. my.isInLastN = function(resource) {
  8696. return lastNCount < 0 || // lastN is disabled
  8697. // lastNEndpoints cache not built yet
  8698. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8699. (lastNEndpointsCache &&
  8700. lastNEndpointsCache.indexOf(resource) !== -1);
  8701. };
  8702. my.changeLocalStream = function (stream, isMuted) {
  8703. VideoLayout.changeLocalVideo(stream, isMuted);
  8704. };
  8705. my.changeLocalAudio = function(stream, isMuted) {
  8706. if (isMuted)
  8707. APP.UI.setAudioMuted(true, true);
  8708. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8709. var localAudio = document.getElementById('localAudio');
  8710. // Writing volume not allowed in IE
  8711. if (!RTCBrowserType.isIExplorer()) {
  8712. localAudio.autoplay = true;
  8713. localAudio.volume = 0;
  8714. }
  8715. };
  8716. my.changeLocalVideo = function(stream, isMuted) {
  8717. // Set default display name.
  8718. localVideoThumbnail.setDisplayName();
  8719. localVideoThumbnail.createConnectionIndicator();
  8720. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  8721. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8722. localVideoThumbnail.changeVideo(stream, isMuted);
  8723. /* force update if we're currently being displayed */
  8724. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8725. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8726. }
  8727. };
  8728. my.mucJoined = function () {
  8729. var myResourceJid = APP.xmpp.myResource();
  8730. localVideoThumbnail.joined(APP.xmpp.myJid());
  8731. if (!LargeVideo.getResourceJid())
  8732. LargeVideo.updateLargeVideo(myResourceJid, true);
  8733. };
  8734. /**
  8735. * Adds or removes icons for not available camera and microphone.
  8736. * @param resourceJid the jid of user
  8737. * @param devices available devices
  8738. */
  8739. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8740. if(!devices)
  8741. return;
  8742. if(!resourceJid) {
  8743. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8744. } else {
  8745. if(remoteVideos[resourceJid])
  8746. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8747. }
  8748. };
  8749. /**
  8750. * Checks if removed video is currently displayed and tries to display
  8751. * another one instead.
  8752. * @param removedVideoSrc src stream identifier of the video.
  8753. */
  8754. my.updateRemovedVideo = function(resourceJid) {
  8755. if (resourceJid === LargeVideo.getResourceJid()) {
  8756. var newResourceJid;
  8757. // We'll show user's avatar if he is the dominant speaker or if
  8758. // his video thumbnail is pinned
  8759. if (remoteVideos[resourceJid] &&
  8760. resourceJid === focusedVideoResourceJid ||
  8761. resourceJid === currentDominantSpeaker) {
  8762. newResourceJid = resourceJid;
  8763. } else {
  8764. // Otherwise select last visible video
  8765. newResourceJid = this.electLastVisibleVideo();
  8766. }
  8767. LargeVideo.updateLargeVideo(newResourceJid);
  8768. }
  8769. };
  8770. my.electLastVisibleVideo = function() {
  8771. // pick the last visible video in the row
  8772. // if nobody else is left, this picks the local video
  8773. var jid;
  8774. var videoElem = RTC.getVideoElementName();
  8775. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8776. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8777. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8778. } else {
  8779. console.info("Last visible video no longer exists");
  8780. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8781. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8782. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8783. } else {
  8784. // Try local video
  8785. console.info("Fallback to local video...");
  8786. jid = APP.xmpp.myResource();
  8787. }
  8788. }
  8789. console.info("electLastVisibleVideo: " + jid);
  8790. return jid;
  8791. };
  8792. my.onRemoteStreamAdded = function (stream) {
  8793. if (stream.peerjid) {
  8794. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8795. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8796. remoteVideos[resourceJid].addRemoteStreamElement(
  8797. stream.sid,
  8798. stream.getOriginalStream(),
  8799. stream.ssrc);
  8800. }
  8801. };
  8802. my.getLargeVideoResource = function () {
  8803. return LargeVideo.getResourceJid();
  8804. };
  8805. /**
  8806. * Called when large video update is finished
  8807. * @param currentSmallVideo small video currently displayed on large video
  8808. */
  8809. my.largeVideoUpdated = function (currentSmallVideo) {
  8810. // Makes sure that dominant speaker UI
  8811. // is enabled only on current small video
  8812. localVideoThumbnail.enableDominantSpeaker(
  8813. localVideoThumbnail === currentSmallVideo);
  8814. Object.keys(remoteVideos).forEach(
  8815. function (resourceJid) {
  8816. var remoteVideo = remoteVideos[resourceJid];
  8817. if (remoteVideo) {
  8818. remoteVideo.enableDominantSpeaker(
  8819. remoteVideo === currentSmallVideo);
  8820. }
  8821. }
  8822. );
  8823. };
  8824. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8825. resourceJid) {
  8826. if(focusedVideoResourceJid) {
  8827. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8828. if (oldSmallVideo && !interfaceConfig.filmStripOnly)
  8829. oldSmallVideo.focus(false);
  8830. }
  8831. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8832. // Unlock current focused.
  8833. if (focusedVideoResourceJid === resourceJid)
  8834. {
  8835. focusedVideoResourceJid = null;
  8836. // Enable the currently set dominant speaker.
  8837. if (currentDominantSpeaker) {
  8838. if(smallVideo && smallVideo.hasVideo()) {
  8839. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8840. }
  8841. }
  8842. if (!noPinnedEndpointChangedEvent) {
  8843. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8844. }
  8845. return;
  8846. }
  8847. // Lock new video
  8848. focusedVideoResourceJid = resourceJid;
  8849. // Update focused/pinned interface.
  8850. if (resourceJid) {
  8851. if (smallVideo && !interfaceConfig.filmStripOnly)
  8852. smallVideo.focus(true);
  8853. if (!noPinnedEndpointChangedEvent) {
  8854. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8855. }
  8856. }
  8857. LargeVideo.setState("video");
  8858. LargeVideo.updateLargeVideo(resourceJid);
  8859. // Writing volume not allowed in IE
  8860. if (!RTCBrowserType.isIExplorer()) {
  8861. $('audio').each(function (idx, el) {
  8862. el.volume = 0;
  8863. el.volume = 1;
  8864. });
  8865. }
  8866. };
  8867. /**
  8868. * Checks if container for participant identified by given peerJid exists
  8869. * in the document and creates it eventually.
  8870. *
  8871. * @param peerJid peer Jid to check.
  8872. *
  8873. * @return Returns <tt>true</tt> if the peer container exists,
  8874. * <tt>false</tt> - otherwise
  8875. */
  8876. my.ensurePeerContainerExists = function(peerJid) {
  8877. ContactList.ensureAddContact(peerJid);
  8878. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8879. if (!remoteVideos[resourceJid]) {
  8880. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  8881. remoteVideos[resourceJid] = remoteVideo;
  8882. var videoType = remoteVideoTypes[resourceJid];
  8883. if (videoType) {
  8884. remoteVideo.setVideoType(videoType);
  8885. }
  8886. // In case this is not currently in the last n we don't show it.
  8887. if (localLastNCount &&
  8888. localLastNCount > 0 &&
  8889. $('#remoteVideos>span').length >= localLastNCount + 2) {
  8890. remoteVideo.showPeerContainer('hide');
  8891. }
  8892. else
  8893. VideoLayout.resizeThumbnails();
  8894. }
  8895. };
  8896. my.inputDisplayNameHandler = function (name) {
  8897. localVideoThumbnail.inputDisplayNameHandler(name);
  8898. };
  8899. my.videoactive = function (videoelem, resourceJid) {
  8900. console.info(resourceJid + " video is now active");
  8901. videoelem.show();
  8902. VideoLayout.resizeThumbnails();
  8903. // Update the large video to the last added video only if there's no
  8904. // current dominant, focused speaker or prezi playing or update it to
  8905. // the current dominant speaker.
  8906. if ((!focusedVideoResourceJid &&
  8907. !currentDominantSpeaker &&
  8908. !require("../prezi/Prezi").isPresentationVisible()) ||
  8909. focusedVideoResourceJid === resourceJid ||
  8910. (resourceJid &&
  8911. currentDominantSpeaker === resourceJid)) {
  8912. LargeVideo.updateLargeVideo(resourceJid, true);
  8913. }
  8914. };
  8915. /**
  8916. * Shows the presence status message for the given video.
  8917. */
  8918. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8919. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8920. };
  8921. /**
  8922. * Shows a visual indicator for the moderator of the conference.
  8923. */
  8924. my.showModeratorIndicator = function () {
  8925. var isModerator = APP.xmpp.isModerator();
  8926. if (isModerator) {
  8927. localVideoThumbnail.createModeratorIndicatorElement();
  8928. }
  8929. var members = APP.xmpp.getMembers();
  8930. Object.keys(members).forEach(function (jid) {
  8931. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8932. // Skip server side focus
  8933. return;
  8934. }
  8935. var resourceJid = Strophe.getResourceFromJid(jid);
  8936. var member = members[jid];
  8937. if (member.role === 'moderator') {
  8938. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8939. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8940. } else if (isModerator) {
  8941. // We are moderator, but user is not - add menu
  8942. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8943. remoteVideos[resourceJid].addRemoteVideoMenu();
  8944. }
  8945. }
  8946. });
  8947. };
  8948. /*
  8949. * Shows or hides the audio muted indicator over the local thumbnail video.
  8950. * @param {boolean} isMuted
  8951. */
  8952. my.showLocalAudioIndicator = function(isMuted) {
  8953. localVideoThumbnail.showAudioIndicator(isMuted);
  8954. };
  8955. /**
  8956. * Resizes the large video container.
  8957. */
  8958. my.resizeLargeVideoContainer = function () {
  8959. if(LargeVideo.isEnabled()) {
  8960. LargeVideo.resize();
  8961. } else {
  8962. VideoLayout.resizeVideoSpace();
  8963. }
  8964. VideoLayout.resizeThumbnails();
  8965. LargeVideo.position();
  8966. };
  8967. /**
  8968. * Resizes thumbnails.
  8969. */
  8970. my.resizeThumbnails = function(animate) {
  8971. var videoSpaceWidth = $('#remoteVideos').width();
  8972. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8973. var width = thumbnailSize[0];
  8974. var height = thumbnailSize[1];
  8975. $('.userAvatar').css('left', (width - height) / 2);
  8976. if(animate) {
  8977. $('#remoteVideos').animate({
  8978. height: height + 2 // adds 2 px because of small video 1px border
  8979. },
  8980. {
  8981. queue: false,
  8982. duration: 500
  8983. });
  8984. $('#remoteVideos>span').animate({
  8985. height: height,
  8986. width: width
  8987. },
  8988. {
  8989. queue: false,
  8990. duration: 500,
  8991. complete: function () {
  8992. $(document).trigger(
  8993. "remotevideo.resized",
  8994. [width,
  8995. height]);
  8996. }
  8997. });
  8998. } else {
  8999. // size videos so that while keeping AR and max height, we have a
  9000. // nice fit
  9001. $('#remoteVideos').height(height + 2);// adds 2 px because of small video 1px border
  9002. $('#remoteVideos>span').width(width);
  9003. $('#remoteVideos>span').height(height);
  9004. $(document).trigger("remotevideo.resized", [width, height]);
  9005. }
  9006. };
  9007. /**
  9008. * Calculates the thumbnail size.
  9009. *
  9010. * @param videoSpaceWidth the width of the video space
  9011. */
  9012. my.calculateThumbnailSize = function (videoSpaceWidth) {
  9013. // Calculate the available height, which is the inner window height minus
  9014. // 39px for the header minus 2px for the delimiter lines on the top and
  9015. // bottom of the large video, minus the 36px space inside the remoteVideos
  9016. // container used for highlighting shadow.
  9017. var availableHeight = 100;
  9018. var numvids = $('#remoteVideos>span:visible').length;
  9019. if (localLastNCount && localLastNCount > 0) {
  9020. numvids = Math.min(localLastNCount + 1, numvids);
  9021. }
  9022. // Remove the 3px borders arround videos and border around the remote
  9023. // videos area and the 4 pixels between the local video and the others
  9024. //TODO: Find out where the 4 pixels come from and remove them
  9025. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  9026. var availableWidth = availableWinWidth / numvids;
  9027. var aspectRatio = 16.0 / 9.0;
  9028. var maxHeight = Math.min(160, availableHeight);
  9029. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio, window.innerHeight - 18);
  9030. if (availableHeight < availableWidth / aspectRatio) {
  9031. availableWidth = Math.floor(availableHeight * aspectRatio);
  9032. }
  9033. return [availableWidth, availableHeight];
  9034. };
  9035. /**
  9036. * Returns the corresponding resource jid to the given peer container
  9037. * DOM element.
  9038. *
  9039. * @return the corresponding resource jid to the given peer container
  9040. * DOM element
  9041. */
  9042. my.getPeerContainerResourceJid = function (containerElement) {
  9043. var i = containerElement.id.indexOf('participant_');
  9044. if (i >= 0)
  9045. return containerElement.id.substring(i + 12);
  9046. };
  9047. my.getPeerVideoSel = function (peerResourceJid) {
  9048. return $('#participant_' + peerResourceJid +
  9049. '>' + APP.RTC.getVideoElementName());
  9050. };
  9051. /**
  9052. * On contact list item clicked.
  9053. */
  9054. $(ContactList).bind('contactclicked', function(event, jid) {
  9055. if (!jid) {
  9056. return;
  9057. }
  9058. if (jid === APP.xmpp.myJid()) {
  9059. $("#localVideoContainer").click();
  9060. return;
  9061. }
  9062. var resource = Strophe.getResourceFromJid(jid);
  9063. var videoSel = VideoLayout.getPeerVideoSel(resource);
  9064. if (videoSel.length > 0) {
  9065. var videoThumb = videoSel[0];
  9066. // It is not always the case that a videoThumb exists (if there is
  9067. // no actual video).
  9068. if (RTC.getVideoSrc(videoThumb)) {
  9069. // We have a video src, great! Let's update the large video
  9070. // now.
  9071. VideoLayout.handleVideoThumbClicked(
  9072. false,
  9073. Strophe.getResourceFromJid(jid));
  9074. } else {
  9075. // If we don't have a video src for jid, there's absolutely
  9076. // no point in calling handleVideoThumbClicked; Quite
  9077. // simply, it won't work because it needs an src to attach
  9078. // to the large video.
  9079. //
  9080. // Instead, we trigger the pinned endpoint changed event to
  9081. // let the bridge adjust its lastN set for myjid and store
  9082. // the pinned user in the lastNPickupJid variable to be
  9083. // picked up later by the lastN changed event handler.
  9084. lastNPickupJid = jid;
  9085. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9086. Strophe.getResourceFromJid(jid));
  9087. }
  9088. }
  9089. });
  9090. /**
  9091. * On audio muted event.
  9092. */
  9093. my.onAudioMute = function (jid, isMuted) {
  9094. var resourceJid = Strophe.getResourceFromJid(jid);
  9095. if (resourceJid === APP.xmpp.myResource()) {
  9096. localVideoThumbnail.showAudioIndicator(isMuted);
  9097. } else {
  9098. VideoLayout.ensurePeerContainerExists(jid);
  9099. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9100. if (APP.xmpp.isModerator()) {
  9101. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9102. }
  9103. }
  9104. };
  9105. /**
  9106. * On video muted event.
  9107. */
  9108. my.onVideoMute = function (jid, value) {
  9109. if (jid !== APP.xmpp.myJid() &&
  9110. !APP.RTC.muteRemoteVideoStream(jid, value))
  9111. return;
  9112. if (jid === APP.xmpp.myJid()) {
  9113. localVideoThumbnail.showVideoIndicator(value);
  9114. } else {
  9115. var resource = Strophe.getResourceFromJid(jid);
  9116. VideoLayout.ensurePeerContainerExists(jid);
  9117. remoteVideos[resource].showVideoIndicator(value);
  9118. var el = VideoLayout.getPeerVideoSel(resource);
  9119. if (!value)
  9120. el.show();
  9121. else
  9122. el.hide();
  9123. }
  9124. };
  9125. /**
  9126. * Display name changed.
  9127. */
  9128. my.onDisplayNameChanged =
  9129. function (jid, displayName, status) {
  9130. if (jid === 'localVideoContainer' ||
  9131. jid === APP.xmpp.myJid()) {
  9132. localVideoThumbnail.setDisplayName(displayName);
  9133. } else {
  9134. VideoLayout.ensurePeerContainerExists(jid);
  9135. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9136. displayName,
  9137. status);
  9138. }
  9139. };
  9140. /**
  9141. * On dominant speaker changed event.
  9142. */
  9143. my.onDominantSpeakerChanged = function (resourceJid) {
  9144. // We ignore local user events.
  9145. if (resourceJid === APP.xmpp.myResource())
  9146. return;
  9147. var members = APP.xmpp.getMembers();
  9148. // Update the current dominant speaker.
  9149. if (resourceJid !== currentDominantSpeaker) {
  9150. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9151. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9152. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9153. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9154. remoteVideos[resourceJid].setDisplayName(null);
  9155. }
  9156. if(resourceJid && (!members || !members[newJID] ||
  9157. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9158. remoteVideos[resourceJid].setDisplayName(null,
  9159. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9160. }
  9161. currentDominantSpeaker = resourceJid;
  9162. } else {
  9163. return;
  9164. }
  9165. // Obtain container for new dominant speaker.
  9166. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9167. // Local video will not have container found, but that's ok
  9168. // since we don't want to switch to local video.
  9169. if (!focusedVideoResourceJid && videoSel.length) {
  9170. // Update the large video if the video source is already available,
  9171. // otherwise wait for the "videoactive.jingle" event.
  9172. if (videoSel[0].currentTime > 0) {
  9173. LargeVideo.updateLargeVideo(resourceJid);
  9174. }
  9175. }
  9176. };
  9177. /**
  9178. * On last N change event.
  9179. *
  9180. * @param lastNEndpoints the list of last N endpoints
  9181. * @param endpointsEnteringLastN the list currently entering last N
  9182. * endpoints
  9183. */
  9184. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9185. endpointsEnteringLastN,
  9186. stream) {
  9187. if (lastNCount !== lastNEndpoints.length)
  9188. lastNCount = lastNEndpoints.length;
  9189. lastNEndpointsCache = lastNEndpoints;
  9190. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9191. //
  9192. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9193. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9194. // so E sees them. C is only in E's local LastN set.
  9195. //
  9196. // If F starts talking and LastN = 3, then E should see thumbnails for
  9197. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9198. // enters E's local LastN ejecting C.
  9199. // Increase the local LastN set size, if necessary.
  9200. if (lastNCount > localLastNCount) {
  9201. localLastNCount = lastNCount;
  9202. }
  9203. // Update the local LastN set preserving the order in which the
  9204. // endpoints appeared in the LastN/local LastN set.
  9205. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9206. for (var i = 0; i < localLastNSet.length; i++) {
  9207. if (nextLocalLastNSet.length >= localLastNCount) {
  9208. break;
  9209. }
  9210. var resourceJid = localLastNSet[i];
  9211. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9212. nextLocalLastNSet.push(resourceJid);
  9213. }
  9214. }
  9215. localLastNSet = nextLocalLastNSet;
  9216. var updateLargeVideo = false;
  9217. // Handle LastN/local LastN changes.
  9218. $('#remoteVideos>span').each(function( index, element ) {
  9219. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9220. var isReceived = true;
  9221. if (resourceJid &&
  9222. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9223. localLastNSet.indexOf(resourceJid) < 0) {
  9224. console.log("Remove from last N", resourceJid);
  9225. remoteVideos[resourceJid].showPeerContainer('hide');
  9226. isReceived = false;
  9227. } else if (resourceJid &&
  9228. $('#participant_' + resourceJid).is(':visible') &&
  9229. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9230. localLastNSet.indexOf(resourceJid) >= 0) {
  9231. remoteVideos[resourceJid].showPeerContainer('avatar');
  9232. isReceived = false;
  9233. }
  9234. if (!isReceived) {
  9235. // resourceJid has dropped out of the server side lastN set, so
  9236. // it is no longer being received. If resourceJid was being
  9237. // displayed in the large video we have to switch to another
  9238. // user.
  9239. if (!updateLargeVideo &&
  9240. resourceJid === LargeVideo.getResourceJid()) {
  9241. updateLargeVideo = true;
  9242. }
  9243. }
  9244. });
  9245. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9246. endpointsEnteringLastN = lastNEndpoints;
  9247. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9248. endpointsEnteringLastN.forEach(function (resourceJid) {
  9249. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9250. remoteVideos[resourceJid].showPeerContainer('show');
  9251. if (!isVisible) {
  9252. console.log("Add to last N", resourceJid);
  9253. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9254. var mediaStream =
  9255. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9256. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9257. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9258. if (lastNPickupJid == mediaStream.peerjid) {
  9259. // Clean up the lastN pickup jid.
  9260. lastNPickupJid = null;
  9261. // Don't fire the events again, they've already
  9262. // been fired in the contact list click handler.
  9263. VideoLayout.handleVideoThumbClicked(
  9264. false,
  9265. Strophe.getResourceFromJid(mediaStream.peerjid));
  9266. updateLargeVideo = false;
  9267. }
  9268. remoteVideos[resourceJid].
  9269. waitForPlayback(sel, mediaStream.stream);
  9270. }
  9271. });
  9272. }
  9273. // The endpoint that was being shown in the large video has dropped out
  9274. // of the lastN set and there was no lastN pickup jid. We need to update
  9275. // the large video now.
  9276. if (updateLargeVideo) {
  9277. var resource;
  9278. var myResource
  9279. = APP.xmpp.myResource();
  9280. // Find out which endpoint to show in the large video.
  9281. for (i = 0; i < lastNEndpoints.length; i++) {
  9282. resource = lastNEndpoints[i];
  9283. if (!resource || resource === myResource)
  9284. continue;
  9285. // videoSrcToSsrc needs to be update for this call to succeed.
  9286. LargeVideo.updateLargeVideo(resource);
  9287. break;
  9288. }
  9289. }
  9290. };
  9291. /**
  9292. * Updates local stats
  9293. * @param percent
  9294. * @param object
  9295. */
  9296. my.updateLocalConnectionStats = function (percent, object) {
  9297. var resolution = null;
  9298. if (object.resolution !== null) {
  9299. resolution = object.resolution;
  9300. object.resolution = resolution[APP.xmpp.myJid()];
  9301. delete resolution[APP.xmpp.myJid()];
  9302. }
  9303. localVideoThumbnail.updateStatsIndicator(percent, object);
  9304. for (var jid in resolution) {
  9305. if (resolution[jid] === null)
  9306. continue;
  9307. var resourceJid = Strophe.getResourceFromJid(jid);
  9308. if (remoteVideos[resourceJid] &&
  9309. remoteVideos[resourceJid].connectionIndicator) {
  9310. remoteVideos[resourceJid].connectionIndicator.
  9311. updateResolution(resolution[jid]);
  9312. }
  9313. }
  9314. };
  9315. /**
  9316. * Updates remote stats.
  9317. * @param jid the jid associated with the stats
  9318. * @param percent the connection quality percent
  9319. * @param object the stats data
  9320. */
  9321. my.updateConnectionStats = function (jid, percent, object) {
  9322. var resourceJid = Strophe.getResourceFromJid(jid);
  9323. if (remoteVideos[resourceJid])
  9324. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9325. };
  9326. /**
  9327. * Hides the connection indicator
  9328. * @param jid
  9329. */
  9330. my.hideConnectionIndicator = function (jid) {
  9331. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9332. };
  9333. /**
  9334. * Hides all the indicators
  9335. */
  9336. my.onStatsStop = function () {
  9337. for(var video in remoteVideos) {
  9338. remoteVideos[video].hideIndicator();
  9339. }
  9340. localVideoThumbnail.hideIndicator();
  9341. };
  9342. my.participantLeft = function (jid) {
  9343. // Unlock large video
  9344. var resourceJid = Strophe.getResourceFromJid(jid);
  9345. if (focusedVideoResourceJid === resourceJid) {
  9346. console.info("Focused video owner has left the conference");
  9347. focusedVideoResourceJid = null;
  9348. }
  9349. if (currentDominantSpeaker === resourceJid)
  9350. {
  9351. console.info("Dominant speaker has left the conference");
  9352. currentDominantSpeaker = null;
  9353. }
  9354. var remoteVideo = remoteVideos[resourceJid];
  9355. if (remoteVideo) {
  9356. // Remove remote video
  9357. console.info("Removing remote video: " + resourceJid);
  9358. remoteVideo.remove();
  9359. delete remoteVideos[resourceJid];
  9360. } else {
  9361. console.warn("No remote video for " + resourceJid);
  9362. }
  9363. VideoLayout.resizeThumbnails();
  9364. };
  9365. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9366. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9367. return;
  9368. }
  9369. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9370. remoteVideoTypes[resourceJid] = newVideoType;
  9371. var smallVideo;
  9372. if (resourceJid === APP.xmpp.myResource()) {
  9373. if (!localVideoThumbnail) {
  9374. console.warn("Local video not ready yet");
  9375. return;
  9376. }
  9377. smallVideo = localVideoThumbnail;
  9378. } else if (remoteVideos[resourceJid]) {
  9379. smallVideo = remoteVideos[resourceJid];
  9380. } else {
  9381. return;
  9382. }
  9383. smallVideo.setVideoType(newVideoType);
  9384. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9385. };
  9386. my.showMore = function (jid) {
  9387. if (jid === 'local') {
  9388. localVideoThumbnail.connectionIndicator.showMore();
  9389. } else {
  9390. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9391. if (remoteVideo) {
  9392. remoteVideo.connectionIndicator.showMore();
  9393. } else {
  9394. console.info("Error - no remote video for jid: " + jid);
  9395. }
  9396. }
  9397. };
  9398. my.addPreziContainer = function (id) {
  9399. var container = RemoteVideo.createContainer(id);
  9400. VideoLayout.resizeThumbnails();
  9401. return container;
  9402. };
  9403. my.setLargeVideoVisible = function (isVisible) {
  9404. LargeVideo.setLargeVideoVisible(isVisible);
  9405. if(!isVisible && focusedVideoResourceJid) {
  9406. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9407. if(smallVideo) {
  9408. smallVideo.focus(false);
  9409. smallVideo.showAvatar();
  9410. }
  9411. focusedVideoResourceJid = null;
  9412. }
  9413. };
  9414. /**
  9415. * Resizes the video area
  9416. * @param callback a function to be called when the video space is
  9417. * resized.
  9418. */
  9419. my.resizeVideoArea = function(isVisible, callback) {
  9420. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9421. VideoLayout.resizeThumbnails(true);
  9422. };
  9423. /**
  9424. * Resizes the #videospace html element
  9425. * @param animate boolean property that indicates whether the resize should be animated or not.
  9426. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  9427. * If that parameter is null the method will check the chat pannel visibility.
  9428. * @param completeFunction a function to be called when the video space is resized
  9429. */
  9430. my.resizeVideoSpace = function (animate, isChatVisible, completeFunction) {
  9431. var availableHeight = window.innerHeight;
  9432. var availableWidth = UIUtil.getAvailableVideoWidth(isChatVisible);
  9433. if (availableWidth < 0 || availableHeight < 0) return;
  9434. if(animate) {
  9435. $('#videospace').animate({
  9436. right: window.innerWidth - availableWidth,
  9437. width: availableWidth,
  9438. height: availableHeight
  9439. },
  9440. {
  9441. queue: false,
  9442. duration: 500,
  9443. complete: completeFunction
  9444. });
  9445. } else {
  9446. $('#videospace').width(availableWidth);
  9447. $('#videospace').height(availableHeight);
  9448. }
  9449. };
  9450. my.getSmallVideo = function (resourceJid) {
  9451. if(resourceJid == APP.xmpp.myResource()) {
  9452. return localVideoThumbnail;
  9453. } else {
  9454. if(!remoteVideos[resourceJid])
  9455. return null;
  9456. return remoteVideos[resourceJid];
  9457. }
  9458. };
  9459. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9460. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9461. if(smallVideo)
  9462. smallVideo.avatarChanged(thumbUrl);
  9463. else
  9464. console.warn(
  9465. "Missed avatar update - no small video yet for " + resourceJid);
  9466. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9467. };
  9468. my.createEtherpadIframe = function(src, onloadHandler)
  9469. {
  9470. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9471. };
  9472. my.setLargeVideoState = function (state) {
  9473. LargeVideo.setState(state);
  9474. };
  9475. my.getLargeVideoState = function () {
  9476. return LargeVideo.getState();
  9477. };
  9478. my.setLargeVideoHover = function (inHandler, outHandler) {
  9479. LargeVideo.setHover(inHandler, outHandler);
  9480. };
  9481. /**
  9482. * Indicates that the video has been interrupted.
  9483. */
  9484. my.onVideoInterrupted = function () {
  9485. LargeVideo.enableVideoProblemFilter(true);
  9486. var reconnectingKey = "connection.RECONNECTING";
  9487. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9488. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9489. $('#videoConnectionMessage').css({display: "block"});
  9490. };
  9491. /**
  9492. * Indicates that the video has been restored.
  9493. */
  9494. my.onVideoRestored = function () {
  9495. LargeVideo.enableVideoProblemFilter(false);
  9496. $('#videoConnectionMessage').css({display: "none"});
  9497. };
  9498. return my;
  9499. }(VideoLayout || {}));
  9500. module.exports = VideoLayout;
  9501. },{"../../../service/RTC/MediaStreamTypes":151,"../../../service/UI/UIEvents":155,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"../util/UIUtil":33,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  9502. //var nouns = [
  9503. //];
  9504. var pluralNouns = [
  9505. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9506. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9507. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9508. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9509. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9510. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9511. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9512. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9513. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9514. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9515. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9516. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9517. ];
  9518. //var places = [
  9519. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9520. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9521. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9522. // "Bridge"
  9523. //];
  9524. var verbs = [
  9525. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9526. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9527. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9528. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9529. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9530. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9531. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9532. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9533. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9534. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9535. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9536. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9537. ];
  9538. var adverbs = [
  9539. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9540. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9541. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9542. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9543. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9544. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9545. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9546. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9547. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9548. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9549. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9550. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9551. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9552. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9553. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9554. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9555. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9556. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9557. ];
  9558. var adjectives = [
  9559. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9560. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9561. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9562. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9563. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9564. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9565. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9566. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9567. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9568. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9569. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9570. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9571. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9572. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9573. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9574. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9575. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9576. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9577. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9578. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9579. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9580. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9581. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9582. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9583. "Zealous"
  9584. ];
  9585. //var pronouns = [
  9586. //];
  9587. //var conjunctions = [
  9588. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9589. //];
  9590. /*
  9591. * Maps a string (category name) to the array of words from that category.
  9592. */
  9593. var CATEGORIES =
  9594. {
  9595. //"_NOUN_": nouns,
  9596. "_PLURALNOUN_": pluralNouns,
  9597. //"_PLACE_": places,
  9598. "_VERB_": verbs,
  9599. "_ADVERB_": adverbs,
  9600. "_ADJECTIVE_": adjectives
  9601. //"_PRONOUN_": pronouns,
  9602. //"_CONJUNCTION_": conjunctions,
  9603. };
  9604. var PATTERNS = [
  9605. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9606. // BeautifulFungiOrSpaghetti
  9607. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9608. // AmazinglyScaryToy
  9609. //"_ADVERB__ADJECTIVE__NOUN_",
  9610. // NeitherTrashNorRifle
  9611. //"Neither_NOUN_Nor_NOUN_",
  9612. //"Either_NOUN_Or_NOUN_",
  9613. // EitherCopulateOrInvestigate
  9614. //"Either_VERB_Or_VERB_",
  9615. //"Neither_VERB_Nor_VERB_",
  9616. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9617. //"The_ADVERB__ADJECTIVE__NOUN_",
  9618. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9619. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9620. // WolvesComputeBadly
  9621. //"_PLURALNOUN__VERB__ADVERB_",
  9622. // UniteFacilitateAndMerge
  9623. //"_VERB__VERB_And_VERB_",
  9624. //NastyWitchesAtThePub
  9625. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9626. ];
  9627. /*
  9628. * Returns a random element from the array 'arr'
  9629. */
  9630. function randomElement(arr) {
  9631. return arr[Math.floor(Math.random() * arr.length)];
  9632. }
  9633. /*
  9634. * Returns true if the string 's' contains one of the
  9635. * template strings.
  9636. */
  9637. function hasTemplate(s) {
  9638. for (var template in CATEGORIES){
  9639. if (s.indexOf(template) >= 0){
  9640. return true;
  9641. }
  9642. }
  9643. }
  9644. /**
  9645. * Generates new room name.
  9646. */
  9647. var RoomNameGenerator = {
  9648. generateRoomWithoutSeparator: function() {
  9649. // Note that if more than one pattern is available, the choice of
  9650. // 'name' won't have a uniform distribution amongst all patterns (names
  9651. // from patterns with fewer options will have higher probability of
  9652. // being chosen that names from patterns with more options).
  9653. var name = randomElement(PATTERNS);
  9654. var word;
  9655. while (hasTemplate(name)) {
  9656. for (var template in CATEGORIES) {
  9657. word = randomElement(CATEGORIES[template]);
  9658. name = name.replace(template, word);
  9659. }
  9660. }
  9661. return name;
  9662. }
  9663. };
  9664. module.exports = RoomNameGenerator;
  9665. },{}],41:[function(require,module,exports){
  9666. /* global $, interfaceConfig */
  9667. var animateTimeout, updateTimeout;
  9668. var RoomNameGenerator = require("./RoomnameGenerator");
  9669. function enter_room() {
  9670. var val = $("#enter_room_field").val();
  9671. if(!val) {
  9672. val = $("#enter_room_field").attr("room_name");
  9673. }
  9674. if (val) {
  9675. window.location.pathname = "/" + val;
  9676. }
  9677. }
  9678. function animate(word) {
  9679. var currentVal = $("#enter_room_field").attr("placeholder");
  9680. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9681. animateTimeout = setTimeout(function() {
  9682. animate(word.substring(1, word.length))
  9683. }, 70);
  9684. }
  9685. function update_roomname() {
  9686. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9687. $("#enter_room_field").attr("room_name", word);
  9688. $("#enter_room_field").attr("placeholder", "");
  9689. clearTimeout(animateTimeout);
  9690. animate(word);
  9691. updateTimeout = setTimeout(update_roomname, 10000);
  9692. }
  9693. function setupWelcomePage() {
  9694. $("#videoconference_page").hide();
  9695. $("#domain_name").text(
  9696. window.location.protocol + "//" + window.location.host + "/");
  9697. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9698. var leftWatermarkDiv =
  9699. $("#welcome_page_header div[class='watermark leftwatermark']");
  9700. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9701. leftWatermarkDiv.css({display: 'block'});
  9702. leftWatermarkDiv.parent().get(0).href =
  9703. interfaceConfig.JITSI_WATERMARK_LINK;
  9704. }
  9705. }
  9706. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9707. var rightWatermarkDiv =
  9708. $("#welcome_page_header div[class='watermark rightwatermark']");
  9709. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9710. rightWatermarkDiv.css({display: 'block'});
  9711. rightWatermarkDiv.parent().get(0).href =
  9712. interfaceConfig.BRAND_WATERMARK_LINK;
  9713. rightWatermarkDiv.get(0).style.backgroundImage =
  9714. "url(images/rightwatermark.png)";
  9715. }
  9716. }
  9717. if (interfaceConfig.SHOW_POWERED_BY) {
  9718. $("#welcome_page_header>a[class='poweredby']")
  9719. .css({display: 'block'});
  9720. }
  9721. $("#enter_room_button").click(function() {
  9722. enter_room();
  9723. });
  9724. $("#enter_room_field").keydown(function (event) {
  9725. if (event.keyCode === 13 /* enter */) {
  9726. enter_room();
  9727. }
  9728. });
  9729. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9730. var updateTimeout;
  9731. var animateTimeout;
  9732. var selector = $("#reload_roomname");
  9733. selector.click(function () {
  9734. clearTimeout(updateTimeout);
  9735. clearTimeout(animateTimeout);
  9736. update_roomname();
  9737. });
  9738. selector.show();
  9739. update_roomname();
  9740. }
  9741. $("#disable_welcome").click(function () {
  9742. window.localStorage.welcomePageDisabled =
  9743. $("#disable_welcome").is(":checked");
  9744. });
  9745. }
  9746. module.exports = setupWelcomePage;
  9747. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9748. /* global $, $iq, config, interfaceConfig */
  9749. var params = {};
  9750. function getConfigParamsFromUrl() {
  9751. if(!location.hash)
  9752. return {};
  9753. var hash = location.hash.substr(1);
  9754. var result = {};
  9755. hash.split("&").forEach(function(part) {
  9756. var item = part.split("=");
  9757. result[item[0]] = JSON.parse(
  9758. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9759. });
  9760. return result;
  9761. }
  9762. params = getConfigParamsFromUrl();
  9763. var URLProcessor = {
  9764. setConfigParametersFromUrl: function () {
  9765. for(var key in params) {
  9766. if(typeof key !== "string")
  9767. continue;
  9768. var confObj = null, confKey;
  9769. if (key.indexOf("config.") === 0) {
  9770. confObj = config;
  9771. confKey = key.substr("config.".length);
  9772. } else if (key.indexOf("interfaceConfig.") === 0) {
  9773. confObj = interfaceConfig;
  9774. confKey = key.substr("interfaceConfig.".length);
  9775. }
  9776. if (!confObj)
  9777. continue;
  9778. var value = params[key];
  9779. if (confObj[confKey] && typeof confObj[confKey] !== typeof value)
  9780. {
  9781. console.warn("The type of " + key +
  9782. " is wrong. That parameter won't be updated in config.js.");
  9783. continue;
  9784. }
  9785. confObj[confKey] = value;
  9786. }
  9787. }
  9788. };
  9789. module.exports = URLProcessor;
  9790. },{}],43:[function(require,module,exports){
  9791. /* global APP, require */
  9792. var EventEmitter = require("events");
  9793. var eventEmitter = new EventEmitter();
  9794. var CQEvents = require("../../service/connectionquality/CQEvents");
  9795. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9796. /**
  9797. * local stats
  9798. * @type {{}}
  9799. */
  9800. var stats = {};
  9801. /**
  9802. * remote stats
  9803. * @type {{}}
  9804. */
  9805. var remoteStats = {};
  9806. /**
  9807. * Interval for sending statistics to other participants
  9808. * @type {null}
  9809. */
  9810. var sendIntervalId = null;
  9811. /**
  9812. * Start statistics sending.
  9813. */
  9814. function startSendingStats() {
  9815. sendStats();
  9816. sendIntervalId = setInterval(sendStats, 10000);
  9817. }
  9818. /**
  9819. * Sends statistics to other participants
  9820. */
  9821. function sendStats() {
  9822. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9823. }
  9824. /**
  9825. * Converts statistics to format for sending through XMPP
  9826. * @param stats the statistics
  9827. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9828. */
  9829. function convertToMUCStats(stats) {
  9830. return {
  9831. "bitrate_download": stats.bitrate.download,
  9832. "bitrate_upload": stats.bitrate.upload,
  9833. "packetLoss_total": stats.packetLoss.total,
  9834. "packetLoss_download": stats.packetLoss.download,
  9835. "packetLoss_upload": stats.packetLoss.upload
  9836. };
  9837. }
  9838. /**
  9839. * Converts statistics to format used by VideoLayout
  9840. * @param stats
  9841. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9842. */
  9843. function parseMUCStats(stats) {
  9844. return {
  9845. bitrate: {
  9846. download: stats.bitrate_download,
  9847. upload: stats.bitrate_upload
  9848. },
  9849. packetLoss: {
  9850. total: stats.packetLoss_total,
  9851. download: stats.packetLoss_download,
  9852. upload: stats.packetLoss_upload
  9853. }
  9854. };
  9855. }
  9856. var ConnectionQuality = {
  9857. init: function () {
  9858. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9859. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9860. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9861. },
  9862. /**
  9863. * Updates the local statistics
  9864. * @param data new statistics
  9865. */
  9866. updateLocalStats: function (data) {
  9867. stats = data;
  9868. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9869. if (sendIntervalId == null) {
  9870. startSendingStats();
  9871. }
  9872. },
  9873. /**
  9874. * Updates remote statistics
  9875. * @param jid the jid associated with the statistics
  9876. * @param data the statistics
  9877. */
  9878. updateRemoteStats: function (jid, data) {
  9879. if (data == null || data.packetLoss_total == null) {
  9880. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9881. return;
  9882. }
  9883. remoteStats[jid] = parseMUCStats(data);
  9884. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9885. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9886. },
  9887. /**
  9888. * Stops statistics sending.
  9889. */
  9890. stopSendingStats: function () {
  9891. clearInterval(sendIntervalId);
  9892. sendIntervalId = null;
  9893. //notify UI about stopping statistics gathering
  9894. eventEmitter.emit(CQEvents.STOP);
  9895. },
  9896. /**
  9897. * Returns the local statistics.
  9898. */
  9899. getStats: function () {
  9900. return stats;
  9901. },
  9902. addListener: function (type, listener) {
  9903. eventEmitter.on(type, listener);
  9904. }
  9905. };
  9906. module.exports = ConnectionQuality;
  9907. },{"../../service/connectionquality/CQEvents":157,"../../service/xmpp/XMPPEvents":161,"events":162}],44:[function(require,module,exports){
  9908. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9909. getUserMediaWithConstraints */
  9910. /**
  9911. * Indicates that desktop stream is currently in use(for toggle purpose).
  9912. * @type {boolean}
  9913. */
  9914. var isUsingScreenStream = false;
  9915. /**
  9916. * Indicates that switch stream operation is in progress and prevent from
  9917. * triggering new events.
  9918. * @type {boolean}
  9919. */
  9920. var switchInProgress = false;
  9921. /**
  9922. * Method used to get screen sharing stream.
  9923. *
  9924. * @type {function (stream_callback, failure_callback}
  9925. */
  9926. var obtainDesktopStream = null;
  9927. /**
  9928. * Indicates whether desktop sharing extension is installed.
  9929. * @type {boolean}
  9930. */
  9931. var extInstalled = false;
  9932. /**
  9933. * Indicates whether update of desktop sharing extension is required.
  9934. * @type {boolean}
  9935. */
  9936. var extUpdateRequired = false;
  9937. var AdapterJS = require("../RTC/adapter.screenshare");
  9938. var EventEmitter = require("events");
  9939. var eventEmitter = new EventEmitter();
  9940. var DesktopSharingEventTypes
  9941. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9942. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9943. var RTCEvents = require("../../service/RTC/RTCEvents");
  9944. /**
  9945. * Method obtains desktop stream from WebRTC 'screen' source.
  9946. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9947. */
  9948. function obtainWebRTCScreen(streamCallback, failCallback) {
  9949. APP.RTC.getUserMediaWithConstraints(
  9950. ['screen'],
  9951. streamCallback,
  9952. failCallback
  9953. );
  9954. }
  9955. /**
  9956. * Constructs inline install URL for Chrome desktop streaming extension.
  9957. * The 'chromeExtensionId' must be defined in config.js.
  9958. * @returns {string}
  9959. */
  9960. function getWebStoreInstallUrl()
  9961. {
  9962. return "https://chrome.google.com/webstore/detail/" +
  9963. config.chromeExtensionId;
  9964. }
  9965. /**
  9966. * Checks whether extension update is required.
  9967. * @param minVersion minimal required version
  9968. * @param extVersion current extension version
  9969. * @returns {boolean}
  9970. */
  9971. function isUpdateRequired(minVersion, extVersion)
  9972. {
  9973. try
  9974. {
  9975. var s1 = minVersion.split('.');
  9976. var s2 = extVersion.split('.');
  9977. var len = Math.max(s1.length, s2.length);
  9978. for (var i = 0; i < len; i++)
  9979. {
  9980. var n1 = 0,
  9981. n2 = 0;
  9982. if (i < s1.length)
  9983. n1 = parseInt(s1[i]);
  9984. if (i < s2.length)
  9985. n2 = parseInt(s2[i]);
  9986. if (isNaN(n1) || isNaN(n2))
  9987. {
  9988. return true;
  9989. }
  9990. else if (n1 !== n2)
  9991. {
  9992. return n1 > n2;
  9993. }
  9994. }
  9995. // will happen if boths version has identical numbers in
  9996. // their components (even if one of them is longer, has more components)
  9997. return false;
  9998. }
  9999. catch (e)
  10000. {
  10001. console.error("Failed to parse extension version", e);
  10002. APP.UI.messageHandler.showError("dialog.error",
  10003. "dialog.detectext");
  10004. return true;
  10005. }
  10006. }
  10007. function checkChromeExtInstalled(callback) {
  10008. if (!chrome.runtime) {
  10009. // No API, so no extension for sure
  10010. callback(false, false);
  10011. return;
  10012. }
  10013. chrome.runtime.sendMessage(
  10014. config.chromeExtensionId,
  10015. { getVersion: true },
  10016. function (response) {
  10017. if (!response || !response.version) {
  10018. // Communication failure - assume that no endpoint exists
  10019. console.warn(
  10020. "Extension not installed?: ", chrome.runtime.lastError);
  10021. callback(false, false);
  10022. return;
  10023. }
  10024. // Check installed extension version
  10025. var extVersion = response.version;
  10026. console.log('Extension version is: ' + extVersion);
  10027. var updateRequired
  10028. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  10029. callback(!updateRequired, updateRequired);
  10030. }
  10031. );
  10032. }
  10033. function doGetStreamFromExtension(streamCallback, failCallback) {
  10034. // Sends 'getStream' msg to the extension.
  10035. // Extension id must be defined in the config.
  10036. chrome.runtime.sendMessage(
  10037. config.chromeExtensionId,
  10038. { getStream: true, sources: config.desktopSharingSources },
  10039. function (response) {
  10040. if (!response) {
  10041. failCallback(chrome.runtime.lastError);
  10042. return;
  10043. }
  10044. console.log("Response from extension: " + response);
  10045. if (response.streamId) {
  10046. APP.RTC.getUserMediaWithConstraints(
  10047. ['desktop'],
  10048. function (stream) {
  10049. streamCallback(stream);
  10050. },
  10051. failCallback,
  10052. null, null, null,
  10053. response.streamId);
  10054. } else {
  10055. failCallback("Extension failed to get the stream");
  10056. }
  10057. }
  10058. );
  10059. }
  10060. /**
  10061. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10062. * stream for returned stream token.
  10063. */
  10064. function obtainScreenFromExtension(streamCallback, failCallback) {
  10065. if (extInstalled) {
  10066. doGetStreamFromExtension(streamCallback, failCallback);
  10067. } else {
  10068. if (extUpdateRequired) {
  10069. alert(
  10070. 'Jitsi Desktop Streamer requires update. ' +
  10071. 'Changes will take effect after next Chrome restart.');
  10072. }
  10073. chrome.webstore.install(
  10074. getWebStoreInstallUrl(),
  10075. function (arg) {
  10076. console.log("Extension installed successfully", arg);
  10077. extInstalled = true;
  10078. // We need to give a moment for the endpoint to become available
  10079. window.setTimeout(function () {
  10080. doGetStreamFromExtension(streamCallback, failCallback);
  10081. }, 500);
  10082. },
  10083. function (arg) {
  10084. console.log("Failed to install the extension", arg);
  10085. failCallback(arg);
  10086. APP.UI.messageHandler.showError("dialog.error",
  10087. "dialog.failtoinstall");
  10088. }
  10089. );
  10090. }
  10091. }
  10092. /**
  10093. * Call this method to toggle desktop sharing feature.
  10094. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10095. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10096. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10097. * enabled), pass any other string or nothing in order to disable this
  10098. * feature completely.
  10099. */
  10100. function setDesktopSharing(method) {
  10101. obtainDesktopStream = null;
  10102. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10103. // care about 'method' parameter
  10104. if (RTCBrowserType.isTemasysPluginUsed()) {
  10105. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10106. console.info("Screensharing not supported by this plugin version");
  10107. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10108. console.info(
  10109. "Screensharing not available with Temasys plugin on this site");
  10110. } else {
  10111. obtainDesktopStream = obtainWebRTCScreen;
  10112. console.info("Using Temasys plugin for desktop sharing");
  10113. }
  10114. } else if (RTCBrowserType.isChrome()) {
  10115. if (method == "ext") {
  10116. if (RTCBrowserType.getChromeVersion() >= 34) {
  10117. obtainDesktopStream = obtainScreenFromExtension;
  10118. console.info("Using Chrome extension for desktop sharing");
  10119. initChromeExtension();
  10120. } else {
  10121. console.info("Chrome extension not supported until ver 34");
  10122. }
  10123. } else if (method == "webrtc") {
  10124. obtainDesktopStream = obtainWebRTCScreen;
  10125. console.info("Using Chrome WebRTC for desktop sharing");
  10126. }
  10127. }
  10128. if (!obtainDesktopStream) {
  10129. console.info("Desktop sharing disabled");
  10130. }
  10131. }
  10132. /**
  10133. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10134. * config.js to support inline installs. Host site must be selected as main
  10135. * website of published extension.
  10136. */
  10137. function initInlineInstalls()
  10138. {
  10139. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10140. }
  10141. function initChromeExtension() {
  10142. // Initialize Chrome extension inline installs
  10143. initInlineInstalls();
  10144. // Check if extension is installed
  10145. checkChromeExtInstalled(function (installed, updateRequired) {
  10146. extInstalled = installed;
  10147. extUpdateRequired = updateRequired;
  10148. console.info(
  10149. "Chrome extension installed: " + extInstalled +
  10150. " updateRequired: " + extUpdateRequired);
  10151. });
  10152. }
  10153. function getVideoStreamFailed(error) {
  10154. console.error("Failed to obtain the stream to switch to", error);
  10155. switchInProgress = false;
  10156. isUsingScreenStream = false;
  10157. newStreamCreated(null);
  10158. }
  10159. function getDesktopStreamFailed(error) {
  10160. console.error("Failed to obtain the stream to switch to", error);
  10161. switchInProgress = false;
  10162. }
  10163. function streamSwitchDone() {
  10164. switchInProgress = false;
  10165. eventEmitter.emit(
  10166. DesktopSharingEventTypes.SWITCHING_DONE,
  10167. isUsingScreenStream);
  10168. }
  10169. function newStreamCreated(stream)
  10170. {
  10171. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10172. stream, isUsingScreenStream, streamSwitchDone);
  10173. }
  10174. function onEndedHandler(stream) {
  10175. if (!switchInProgress && isUsingScreenStream) {
  10176. APP.desktopsharing.toggleScreenSharing();
  10177. }
  10178. //FIXME: to be verified
  10179. if (stream.removeEventListener) {
  10180. stream.removeEventListener('ended', onEndedHandler);
  10181. } else {
  10182. stream.detachEvent('ended', onEndedHandler);
  10183. }
  10184. }
  10185. // Called when RTC finishes initialization
  10186. function onWebRtcReady() {
  10187. setDesktopSharing(config.desktopSharing);
  10188. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10189. }
  10190. module.exports = {
  10191. isUsingScreenStream: function () {
  10192. return isUsingScreenStream;
  10193. },
  10194. /**
  10195. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10196. * and enabled.
  10197. */
  10198. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10199. init: function () {
  10200. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10201. },
  10202. addListener: function (listener, type)
  10203. {
  10204. eventEmitter.on(type, listener);
  10205. },
  10206. removeListener: function (listener, type) {
  10207. eventEmitter.removeListener(type, listener);
  10208. },
  10209. /*
  10210. * Toggles screen sharing.
  10211. */
  10212. toggleScreenSharing: function () {
  10213. if (switchInProgress || !obtainDesktopStream) {
  10214. console.warn("Switch in progress or no method defined");
  10215. return;
  10216. }
  10217. switchInProgress = true;
  10218. if (!isUsingScreenStream)
  10219. {
  10220. // Switch to desktop stream
  10221. obtainDesktopStream(
  10222. function (stream) {
  10223. // We now use screen stream
  10224. isUsingScreenStream = true;
  10225. // Hook 'ended' event to restore camera
  10226. // when screen stream stops
  10227. //FIXME: to be verified
  10228. if (stream.addEventListener) {
  10229. stream.addEventListener('ended', function () {
  10230. onEndedHandler(stream);
  10231. });
  10232. } else {
  10233. stream.attachEvent('ended', function () {
  10234. onEndedHandler(stream);
  10235. });
  10236. }
  10237. newStreamCreated(stream);
  10238. },
  10239. getDesktopStreamFailed);
  10240. } else {
  10241. // Disable screen stream
  10242. APP.RTC.getUserMediaWithConstraints(
  10243. ['video'],
  10244. function (stream) {
  10245. // We are now using camera stream
  10246. isUsingScreenStream = false;
  10247. newStreamCreated(stream);
  10248. },
  10249. getVideoStreamFailed, config.resolution || '360'
  10250. );
  10251. }
  10252. }
  10253. };
  10254. },{"../../service/RTC/RTCEvents":152,"../../service/desktopsharing/DesktopSharingEventTypes":158,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":162}],45:[function(require,module,exports){
  10255. /* global APP, $ */
  10256. //maps keycode to character, id of popover for given function and function
  10257. var shortcuts = {};
  10258. function initShortcutHandlers() {
  10259. shortcuts = {
  10260. 67: {
  10261. character: "C",
  10262. id: "toggleChatPopover",
  10263. function: APP.UI.toggleChat
  10264. },
  10265. 70: {
  10266. character: "F",
  10267. id: "filmstripPopover",
  10268. function: APP.UI.toggleFilmStrip
  10269. },
  10270. 77: {
  10271. character: "M",
  10272. id: "mutePopover",
  10273. function: APP.UI.toggleAudio
  10274. },
  10275. 84: {
  10276. character: "T",
  10277. function: function() {
  10278. if(!APP.RTC.localAudio.isMuted()) {
  10279. APP.UI.toggleAudio();
  10280. }
  10281. }
  10282. },
  10283. 86: {
  10284. character: "V",
  10285. id: "toggleVideoPopover",
  10286. function: APP.UI.toggleVideo
  10287. }
  10288. };
  10289. }
  10290. var KeyboardShortcut = {
  10291. init: function () {
  10292. initShortcutHandlers();
  10293. window.onkeyup = function(e) {
  10294. var keycode = e.which;
  10295. if(!($(":focus").is("input[type=text]") ||
  10296. $(":focus").is("input[type=password]") ||
  10297. $(":focus").is("textarea"))) {
  10298. if (typeof shortcuts[keycode] === "object") {
  10299. shortcuts[keycode].function();
  10300. }
  10301. else if (keycode >= "0".charCodeAt(0) &&
  10302. keycode <= "9".charCodeAt(0)) {
  10303. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10304. }
  10305. //esc while the smileys are visible hides them
  10306. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10307. APP.UI.toggleSmileys();
  10308. }
  10309. };
  10310. window.onkeydown = function(e) {
  10311. if(!($(":focus").is("input[type=text]") ||
  10312. $(":focus").is("input[type=password]") ||
  10313. $(":focus").is("textarea"))) {
  10314. if(e.which === "T".charCodeAt(0)) {
  10315. if(APP.RTC.localAudio.isMuted()) {
  10316. APP.UI.toggleAudio();
  10317. }
  10318. }
  10319. }
  10320. };
  10321. var self = this;
  10322. $('body').popover({ selector: '[data-toggle=popover]',
  10323. trigger: 'click hover',
  10324. content: function() {
  10325. return this.getAttribute("content") +
  10326. self.getShortcut(this.getAttribute("shortcut"));
  10327. }
  10328. });
  10329. },
  10330. /**
  10331. *
  10332. * @param id indicates the popover associated with the shortcut
  10333. * @returns {string} the keyboard shortcut used for the id given
  10334. */
  10335. getShortcut: function (id) {
  10336. for (var keycode in shortcuts) {
  10337. if (shortcuts.hasOwnProperty(keycode)) {
  10338. if (shortcuts[keycode].id === id) {
  10339. return " (" + shortcuts[keycode].character + ")";
  10340. }
  10341. }
  10342. }
  10343. return "";
  10344. }
  10345. };
  10346. module.exports = KeyboardShortcut;
  10347. },{}],46:[function(require,module,exports){
  10348. /* global APP, require, $ */
  10349. /**
  10350. * This module is meant to (eventually) contain and manage all information
  10351. * about members/participants of the conference, so that other modules don't
  10352. * have to do it on their own, and so that other modules can access members'
  10353. * information from a single place.
  10354. *
  10355. * Currently this module only manages information about the support of jingle
  10356. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10357. * be added as needed.
  10358. */
  10359. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10360. var Events = require("../../service/members/Events");
  10361. var EventEmitter = require("events");
  10362. var eventEmitter = new EventEmitter();
  10363. /**
  10364. * The actual container.
  10365. */
  10366. var members = {};
  10367. /**
  10368. * There is at least one member that supports DTMF (i.e. is jigasi).
  10369. */
  10370. var atLeastOneDtmf = false;
  10371. function registerListeners() {
  10372. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10373. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10374. }
  10375. /**
  10376. * Handles a new member joining the MUC.
  10377. */
  10378. function onMucMemberJoined(jid, id, displayName) {
  10379. var member = {
  10380. displayName: displayName
  10381. };
  10382. APP.xmpp.getConnection().disco.info(
  10383. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10384. members[jid] = member;
  10385. }
  10386. /**
  10387. * Handles a member leaving the MUC.
  10388. */
  10389. function onMucMemberLeft(jid) {
  10390. delete members[jid];
  10391. updateAtLeastOneDtmf();
  10392. }
  10393. /**
  10394. * Handles the reception of a disco#info packet from a particular JID.
  10395. * @param jid the JID sending the packet.
  10396. * @param iq the packet.
  10397. */
  10398. function onDiscoInfoReceived(jid, iq) {
  10399. if (!members[jid])
  10400. return;
  10401. var supportsDtmf
  10402. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10403. updateDtmf(jid, supportsDtmf);
  10404. }
  10405. /**
  10406. * Updates the 'supportsDtmf' field for a member.
  10407. * @param jid the jid of the member.
  10408. * @param newValue the new value for the 'supportsDtmf' field.
  10409. */
  10410. function updateDtmf(jid, newValue) {
  10411. var oldValue = members[jid].supportsDtmf;
  10412. members[jid].supportsDtmf = newValue;
  10413. if (newValue != oldValue) {
  10414. updateAtLeastOneDtmf();
  10415. }
  10416. }
  10417. /**
  10418. * Checks each member's 'supportsDtmf' field and updates
  10419. * 'atLastOneSupportsDtmf'.
  10420. */
  10421. function updateAtLeastOneDtmf() {
  10422. var newAtLeastOneDtmf = false;
  10423. for (var key in members) {
  10424. if (typeof members[key].supportsDtmf !== 'undefined'
  10425. && members[key].supportsDtmf) {
  10426. newAtLeastOneDtmf= true;
  10427. break;
  10428. }
  10429. }
  10430. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10431. atLeastOneDtmf = newAtLeastOneDtmf;
  10432. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10433. }
  10434. }
  10435. /**
  10436. * Exported interface.
  10437. */
  10438. var Members = {
  10439. start: function() {
  10440. registerListeners();
  10441. },
  10442. addListener: function(type, listener) {
  10443. eventEmitter.on(type, listener);
  10444. },
  10445. removeListener: function (type, listener) {
  10446. eventEmitter.removeListener(type, listener);
  10447. },
  10448. size: function () {
  10449. return Object.keys(members).length;
  10450. },
  10451. getMembers: function () {
  10452. return members;
  10453. }
  10454. };
  10455. module.exports = Members;
  10456. },{"../../service/members/Events":159,"../../service/xmpp/XMPPEvents":161,"events":162}],47:[function(require,module,exports){
  10457. var email = '';
  10458. var displayName = '';
  10459. var userId;
  10460. var language = null;
  10461. function supportsLocalStorage() {
  10462. try {
  10463. return 'localStorage' in window && window.localStorage !== null;
  10464. } catch (e) {
  10465. console.log("localstorage is not supported");
  10466. return false;
  10467. }
  10468. }
  10469. function generateUniqueId() {
  10470. function _p8() {
  10471. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10472. }
  10473. return _p8() + _p8() + _p8() + _p8();
  10474. }
  10475. if (supportsLocalStorage()) {
  10476. if (!window.localStorage.jitsiMeetId) {
  10477. window.localStorage.jitsiMeetId = generateUniqueId();
  10478. console.log("generated id", window.localStorage.jitsiMeetId);
  10479. }
  10480. userId = window.localStorage.jitsiMeetId || '';
  10481. email = window.localStorage.email || '';
  10482. displayName = window.localStorage.displayname || '';
  10483. language = window.localStorage.language;
  10484. } else {
  10485. console.log("local storage is not supported");
  10486. userId = generateUniqueId();
  10487. }
  10488. var Settings = {
  10489. setDisplayName: function (newDisplayName) {
  10490. displayName = newDisplayName;
  10491. window.localStorage.displayname = displayName;
  10492. return displayName;
  10493. },
  10494. setEmail: function (newEmail) {
  10495. email = newEmail;
  10496. window.localStorage.email = newEmail;
  10497. return email;
  10498. },
  10499. getSettings: function () {
  10500. return {
  10501. email: email,
  10502. displayName: displayName,
  10503. uid: userId,
  10504. language: language
  10505. };
  10506. },
  10507. setLanguage: function (lang) {
  10508. language = lang;
  10509. window.localStorage.language = lang;
  10510. }
  10511. };
  10512. module.exports = Settings;
  10513. },{}],48:[function(require,module,exports){
  10514. /* global config, $, APP, Strophe, callstats */
  10515. var jsSHA = require('jssha');
  10516. var io = require('socket.io-client');
  10517. var callStats = null;
  10518. function initCallback (err, msg) {
  10519. console.log("Initializing Status: err="+err+" msg="+msg);
  10520. }
  10521. var CallStats = {
  10522. init: function (jingleSession) {
  10523. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10524. return;
  10525. callStats = new callstats($, io, jsSHA);
  10526. this.session = jingleSession;
  10527. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10528. this.userID = APP.xmpp.myResource();
  10529. var location = window.location;
  10530. this.confID = location.protocol + "//" +
  10531. location.hostname + location.pathname;
  10532. //userID is generated or given by the origin server
  10533. callStats.initialize(config.callStatsID,
  10534. config.callStatsSecret,
  10535. this.userID,
  10536. initCallback);
  10537. var usage = callStats.fabricUsage.multiplex;
  10538. callStats.addNewFabric(this.peerconnection,
  10539. Strophe.getResourceFromJid(jingleSession.peerjid),
  10540. usage,
  10541. this.confID,
  10542. this.pcCallback.bind(this));
  10543. },
  10544. pcCallback: function (err, msg) {
  10545. if (!callStats)
  10546. return;
  10547. console.log("Monitoring status: "+ err + " msg: " + msg);
  10548. callStats.sendFabricEvent(this.peerconnection,
  10549. callStats.fabricEvent.fabricSetup, this.confID);
  10550. },
  10551. sendMuteEvent: function (mute, type) {
  10552. if (!callStats)
  10553. return;
  10554. var event = null;
  10555. if (type === "video") {
  10556. event = (mute? callStats.fabricEvent.videoPause :
  10557. callStats.fabricEvent.videoResume);
  10558. }
  10559. else {
  10560. event = (mute? callStats.fabricEvent.audioMute :
  10561. callStats.fabricEvent.audioUnmute);
  10562. }
  10563. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10564. },
  10565. sendTerminateEvent: function () {
  10566. if(!callStats) {
  10567. return;
  10568. }
  10569. callStats.sendFabricEvent(this.peerconnection,
  10570. callStats.fabricEvent.fabricTerminated, this.confID);
  10571. },
  10572. sendSetupFailedEvent: function () {
  10573. if(!callStats) {
  10574. return;
  10575. }
  10576. callStats.sendFabricEvent(this.peerconnection,
  10577. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10578. }
  10579. };
  10580. module.exports = CallStats;
  10581. },{"jssha":71,"socket.io-client":101}],49:[function(require,module,exports){
  10582. /* global config */
  10583. /**
  10584. * Provides statistics for the local stream.
  10585. */
  10586. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10587. /**
  10588. * Size of the webaudio analyzer buffer.
  10589. * @type {number}
  10590. */
  10591. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10592. /**
  10593. * Value of the webaudio analyzer smoothing time parameter.
  10594. * @type {number}
  10595. */
  10596. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10597. /**
  10598. * Converts time domain data array to audio level.
  10599. * @param samples the time domain data array.
  10600. * @returns {number} the audio level
  10601. */
  10602. function timeDomainDataToAudioLevel(samples) {
  10603. var maxVolume = 0;
  10604. var length = samples.length;
  10605. for (var i = 0; i < length; i++) {
  10606. if (maxVolume < samples[i])
  10607. maxVolume = samples[i];
  10608. }
  10609. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10610. }
  10611. /**
  10612. * Animates audio level change
  10613. * @param newLevel the new audio level
  10614. * @param lastLevel the last audio level
  10615. * @returns {Number} the audio level to be set
  10616. */
  10617. function animateLevel(newLevel, lastLevel) {
  10618. var value = 0;
  10619. var diff = lastLevel - newLevel;
  10620. if(diff > 0.2) {
  10621. value = lastLevel - 0.2;
  10622. }
  10623. else if(diff < -0.4) {
  10624. value = lastLevel + 0.4;
  10625. }
  10626. else {
  10627. value = newLevel;
  10628. }
  10629. return parseFloat(value.toFixed(3));
  10630. }
  10631. /**
  10632. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10633. *
  10634. * @param stream the local stream
  10635. * @param interval stats refresh interval given in ms.
  10636. * @constructor
  10637. */
  10638. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10639. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10640. this.stream = stream;
  10641. this.intervalId = null;
  10642. this.intervalMilis = interval;
  10643. this.eventEmitter = eventEmitter;
  10644. this.audioLevel = 0;
  10645. this.statisticsService = statisticsService;
  10646. }
  10647. /**
  10648. * Starts the collecting the statistics.
  10649. */
  10650. LocalStatsCollector.prototype.start = function () {
  10651. if (config.disableAudioLevels || !window.AudioContext ||
  10652. RTCBrowserType.isTemasysPluginUsed())
  10653. return;
  10654. var context = new AudioContext();
  10655. var analyser = context.createAnalyser();
  10656. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10657. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10658. var source = context.createMediaStreamSource(this.stream);
  10659. source.connect(analyser);
  10660. var self = this;
  10661. this.intervalId = setInterval(
  10662. function () {
  10663. var array = new Uint8Array(analyser.frequencyBinCount);
  10664. analyser.getByteTimeDomainData(array);
  10665. var audioLevel = timeDomainDataToAudioLevel(array);
  10666. if (audioLevel != self.audioLevel) {
  10667. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10668. self.eventEmitter.emit(
  10669. "statistics.audioLevel",
  10670. self.statisticsService.LOCAL_JID,
  10671. self.audioLevel);
  10672. }
  10673. },
  10674. this.intervalMilis
  10675. );
  10676. };
  10677. /**
  10678. * Stops collecting the statistics.
  10679. */
  10680. LocalStatsCollector.prototype.stop = function () {
  10681. if (this.intervalId) {
  10682. clearInterval(this.intervalId);
  10683. this.intervalId = null;
  10684. }
  10685. };
  10686. module.exports = LocalStatsCollector;
  10687. },{"../RTC/RTCBrowserType":8}],50:[function(require,module,exports){
  10688. /* global require, ssrc2jid */
  10689. /* jshint -W117 */
  10690. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10691. /* Whether we support the browser we are running into for logging statistics */
  10692. var browserSupported = RTCBrowserType.isChrome() ||
  10693. RTCBrowserType.isOpera();
  10694. /**
  10695. * Calculates packet lost percent using the number of lost packets and the
  10696. * number of all packet.
  10697. * @param lostPackets the number of lost packets
  10698. * @param totalPackets the number of all packets.
  10699. * @returns {number} packet loss percent
  10700. */
  10701. function calculatePacketLoss(lostPackets, totalPackets) {
  10702. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10703. return 0;
  10704. return Math.round((lostPackets/totalPackets)*100);
  10705. }
  10706. function getStatValue(item, name) {
  10707. var browserType = RTCBrowserType.getBrowserType();
  10708. if (!keyMap[browserType][name])
  10709. throw "The property isn't supported!";
  10710. var key = keyMap[browserType][name];
  10711. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10712. item.stat(key) : item[key];
  10713. }
  10714. /**
  10715. * Peer statistics data holder.
  10716. * @constructor
  10717. */
  10718. function PeerStats()
  10719. {
  10720. this.ssrc2Loss = {};
  10721. this.ssrc2AudioLevel = {};
  10722. this.ssrc2bitrate = {};
  10723. this.ssrc2resolution = {};
  10724. }
  10725. /**
  10726. * The bandwidth
  10727. * @type {{}}
  10728. */
  10729. PeerStats.bandwidth = {};
  10730. /**
  10731. * The bit rate
  10732. * @type {{}}
  10733. */
  10734. PeerStats.bitrate = {};
  10735. /**
  10736. * The packet loss rate
  10737. * @type {{}}
  10738. */
  10739. PeerStats.packetLoss = null;
  10740. /**
  10741. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10742. * represented by this instance.
  10743. * @param ssrc audio or video RTP stream SSRC.
  10744. * @param lossRate new packet loss rate value to be set.
  10745. */
  10746. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10747. {
  10748. this.ssrc2Loss[ssrc] = lossRate;
  10749. };
  10750. /**
  10751. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10752. * represented by this instance.
  10753. * @param ssrc audio or video RTP stream SSRC.
  10754. * @param resolution new resolution value to be set.
  10755. */
  10756. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10757. {
  10758. if(resolution === null && this.ssrc2resolution[ssrc])
  10759. {
  10760. delete this.ssrc2resolution[ssrc];
  10761. }
  10762. else if(resolution !== null)
  10763. this.ssrc2resolution[ssrc] = resolution;
  10764. };
  10765. /**
  10766. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10767. * represented by this instance.
  10768. * @param ssrc audio or video RTP stream SSRC.
  10769. * @param bitrate new bitrate value to be set.
  10770. */
  10771. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10772. {
  10773. if(this.ssrc2bitrate[ssrc])
  10774. {
  10775. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10776. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10777. }
  10778. else {
  10779. this.ssrc2bitrate[ssrc] = bitrate;
  10780. }
  10781. };
  10782. /**
  10783. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10784. * the stream which belongs to the peer represented by this instance.
  10785. * @param ssrc RTP stream SSRC for which current audio level value will be
  10786. * updated.
  10787. * @param audioLevel the new audio level value to be set. Value is truncated to
  10788. * fit the range from 0 to 1.
  10789. */
  10790. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10791. {
  10792. // Range limit 0 - 1
  10793. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10794. };
  10795. function formatAudioLevel(audioLevel) {
  10796. return Math.min(Math.max(audioLevel, 0), 1);
  10797. }
  10798. /**
  10799. * Array with the transport information.
  10800. * @type {Array}
  10801. */
  10802. PeerStats.transport = [];
  10803. /**
  10804. * <tt>StatsCollector</tt> registers for stats updates of given
  10805. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10806. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10807. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10808. * instance as an event source.
  10809. *
  10810. * @param peerconnection webRTC peer connection object.
  10811. * @param interval stats refresh interval given in ms.
  10812. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10813. * called on stats update.
  10814. * @constructor
  10815. */
  10816. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10817. {
  10818. this.peerconnection = peerconnection;
  10819. this.baselineAudioLevelsReport = null;
  10820. this.currentAudioLevelsReport = null;
  10821. this.currentStatsReport = null;
  10822. this.baselineStatsReport = null;
  10823. this.audioLevelsIntervalId = null;
  10824. this.eventEmitter = eventEmitter;
  10825. /**
  10826. * Gather PeerConnection stats once every this many milliseconds.
  10827. */
  10828. this.GATHER_INTERVAL = 15000;
  10829. /**
  10830. * Log stats via the focus once every this many milliseconds.
  10831. */
  10832. this.LOG_INTERVAL = 60000;
  10833. /**
  10834. * Gather stats and store them in this.statsToBeLogged.
  10835. */
  10836. this.gatherStatsIntervalId = null;
  10837. /**
  10838. * Send the stats already saved in this.statsToBeLogged to be logged via
  10839. * the focus.
  10840. */
  10841. this.logStatsIntervalId = null;
  10842. /**
  10843. * Stores the statistics which will be send to the focus to be logged.
  10844. */
  10845. this.statsToBeLogged =
  10846. {
  10847. timestamps: [],
  10848. stats: {}
  10849. };
  10850. // Updates stats interval
  10851. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10852. this.statsIntervalId = null;
  10853. this.statsIntervalMilis = statsInterval;
  10854. // Map of jids to PeerStats
  10855. this.jid2stats = {};
  10856. }
  10857. module.exports = StatsCollector;
  10858. /**
  10859. * Stops stats updates.
  10860. */
  10861. StatsCollector.prototype.stop = function () {
  10862. if (this.audioLevelsIntervalId) {
  10863. clearInterval(this.audioLevelsIntervalId);
  10864. this.audioLevelsIntervalId = null;
  10865. }
  10866. if (this.statsIntervalId)
  10867. {
  10868. clearInterval(this.statsIntervalId);
  10869. this.statsIntervalId = null;
  10870. }
  10871. if(this.logStatsIntervalId)
  10872. {
  10873. clearInterval(this.logStatsIntervalId);
  10874. this.logStatsIntervalId = null;
  10875. }
  10876. if(this.gatherStatsIntervalId)
  10877. {
  10878. clearInterval(this.gatherStatsIntervalId);
  10879. this.gatherStatsIntervalId = null;
  10880. }
  10881. };
  10882. /**
  10883. * Callback passed to <tt>getStats</tt> method.
  10884. * @param error an error that occurred on <tt>getStats</tt> call.
  10885. */
  10886. StatsCollector.prototype.errorCallback = function (error)
  10887. {
  10888. console.error("Get stats error", error);
  10889. this.stop();
  10890. };
  10891. /**
  10892. * Starts stats updates.
  10893. */
  10894. StatsCollector.prototype.start = function ()
  10895. {
  10896. var self = this;
  10897. if (!config.disableAudioLevels) {
  10898. this.audioLevelsIntervalId = setInterval(
  10899. function () {
  10900. // Interval updates
  10901. self.peerconnection.getStats(
  10902. function (report) {
  10903. var results = null;
  10904. if (!report || !report.result ||
  10905. typeof report.result != 'function') {
  10906. results = report;
  10907. }
  10908. else {
  10909. results = report.result();
  10910. }
  10911. //console.error("Got interval report", results);
  10912. self.currentAudioLevelsReport = results;
  10913. self.processAudioLevelReport();
  10914. self.baselineAudioLevelsReport =
  10915. self.currentAudioLevelsReport;
  10916. },
  10917. self.errorCallback
  10918. );
  10919. },
  10920. self.audioLevelsIntervalMilis
  10921. );
  10922. }
  10923. if (!config.disableStats && browserSupported) {
  10924. this.statsIntervalId = setInterval(
  10925. function () {
  10926. // Interval updates
  10927. self.peerconnection.getStats(
  10928. function (report) {
  10929. var results = null;
  10930. if (!report || !report.result ||
  10931. typeof report.result != 'function') {
  10932. //firefox
  10933. results = report;
  10934. }
  10935. else {
  10936. //chrome
  10937. results = report.result();
  10938. }
  10939. //console.error("Got interval report", results);
  10940. self.currentStatsReport = results;
  10941. try {
  10942. self.processStatsReport();
  10943. }
  10944. catch (e) {
  10945. console.error("Unsupported key:" + e, e);
  10946. }
  10947. self.baselineStatsReport = self.currentStatsReport;
  10948. },
  10949. self.errorCallback
  10950. );
  10951. },
  10952. self.statsIntervalMilis
  10953. );
  10954. }
  10955. if (config.logStats && browserSupported) {
  10956. this.gatherStatsIntervalId = setInterval(
  10957. function () {
  10958. self.peerconnection.getStats(
  10959. function (report) {
  10960. self.addStatsToBeLogged(report.result());
  10961. },
  10962. function () {
  10963. }
  10964. );
  10965. },
  10966. this.GATHER_INTERVAL
  10967. );
  10968. this.logStatsIntervalId = setInterval(
  10969. function() { self.logStats(); },
  10970. this.LOG_INTERVAL);
  10971. }
  10972. };
  10973. /**
  10974. * Checks whether a certain record should be included in the logged statistics.
  10975. */
  10976. function acceptStat(reportId, reportType, statName) {
  10977. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10978. return false;
  10979. if (reportType == "ssrc") {
  10980. if (statName == "googTrackId" ||
  10981. statName == "transportId" ||
  10982. statName == "ssrc")
  10983. return false;
  10984. }
  10985. return true;
  10986. }
  10987. /**
  10988. * Checks whether a certain record should be included in the logged statistics.
  10989. */
  10990. function acceptReport(id, type) {
  10991. if (id.substring(0, 15) == "googCertificate" ||
  10992. id.substring(0, 9) == "googTrack" ||
  10993. id.substring(0, 20) == "googLibjingleSession")
  10994. return false;
  10995. if (type == "googComponent")
  10996. return false;
  10997. return true;
  10998. }
  10999. /**
  11000. * Converts the stats to the format used for logging, and saves the data in
  11001. * this.statsToBeLogged.
  11002. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  11003. */
  11004. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  11005. var self = this;
  11006. var num_records = this.statsToBeLogged.timestamps.length;
  11007. this.statsToBeLogged.timestamps.push(new Date().getTime());
  11008. reports.map(function (report) {
  11009. if (!acceptReport(report.id, report.type))
  11010. return;
  11011. var stat = self.statsToBeLogged.stats[report.id];
  11012. if (!stat) {
  11013. stat = self.statsToBeLogged.stats[report.id] = {};
  11014. }
  11015. stat.type = report.type;
  11016. report.names().map(function (name) {
  11017. if (!acceptStat(report.id, report.type, name))
  11018. return;
  11019. var values = stat[name];
  11020. if (!values) {
  11021. values = stat[name] = [];
  11022. }
  11023. while (values.length < num_records) {
  11024. values.push(null);
  11025. }
  11026. values.push(report.stat(name));
  11027. });
  11028. });
  11029. };
  11030. StatsCollector.prototype.logStats = function () {
  11031. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  11032. return;
  11033. // Reset the stats
  11034. this.statsToBeLogged.stats = {};
  11035. this.statsToBeLogged.timestamps = [];
  11036. };
  11037. var keyMap = {};
  11038. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11039. "ssrc": "ssrc",
  11040. "packetsReceived": "packetsReceived",
  11041. "packetsLost": "packetsLost",
  11042. "packetsSent": "packetsSent",
  11043. "bytesReceived": "bytesReceived",
  11044. "bytesSent": "bytesSent"
  11045. };
  11046. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11047. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11048. "sendBandwidth": "googAvailableSendBandwidth",
  11049. "remoteAddress": "googRemoteAddress",
  11050. "transportType": "googTransportType",
  11051. "localAddress": "googLocalAddress",
  11052. "activeConnection": "googActiveConnection",
  11053. "ssrc": "ssrc",
  11054. "packetsReceived": "packetsReceived",
  11055. "packetsSent": "packetsSent",
  11056. "packetsLost": "packetsLost",
  11057. "bytesReceived": "bytesReceived",
  11058. "bytesSent": "bytesSent",
  11059. "googFrameHeightReceived": "googFrameHeightReceived",
  11060. "googFrameWidthReceived": "googFrameWidthReceived",
  11061. "googFrameHeightSent": "googFrameHeightSent",
  11062. "googFrameWidthSent": "googFrameWidthSent",
  11063. "audioInputLevel": "audioInputLevel",
  11064. "audioOutputLevel": "audioOutputLevel"
  11065. };
  11066. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11067. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11068. /**
  11069. * Stats processing logic.
  11070. */
  11071. StatsCollector.prototype.processStatsReport = function () {
  11072. if (!this.baselineStatsReport) {
  11073. return;
  11074. }
  11075. for (var idx in this.currentStatsReport) {
  11076. var now = this.currentStatsReport[idx];
  11077. try {
  11078. if (getStatValue(now, 'receiveBandwidth') ||
  11079. getStatValue(now, 'sendBandwidth')) {
  11080. PeerStats.bandwidth = {
  11081. "download": Math.round(
  11082. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11083. "upload": Math.round(
  11084. (getStatValue(now, 'sendBandwidth')) / 1000)
  11085. };
  11086. }
  11087. }
  11088. catch(e){/*not supported*/}
  11089. if(now.type == 'googCandidatePair')
  11090. {
  11091. var ip, type, localIP, active;
  11092. try {
  11093. ip = getStatValue(now, 'remoteAddress');
  11094. type = getStatValue(now, "transportType");
  11095. localIP = getStatValue(now, "localAddress");
  11096. active = getStatValue(now, "activeConnection");
  11097. }
  11098. catch(e){/*not supported*/}
  11099. if(!ip || !type || !localIP || active != "true")
  11100. continue;
  11101. var addressSaved = false;
  11102. for(var i = 0; i < PeerStats.transport.length; i++)
  11103. {
  11104. if(PeerStats.transport[i].ip == ip &&
  11105. PeerStats.transport[i].type == type &&
  11106. PeerStats.transport[i].localip == localIP)
  11107. {
  11108. addressSaved = true;
  11109. }
  11110. }
  11111. if(addressSaved)
  11112. continue;
  11113. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11114. continue;
  11115. }
  11116. if(now.type == "candidatepair")
  11117. {
  11118. if(now.state == "succeeded")
  11119. continue;
  11120. var local = this.currentStatsReport[now.localCandidateId];
  11121. var remote = this.currentStatsReport[now.remoteCandidateId];
  11122. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11123. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11124. }
  11125. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11126. now.type != "inboundrtp") {
  11127. continue;
  11128. }
  11129. var before = this.baselineStatsReport[idx];
  11130. if (!before) {
  11131. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11132. continue;
  11133. }
  11134. var ssrc = getStatValue(now, 'ssrc');
  11135. if(!ssrc)
  11136. continue;
  11137. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11138. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11139. console.warn("No jid for ssrc: " + ssrc);
  11140. continue;
  11141. }
  11142. var jidStats = this.jid2stats[jid];
  11143. if (!jidStats) {
  11144. jidStats = new PeerStats();
  11145. this.jid2stats[jid] = jidStats;
  11146. }
  11147. var isDownloadStream = true;
  11148. var key = 'packetsReceived';
  11149. if (!getStatValue(now, key))
  11150. {
  11151. isDownloadStream = false;
  11152. key = 'packetsSent';
  11153. if (!getStatValue(now, key))
  11154. {
  11155. console.warn("No packetsReceived nor packetSent stat found");
  11156. continue;
  11157. }
  11158. }
  11159. var packetsNow = getStatValue(now, key);
  11160. if(!packetsNow || packetsNow < 0)
  11161. packetsNow = 0;
  11162. var packetsBefore = getStatValue(before, key);
  11163. if(!packetsBefore || packetsBefore < 0)
  11164. packetsBefore = 0;
  11165. var packetRate = packetsNow - packetsBefore;
  11166. if(!packetRate || packetRate < 0)
  11167. packetRate = 0;
  11168. var currentLoss = getStatValue(now, 'packetsLost');
  11169. if(!currentLoss || currentLoss < 0)
  11170. currentLoss = 0;
  11171. var previousLoss = getStatValue(before, 'packetsLost');
  11172. if(!previousLoss || previousLoss < 0)
  11173. previousLoss = 0;
  11174. var lossRate = currentLoss - previousLoss;
  11175. if(!lossRate || lossRate < 0)
  11176. lossRate = 0;
  11177. var packetsTotal = (packetRate + lossRate);
  11178. jidStats.setSsrcLoss(ssrc,
  11179. {"packetsTotal": packetsTotal,
  11180. "packetsLost": lossRate,
  11181. "isDownloadStream": isDownloadStream});
  11182. var bytesReceived = 0, bytesSent = 0;
  11183. if(getStatValue(now, "bytesReceived"))
  11184. {
  11185. bytesReceived = getStatValue(now, "bytesReceived") -
  11186. getStatValue(before, "bytesReceived");
  11187. }
  11188. if(getStatValue(now, "bytesSent"))
  11189. {
  11190. bytesSent = getStatValue(now, "bytesSent") -
  11191. getStatValue(before, "bytesSent");
  11192. }
  11193. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11194. if(bytesReceived <= 0 || time <= 0)
  11195. {
  11196. bytesReceived = 0;
  11197. }
  11198. else
  11199. {
  11200. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11201. }
  11202. if(bytesSent <= 0 || time <= 0)
  11203. {
  11204. bytesSent = 0;
  11205. }
  11206. else
  11207. {
  11208. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11209. }
  11210. jidStats.setSsrcBitrate(ssrc, {
  11211. "download": bytesReceived,
  11212. "upload": bytesSent});
  11213. var resolution = {height: null, width: null};
  11214. try {
  11215. if (getStatValue(now, "googFrameHeightReceived") &&
  11216. getStatValue(now, "googFrameWidthReceived")) {
  11217. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11218. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11219. }
  11220. else if (getStatValue(now, "googFrameHeightSent") &&
  11221. getStatValue(now, "googFrameWidthSent")) {
  11222. resolution.height = getStatValue(now, "googFrameHeightSent");
  11223. resolution.width = getStatValue(now, "googFrameWidthSent");
  11224. }
  11225. }
  11226. catch(e){/*not supported*/}
  11227. if(resolution.height && resolution.width)
  11228. {
  11229. jidStats.setSsrcResolution(ssrc, resolution);
  11230. }
  11231. else
  11232. {
  11233. jidStats.setSsrcResolution(ssrc, null);
  11234. }
  11235. }
  11236. var self = this;
  11237. // Jid stats
  11238. var totalPackets = {download: 0, upload: 0};
  11239. var lostPackets = {download: 0, upload: 0};
  11240. var bitrateDownload = 0;
  11241. var bitrateUpload = 0;
  11242. var resolutions = {};
  11243. Object.keys(this.jid2stats).forEach(
  11244. function (jid)
  11245. {
  11246. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11247. function (ssrc)
  11248. {
  11249. var type = "upload";
  11250. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11251. type = "download";
  11252. totalPackets[type] +=
  11253. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11254. lostPackets[type] +=
  11255. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11256. }
  11257. );
  11258. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11259. function (ssrc) {
  11260. bitrateDownload +=
  11261. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11262. bitrateUpload +=
  11263. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11264. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11265. }
  11266. );
  11267. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11268. }
  11269. );
  11270. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11271. PeerStats.packetLoss = {
  11272. total:
  11273. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11274. totalPackets.download + totalPackets.upload),
  11275. download:
  11276. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11277. upload:
  11278. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11279. };
  11280. this.eventEmitter.emit("statistics.connectionstats",
  11281. {
  11282. "bitrate": PeerStats.bitrate,
  11283. "packetLoss": PeerStats.packetLoss,
  11284. "bandwidth": PeerStats.bandwidth,
  11285. "resolution": resolutions,
  11286. "transport": PeerStats.transport
  11287. });
  11288. PeerStats.transport = [];
  11289. };
  11290. /**
  11291. * Stats processing logic.
  11292. */
  11293. StatsCollector.prototype.processAudioLevelReport = function () {
  11294. if (!this.baselineAudioLevelsReport) {
  11295. return;
  11296. }
  11297. for (var idx in this.currentAudioLevelsReport) {
  11298. var now = this.currentAudioLevelsReport[idx];
  11299. if (now.type != 'ssrc') {
  11300. continue;
  11301. }
  11302. var before = this.baselineAudioLevelsReport[idx];
  11303. if (!before) {
  11304. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11305. continue;
  11306. }
  11307. var ssrc = getStatValue(now, 'ssrc');
  11308. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11309. if (!jid) {
  11310. if((Date.now() - now.timestamp) < 3000)
  11311. console.warn("No jid for ssrc: " + ssrc);
  11312. continue;
  11313. }
  11314. var jidStats = this.jid2stats[jid];
  11315. if (!jidStats) {
  11316. jidStats = new PeerStats();
  11317. this.jid2stats[jid] = jidStats;
  11318. }
  11319. // Audio level
  11320. var audioLevel = null;
  11321. try {
  11322. audioLevel = getStatValue(now, 'audioInputLevel');
  11323. if (!audioLevel)
  11324. audioLevel = getStatValue(now, 'audioOutputLevel');
  11325. }
  11326. catch(e) {/*not supported*/
  11327. console.warn("Audio Levels are not available in the statistics.");
  11328. clearInterval(this.audioLevelsIntervalId);
  11329. return;
  11330. }
  11331. if (audioLevel) {
  11332. // TODO: can't find specs about what this value really is,
  11333. // but it seems to vary between 0 and around 32k.
  11334. audioLevel = audioLevel / 32767;
  11335. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11336. if(jid != APP.xmpp.myJid())
  11337. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11338. }
  11339. }
  11340. };
  11341. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11342. /* global require, APP */
  11343. /**
  11344. * Created by hristo on 8/4/14.
  11345. */
  11346. var LocalStats = require("./LocalStatsCollector.js");
  11347. var RTPStats = require("./RTPStatsCollector.js");
  11348. var EventEmitter = require("events");
  11349. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11350. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11351. var CallStats = require("./CallStats");
  11352. var RTCEvents = require("../../service/RTC/RTCEvents");
  11353. var eventEmitter = new EventEmitter();
  11354. var localStats = null;
  11355. var rtpStats = null;
  11356. function stopLocal() {
  11357. if (localStats) {
  11358. localStats.stop();
  11359. localStats = null;
  11360. }
  11361. }
  11362. function stopRemote() {
  11363. if (rtpStats) {
  11364. rtpStats.stop();
  11365. eventEmitter.emit("statistics.stop");
  11366. rtpStats = null;
  11367. }
  11368. }
  11369. function startRemoteStats (peerconnection) {
  11370. if (rtpStats) {
  11371. rtpStats.stop();
  11372. }
  11373. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11374. rtpStats.start();
  11375. }
  11376. function onStreamCreated(stream) {
  11377. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11378. return;
  11379. }
  11380. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11381. eventEmitter);
  11382. localStats.start();
  11383. }
  11384. function onDisposeConference(onUnload) {
  11385. CallStats.sendTerminateEvent();
  11386. stopRemote();
  11387. if(onUnload) {
  11388. stopLocal();
  11389. eventEmitter.removeAllListeners();
  11390. }
  11391. }
  11392. var statistics = {
  11393. /**
  11394. * Indicates that this audio level is for local jid.
  11395. * @type {string}
  11396. */
  11397. LOCAL_JID: 'local',
  11398. addAudioLevelListener: function(listener)
  11399. {
  11400. eventEmitter.on("statistics.audioLevel", listener);
  11401. },
  11402. removeAudioLevelListener: function(listener)
  11403. {
  11404. eventEmitter.removeListener("statistics.audioLevel", listener);
  11405. },
  11406. addConnectionStatsListener: function(listener)
  11407. {
  11408. eventEmitter.on("statistics.connectionstats", listener);
  11409. },
  11410. removeConnectionStatsListener: function(listener)
  11411. {
  11412. eventEmitter.removeListener("statistics.connectionstats", listener);
  11413. },
  11414. addRemoteStatsStopListener: function(listener)
  11415. {
  11416. eventEmitter.on("statistics.stop", listener);
  11417. },
  11418. removeRemoteStatsStopListener: function(listener)
  11419. {
  11420. eventEmitter.removeListener("statistics.stop", listener);
  11421. },
  11422. stop: function () {
  11423. stopLocal();
  11424. stopRemote();
  11425. if(eventEmitter)
  11426. {
  11427. eventEmitter.removeAllListeners();
  11428. }
  11429. },
  11430. stopRemoteStatistics: function()
  11431. {
  11432. stopRemote();
  11433. },
  11434. start: function () {
  11435. APP.RTC.addStreamListener(onStreamCreated,
  11436. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11437. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11438. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11439. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11440. startRemoteStats(event.peerconnection);
  11441. // CallStats.init(event);
  11442. });
  11443. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11444. CallStats.init(session);
  11445. });
  11446. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11447. CallStats.sendMuteEvent(mute, "audio");
  11448. });
  11449. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11450. CallStats.sendSetupFailedEvent();
  11451. });
  11452. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11453. CallStats.sendMuteEvent(mute, "video");
  11454. });
  11455. }
  11456. };
  11457. module.exports = statistics;
  11458. },{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes.js":154,"../../service/xmpp/XMPPEvents":161,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":162}],52:[function(require,module,exports){
  11459. /* global $, require, config, interfaceConfig */
  11460. var i18n = require("i18next-client");
  11461. var languages = require("../../service/translation/languages");
  11462. var Settings = require("../settings/Settings");
  11463. var DEFAULT_LANG = languages.EN;
  11464. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11465. return value.replace("__app__", interfaceConfig.APP_NAME);
  11466. });
  11467. var defaultOptions = {
  11468. detectLngQS: "lang",
  11469. useCookie: false,
  11470. fallbackLng: DEFAULT_LANG,
  11471. load: "unspecific",
  11472. resGetPath: 'lang/__ns__-__lng__.json',
  11473. ns: {
  11474. namespaces: ['main', 'languages'],
  11475. defaultNs: 'main'
  11476. },
  11477. lngWhitelist : languages.getLanguages(),
  11478. fallbackOnNull: true,
  11479. fallbackOnEmpty: true,
  11480. useDataAttrOptions: true,
  11481. app: interfaceConfig.APP_NAME,
  11482. getAsync: false,
  11483. defaultValueFromContent: false,
  11484. customLoad: function(lng, ns, options, done) {
  11485. var resPath = "lang/__ns__-__lng__.json";
  11486. if(lng === languages.EN)
  11487. resPath = "lang/__ns__.json";
  11488. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11489. i18n.functions.ajax({
  11490. url: url,
  11491. success: function(data, status, xhr) {
  11492. i18n.functions.log('loaded: ' + url);
  11493. done(null, data);
  11494. },
  11495. error : function(xhr, status, error) {
  11496. if ((status && status == 200) ||
  11497. (xhr && xhr.status && xhr.status == 200)) {
  11498. // file loaded but invalid json, stop waste time !
  11499. i18n.functions.error('There is a typo in: ' + url);
  11500. } else if ((status && status == 404) ||
  11501. (xhr && xhr.status && xhr.status == 404)) {
  11502. i18n.functions.log('Does not exist: ' + url);
  11503. } else {
  11504. var theStatus = status ? status :
  11505. ((xhr && xhr.status) ? xhr.status : null);
  11506. i18n.functions.log(theStatus + ' when loading ' + url);
  11507. }
  11508. done(error, {});
  11509. },
  11510. dataType: "json",
  11511. async : options.getAsync
  11512. });
  11513. }
  11514. // options for caching
  11515. // useLocalStorage: true,
  11516. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11517. };
  11518. function initCompleted(t) {
  11519. $("[data-i18n]").i18n();
  11520. }
  11521. function checkForParameter() {
  11522. var query = window.location.search.substring(1);
  11523. var vars = query.split("&");
  11524. for (var i=0;i<vars.length;i++) {
  11525. var pair = vars[i].split("=");
  11526. if(pair[0] == "lang")
  11527. {
  11528. return pair[1];
  11529. }
  11530. }
  11531. return null;
  11532. }
  11533. module.exports = {
  11534. init: function (lang) {
  11535. var options = defaultOptions;
  11536. if(!lang)
  11537. {
  11538. lang = checkForParameter();
  11539. if(!lang)
  11540. {
  11541. var settings = Settings.getSettings();
  11542. if(settings)
  11543. lang = settings.language;
  11544. if(!lang && config.defaultLanguage)
  11545. {
  11546. lang = config.defaultLanguage;
  11547. }
  11548. }
  11549. }
  11550. if(lang) {
  11551. options.lng = lang;
  11552. }
  11553. i18n.init(options, initCompleted);
  11554. },
  11555. translateString: function (key, options) {
  11556. return i18n.t(key, options);
  11557. },
  11558. setLanguage: function (lang) {
  11559. if(!lang)
  11560. lang = DEFAULT_LANG;
  11561. i18n.setLng(lang, defaultOptions, initCompleted);
  11562. },
  11563. getCurrentLanguage: function () {
  11564. return i18n.lng();
  11565. },
  11566. translateElement: function (selector) {
  11567. selector.i18n();
  11568. },
  11569. generateTranslationHTML: function (key, options) {
  11570. var str = "<span data-i18n=\"" + key + "\"";
  11571. if(options)
  11572. {
  11573. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11574. }
  11575. str += ">";
  11576. str += this.translateString(key, options);
  11577. str += "</span>";
  11578. return str;
  11579. }
  11580. };
  11581. },{"../../service/translation/languages":160,"../settings/Settings":47,"i18next-client":70}],53:[function(require,module,exports){
  11582. /*
  11583. * JingleSession provides an API to manage a single Jingle session. We will
  11584. * have different implementations depending on the underlying interface used
  11585. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  11586. */
  11587. function JingleSession(me, sid, connection, service, eventEmitter) {
  11588. /**
  11589. * Our JID.
  11590. */
  11591. this.me = me;
  11592. /**
  11593. * The Jingle session identifier.
  11594. */
  11595. this.sid = sid;
  11596. /**
  11597. * The XMPP connection.
  11598. */
  11599. this.connection = connection;
  11600. /**
  11601. * The XMPP service.
  11602. */
  11603. this.service = service;
  11604. /**
  11605. * The event emitter.
  11606. */
  11607. this.eventEmitter = eventEmitter;
  11608. /**
  11609. * Whether to use dripping or not. Dripping is sending trickle candidates
  11610. * not one-by-one.
  11611. * Note: currently we do not support 'false'.
  11612. */
  11613. this.usedrip = true;
  11614. /**
  11615. * When dripping is used, stores ICE candidates which are to be sent.
  11616. */
  11617. this.drip_container = [];
  11618. // Media constraints. Is this WebRTC only?
  11619. this.media_constraints = null;
  11620. // ICE servers config (RTCConfiguration?).
  11621. this.ice_config = {};
  11622. }
  11623. /**
  11624. * Prepares this object to initiate a session.
  11625. * @param peerjid the JID of the remote peer.
  11626. * @param isInitiator whether we will be the Jingle initiator.
  11627. * @param media_constraints
  11628. * @param ice_config
  11629. */
  11630. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  11631. media_constraints, ice_config) {
  11632. this.media_constraints = media_constraints;
  11633. this.ice_config = ice_config;
  11634. if (this.state !== null) {
  11635. console.error('attempt to initiate on session ' + this.sid +
  11636. 'in state ' + this.state);
  11637. return;
  11638. }
  11639. this.state = 'pending';
  11640. this.initiator = isInitiator ? this.me : peerjid;
  11641. this.responder = !isInitiator ? this.me : peerjid;
  11642. this.peerjid = peerjid;
  11643. this.doInitialize();
  11644. };
  11645. /**
  11646. * Finishes initialization.
  11647. */
  11648. JingleSession.prototype.doInitialize = function() {};
  11649. /**
  11650. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  11651. * Note: currently only used on transport-info
  11652. */
  11653. JingleSession.prototype.addIceCandidates = function(contents) {};
  11654. /**
  11655. * Handles an 'add-source' event.
  11656. *
  11657. * @param contents an array of Jingle 'content' elements.
  11658. */
  11659. JingleSession.prototype.addSources = function(contents) {};
  11660. /**
  11661. * Handles a 'remove-source' event.
  11662. *
  11663. * @param contents an array of Jingle 'content' elements.
  11664. */
  11665. JingleSession.prototype.removeSources = function(contents) {};
  11666. /**
  11667. * Terminates this Jingle session (stops sending media and closes the streams?)
  11668. */
  11669. JingleSession.prototype.terminate = function() {};
  11670. /**
  11671. * Sends a Jingle session-terminate message to the peer and terminates the
  11672. * session.
  11673. * @param reason
  11674. * @param text
  11675. */
  11676. JingleSession.prototype.sendTerminate = function(reason, text) {};
  11677. /**
  11678. * Handles an offer from the remote peer (prepares to accept a session).
  11679. * @param jingle the 'jingle' XML element.
  11680. */
  11681. JingleSession.prototype.setOffer = function(jingle) {};
  11682. /**
  11683. * Handles an answer from the remote peer (prepares to accept a session).
  11684. * @param jingle the 'jingle' XML element.
  11685. */
  11686. JingleSession.prototype.setAnswer = function(jingle) {};
  11687. module.exports = JingleSession;
  11688. },{}],54:[function(require,module,exports){
  11689. /* jshint -W117 */
  11690. var JingleSession = require("./JingleSession");
  11691. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11692. var SDPDiffer = require("./SDPDiffer");
  11693. var SDPUtil = require("./SDPUtil");
  11694. var SDP = require("./SDP");
  11695. var async = require("async");
  11696. var transform = require("sdp-transform");
  11697. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11698. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11699. var SSRCReplacement = require("./LocalSSRCReplacement");
  11700. // Jingle stuff
  11701. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  11702. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  11703. this.initiator = null;
  11704. this.responder = null;
  11705. this.peerjid = null;
  11706. this.state = null;
  11707. this.localSDP = null;
  11708. this.remoteSDP = null;
  11709. this.relayedStreams = [];
  11710. this.pc_constraints = null;
  11711. this.usetrickle = true;
  11712. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11713. this.hadstuncandidate = false;
  11714. this.hadturncandidate = false;
  11715. this.lasticecandidate = false;
  11716. this.statsinterval = null;
  11717. this.reason = null;
  11718. this.addssrc = [];
  11719. this.removessrc = [];
  11720. this.pendingop = null;
  11721. this.switchstreams = false;
  11722. this.wait = true;
  11723. this.localStreamsSSRC = null;
  11724. this.ssrcOwners = {};
  11725. this.ssrcVideoTypes = {};
  11726. this.eventEmitter = eventEmitter;
  11727. /**
  11728. * The indicator which determines whether the (local) video has been muted
  11729. * in response to a user command in contrast to an automatic decision made
  11730. * by the application logic.
  11731. */
  11732. this.videoMuteByUser = false;
  11733. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11734. // We start with the queue paused. We resume it when the signaling state is
  11735. // stable and the ice connection state is connected.
  11736. this.modifySourcesQueue.pause();
  11737. }
  11738. JingleSessionPC.prototype = JingleSession.prototype;
  11739. JingleSessionPC.prototype.constructor = JingleSessionPC;
  11740. JingleSessionPC.prototype.setOffer = function(offer) {
  11741. this.setRemoteDescription(offer, 'offer');
  11742. };
  11743. JingleSessionPC.prototype.setAnswer = function(answer) {
  11744. this.setRemoteDescription(answer, 'answer');
  11745. };
  11746. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  11747. var signalingState = this.peerconnection.signalingState;
  11748. var iceConnectionState = this.peerconnection.iceConnectionState;
  11749. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11750. this.modifySourcesQueue.resume();
  11751. } else {
  11752. this.modifySourcesQueue.pause();
  11753. }
  11754. };
  11755. JingleSessionPC.prototype.doInitialize = function () {
  11756. var self = this;
  11757. this.hadstuncandidate = false;
  11758. this.hadturncandidate = false;
  11759. this.lasticecandidate = false;
  11760. this.isreconnect = false;
  11761. this.peerconnection = new TraceablePeerConnection(
  11762. this.connection.jingle.ice_config,
  11763. this.connection.jingle.pc_constraints,
  11764. this);
  11765. this.peerconnection.onicecandidate = function (event) {
  11766. self.sendIceCandidate(event.candidate);
  11767. };
  11768. this.peerconnection.onaddstream = function (event) {
  11769. if (event.stream.id !== 'default') {
  11770. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11771. self.remoteStreamAdded(event);
  11772. } else {
  11773. // This is a recvonly stream. Clients that implement Unified Plan,
  11774. // such as Firefox use recvonly "streams/channels/tracks" for
  11775. // receiving remote stream/tracks, as opposed to Plan B where there
  11776. // are only 3 channels: audio, video and data.
  11777. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11778. }
  11779. };
  11780. this.peerconnection.onremovestream = function (event) {
  11781. // Remove the stream from remoteStreams
  11782. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11783. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11784. };
  11785. this.peerconnection.onsignalingstatechange = function (event) {
  11786. if (!(self && self.peerconnection)) return;
  11787. self.updateModifySourcesQueue();
  11788. };
  11789. /**
  11790. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  11791. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  11792. * RTCPeerConnection.iceConnectionState changes.
  11793. *
  11794. * @param event the event containing information about the change
  11795. */
  11796. this.peerconnection.oniceconnectionstatechange = function (event) {
  11797. if (!(self && self.peerconnection)) return;
  11798. self.updateModifySourcesQueue();
  11799. switch (self.peerconnection.iceConnectionState) {
  11800. case 'connected':
  11801. // Informs interested parties that the connection has been restored.
  11802. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  11803. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  11804. self.isreconnect = false;
  11805. break;
  11806. case 'disconnected':
  11807. self.isreconnect = true;
  11808. // Informs interested parties that the connection has been interrupted.
  11809. if (self.peerconnection.signalingState === 'stable')
  11810. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  11811. break;
  11812. case 'failed':
  11813. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11814. break;
  11815. }
  11816. onIceConnectionStateChange(self.sid, self);
  11817. };
  11818. this.peerconnection.onnegotiationneeded = function (event) {
  11819. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11820. };
  11821. // add any local and relayed stream
  11822. APP.RTC.localStreams.forEach(function(stream) {
  11823. self.peerconnection.addStream(stream.getOriginalStream());
  11824. });
  11825. this.relayedStreams.forEach(function(stream) {
  11826. self.peerconnection.addStream(stream);
  11827. });
  11828. };
  11829. function onIceConnectionStateChange(sid, session) {
  11830. switch (session.peerconnection.iceConnectionState) {
  11831. case 'checking':
  11832. session.timeChecking = (new Date()).getTime();
  11833. session.firstconnect = true;
  11834. break;
  11835. case 'completed': // on caller side
  11836. case 'connected':
  11837. if (session.firstconnect) {
  11838. session.firstconnect = false;
  11839. var metadata = {};
  11840. metadata.setupTime
  11841. = (new Date()).getTime() - session.timeChecking;
  11842. session.peerconnection.getStats(function (res) {
  11843. if(res && res.result) {
  11844. res.result().forEach(function (report) {
  11845. if (report.type == 'googCandidatePair' &&
  11846. report.stat('googActiveConnection') == 'true') {
  11847. metadata.localCandidateType
  11848. = report.stat('googLocalCandidateType');
  11849. metadata.remoteCandidateType
  11850. = report.stat('googRemoteCandidateType');
  11851. // log pair as well so we can get nice pie
  11852. // charts
  11853. metadata.candidatePair
  11854. = report.stat('googLocalCandidateType') +
  11855. ';' +
  11856. report.stat('googRemoteCandidateType');
  11857. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11858. {
  11859. metadata.ipv6 = true;
  11860. }
  11861. }
  11862. });
  11863. }
  11864. });
  11865. }
  11866. break;
  11867. }
  11868. }
  11869. JingleSessionPC.prototype.accept = function () {
  11870. this.state = 'active';
  11871. var pranswer = this.peerconnection.localDescription;
  11872. if (!pranswer || pranswer.type != 'pranswer') {
  11873. return;
  11874. }
  11875. console.log('going from pranswer to answer');
  11876. if (this.usetrickle) {
  11877. // remove candidates already sent from session-accept
  11878. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11879. for (var i = 0; i < lines.length; i++) {
  11880. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11881. }
  11882. }
  11883. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11884. // FIXME: change any inactive to sendrecv or whatever they were originally
  11885. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11886. }
  11887. var prsdp = new SDP(pranswer.sdp);
  11888. var accept = $iq({to: this.peerjid,
  11889. type: 'set'})
  11890. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11891. action: 'session-accept',
  11892. initiator: this.initiator,
  11893. responder: this.responder,
  11894. sid: this.sid });
  11895. // FIXME why do we generate session-accept in 3 different places ?
  11896. prsdp.toJingle(
  11897. accept,
  11898. this.initiator == this.me ? 'initiator' : 'responder',
  11899. this.localStreamsSSRC);
  11900. var sdp = this.peerconnection.localDescription.sdp;
  11901. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11902. // FIXME: change any inactive to sendrecv or whatever they were originally
  11903. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11904. }
  11905. var self = this;
  11906. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11907. function () {
  11908. //console.log('setLocalDescription success');
  11909. self.setLocalDescription();
  11910. SSRCReplacement.processSessionInit(accept);
  11911. self.connection.sendIQ(accept,
  11912. function () {
  11913. var ack = {};
  11914. ack.source = 'answer';
  11915. $(document).trigger('ack.jingle', [self.sid, ack]);
  11916. },
  11917. function (stanza) {
  11918. var error = ($(stanza).find('error').length) ? {
  11919. code: $(stanza).find('error').attr('code'),
  11920. reason: $(stanza).find('error :first')[0].tagName
  11921. }:{};
  11922. error.source = 'answer';
  11923. JingleSessionPC.onJingleError(self.sid, error);
  11924. },
  11925. 10000);
  11926. },
  11927. function (e) {
  11928. console.error('setLocalDescription failed', e);
  11929. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11930. }
  11931. );
  11932. };
  11933. JingleSessionPC.prototype.terminate = function (reason) {
  11934. this.state = 'ended';
  11935. this.reason = reason;
  11936. this.peerconnection.close();
  11937. if (this.statsinterval !== null) {
  11938. window.clearInterval(this.statsinterval);
  11939. this.statsinterval = null;
  11940. }
  11941. };
  11942. JingleSessionPC.prototype.active = function () {
  11943. return this.state == 'active';
  11944. };
  11945. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  11946. var self = this;
  11947. if (candidate && !this.lasticecandidate) {
  11948. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11949. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11950. if (!(ice && jcand)) {
  11951. console.error('failed to get ice && jcand');
  11952. return;
  11953. }
  11954. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11955. if (jcand.type === 'srflx') {
  11956. this.hadstuncandidate = true;
  11957. } else if (jcand.type === 'relay') {
  11958. this.hadturncandidate = true;
  11959. }
  11960. if (this.usetrickle) {
  11961. if (this.usedrip) {
  11962. if (this.drip_container.length === 0) {
  11963. // start 20ms callout
  11964. window.setTimeout(function () {
  11965. if (self.drip_container.length === 0) return;
  11966. self.sendIceCandidates(self.drip_container);
  11967. self.drip_container = [];
  11968. }, 20);
  11969. }
  11970. this.drip_container.push(candidate);
  11971. return;
  11972. } else {
  11973. self.sendIceCandidate([candidate]);
  11974. }
  11975. }
  11976. } else {
  11977. //console.log('sendIceCandidate: last candidate.');
  11978. if (!this.usetrickle) {
  11979. //console.log('should send full offer now...');
  11980. //FIXME why do we generate session-accept in 3 different places ?
  11981. var init = $iq({to: this.peerjid,
  11982. type: 'set'})
  11983. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11984. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11985. initiator: this.initiator,
  11986. sid: this.sid});
  11987. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11988. var sendJingle = function (ssrc) {
  11989. if(!ssrc)
  11990. ssrc = {};
  11991. self.localSDP.toJingle(
  11992. init,
  11993. self.initiator == self.me ? 'initiator' : 'responder',
  11994. ssrc);
  11995. SSRCReplacement.processSessionInit(init);
  11996. self.connection.sendIQ(init,
  11997. function () {
  11998. //console.log('session initiate ack');
  11999. var ack = {};
  12000. ack.source = 'offer';
  12001. $(document).trigger('ack.jingle', [self.sid, ack]);
  12002. },
  12003. function (stanza) {
  12004. self.state = 'error';
  12005. self.peerconnection.close();
  12006. var error = ($(stanza).find('error').length) ? {
  12007. code: $(stanza).find('error').attr('code'),
  12008. reason: $(stanza).find('error :first')[0].tagName,
  12009. }:{};
  12010. error.source = 'offer';
  12011. JingleSessionPC.onJingleError(self.sid, error);
  12012. },
  12013. 10000);
  12014. };
  12015. sendJingle();
  12016. }
  12017. this.lasticecandidate = true;
  12018. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  12019. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  12020. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  12021. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  12022. }
  12023. }
  12024. };
  12025. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  12026. console.log('sendIceCandidates', candidates);
  12027. var cand = $iq({to: this.peerjid, type: 'set'})
  12028. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12029. action: 'transport-info',
  12030. initiator: this.initiator,
  12031. sid: this.sid});
  12032. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  12033. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  12034. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  12035. if (cands.length > 0) {
  12036. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  12037. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12038. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  12039. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  12040. }).c('transport', ice);
  12041. for (var i = 0; i < cands.length; i++) {
  12042. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  12043. }
  12044. // add fingerprint
  12045. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  12046. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  12047. tmp.required = true;
  12048. cand.c(
  12049. 'fingerprint',
  12050. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  12051. .t(tmp.fingerprint);
  12052. delete tmp.fingerprint;
  12053. cand.attrs(tmp);
  12054. cand.up();
  12055. }
  12056. cand.up(); // transport
  12057. cand.up(); // content
  12058. }
  12059. }
  12060. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  12061. //console.log('was this the last candidate', this.lasticecandidate);
  12062. this.connection.sendIQ(cand,
  12063. function () {
  12064. var ack = {};
  12065. ack.source = 'transportinfo';
  12066. $(document).trigger('ack.jingle', [this.sid, ack]);
  12067. },
  12068. function (stanza) {
  12069. var error = ($(stanza).find('error').length) ? {
  12070. code: $(stanza).find('error').attr('code'),
  12071. reason: $(stanza).find('error :first')[0].tagName,
  12072. }:{};
  12073. error.source = 'transportinfo';
  12074. JingleSessionPC.onJingleError(this.sid, error);
  12075. },
  12076. 10000);
  12077. };
  12078. JingleSessionPC.prototype.sendOffer = function () {
  12079. //console.log('sendOffer...');
  12080. var self = this;
  12081. this.peerconnection.createOffer(function (sdp) {
  12082. self.createdOffer(sdp);
  12083. },
  12084. function (e) {
  12085. console.error('createOffer failed', e);
  12086. },
  12087. this.media_constraints
  12088. );
  12089. };
  12090. // FIXME createdOffer is never used in jitsi-meet
  12091. JingleSessionPC.prototype.createdOffer = function (sdp) {
  12092. //console.log('createdOffer', sdp);
  12093. var self = this;
  12094. this.localSDP = new SDP(sdp.sdp);
  12095. //this.localSDP.mangle();
  12096. var sendJingle = function () {
  12097. var init = $iq({to: this.peerjid,
  12098. type: 'set'})
  12099. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12100. action: 'session-initiate',
  12101. initiator: this.initiator,
  12102. sid: this.sid});
  12103. self.localSDP.toJingle(
  12104. init,
  12105. this.initiator == this.me ? 'initiator' : 'responder',
  12106. this.localStreamsSSRC);
  12107. SSRCReplacement.processSessionInit(init);
  12108. self.connection.sendIQ(init,
  12109. function () {
  12110. var ack = {};
  12111. ack.source = 'offer';
  12112. $(document).trigger('ack.jingle', [self.sid, ack]);
  12113. },
  12114. function (stanza) {
  12115. self.state = 'error';
  12116. self.peerconnection.close();
  12117. var error = ($(stanza).find('error').length) ? {
  12118. code: $(stanza).find('error').attr('code'),
  12119. reason: $(stanza).find('error :first')[0].tagName,
  12120. }:{};
  12121. error.source = 'offer';
  12122. JingleSessionPC.onJingleError(self.sid, error);
  12123. },
  12124. 10000);
  12125. }
  12126. sdp.sdp = this.localSDP.raw;
  12127. this.peerconnection.setLocalDescription(sdp,
  12128. function () {
  12129. if(self.usetrickle)
  12130. {
  12131. sendJingle();
  12132. }
  12133. self.setLocalDescription();
  12134. //console.log('setLocalDescription success');
  12135. },
  12136. function (e) {
  12137. console.error('setLocalDescription failed', e);
  12138. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12139. }
  12140. );
  12141. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12142. for (var i = 0; i < cands.length; i++) {
  12143. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12144. if (cand.type == 'srflx') {
  12145. this.hadstuncandidate = true;
  12146. } else if (cand.type == 'relay') {
  12147. this.hadturncandidate = true;
  12148. }
  12149. }
  12150. };
  12151. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  12152. var self = this;
  12153. $(contents).each(function (idx, content) {
  12154. var name = $(content).attr('name');
  12155. var mediaType = this.getAttribute('name');
  12156. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12157. ssrcs.each(function () {
  12158. var ssrc = this.getAttribute('ssrc');
  12159. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12160. function () {
  12161. var owner = this.getAttribute('owner');
  12162. self.ssrcOwners[ssrc] = owner;
  12163. }
  12164. );
  12165. });
  12166. });
  12167. };
  12168. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  12169. return this.ssrcOwners[ssrc];
  12170. };
  12171. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  12172. //console.log('setting remote description... ', desctype);
  12173. this.remoteSDP = new SDP('');
  12174. this.remoteSDP.fromJingle(elem);
  12175. this.readSsrcInfo($(elem).find(">content"));
  12176. if (this.peerconnection.remoteDescription !== null) {
  12177. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12178. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12179. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12180. for (var i = 0; i < pranswer.media.length; i++) {
  12181. // make sure we have ice ufrag and pwd
  12182. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12183. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12184. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12185. } else {
  12186. console.warn('no ice ufrag?');
  12187. }
  12188. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12189. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12190. } else {
  12191. console.warn('no ice pwd?');
  12192. }
  12193. }
  12194. // copy over candidates
  12195. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12196. for (var j = 0; j < lines.length; j++) {
  12197. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12198. }
  12199. }
  12200. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12201. }
  12202. }
  12203. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12204. this.peerconnection.setRemoteDescription(remotedesc,
  12205. function () {
  12206. //console.log('setRemoteDescription success');
  12207. },
  12208. function (e) {
  12209. console.error('setRemoteDescription error', e);
  12210. JingleSessionPC.onJingleFatalError(self, e);
  12211. }
  12212. );
  12213. };
  12214. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  12215. var self = this;
  12216. if (this.peerconnection.signalingState == 'closed') {
  12217. return;
  12218. }
  12219. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12220. console.log('trickle ice candidate arriving before session accept...');
  12221. // create a PRANSWER for setRemoteDescription
  12222. if (!this.remoteSDP) {
  12223. var cobbled = 'v=0\r\n' +
  12224. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12225. 's=-\r\n' +
  12226. 't=0 0\r\n';
  12227. // first, take some things from the local description
  12228. for (var i = 0; i < this.localSDP.media.length; i++) {
  12229. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12230. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12231. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12232. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12233. }
  12234. cobbled += 'a=inactive\r\n';
  12235. }
  12236. this.remoteSDP = new SDP(cobbled);
  12237. }
  12238. // then add things like ice and dtls from remote candidate
  12239. elem.each(function () {
  12240. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12241. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12242. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12243. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12244. var tmp = $(this).find('transport');
  12245. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12246. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12247. tmp = $(this).find('transport>fingerprint');
  12248. if (tmp.length) {
  12249. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12250. } else {
  12251. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12252. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12253. }
  12254. break;
  12255. }
  12256. }
  12257. }
  12258. });
  12259. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12260. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12261. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12262. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12263. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12264. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12265. }).length == this.remoteSDP.media.length;
  12266. if (iscomplete) {
  12267. console.log('setting pranswer');
  12268. try {
  12269. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12270. function() {
  12271. },
  12272. function(e) {
  12273. console.log('setRemoteDescription pranswer failed', e.toString());
  12274. });
  12275. } catch (e) {
  12276. console.error('setting pranswer failed', e);
  12277. }
  12278. } else {
  12279. //console.log('not yet setting pranswer');
  12280. }
  12281. }
  12282. // operate on each content element
  12283. elem.each(function () {
  12284. // would love to deactivate this, but firefox still requires it
  12285. var idx = -1;
  12286. var i;
  12287. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12288. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12289. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12290. idx = i;
  12291. break;
  12292. }
  12293. }
  12294. if (idx == -1) { // fall back to localdescription
  12295. for (i = 0; i < self.localSDP.media.length; i++) {
  12296. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12297. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12298. idx = i;
  12299. break;
  12300. }
  12301. }
  12302. }
  12303. var name = $(this).attr('name');
  12304. // TODO: check ice-pwd and ice-ufrag?
  12305. $(this).find('transport>candidate').each(function () {
  12306. var line, candidate;
  12307. line = SDPUtil.candidateFromJingle(this);
  12308. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12309. sdpMid: name,
  12310. candidate: line});
  12311. try {
  12312. self.peerconnection.addIceCandidate(candidate);
  12313. } catch (e) {
  12314. console.error('addIceCandidate failed', e.toString(), line);
  12315. }
  12316. });
  12317. });
  12318. };
  12319. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  12320. //console.log('createAnswer', provisional);
  12321. var self = this;
  12322. this.peerconnection.createAnswer(
  12323. function (sdp) {
  12324. self.createdAnswer(sdp, provisional);
  12325. },
  12326. function (e) {
  12327. console.error('createAnswer failed', e);
  12328. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12329. },
  12330. this.media_constraints
  12331. );
  12332. };
  12333. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  12334. //console.log('createAnswer callback');
  12335. var self = this;
  12336. this.localSDP = new SDP(sdp.sdp);
  12337. //this.localSDP.mangle();
  12338. this.usepranswer = provisional === true;
  12339. if (this.usetrickle) {
  12340. if (this.usepranswer) {
  12341. sdp.type = 'pranswer';
  12342. for (var i = 0; i < this.localSDP.media.length; i++) {
  12343. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12344. }
  12345. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12346. }
  12347. }
  12348. var self = this;
  12349. var sendJingle = function (ssrcs) {
  12350. // FIXME why do we generate session-accept in 3 different places ?
  12351. var accept = $iq({to: self.peerjid,
  12352. type: 'set'})
  12353. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12354. action: 'session-accept',
  12355. initiator: self.initiator,
  12356. responder: self.responder,
  12357. sid: self.sid });
  12358. self.localSDP.toJingle(
  12359. accept,
  12360. self.initiator == self.me ? 'initiator' : 'responder',
  12361. ssrcs);
  12362. SSRCReplacement.processSessionInit(accept);
  12363. self.connection.sendIQ(accept,
  12364. function () {
  12365. var ack = {};
  12366. ack.source = 'answer';
  12367. $(document).trigger('ack.jingle', [self.sid, ack]);
  12368. },
  12369. function (stanza) {
  12370. var error = ($(stanza).find('error').length) ? {
  12371. code: $(stanza).find('error').attr('code'),
  12372. reason: $(stanza).find('error :first')[0].tagName,
  12373. }:{};
  12374. error.source = 'answer';
  12375. JingleSessionPC.onJingleError(self.sid, error);
  12376. },
  12377. 10000);
  12378. }
  12379. sdp.sdp = this.localSDP.raw;
  12380. this.peerconnection.setLocalDescription(sdp,
  12381. function () {
  12382. //console.log('setLocalDescription success');
  12383. if (self.usetrickle && !self.usepranswer) {
  12384. sendJingle();
  12385. }
  12386. self.setLocalDescription();
  12387. },
  12388. function (e) {
  12389. console.error('setLocalDescription failed', e);
  12390. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12391. }
  12392. );
  12393. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12394. for (var j = 0; j < cands.length; j++) {
  12395. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12396. if (cand.type == 'srflx') {
  12397. this.hadstuncandidate = true;
  12398. } else if (cand.type == 'relay') {
  12399. this.hadturncandidate = true;
  12400. }
  12401. }
  12402. };
  12403. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  12404. var self = this,
  12405. term = $iq({to: this.peerjid,
  12406. type: 'set'})
  12407. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12408. action: 'session-terminate',
  12409. initiator: this.initiator,
  12410. sid: this.sid})
  12411. .c('reason')
  12412. .c(reason || 'success');
  12413. if (text) {
  12414. term.up().c('text').t(text);
  12415. }
  12416. this.connection.sendIQ(term,
  12417. function () {
  12418. self.peerconnection.close();
  12419. self.peerconnection = null;
  12420. self.terminate();
  12421. var ack = {};
  12422. ack.source = 'terminate';
  12423. $(document).trigger('ack.jingle', [self.sid, ack]);
  12424. },
  12425. function (stanza) {
  12426. var error = ($(stanza).find('error').length) ? {
  12427. code: $(stanza).find('error').attr('code'),
  12428. reason: $(stanza).find('error :first')[0].tagName,
  12429. }:{};
  12430. $(document).trigger('ack.jingle', [self.sid, error]);
  12431. },
  12432. 10000);
  12433. if (this.statsinterval !== null) {
  12434. window.clearInterval(this.statsinterval);
  12435. this.statsinterval = null;
  12436. }
  12437. };
  12438. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  12439. var self = this;
  12440. // FIXME: dirty waiting
  12441. if (!this.peerconnection.localDescription)
  12442. {
  12443. console.warn("addSource - localDescription not ready yet")
  12444. setTimeout(function()
  12445. {
  12446. self.addSource(elem, fromJid);
  12447. },
  12448. 200
  12449. );
  12450. return;
  12451. }
  12452. console.log('addssrc', new Date().getTime());
  12453. console.log('ice', this.peerconnection.iceConnectionState);
  12454. this.readSsrcInfo(elem);
  12455. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12456. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12457. $(elem).each(function (idx, content) {
  12458. var name = $(content).attr('name');
  12459. var lines = '';
  12460. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12461. var semantics = this.getAttribute('semantics');
  12462. var ssrcs = $(this).find('>source').map(function () {
  12463. return this.getAttribute('ssrc');
  12464. }).get();
  12465. if (ssrcs.length != 0) {
  12466. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12467. }
  12468. });
  12469. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12470. tmp.each(function () {
  12471. var ssrc = $(this).attr('ssrc');
  12472. if(mySdp.containsSSRC(ssrc)){
  12473. /**
  12474. * This happens when multiple participants change their streams at the same time and
  12475. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12476. * addssrc are scheduled for update IQ. See
  12477. */
  12478. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12479. return;
  12480. }
  12481. if (sdp.containsSSRC(ssrc)) {
  12482. console.warn("Source-add request for existing SSRC: " + ssrc);
  12483. return;
  12484. }
  12485. $(this).find('>parameter').each(function () {
  12486. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12487. if ($(this).attr('value') && $(this).attr('value').length)
  12488. lines += ':' + $(this).attr('value');
  12489. lines += '\r\n';
  12490. });
  12491. });
  12492. sdp.media.forEach(function(media, idx) {
  12493. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12494. return;
  12495. sdp.media[idx] += lines;
  12496. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12497. self.addssrc[idx] += lines;
  12498. });
  12499. sdp.raw = sdp.session + sdp.media.join('');
  12500. });
  12501. this.modifySourcesQueue.push(function() {
  12502. // When a source is added and if this is FF, a new channel is allocated
  12503. // for receiving the added source. We need to diffuse the SSRC of this
  12504. // new recvonly channel to the rest of the peers.
  12505. console.log('modify sources done');
  12506. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12507. console.log("SDPs", mySdp, newSdp);
  12508. self.notifyMySSRCUpdate(mySdp, newSdp);
  12509. });
  12510. };
  12511. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  12512. var self = this;
  12513. // FIXME: dirty waiting
  12514. if (!this.peerconnection.localDescription)
  12515. {
  12516. console.warn("removeSource - localDescription not ready yet")
  12517. setTimeout(function()
  12518. {
  12519. self.removeSource(elem, fromJid);
  12520. },
  12521. 200
  12522. );
  12523. return;
  12524. }
  12525. console.log('removessrc', new Date().getTime());
  12526. console.log('ice', this.peerconnection.iceConnectionState);
  12527. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12528. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12529. $(elem).each(function (idx, content) {
  12530. var name = $(content).attr('name');
  12531. var lines = '';
  12532. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12533. var semantics = this.getAttribute('semantics');
  12534. var ssrcs = $(this).find('>source').map(function () {
  12535. return this.getAttribute('ssrc');
  12536. }).get();
  12537. if (ssrcs.length != 0) {
  12538. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12539. }
  12540. });
  12541. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12542. tmp.each(function () {
  12543. var ssrc = $(this).attr('ssrc');
  12544. // This should never happen, but can be useful for bug detection
  12545. if(mySdp.containsSSRC(ssrc)){
  12546. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12547. return;
  12548. }
  12549. $(this).find('>parameter').each(function () {
  12550. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12551. if ($(this).attr('value') && $(this).attr('value').length)
  12552. lines += ':' + $(this).attr('value');
  12553. lines += '\r\n';
  12554. });
  12555. });
  12556. sdp.media.forEach(function(media, idx) {
  12557. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12558. return;
  12559. sdp.media[idx] += lines;
  12560. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12561. self.removessrc[idx] += lines;
  12562. });
  12563. sdp.raw = sdp.session + sdp.media.join('');
  12564. });
  12565. this.modifySourcesQueue.push(function() {
  12566. // When a source is removed and if this is FF, the recvonly channel that
  12567. // receives the remote stream is deactivated . We need to diffuse the
  12568. // recvonly SSRC removal to the rest of the peers.
  12569. console.log('modify sources done');
  12570. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12571. console.log("SDPs", mySdp, newSdp);
  12572. self.notifyMySSRCUpdate(mySdp, newSdp);
  12573. });
  12574. };
  12575. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  12576. var self = this;
  12577. if (this.peerconnection.signalingState == 'closed') return;
  12578. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12579. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12580. this.setLocalDescription();
  12581. if(successCallback){
  12582. successCallback();
  12583. }
  12584. queueCallback();
  12585. return;
  12586. }
  12587. // Reset switch streams flag
  12588. this.switchstreams = false;
  12589. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12590. // add sources
  12591. this.addssrc.forEach(function(lines, idx) {
  12592. sdp.media[idx] += lines;
  12593. });
  12594. this.addssrc = [];
  12595. // remove sources
  12596. this.removessrc.forEach(function(lines, idx) {
  12597. lines = lines.split('\r\n');
  12598. lines.pop(); // remove empty last element;
  12599. lines.forEach(function(line) {
  12600. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12601. });
  12602. });
  12603. this.removessrc = [];
  12604. sdp.raw = sdp.session + sdp.media.join('');
  12605. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12606. function() {
  12607. if(self.signalingState == 'closed') {
  12608. console.error("createAnswer attempt on closed state");
  12609. queueCallback("createAnswer attempt on closed state");
  12610. return;
  12611. }
  12612. self.peerconnection.createAnswer(
  12613. function(modifiedAnswer) {
  12614. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12615. if (self.pendingop !== null) {
  12616. var sdp = new SDP(modifiedAnswer.sdp);
  12617. if (sdp.media.length > 1) {
  12618. switch(self.pendingop) {
  12619. case 'mute':
  12620. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12621. break;
  12622. case 'unmute':
  12623. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12624. break;
  12625. }
  12626. sdp.raw = sdp.session + sdp.media.join('');
  12627. modifiedAnswer.sdp = sdp.raw;
  12628. }
  12629. self.pendingop = null;
  12630. }
  12631. // FIXME: pushing down an answer while ice connection state
  12632. // is still checking is bad...
  12633. //console.log(self.peerconnection.iceConnectionState);
  12634. // trying to work around another chrome bug
  12635. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12636. self.peerconnection.setLocalDescription(modifiedAnswer,
  12637. function() {
  12638. //console.log('modified setLocalDescription ok');
  12639. self.setLocalDescription();
  12640. if(successCallback){
  12641. successCallback();
  12642. }
  12643. queueCallback();
  12644. },
  12645. function(error) {
  12646. console.error('modified setLocalDescription failed', error);
  12647. queueCallback(error);
  12648. }
  12649. );
  12650. },
  12651. function(error) {
  12652. console.error('modified answer failed', error);
  12653. queueCallback(error);
  12654. }
  12655. );
  12656. },
  12657. function(error) {
  12658. console.error('modify failed', error);
  12659. queueCallback(error);
  12660. }
  12661. );
  12662. };
  12663. /**
  12664. * Switches video streams.
  12665. * @param new_stream new stream that will be used as video of this session.
  12666. * @param oldStream old video stream of this session.
  12667. * @param success_callback callback executed after successful stream switch.
  12668. */
  12669. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12670. var self = this;
  12671. // Remember SDP to figure out added/removed SSRCs
  12672. var oldSdp = null;
  12673. if(self.peerconnection) {
  12674. if(self.peerconnection.localDescription) {
  12675. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12676. }
  12677. self.peerconnection.removeStream(oldStream, true);
  12678. if(new_stream)
  12679. self.peerconnection.addStream(new_stream);
  12680. }
  12681. // Conference is not active
  12682. if(!oldSdp || !self.peerconnection) {
  12683. success_callback();
  12684. return;
  12685. }
  12686. self.switchstreams = true;
  12687. self.modifySourcesQueue.push(function() {
  12688. console.log('modify sources done');
  12689. success_callback();
  12690. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12691. console.log("SDPs", oldSdp, newSdp);
  12692. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12693. });
  12694. };
  12695. /**
  12696. * Figures out added/removed ssrcs and send update IQs.
  12697. * @param old_sdp SDP object for old description.
  12698. * @param new_sdp SDP object for new description.
  12699. */
  12700. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12701. if (!(this.peerconnection.signalingState == 'stable' &&
  12702. this.peerconnection.iceConnectionState == 'connected')){
  12703. console.log("Too early to send updates");
  12704. return;
  12705. }
  12706. // send source-remove IQ.
  12707. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12708. var remove = $iq({to: this.peerjid, type: 'set'})
  12709. .c('jingle', {
  12710. xmlns: 'urn:xmpp:jingle:1',
  12711. action: 'source-remove',
  12712. initiator: this.initiator,
  12713. sid: this.sid
  12714. }
  12715. );
  12716. var removed = sdpDiffer.toJingle(remove);
  12717. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  12718. // it in the current form
  12719. if (removed)
  12720. remove = SSRCReplacement.processSourceRemove(remove);
  12721. if (removed && remove) {
  12722. console.info("Sending source-remove", remove);
  12723. this.connection.sendIQ(remove,
  12724. function (res) {
  12725. console.info('got remove result', res);
  12726. },
  12727. function (err) {
  12728. console.error('got remove error', err);
  12729. }
  12730. );
  12731. } else {
  12732. console.log('removal not necessary');
  12733. }
  12734. // send source-add IQ.
  12735. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12736. var add = $iq({to: this.peerjid, type: 'set'})
  12737. .c('jingle', {
  12738. xmlns: 'urn:xmpp:jingle:1',
  12739. action: 'source-add',
  12740. initiator: this.initiator,
  12741. sid: this.sid
  12742. }
  12743. );
  12744. var added = sdpDiffer.toJingle(add);
  12745. // Let 'source-add' IQ through the hack and see if we're allowed to send
  12746. // it in the current form
  12747. if (added)
  12748. add = SSRCReplacement.processSourceAdd(add);
  12749. if (added && add) {
  12750. console.info("Sending source-add", add);
  12751. this.connection.sendIQ(add,
  12752. function (res) {
  12753. console.info('got add result', res);
  12754. },
  12755. function (err) {
  12756. console.error('got add error', err);
  12757. }
  12758. );
  12759. } else {
  12760. console.log('addition not necessary');
  12761. }
  12762. };
  12763. /**
  12764. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12765. *
  12766. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12767. * tracks; otherwise, <tt>false</tt>
  12768. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12769. * tracks have been enabled/disabled. The function may, optionally, return
  12770. * another function which is to be invoked after the whole mute/unmute operation
  12771. * has completed successfully.
  12772. * @param options an object which specifies optional arguments such as the
  12773. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12774. * specifies whether the method was initiated in response to a user command (in
  12775. * contrast to an automatic decision made by the application logic)
  12776. */
  12777. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  12778. var byUser;
  12779. if (options) {
  12780. byUser = options.byUser;
  12781. if (typeof byUser === 'undefined') {
  12782. byUser = true;
  12783. }
  12784. } else {
  12785. byUser = true;
  12786. }
  12787. // The user's command to mute the (local) video takes precedence over any
  12788. // automatic decision made by the application logic.
  12789. if (byUser) {
  12790. this.videoMuteByUser = mute;
  12791. } else if (this.videoMuteByUser) {
  12792. return;
  12793. }
  12794. this.hardMuteVideo(mute);
  12795. var self = this;
  12796. var oldSdp = null;
  12797. if(self.peerconnection) {
  12798. if(self.peerconnection.localDescription) {
  12799. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12800. }
  12801. }
  12802. this.modifySourcesQueue.push(function() {
  12803. console.log('modify sources done');
  12804. callback(mute);
  12805. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12806. console.log("SDPs", oldSdp, newSdp);
  12807. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12808. });
  12809. };
  12810. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  12811. this.pendingop = muted ? 'mute' : 'unmute';
  12812. };
  12813. JingleSessionPC.prototype.sendMute = function (muted, content) {
  12814. var info = $iq({to: this.peerjid,
  12815. type: 'set'})
  12816. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12817. action: 'session-info',
  12818. initiator: this.initiator,
  12819. sid: this.sid });
  12820. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12821. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12822. if (content) {
  12823. info.attrs({'name': content});
  12824. }
  12825. this.connection.send(info);
  12826. };
  12827. JingleSessionPC.prototype.sendRinging = function () {
  12828. var info = $iq({to: this.peerjid,
  12829. type: 'set'})
  12830. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12831. action: 'session-info',
  12832. initiator: this.initiator,
  12833. sid: this.sid });
  12834. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12835. this.connection.send(info);
  12836. };
  12837. JingleSessionPC.prototype.getStats = function (interval) {
  12838. var self = this;
  12839. var recv = {audio: 0, video: 0};
  12840. var lost = {audio: 0, video: 0};
  12841. var lastrecv = {audio: 0, video: 0};
  12842. var lastlost = {audio: 0, video: 0};
  12843. var loss = {audio: 0, video: 0};
  12844. var delta = {audio: 0, video: 0};
  12845. this.statsinterval = window.setInterval(function () {
  12846. if (self && self.peerconnection && self.peerconnection.getStats) {
  12847. self.peerconnection.getStats(function (stats) {
  12848. var results = stats.result();
  12849. // TODO: there are so much statistics you can get from this..
  12850. for (var i = 0; i < results.length; ++i) {
  12851. if (results[i].type == 'ssrc') {
  12852. var packetsrecv = results[i].stat('packetsReceived');
  12853. var packetslost = results[i].stat('packetsLost');
  12854. if (packetsrecv && packetslost) {
  12855. packetsrecv = parseInt(packetsrecv, 10);
  12856. packetslost = parseInt(packetslost, 10);
  12857. if (results[i].stat('googFrameRateReceived')) {
  12858. lastlost.video = lost.video;
  12859. lastrecv.video = recv.video;
  12860. recv.video = packetsrecv;
  12861. lost.video = packetslost;
  12862. } else {
  12863. lastlost.audio = lost.audio;
  12864. lastrecv.audio = recv.audio;
  12865. recv.audio = packetsrecv;
  12866. lost.audio = packetslost;
  12867. }
  12868. }
  12869. }
  12870. }
  12871. delta.audio = recv.audio - lastrecv.audio;
  12872. delta.video = recv.video - lastrecv.video;
  12873. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12874. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12875. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12876. });
  12877. }
  12878. }, interval || 3000);
  12879. return this.statsinterval;
  12880. };
  12881. JingleSessionPC.onJingleError = function (session, error)
  12882. {
  12883. console.error("Jingle error", error);
  12884. }
  12885. JingleSessionPC.onJingleFatalError = function (session, error)
  12886. {
  12887. this.service.sessionTerminated = true;
  12888. this.connection.emuc.doLeave();
  12889. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12890. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12891. }
  12892. JingleSessionPC.prototype.setLocalDescription = function () {
  12893. var self = this;
  12894. var newssrcs = [];
  12895. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12896. session.media.forEach(function (media) {
  12897. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12898. // TODO(gp) maybe exclude FID streams?
  12899. media.ssrcs.forEach(function (ssrc) {
  12900. if (ssrc.attribute !== 'cname') {
  12901. return;
  12902. }
  12903. newssrcs.push({
  12904. 'ssrc': ssrc.id,
  12905. 'type': media.type
  12906. });
  12907. });
  12908. }
  12909. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12910. {
  12911. newssrcs.push({
  12912. 'ssrc': self.localStreamsSSRC[media.type],
  12913. 'type': media.type
  12914. });
  12915. }
  12916. });
  12917. console.log('new ssrcs', newssrcs);
  12918. // Bind us as local SSRCs owner
  12919. if (newssrcs.length > 0) {
  12920. for (var i = 1; i <= newssrcs.length; i ++) {
  12921. var ssrc = newssrcs[i-1].ssrc;
  12922. var myJid = self.connection.emuc.myroomjid;
  12923. self.ssrcOwners[ssrc] = myJid;
  12924. }
  12925. }
  12926. }
  12927. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12928. function sendKeyframe(pc) {
  12929. console.log('sendkeyframe', pc.iceConnectionState);
  12930. if (pc.iceConnectionState !== 'connected') return; // safe...
  12931. var self = this;
  12932. pc.setRemoteDescription(
  12933. pc.remoteDescription,
  12934. function () {
  12935. pc.createAnswer(
  12936. function (modifiedAnswer) {
  12937. pc.setLocalDescription(
  12938. modifiedAnswer,
  12939. function () {
  12940. // noop
  12941. },
  12942. function (error) {
  12943. console.log('triggerKeyframe setLocalDescription failed', error);
  12944. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  12945. }
  12946. );
  12947. },
  12948. function (error) {
  12949. console.log('triggerKeyframe createAnswer failed', error);
  12950. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  12951. }
  12952. );
  12953. },
  12954. function (error) {
  12955. console.log('triggerKeyframe setRemoteDescription failed', error);
  12956. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  12957. }
  12958. );
  12959. }
  12960. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  12961. var self = this;
  12962. var thessrc;
  12963. var streamId = APP.RTC.getStreamID(data.stream);
  12964. // look up an associated JID for a stream id
  12965. if (!streamId) {
  12966. console.error("No stream ID for", data.stream);
  12967. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12968. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12969. var ssrclines
  12970. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12971. ssrclines = ssrclines.filter(function (line) {
  12972. // NOTE(gp) previously we filtered on the mslabel, but that property
  12973. // is not always present.
  12974. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12975. if (RTCBrowserType.isTemasysPluginUsed()) {
  12976. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12977. } else {
  12978. return ((line.indexOf('msid:' + streamId) !== -1));
  12979. }
  12980. });
  12981. if (ssrclines.length) {
  12982. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12983. if (!self.ssrcOwners[thessrc]) {
  12984. console.error("No SSRC owner known for: " + thessrc);
  12985. return;
  12986. }
  12987. data.peerjid = self.ssrcOwners[thessrc];
  12988. console.log('associated jid', self.ssrcOwners[thessrc]);
  12989. } else {
  12990. console.error("No SSRC lines for ", streamId);
  12991. }
  12992. }
  12993. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12994. var isVideo = data.stream.getVideoTracks().length > 0;
  12995. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12996. if (isVideo &&
  12997. data.peerjid && this.peerjid === data.peerjid &&
  12998. data.stream.getVideoTracks().length === 0 &&
  12999. APP.RTC.localVideo.getTracks().length > 0) {
  13000. window.setTimeout(function () {
  13001. sendKeyframe(self.peerconnection);
  13002. }, 3000);
  13003. }
  13004. }
  13005. module.exports = JingleSessionPC;
  13006. },{"../../service/xmpp/XMPPEvents":161,"../RTC/RTCBrowserType":8,"./JingleSession":53,"./LocalSSRCReplacement":55,"./SDP":56,"./SDPDiffer":57,"./SDPUtil":58,"./TraceablePeerConnection":59,"async":69,"sdp-transform":98}],55:[function(require,module,exports){
  13007. /* global $ */
  13008. /*
  13009. Here we do modifications of local video SSRCs. There are 2 situations we have
  13010. to handle:
  13011. 1. We generate SSRC for local recvonly video stream. This is the case when we
  13012. have no local camera and it is not generated automatically, but SSRC=1 is
  13013. used implicitly. If that happens RTCP packets will be dropped by the JVB
  13014. and we won't be able to request video key frames correctly.
  13015. 2. A hack to re-use SSRC of the first video stream for any new stream created
  13016. in future. It turned out that Chrome may keep on using the SSRC of removed
  13017. video stream in RTCP even though a new one has been created. So we just
  13018. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  13019. notifications are blocked once first video SSRC is advertised to the focus.
  13020. What this hack does:
  13021. 1. Stores the SSRC of the first video stream created by
  13022. a) scanning Jingle session-accept/session-invite for existing video SSRC
  13023. b) watching for 'source-add' for new video stream if it has not been
  13024. created in step a)
  13025. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  13026. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  13027. returned to the other parts of the application.
  13028. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  13029. blocks those notifications. This makes Jicofo and all participants think
  13030. that it exists all the time even if the video stream has been removed or
  13031. replaced locally. Thanks to that there is no additional signaling activity
  13032. on video mute or when switching to the desktop stream.
  13033. */
  13034. var SDP = require('./SDP');
  13035. var RTCBrowserType = require('../RTC/RTCBrowserType');
  13036. /**
  13037. * The hack is enabled on all browsers except FF by default
  13038. * FIXME finish the hack once removeStream method is implemented in FF
  13039. * @type {boolean}
  13040. */
  13041. var isEnabled = !RTCBrowserType.isFirefox();
  13042. /**
  13043. * Stored SSRC of local video stream.
  13044. */
  13045. var localVideoSSRC;
  13046. /**
  13047. * SSRC used for recvonly video stream when we have no local camera.
  13048. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  13049. * instead of 1.
  13050. */
  13051. var localRecvOnlySSRC;
  13052. /**
  13053. * cname for <tt>localRecvOnlySSRC</tt>
  13054. */
  13055. var localRecvOnlyCName;
  13056. /**
  13057. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  13058. * from given Jingle IQ.
  13059. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  13060. * @param actionName display name of the action which will be printed in log
  13061. * messages.
  13062. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  13063. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  13064. * other SSRCs left to be signaled after removing it.
  13065. */
  13066. var filterOutSource = function (modifyIq, actionName) {
  13067. var modifyIqTree = $(modifyIq.tree());
  13068. if (!localVideoSSRC)
  13069. return modifyIqTree[0];
  13070. var videoSSRC = modifyIqTree.find(
  13071. '>jingle>content[name="video"]' +
  13072. '>description>source[ssrc="' + localVideoSSRC + '"]');
  13073. if (!videoSSRC.length) {
  13074. return modifyIqTree[0];
  13075. }
  13076. console.info(
  13077. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  13078. videoSSRC.remove();
  13079. // Check if any sources still left to be added/removed
  13080. if (modifyIqTree.find('>jingle>content>description>source').length) {
  13081. return modifyIqTree[0];
  13082. } else {
  13083. return null;
  13084. }
  13085. };
  13086. /**
  13087. * Scans given Jingle IQ for video SSRC and stores it.
  13088. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  13089. */
  13090. var storeLocalVideoSSRC = function (jingleIq) {
  13091. var videoSSRCs =
  13092. $(jingleIq.tree())
  13093. .find('>jingle>content[name="video"]>description>source');
  13094. videoSSRCs.each(function (idx, ssrcElem) {
  13095. if (localVideoSSRC)
  13096. return;
  13097. // We consider SSRC real only if it has msid attribute
  13098. // recvonly streams in FF do not have it as well as local SSRCs
  13099. // we generate for recvonly streams in Chrome
  13100. var ssrSel = $(ssrcElem);
  13101. var msid = ssrSel.find('>parameter[name="msid"]');
  13102. if (msid.length) {
  13103. var ssrcVal = ssrSel.attr('ssrc');
  13104. if (ssrcVal) {
  13105. localVideoSSRC = ssrcVal;
  13106. console.info('Stored local video SSRC' +
  13107. ' for future re-use: ' + localVideoSSRC);
  13108. }
  13109. }
  13110. });
  13111. };
  13112. /**
  13113. * Generates new SSRC for local video recvonly stream.
  13114. * FIXME what about eventual SSRC collision ?
  13115. */
  13116. function generateRecvonlySSRC() {
  13117. //
  13118. localRecvOnlySSRC =
  13119. Math.random().toString(10).substring(2, 11);
  13120. localRecvOnlyCName =
  13121. Math.random().toString(36).substring(2);
  13122. console.info(
  13123. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  13124. ", cname: " + localRecvOnlyCName);
  13125. }
  13126. var LocalSSRCReplacement = {
  13127. /**
  13128. * Method must be called before 'session-initiate' or 'session-invite' is
  13129. * sent. Scans the IQ for local video SSRC and stores it if detected.
  13130. *
  13131. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  13132. * which will be scanned for local video SSRC.
  13133. */
  13134. processSessionInit: function (sessionInit) {
  13135. if (!isEnabled)
  13136. return;
  13137. if (localVideoSSRC) {
  13138. console.error("Local SSRC stored already: " + localVideoSSRC);
  13139. return;
  13140. }
  13141. storeLocalVideoSSRC(sessionInit);
  13142. },
  13143. /**
  13144. * If we have local video SSRC stored searched given
  13145. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  13146. * with the stored one.
  13147. * @param localDescription local description object that will have local
  13148. * video SSRC replaced with the stored one
  13149. * @returns modified <tt>localDescription</tt> object.
  13150. */
  13151. mungeLocalVideoSSRC: function (localDescription) {
  13152. if (!isEnabled)
  13153. return localDescription;
  13154. if (!localDescription) {
  13155. console.warn("localDescription is null or undefined");
  13156. return localDescription;
  13157. }
  13158. // IF we have local video SSRC stored make sure it is replaced
  13159. // with old SSRC
  13160. if (localVideoSSRC) {
  13161. var newSdp = new SDP(localDescription.sdp);
  13162. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  13163. !newSdp.containsSSRC(localVideoSSRC)) {
  13164. // Get new video SSRC
  13165. var map = newSdp.getMediaSsrcMap();
  13166. var videoPart = map[1];
  13167. var videoSSRCs = videoPart.ssrcs;
  13168. var newSSRC = Object.keys(videoSSRCs)[0];
  13169. console.info(
  13170. "Replacing new video SSRC: " + newSSRC +
  13171. " with " + localVideoSSRC);
  13172. localDescription.sdp =
  13173. newSdp.raw.replace(
  13174. new RegExp('a=ssrc:' + newSSRC, 'g'),
  13175. 'a=ssrc:' + localVideoSSRC);
  13176. }
  13177. } else {
  13178. // Make sure we have any SSRC for recvonly video stream
  13179. var sdp = new SDP(localDescription.sdp);
  13180. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  13181. sdp.media[1].indexOf('a=recvonly') !== -1) {
  13182. if (!localRecvOnlySSRC) {
  13183. generateRecvonlySSRC();
  13184. }
  13185. console.info('No SSRC in video recvonly stream' +
  13186. ' - adding SSRC: ' + localRecvOnlySSRC);
  13187. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  13188. ' cname:' + localRecvOnlyCName + '\r\n';
  13189. localDescription.sdp = sdp.session + sdp.media.join('');
  13190. }
  13191. }
  13192. return localDescription;
  13193. },
  13194. /**
  13195. * Method must be called before 'source-add' notification is sent. In case
  13196. * we have local video SSRC advertised already it will be removed from the
  13197. * notification. If no other SSRCs are described by given IQ null will be
  13198. * returned which means that there is no point in sending the notification.
  13199. * @param sourceAdd 'source-add' Jingle IQ to be processed
  13200. * @returns modified 'source-add' IQ which can be sent to the focus or
  13201. * <tt>null</tt> if no notification shall be sent. It is no longer
  13202. * a Strophe IQ Builder instance, but DOM element tree.
  13203. */
  13204. processSourceAdd: function (sourceAdd) {
  13205. if (!isEnabled)
  13206. return sourceAdd;
  13207. if (!localVideoSSRC) {
  13208. // Store local SSRC if available
  13209. storeLocalVideoSSRC(sourceAdd);
  13210. return sourceAdd;
  13211. } else {
  13212. return filterOutSource(sourceAdd, 'source-add');
  13213. }
  13214. },
  13215. /**
  13216. * Method must be called before 'source-remove' notification is sent.
  13217. * Removes local video SSRC from the notification. If there are no other
  13218. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  13219. * means that there is no point in sending the notification.
  13220. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  13221. * @returns modified 'source-remove' IQ which can be sent to the focus or
  13222. * <tt>null</tt> if no notification shall be sent. It is no longer
  13223. * a Strophe IQ Builder instance, but DOM element tree.
  13224. */
  13225. processSourceRemove: function (sourceRemove) {
  13226. if (!isEnabled)
  13227. return sourceRemove;
  13228. return filterOutSource(sourceRemove, 'source-remove');
  13229. },
  13230. /**
  13231. * Turns the hack on or off
  13232. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  13233. * to disable it
  13234. */
  13235. setEnabled: function (enabled) {
  13236. isEnabled = enabled;
  13237. }
  13238. };
  13239. module.exports = LocalSSRCReplacement;
  13240. },{"../RTC/RTCBrowserType":8,"./SDP":56}],56:[function(require,module,exports){
  13241. /* jshint -W117 */
  13242. var SDPUtil = require("./SDPUtil");
  13243. // SDP STUFF
  13244. function SDP(sdp) {
  13245. this.media = sdp.split('\r\nm=');
  13246. for (var i = 1; i < this.media.length; i++) {
  13247. this.media[i] = 'm=' + this.media[i];
  13248. if (i != this.media.length - 1) {
  13249. this.media[i] += '\r\n';
  13250. }
  13251. }
  13252. this.session = this.media.shift() + '\r\n';
  13253. this.raw = this.session + this.media.join('');
  13254. }
  13255. /**
  13256. * Returns map of MediaChannel mapped per channel idx.
  13257. */
  13258. SDP.prototype.getMediaSsrcMap = function() {
  13259. var self = this;
  13260. var media_ssrcs = {};
  13261. var tmp;
  13262. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13263. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13264. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13265. var media = {
  13266. mediaindex: mediaindex,
  13267. mid: mid,
  13268. ssrcs: {},
  13269. ssrcGroups: []
  13270. };
  13271. media_ssrcs[mediaindex] = media;
  13272. tmp.forEach(function (line) {
  13273. var linessrc = line.substring(7).split(' ')[0];
  13274. // allocate new ChannelSsrc
  13275. if(!media.ssrcs[linessrc]) {
  13276. media.ssrcs[linessrc] = {
  13277. ssrc: linessrc,
  13278. lines: []
  13279. };
  13280. }
  13281. media.ssrcs[linessrc].lines.push(line);
  13282. });
  13283. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13284. tmp.forEach(function(line){
  13285. var semantics = line.substr(0, idx).substr(13);
  13286. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13287. if (ssrcs.length != 0) {
  13288. media.ssrcGroups.push({
  13289. semantics: semantics,
  13290. ssrcs: ssrcs
  13291. });
  13292. }
  13293. });
  13294. }
  13295. return media_ssrcs;
  13296. };
  13297. /**
  13298. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13299. * @param ssrc the ssrc to check.
  13300. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13301. */
  13302. SDP.prototype.containsSSRC = function(ssrc) {
  13303. var medias = this.getMediaSsrcMap();
  13304. var contains = false;
  13305. Object.keys(medias).forEach(function(mediaindex){
  13306. var media = medias[mediaindex];
  13307. //console.log("Check", channel, ssrc);
  13308. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13309. contains = true;
  13310. }
  13311. });
  13312. return contains;
  13313. };
  13314. // remove iSAC and CN from SDP
  13315. SDP.prototype.mangle = function () {
  13316. var i, j, mline, lines, rtpmap, newdesc;
  13317. for (i = 0; i < this.media.length; i++) {
  13318. lines = this.media[i].split('\r\n');
  13319. lines.pop(); // remove empty last element
  13320. mline = SDPUtil.parse_mline(lines.shift());
  13321. if (mline.media != 'audio')
  13322. continue;
  13323. newdesc = '';
  13324. mline.fmt.length = 0;
  13325. for (j = 0; j < lines.length; j++) {
  13326. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13327. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13328. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13329. continue;
  13330. mline.fmt.push(rtpmap.id);
  13331. newdesc += lines[j] + '\r\n';
  13332. } else {
  13333. newdesc += lines[j] + '\r\n';
  13334. }
  13335. }
  13336. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13337. this.media[i] += newdesc;
  13338. }
  13339. this.raw = this.session + this.media.join('');
  13340. };
  13341. // remove lines matching prefix from session section
  13342. SDP.prototype.removeSessionLines = function(prefix) {
  13343. var self = this;
  13344. var lines = SDPUtil.find_lines(this.session, prefix);
  13345. lines.forEach(function(line) {
  13346. self.session = self.session.replace(line + '\r\n', '');
  13347. });
  13348. this.raw = this.session + this.media.join('');
  13349. return lines;
  13350. }
  13351. // remove lines matching prefix from a media section specified by mediaindex
  13352. // TODO: non-numeric mediaindex could match mid
  13353. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13354. var self = this;
  13355. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13356. lines.forEach(function(line) {
  13357. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13358. });
  13359. this.raw = this.session + this.media.join('');
  13360. return lines;
  13361. }
  13362. // add content's to a jingle element
  13363. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13364. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13365. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13366. var self = this;
  13367. // new bundle plan
  13368. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13369. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13370. for (i = 0; i < lines.length; i++) {
  13371. tmp = lines[i].split(' ');
  13372. var semantics = tmp.shift().substr(8);
  13373. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13374. for (j = 0; j < tmp.length; j++) {
  13375. elem.c('content', {name: tmp[j]}).up();
  13376. }
  13377. elem.up();
  13378. }
  13379. }
  13380. for (i = 0; i < this.media.length; i++) {
  13381. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13382. if (!(mline.media === 'audio' ||
  13383. mline.media === 'video' ||
  13384. mline.media === 'application'))
  13385. {
  13386. continue;
  13387. }
  13388. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13389. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13390. } else {
  13391. if(ssrcs && ssrcs[mline.media])
  13392. {
  13393. ssrc = ssrcs[mline.media];
  13394. }
  13395. else
  13396. ssrc = false;
  13397. }
  13398. elem.c('content', {creator: thecreator, name: mline.media});
  13399. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13400. // prefer identifier from a=mid if present
  13401. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13402. elem.attrs({ name: mid });
  13403. }
  13404. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13405. {
  13406. elem.c('description',
  13407. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13408. media: mline.media });
  13409. if (ssrc) {
  13410. elem.attrs({ssrc: ssrc});
  13411. }
  13412. for (j = 0; j < mline.fmt.length; j++) {
  13413. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13414. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13415. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13416. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13417. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13418. for (k = 0; k < tmp.length; k++) {
  13419. elem.c('parameter', tmp[k]).up();
  13420. }
  13421. }
  13422. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13423. elem.up();
  13424. }
  13425. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13426. elem.c('encryption', {required: 1});
  13427. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13428. crypto.forEach(function(line) {
  13429. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13430. });
  13431. elem.up(); // end of encryption
  13432. }
  13433. if (ssrc) {
  13434. // new style mapping
  13435. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13436. // FIXME: group by ssrc and support multiple different ssrcs
  13437. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13438. if(ssrclines.length > 0) {
  13439. ssrclines.forEach(function (line) {
  13440. idx = line.indexOf(' ');
  13441. var linessrc = line.substr(0, idx).substr(7);
  13442. if (linessrc != ssrc) {
  13443. elem.up();
  13444. ssrc = linessrc;
  13445. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13446. }
  13447. var kv = line.substr(idx + 1);
  13448. elem.c('parameter');
  13449. if (kv.indexOf(':') == -1) {
  13450. elem.attrs({ name: kv });
  13451. } else {
  13452. var k = kv.split(':', 2)[0];
  13453. elem.attrs({ name: k });
  13454. var v = kv.split(':', 2)[1];
  13455. v = SDPUtil.filter_special_chars(v);
  13456. elem.attrs({ value: v });
  13457. }
  13458. elem.up();
  13459. });
  13460. }
  13461. else
  13462. {
  13463. elem.up();
  13464. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13465. elem.c('parameter');
  13466. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13467. elem.up();
  13468. var msid = null;
  13469. if(mline.media == "audio")
  13470. {
  13471. msid = APP.RTC.localAudio.getId();
  13472. }
  13473. else
  13474. {
  13475. msid = APP.RTC.localVideo.getId();
  13476. }
  13477. if(msid != null)
  13478. {
  13479. msid = SDPUtil.filter_special_chars(msid);
  13480. elem.c('parameter');
  13481. elem.attrs({name: "msid", value:msid});
  13482. elem.up();
  13483. elem.c('parameter');
  13484. elem.attrs({name: "mslabel", value:msid});
  13485. elem.up();
  13486. elem.c('parameter');
  13487. elem.attrs({name: "label", value:msid});
  13488. elem.up();
  13489. }
  13490. }
  13491. elem.up();
  13492. // XEP-0339 handle ssrc-group attributes
  13493. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13494. ssrc_group_lines.forEach(function(line) {
  13495. idx = line.indexOf(' ');
  13496. var semantics = line.substr(0, idx).substr(13);
  13497. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13498. if (ssrcs.length != 0) {
  13499. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13500. ssrcs.forEach(function(ssrc) {
  13501. elem.c('source', { ssrc: ssrc })
  13502. .up();
  13503. });
  13504. elem.up();
  13505. }
  13506. });
  13507. }
  13508. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13509. elem.c('rtcp-mux').up();
  13510. }
  13511. // XEP-0293 -- map a=rtcp-fb:*
  13512. this.RtcpFbToJingle(i, elem, '*');
  13513. // XEP-0294
  13514. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13515. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13516. for (j = 0; j < lines.length; j++) {
  13517. tmp = SDPUtil.parse_extmap(lines[j]);
  13518. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13519. uri: tmp.uri,
  13520. id: tmp.value });
  13521. if (tmp.hasOwnProperty('direction')) {
  13522. switch (tmp.direction) {
  13523. case 'sendonly':
  13524. elem.attrs({senders: 'responder'});
  13525. break;
  13526. case 'recvonly':
  13527. elem.attrs({senders: 'initiator'});
  13528. break;
  13529. case 'sendrecv':
  13530. elem.attrs({senders: 'both'});
  13531. break;
  13532. case 'inactive':
  13533. elem.attrs({senders: 'none'});
  13534. break;
  13535. }
  13536. }
  13537. // TODO: handle params
  13538. elem.up();
  13539. }
  13540. }
  13541. elem.up(); // end of description
  13542. }
  13543. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13544. this.TransportToJingle(i, elem);
  13545. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13546. elem.attrs({senders: 'both'});
  13547. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13548. elem.attrs({senders: 'initiator'});
  13549. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13550. elem.attrs({senders: 'responder'});
  13551. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13552. elem.attrs({senders: 'none'});
  13553. }
  13554. if (mline.port == '0') {
  13555. // estos hack to reject an m-line
  13556. elem.attrs({senders: 'rejected'});
  13557. }
  13558. elem.up(); // end of content
  13559. }
  13560. elem.up();
  13561. return elem;
  13562. };
  13563. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13564. var i = mediaindex;
  13565. var tmp;
  13566. var self = this;
  13567. elem.c('transport');
  13568. // XEP-0343 DTLS/SCTP
  13569. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13570. {
  13571. var sctpmap = SDPUtil.find_line(
  13572. this.media[i], 'a=sctpmap:', self.session);
  13573. if (sctpmap)
  13574. {
  13575. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13576. elem.c('sctpmap',
  13577. {
  13578. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13579. number: sctpAttrs[0], /* SCTP port */
  13580. protocol: sctpAttrs[1], /* protocol */
  13581. });
  13582. // Optional stream count attribute
  13583. if (sctpAttrs.length > 2)
  13584. elem.attrs({ streams: sctpAttrs[2]});
  13585. elem.up();
  13586. }
  13587. }
  13588. // XEP-0320
  13589. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13590. fingerprints.forEach(function(line) {
  13591. tmp = SDPUtil.parse_fingerprint(line);
  13592. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13593. elem.c('fingerprint').t(tmp.fingerprint);
  13594. delete tmp.fingerprint;
  13595. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13596. if (line) {
  13597. tmp.setup = line.substr(8);
  13598. }
  13599. elem.attrs(tmp);
  13600. elem.up(); // end of fingerprint
  13601. });
  13602. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13603. if (tmp) {
  13604. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13605. elem.attrs(tmp);
  13606. // XEP-0176
  13607. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13608. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13609. lines.forEach(function (line) {
  13610. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13611. });
  13612. }
  13613. }
  13614. elem.up(); // end of transport
  13615. }
  13616. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13617. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13618. lines.forEach(function (line) {
  13619. var tmp = SDPUtil.parse_rtcpfb(line);
  13620. if (tmp.type == 'trr-int') {
  13621. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13622. elem.up();
  13623. } else {
  13624. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13625. if (tmp.params.length > 0) {
  13626. elem.attrs({'subtype': tmp.params[0]});
  13627. }
  13628. elem.up();
  13629. }
  13630. });
  13631. };
  13632. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13633. var media = '';
  13634. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13635. if (tmp.length) {
  13636. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13637. if (tmp.attr('value')) {
  13638. media += tmp.attr('value');
  13639. } else {
  13640. media += '0';
  13641. }
  13642. media += '\r\n';
  13643. }
  13644. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13645. tmp.each(function () {
  13646. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13647. if ($(this).attr('subtype')) {
  13648. media += ' ' + $(this).attr('subtype');
  13649. }
  13650. media += '\r\n';
  13651. });
  13652. return media;
  13653. };
  13654. // construct an SDP from a jingle stanza
  13655. SDP.prototype.fromJingle = function (jingle) {
  13656. var self = this;
  13657. this.raw = 'v=0\r\n' +
  13658. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13659. 's=-\r\n' +
  13660. 't=0 0\r\n';
  13661. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13662. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13663. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13664. var contents = $(group).find('>content').map(function (idx, content) {
  13665. return content.getAttribute('name');
  13666. }).get();
  13667. if (contents.length > 0) {
  13668. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13669. }
  13670. });
  13671. }
  13672. this.session = this.raw;
  13673. jingle.find('>content').each(function () {
  13674. var m = self.jingle2media($(this));
  13675. self.media.push(m);
  13676. });
  13677. // reconstruct msid-semantic -- apparently not necessary
  13678. /*
  13679. var msid = SDPUtil.parse_ssrc(this.raw);
  13680. if (msid.hasOwnProperty('mslabel')) {
  13681. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13682. }
  13683. */
  13684. this.raw = this.session + this.media.join('');
  13685. };
  13686. // translate a jingle content element into an an SDP media part
  13687. SDP.prototype.jingle2media = function (content) {
  13688. var media = '',
  13689. desc = content.find('description'),
  13690. ssrc = desc.attr('ssrc'),
  13691. self = this,
  13692. tmp;
  13693. var sctp = content.find(
  13694. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13695. tmp = { media: desc.attr('media') };
  13696. tmp.port = '1';
  13697. if (content.attr('senders') == 'rejected') {
  13698. // estos hack to reject an m-line.
  13699. tmp.port = '0';
  13700. }
  13701. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13702. if (sctp.length)
  13703. tmp.proto = 'DTLS/SCTP';
  13704. else
  13705. tmp.proto = 'RTP/SAVPF';
  13706. } else {
  13707. tmp.proto = 'RTP/AVPF';
  13708. }
  13709. if (!sctp.length)
  13710. {
  13711. tmp.fmt = desc.find('payload-type').map(
  13712. function () { return this.getAttribute('id'); }).get();
  13713. media += SDPUtil.build_mline(tmp) + '\r\n';
  13714. }
  13715. else
  13716. {
  13717. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13718. media += 'a=sctpmap:' + sctp.attr('number') +
  13719. ' ' + sctp.attr('protocol');
  13720. var streamCount = sctp.attr('streams');
  13721. if (streamCount)
  13722. media += ' ' + streamCount + '\r\n';
  13723. else
  13724. media += '\r\n';
  13725. }
  13726. media += 'c=IN IP4 0.0.0.0\r\n';
  13727. if (!sctp.length)
  13728. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13729. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13730. if (tmp.length) {
  13731. if (tmp.attr('ufrag')) {
  13732. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13733. }
  13734. if (tmp.attr('pwd')) {
  13735. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13736. }
  13737. tmp.find('>fingerprint').each(function () {
  13738. // FIXME: check namespace at some point
  13739. media += 'a=fingerprint:' + this.getAttribute('hash');
  13740. media += ' ' + $(this).text();
  13741. media += '\r\n';
  13742. if (this.getAttribute('setup')) {
  13743. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13744. }
  13745. });
  13746. }
  13747. switch (content.attr('senders')) {
  13748. case 'initiator':
  13749. media += 'a=sendonly\r\n';
  13750. break;
  13751. case 'responder':
  13752. media += 'a=recvonly\r\n';
  13753. break;
  13754. case 'none':
  13755. media += 'a=inactive\r\n';
  13756. break;
  13757. case 'both':
  13758. media += 'a=sendrecv\r\n';
  13759. break;
  13760. }
  13761. media += 'a=mid:' + content.attr('name') + '\r\n';
  13762. // <description><rtcp-mux/></description>
  13763. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13764. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13765. if (desc.find('rtcp-mux').length) {
  13766. media += 'a=rtcp-mux\r\n';
  13767. }
  13768. if (desc.find('encryption').length) {
  13769. desc.find('encryption>crypto').each(function () {
  13770. media += 'a=crypto:' + this.getAttribute('tag');
  13771. media += ' ' + this.getAttribute('crypto-suite');
  13772. media += ' ' + this.getAttribute('key-params');
  13773. if (this.getAttribute('session-params')) {
  13774. media += ' ' + this.getAttribute('session-params');
  13775. }
  13776. media += '\r\n';
  13777. });
  13778. }
  13779. desc.find('payload-type').each(function () {
  13780. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13781. if ($(this).find('>parameter').length) {
  13782. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13783. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13784. media += '\r\n';
  13785. }
  13786. // xep-0293
  13787. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13788. });
  13789. // xep-0293
  13790. media += self.RtcpFbFromJingle(desc, '*');
  13791. // xep-0294
  13792. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13793. tmp.each(function () {
  13794. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13795. });
  13796. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13797. media += SDPUtil.candidateFromJingle(this);
  13798. });
  13799. // XEP-0339 handle ssrc-group attributes
  13800. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13801. var semantics = this.getAttribute('semantics');
  13802. var ssrcs = $(this).find('>source').map(function() {
  13803. return this.getAttribute('ssrc');
  13804. }).get();
  13805. if (ssrcs.length != 0) {
  13806. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13807. }
  13808. });
  13809. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13810. tmp.each(function () {
  13811. var ssrc = this.getAttribute('ssrc');
  13812. $(this).find('>parameter').each(function () {
  13813. var name = this.getAttribute('name');
  13814. var value = this.getAttribute('value');
  13815. value = SDPUtil.filter_special_chars(value);
  13816. media += 'a=ssrc:' + ssrc + ' ' + name;
  13817. if (value && value.length)
  13818. media += ':' + value;
  13819. media += '\r\n';
  13820. });
  13821. });
  13822. return media;
  13823. };
  13824. module.exports = SDP;
  13825. },{"./SDPUtil":58}],57:[function(require,module,exports){
  13826. var SDPUtil = require("./SDPUtil");
  13827. function SDPDiffer(mySDP, otherSDP) {
  13828. this.mySDP = mySDP;
  13829. this.otherSDP = otherSDP;
  13830. }
  13831. /**
  13832. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13833. * @param otherSdp the other SDP to check ssrc with.
  13834. */
  13835. SDPDiffer.prototype.getNewMedia = function() {
  13836. // this could be useful in Array.prototype.
  13837. function arrayEquals(array) {
  13838. // if the other array is a falsy value, return
  13839. if (!array)
  13840. return false;
  13841. // compare lengths - can save a lot of time
  13842. if (this.length != array.length)
  13843. return false;
  13844. for (var i = 0, l=this.length; i < l; i++) {
  13845. // Check if we have nested arrays
  13846. if (this[i] instanceof Array && array[i] instanceof Array) {
  13847. // recurse into the nested arrays
  13848. if (!this[i].equals(array[i]))
  13849. return false;
  13850. }
  13851. else if (this[i] != array[i]) {
  13852. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13853. return false;
  13854. }
  13855. }
  13856. return true;
  13857. }
  13858. var myMedias = this.mySDP.getMediaSsrcMap();
  13859. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13860. var newMedia = {};
  13861. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13862. var myMedia = myMedias[othersMediaIdx];
  13863. var othersMedia = othersMedias[othersMediaIdx];
  13864. if(!myMedia && othersMedia) {
  13865. // Add whole channel
  13866. newMedia[othersMediaIdx] = othersMedia;
  13867. return;
  13868. }
  13869. // Look for new ssrcs accross the channel
  13870. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13871. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13872. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13873. if(!newMedia[othersMediaIdx]){
  13874. newMedia[othersMediaIdx] = {
  13875. mediaindex: othersMedia.mediaindex,
  13876. mid: othersMedia.mid,
  13877. ssrcs: {},
  13878. ssrcGroups: []
  13879. };
  13880. }
  13881. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13882. }
  13883. });
  13884. // Look for new ssrc groups across the channels
  13885. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13886. // try to match the other ssrc-group with an ssrc-group of ours
  13887. var matched = false;
  13888. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13889. var mySsrcGroup = myMedia.ssrcGroups[i];
  13890. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13891. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13892. matched = true;
  13893. break;
  13894. }
  13895. }
  13896. if (!matched) {
  13897. // Allocate channel if we've found an ssrc-group that doesn't
  13898. // exist in our channel
  13899. if(!newMedia[othersMediaIdx]){
  13900. newMedia[othersMediaIdx] = {
  13901. mediaindex: othersMedia.mediaindex,
  13902. mid: othersMedia.mid,
  13903. ssrcs: {},
  13904. ssrcGroups: []
  13905. };
  13906. }
  13907. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13908. }
  13909. });
  13910. });
  13911. return newMedia;
  13912. };
  13913. /**
  13914. * Sends SSRC update IQ.
  13915. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13916. * @param sid session identifier that will be put into the IQ.
  13917. * @param initiator initiator identifier.
  13918. * @param toJid destination Jid
  13919. * @param isAdd indicates if this is remove or add operation.
  13920. */
  13921. SDPDiffer.prototype.toJingle = function(modify) {
  13922. var sdpMediaSsrcs = this.getNewMedia();
  13923. var self = this;
  13924. // FIXME: only announce video ssrcs since we mix audio and dont need
  13925. // the audio ssrcs therefore
  13926. var modified = false;
  13927. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13928. modified = true;
  13929. var media = sdpMediaSsrcs[mediaindex];
  13930. modify.c('content', {name: media.mid});
  13931. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13932. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13933. // generate sources from lines
  13934. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13935. var mediaSsrc = media.ssrcs[ssrcNum];
  13936. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13937. modify.attrs({ssrc: mediaSsrc.ssrc});
  13938. // iterate over ssrc lines
  13939. mediaSsrc.lines.forEach(function (line) {
  13940. var idx = line.indexOf(' ');
  13941. var kv = line.substr(idx + 1);
  13942. modify.c('parameter');
  13943. if (kv.indexOf(':') == -1) {
  13944. modify.attrs({ name: kv });
  13945. } else {
  13946. var nv = kv.split(':', 2);
  13947. var name = nv[0];
  13948. var value = SDPUtil.filter_special_chars(nv[1]);
  13949. modify.attrs({ name: name });
  13950. modify.attrs({ value: value });
  13951. }
  13952. modify.up(); // end of parameter
  13953. });
  13954. modify.up(); // end of source
  13955. });
  13956. // generate source groups from lines
  13957. media.ssrcGroups.forEach(function(ssrcGroup) {
  13958. if (ssrcGroup.ssrcs.length != 0) {
  13959. modify.c('ssrc-group', {
  13960. semantics: ssrcGroup.semantics,
  13961. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13962. });
  13963. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13964. modify.c('source', { ssrc: ssrc })
  13965. .up(); // end of source
  13966. });
  13967. modify.up(); // end of ssrc-group
  13968. }
  13969. });
  13970. modify.up(); // end of description
  13971. modify.up(); // end of content
  13972. });
  13973. return modified;
  13974. };
  13975. module.exports = SDPDiffer;
  13976. },{"./SDPUtil":58}],58:[function(require,module,exports){
  13977. SDPUtil = {
  13978. filter_special_chars: function (text) {
  13979. return text.replace(/[\\\/\{,\}\+]/g, "");
  13980. },
  13981. iceparams: function (mediadesc, sessiondesc) {
  13982. var data = null;
  13983. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13984. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13985. data = {
  13986. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13987. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13988. };
  13989. }
  13990. return data;
  13991. },
  13992. parse_iceufrag: function (line) {
  13993. return line.substring(12);
  13994. },
  13995. build_iceufrag: function (frag) {
  13996. return 'a=ice-ufrag:' + frag;
  13997. },
  13998. parse_icepwd: function (line) {
  13999. return line.substring(10);
  14000. },
  14001. build_icepwd: function (pwd) {
  14002. return 'a=ice-pwd:' + pwd;
  14003. },
  14004. parse_mid: function (line) {
  14005. return line.substring(6);
  14006. },
  14007. parse_mline: function (line) {
  14008. var parts = line.substring(2).split(' '),
  14009. data = {};
  14010. data.media = parts.shift();
  14011. data.port = parts.shift();
  14012. data.proto = parts.shift();
  14013. if (parts[parts.length - 1] === '') { // trailing whitespace
  14014. parts.pop();
  14015. }
  14016. data.fmt = parts;
  14017. return data;
  14018. },
  14019. build_mline: function (mline) {
  14020. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  14021. },
  14022. parse_rtpmap: function (line) {
  14023. var parts = line.substring(9).split(' '),
  14024. data = {};
  14025. data.id = parts.shift();
  14026. parts = parts[0].split('/');
  14027. data.name = parts.shift();
  14028. data.clockrate = parts.shift();
  14029. data.channels = parts.length ? parts.shift() : '1';
  14030. return data;
  14031. },
  14032. /**
  14033. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  14034. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  14035. * @returns [SCTP port number, protocol, streams]
  14036. */
  14037. parse_sctpmap: function (line)
  14038. {
  14039. var parts = line.substring(10).split(' ');
  14040. var sctpPort = parts[0];
  14041. var protocol = parts[1];
  14042. // Stream count is optional
  14043. var streamCount = parts.length > 2 ? parts[2] : null;
  14044. return [sctpPort, protocol, streamCount];// SCTP port
  14045. },
  14046. build_rtpmap: function (el) {
  14047. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  14048. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  14049. line += '/' + el.getAttribute('channels');
  14050. }
  14051. return line;
  14052. },
  14053. parse_crypto: function (line) {
  14054. var parts = line.substring(9).split(' '),
  14055. data = {};
  14056. data.tag = parts.shift();
  14057. data['crypto-suite'] = parts.shift();
  14058. data['key-params'] = parts.shift();
  14059. if (parts.length) {
  14060. data['session-params'] = parts.join(' ');
  14061. }
  14062. return data;
  14063. },
  14064. parse_fingerprint: function (line) { // RFC 4572
  14065. var parts = line.substring(14).split(' '),
  14066. data = {};
  14067. data.hash = parts.shift();
  14068. data.fingerprint = parts.shift();
  14069. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  14070. return data;
  14071. },
  14072. parse_fmtp: function (line) {
  14073. var parts = line.split(' '),
  14074. i, key, value,
  14075. data = [];
  14076. parts.shift();
  14077. parts = parts.join(' ').split(';');
  14078. for (i = 0; i < parts.length; i++) {
  14079. key = parts[i].split('=')[0];
  14080. while (key.length && key[0] == ' ') {
  14081. key = key.substring(1);
  14082. }
  14083. value = parts[i].split('=')[1];
  14084. if (key && value) {
  14085. data.push({name: key, value: value});
  14086. } else if (key) {
  14087. // rfc 4733 (DTMF) style stuff
  14088. data.push({name: '', value: key});
  14089. }
  14090. }
  14091. return data;
  14092. },
  14093. parse_icecandidate: function (line) {
  14094. var candidate = {},
  14095. elems = line.split(' ');
  14096. candidate.foundation = elems[0].substring(12);
  14097. candidate.component = elems[1];
  14098. candidate.protocol = elems[2].toLowerCase();
  14099. candidate.priority = elems[3];
  14100. candidate.ip = elems[4];
  14101. candidate.port = elems[5];
  14102. // elems[6] => "typ"
  14103. candidate.type = elems[7];
  14104. candidate.generation = 0; // default value, may be overwritten below
  14105. for (var i = 8; i < elems.length; i += 2) {
  14106. switch (elems[i]) {
  14107. case 'raddr':
  14108. candidate['rel-addr'] = elems[i + 1];
  14109. break;
  14110. case 'rport':
  14111. candidate['rel-port'] = elems[i + 1];
  14112. break;
  14113. case 'generation':
  14114. candidate.generation = elems[i + 1];
  14115. break;
  14116. case 'tcptype':
  14117. candidate.tcptype = elems[i + 1];
  14118. break;
  14119. default: // TODO
  14120. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14121. }
  14122. }
  14123. candidate.network = '1';
  14124. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14125. return candidate;
  14126. },
  14127. build_icecandidate: function (cand) {
  14128. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  14129. line += ' ';
  14130. switch (cand.type) {
  14131. case 'srflx':
  14132. case 'prflx':
  14133. case 'relay':
  14134. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  14135. line += 'raddr';
  14136. line += ' ';
  14137. line += cand['rel-addr'];
  14138. line += ' ';
  14139. line += 'rport';
  14140. line += ' ';
  14141. line += cand['rel-port'];
  14142. line += ' ';
  14143. }
  14144. break;
  14145. }
  14146. if (cand.hasOwnAttribute('tcptype')) {
  14147. line += 'tcptype';
  14148. line += ' ';
  14149. line += cand.tcptype;
  14150. line += ' ';
  14151. }
  14152. line += 'generation';
  14153. line += ' ';
  14154. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  14155. return line;
  14156. },
  14157. parse_ssrc: function (desc) {
  14158. // proprietary mapping of a=ssrc lines
  14159. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  14160. // and parse according to that
  14161. var lines = desc.split('\r\n'),
  14162. data = {};
  14163. for (var i = 0; i < lines.length; i++) {
  14164. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  14165. var idx = lines[i].indexOf(' ');
  14166. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  14167. }
  14168. }
  14169. return data;
  14170. },
  14171. parse_rtcpfb: function (line) {
  14172. var parts = line.substr(10).split(' ');
  14173. var data = {};
  14174. data.pt = parts.shift();
  14175. data.type = parts.shift();
  14176. data.params = parts;
  14177. return data;
  14178. },
  14179. parse_extmap: function (line) {
  14180. var parts = line.substr(9).split(' ');
  14181. var data = {};
  14182. data.value = parts.shift();
  14183. if (data.value.indexOf('/') != -1) {
  14184. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  14185. data.value = data.value.substr(0, data.value.indexOf('/'));
  14186. } else {
  14187. data.direction = 'both';
  14188. }
  14189. data.uri = parts.shift();
  14190. data.params = parts;
  14191. return data;
  14192. },
  14193. find_line: function (haystack, needle, sessionpart) {
  14194. var lines = haystack.split('\r\n');
  14195. for (var i = 0; i < lines.length; i++) {
  14196. if (lines[i].substring(0, needle.length) == needle) {
  14197. return lines[i];
  14198. }
  14199. }
  14200. if (!sessionpart) {
  14201. return false;
  14202. }
  14203. // search session part
  14204. lines = sessionpart.split('\r\n');
  14205. for (var j = 0; j < lines.length; j++) {
  14206. if (lines[j].substring(0, needle.length) == needle) {
  14207. return lines[j];
  14208. }
  14209. }
  14210. return false;
  14211. },
  14212. find_lines: function (haystack, needle, sessionpart) {
  14213. var lines = haystack.split('\r\n'),
  14214. needles = [];
  14215. for (var i = 0; i < lines.length; i++) {
  14216. if (lines[i].substring(0, needle.length) == needle)
  14217. needles.push(lines[i]);
  14218. }
  14219. if (needles.length || !sessionpart) {
  14220. return needles;
  14221. }
  14222. // search session part
  14223. lines = sessionpart.split('\r\n');
  14224. for (var j = 0; j < lines.length; j++) {
  14225. if (lines[j].substring(0, needle.length) == needle) {
  14226. needles.push(lines[j]);
  14227. }
  14228. }
  14229. return needles;
  14230. },
  14231. candidateToJingle: function (line) {
  14232. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14233. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14234. if (line.indexOf('candidate:') === 0) {
  14235. line = 'a=' + line;
  14236. } else if (line.substring(0, 12) != 'a=candidate:') {
  14237. console.log('parseCandidate called with a line that is not a candidate line');
  14238. console.log(line);
  14239. return null;
  14240. }
  14241. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14242. line = line.substring(0, line.length - 2);
  14243. var candidate = {},
  14244. elems = line.split(' '),
  14245. i;
  14246. if (elems[6] != 'typ') {
  14247. console.log('did not find typ in the right place');
  14248. console.log(line);
  14249. return null;
  14250. }
  14251. candidate.foundation = elems[0].substring(12);
  14252. candidate.component = elems[1];
  14253. candidate.protocol = elems[2].toLowerCase();
  14254. candidate.priority = elems[3];
  14255. candidate.ip = elems[4];
  14256. candidate.port = elems[5];
  14257. // elems[6] => "typ"
  14258. candidate.type = elems[7];
  14259. candidate.generation = '0'; // default, may be overwritten below
  14260. for (i = 8; i < elems.length; i += 2) {
  14261. switch (elems[i]) {
  14262. case 'raddr':
  14263. candidate['rel-addr'] = elems[i + 1];
  14264. break;
  14265. case 'rport':
  14266. candidate['rel-port'] = elems[i + 1];
  14267. break;
  14268. case 'generation':
  14269. candidate.generation = elems[i + 1];
  14270. break;
  14271. case 'tcptype':
  14272. candidate.tcptype = elems[i + 1];
  14273. break;
  14274. default: // TODO
  14275. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14276. }
  14277. }
  14278. candidate.network = '1';
  14279. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14280. return candidate;
  14281. },
  14282. candidateFromJingle: function (cand) {
  14283. var line = 'a=candidate:';
  14284. line += cand.getAttribute('foundation');
  14285. line += ' ';
  14286. line += cand.getAttribute('component');
  14287. line += ' ';
  14288. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14289. line += ' ';
  14290. line += cand.getAttribute('priority');
  14291. line += ' ';
  14292. line += cand.getAttribute('ip');
  14293. line += ' ';
  14294. line += cand.getAttribute('port');
  14295. line += ' ';
  14296. line += 'typ';
  14297. line += ' ' + cand.getAttribute('type');
  14298. line += ' ';
  14299. switch (cand.getAttribute('type')) {
  14300. case 'srflx':
  14301. case 'prflx':
  14302. case 'relay':
  14303. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14304. line += 'raddr';
  14305. line += ' ';
  14306. line += cand.getAttribute('rel-addr');
  14307. line += ' ';
  14308. line += 'rport';
  14309. line += ' ';
  14310. line += cand.getAttribute('rel-port');
  14311. line += ' ';
  14312. }
  14313. break;
  14314. }
  14315. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14316. line += 'tcptype';
  14317. line += ' ';
  14318. line += cand.getAttribute('tcptype');
  14319. line += ' ';
  14320. }
  14321. line += 'generation';
  14322. line += ' ';
  14323. line += cand.getAttribute('generation') || '0';
  14324. return line + '\r\n';
  14325. }
  14326. };
  14327. module.exports = SDPUtil;
  14328. },{}],59:[function(require,module,exports){
  14329. var RTC = require('../RTC/RTC');
  14330. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14331. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14332. var SSRCReplacement = require("./LocalSSRCReplacement");
  14333. function TraceablePeerConnection(ice_config, constraints, session) {
  14334. var self = this;
  14335. var RTCPeerConnectionType = null;
  14336. if (RTCBrowserType.isFirefox()) {
  14337. RTCPeerConnectionType = mozRTCPeerConnection;
  14338. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14339. RTCPeerConnectionType = RTCPeerConnection;
  14340. } else {
  14341. RTCPeerConnectionType = webkitRTCPeerConnection;
  14342. }
  14343. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  14344. this.updateLog = [];
  14345. this.stats = {};
  14346. this.statsinterval = null;
  14347. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14348. var Interop = require('sdp-interop').Interop;
  14349. this.interop = new Interop();
  14350. var Simulcast = require('sdp-simulcast');
  14351. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14352. // override as desired
  14353. this.trace = function (what, info) {
  14354. /*console.warn('WTRACE', what, info);
  14355. if (info && RTCBrowserType.isIExplorer()) {
  14356. if (info.length > 1024) {
  14357. console.warn('WTRACE', what, info.substr(1024));
  14358. }
  14359. if (info.length > 2048) {
  14360. console.warn('WTRACE', what, info.substr(2048));
  14361. }
  14362. }*/
  14363. self.updateLog.push({
  14364. time: new Date(),
  14365. type: what,
  14366. value: info || ""
  14367. });
  14368. };
  14369. this.onicecandidate = null;
  14370. this.peerconnection.onicecandidate = function (event) {
  14371. // FIXME: this causes stack overflow with Temasys Plugin
  14372. if (!RTCBrowserType.isTemasysPluginUsed())
  14373. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14374. if (self.onicecandidate !== null) {
  14375. self.onicecandidate(event);
  14376. }
  14377. };
  14378. this.onaddstream = null;
  14379. this.peerconnection.onaddstream = function (event) {
  14380. self.trace('onaddstream', event.stream.id);
  14381. if (self.onaddstream !== null) {
  14382. self.onaddstream(event);
  14383. }
  14384. };
  14385. this.onremovestream = null;
  14386. this.peerconnection.onremovestream = function (event) {
  14387. self.trace('onremovestream', event.stream.id);
  14388. if (self.onremovestream !== null) {
  14389. self.onremovestream(event);
  14390. }
  14391. };
  14392. this.onsignalingstatechange = null;
  14393. this.peerconnection.onsignalingstatechange = function (event) {
  14394. self.trace('onsignalingstatechange', self.signalingState);
  14395. if (self.onsignalingstatechange !== null) {
  14396. self.onsignalingstatechange(event);
  14397. }
  14398. };
  14399. this.oniceconnectionstatechange = null;
  14400. this.peerconnection.oniceconnectionstatechange = function (event) {
  14401. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14402. if (self.oniceconnectionstatechange !== null) {
  14403. self.oniceconnectionstatechange(event);
  14404. }
  14405. };
  14406. this.onnegotiationneeded = null;
  14407. this.peerconnection.onnegotiationneeded = function (event) {
  14408. self.trace('onnegotiationneeded');
  14409. if (self.onnegotiationneeded !== null) {
  14410. self.onnegotiationneeded(event);
  14411. }
  14412. };
  14413. self.ondatachannel = null;
  14414. this.peerconnection.ondatachannel = function (event) {
  14415. self.trace('ondatachannel', event);
  14416. if (self.ondatachannel !== null) {
  14417. self.ondatachannel(event);
  14418. }
  14419. };
  14420. // XXX: do all non-firefox browsers which we support also support this?
  14421. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14422. this.statsinterval = window.setInterval(function() {
  14423. self.peerconnection.getStats(function(stats) {
  14424. var results = stats.result();
  14425. var now = new Date();
  14426. for (var i = 0; i < results.length; ++i) {
  14427. results[i].names().forEach(function (name) {
  14428. var id = results[i].id + '-' + name;
  14429. if (!self.stats[id]) {
  14430. self.stats[id] = {
  14431. startTime: now,
  14432. endTime: now,
  14433. values: [],
  14434. times: []
  14435. };
  14436. }
  14437. self.stats[id].values.push(results[i].stat(name));
  14438. self.stats[id].times.push(now.getTime());
  14439. if (self.stats[id].values.length > self.maxstats) {
  14440. self.stats[id].values.shift();
  14441. self.stats[id].times.shift();
  14442. }
  14443. self.stats[id].endTime = now;
  14444. });
  14445. }
  14446. });
  14447. }, 1000);
  14448. }
  14449. }
  14450. /**
  14451. * Returns a string representation of a SessionDescription object.
  14452. */
  14453. var dumpSDP = function(description) {
  14454. if (typeof description === 'undefined' || description == null) {
  14455. return '';
  14456. }
  14457. return 'type: ' + description.type + '\r\n' + description.sdp;
  14458. };
  14459. /**
  14460. * Takes a SessionDescription object and returns a "normalized" version.
  14461. * Currently it only takes care of ordering the a=ssrc lines.
  14462. */
  14463. var normalizePlanB = function(desc) {
  14464. if (typeof desc !== 'object' || desc === null ||
  14465. typeof desc.sdp !== 'string') {
  14466. console.warn('An empty description was passed as an argument.');
  14467. return desc;
  14468. }
  14469. var transform = require('sdp-transform');
  14470. var session = transform.parse(desc.sdp);
  14471. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14472. Array.isArray(session.media)) {
  14473. session.media.forEach(function (mLine) {
  14474. // Chrome appears to be picky about the order in which a=ssrc lines
  14475. // are listed in an m-line when rtx is enabled (and thus there are
  14476. // a=ssrc-group lines with FID semantics). Specifically if we have
  14477. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14478. // the "a=ssrc:S1" lines, SRD fails.
  14479. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14480. // first.
  14481. var firstSsrcs = [];
  14482. var newSsrcLines = [];
  14483. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14484. mLine.ssrcGroups.forEach(function (group) {
  14485. if (typeof group.semantics !== 'undefined' &&
  14486. group.semantics === 'FID') {
  14487. if (typeof group.ssrcs !== 'undefined') {
  14488. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14489. }
  14490. }
  14491. });
  14492. }
  14493. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14494. for (var i = 0; i<mLine.ssrcs.length; i++){
  14495. if (typeof mLine.ssrcs[i] === 'object'
  14496. && typeof mLine.ssrcs[i].id !== 'undefined'
  14497. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14498. newSsrcLines.push(mLine.ssrcs[i]);
  14499. delete mLine.ssrcs[i];
  14500. }
  14501. }
  14502. for (var i = 0; i<mLine.ssrcs.length; i++){
  14503. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14504. newSsrcLines.push(mLine.ssrcs[i]);
  14505. }
  14506. }
  14507. mLine.ssrcs = newSsrcLines;
  14508. }
  14509. });
  14510. }
  14511. var resStr = transform.write(session);
  14512. return new RTCSessionDescription({
  14513. type: desc.type,
  14514. sdp: resStr
  14515. });
  14516. };
  14517. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14518. TraceablePeerConnection.prototype.__defineGetter__(
  14519. 'signalingState',
  14520. function() { return this.peerconnection.signalingState; });
  14521. TraceablePeerConnection.prototype.__defineGetter__(
  14522. 'iceConnectionState',
  14523. function() { return this.peerconnection.iceConnectionState; });
  14524. TraceablePeerConnection.prototype.__defineGetter__(
  14525. 'localDescription',
  14526. function() {
  14527. var desc = this.peerconnection.localDescription;
  14528. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  14529. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14530. // if we're running on FF, transform to Plan B first.
  14531. if (RTCBrowserType.usesUnifiedPlan()) {
  14532. desc = this.interop.toPlanB(desc);
  14533. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14534. }
  14535. return desc;
  14536. });
  14537. TraceablePeerConnection.prototype.__defineGetter__(
  14538. 'remoteDescription',
  14539. function() {
  14540. var desc = this.peerconnection.remoteDescription;
  14541. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14542. // if we're running on FF, transform to Plan B first.
  14543. if (RTCBrowserType.usesUnifiedPlan()) {
  14544. desc = this.interop.toPlanB(desc);
  14545. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14546. }
  14547. return desc;
  14548. });
  14549. }
  14550. TraceablePeerConnection.prototype.addStream = function (stream) {
  14551. this.trace('addStream', stream.id);
  14552. try
  14553. {
  14554. this.peerconnection.addStream(stream);
  14555. }
  14556. catch (e)
  14557. {
  14558. console.error(e);
  14559. }
  14560. };
  14561. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14562. this.trace('removeStream', stream.id);
  14563. if(stopStreams) {
  14564. stream.getAudioTracks().forEach(function (track) {
  14565. // stop() not supported with IE
  14566. if (track.stop) {
  14567. track.stop();
  14568. }
  14569. });
  14570. stream.getVideoTracks().forEach(function (track) {
  14571. // stop() not supported with IE
  14572. if (track.stop) {
  14573. track.stop();
  14574. }
  14575. });
  14576. if (stream.stop) {
  14577. stream.stop();
  14578. }
  14579. }
  14580. try {
  14581. // FF doesn't support this yet.
  14582. if (this.peerconnection.removeStream)
  14583. this.peerconnection.removeStream(stream);
  14584. } catch (e) {
  14585. console.error(e);
  14586. }
  14587. };
  14588. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14589. this.trace('createDataChannel', label, opts);
  14590. return this.peerconnection.createDataChannel(label, opts);
  14591. };
  14592. TraceablePeerConnection.prototype.setLocalDescription
  14593. = function (description, successCallback, failureCallback) {
  14594. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14595. // if we're running on FF, transform to Plan A first.
  14596. if (RTCBrowserType.usesUnifiedPlan()) {
  14597. description = this.interop.toUnifiedPlan(description);
  14598. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14599. }
  14600. var self = this;
  14601. this.peerconnection.setLocalDescription(description,
  14602. function () {
  14603. self.trace('setLocalDescriptionOnSuccess');
  14604. successCallback();
  14605. },
  14606. function (err) {
  14607. self.trace('setLocalDescriptionOnFailure', err);
  14608. failureCallback(err);
  14609. }
  14610. );
  14611. /*
  14612. if (this.statsinterval === null && this.maxstats > 0) {
  14613. // start gathering stats
  14614. }
  14615. */
  14616. };
  14617. TraceablePeerConnection.prototype.setRemoteDescription
  14618. = function (description, successCallback, failureCallback) {
  14619. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14620. // TODO the focus should squeze or explode the remote simulcast
  14621. description = this.simulcast.mungeRemoteDescription(description);
  14622. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14623. // if we're running on FF, transform to Plan A first.
  14624. if (RTCBrowserType.usesUnifiedPlan()) {
  14625. description = this.interop.toUnifiedPlan(description);
  14626. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14627. }
  14628. if (RTCBrowserType.usesPlanB()) {
  14629. description = normalizePlanB(description);
  14630. }
  14631. var self = this;
  14632. this.peerconnection.setRemoteDescription(description,
  14633. function () {
  14634. self.trace('setRemoteDescriptionOnSuccess');
  14635. successCallback();
  14636. },
  14637. function (err) {
  14638. self.trace('setRemoteDescriptionOnFailure', err);
  14639. failureCallback(err);
  14640. }
  14641. );
  14642. /*
  14643. if (this.statsinterval === null && this.maxstats > 0) {
  14644. // start gathering stats
  14645. }
  14646. */
  14647. };
  14648. TraceablePeerConnection.prototype.close = function () {
  14649. this.trace('stop');
  14650. if (this.statsinterval !== null) {
  14651. window.clearInterval(this.statsinterval);
  14652. this.statsinterval = null;
  14653. }
  14654. this.peerconnection.close();
  14655. };
  14656. TraceablePeerConnection.prototype.createOffer
  14657. = function (successCallback, failureCallback, constraints) {
  14658. var self = this;
  14659. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14660. this.peerconnection.createOffer(
  14661. function (offer) {
  14662. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14663. // NOTE this is not tested because in meet the focus generates the
  14664. // offer.
  14665. // if we're running on FF, transform to Plan B first.
  14666. if (RTCBrowserType.usesUnifiedPlan()) {
  14667. offer = self.interop.toPlanB(offer);
  14668. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14669. }
  14670. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  14671. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14672. offer = self.simulcast.mungeLocalDescription(offer);
  14673. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14674. }
  14675. successCallback(offer);
  14676. },
  14677. function(err) {
  14678. self.trace('createOfferOnFailure', err);
  14679. failureCallback(err);
  14680. },
  14681. constraints
  14682. );
  14683. };
  14684. TraceablePeerConnection.prototype.createAnswer
  14685. = function (successCallback, failureCallback, constraints) {
  14686. var self = this;
  14687. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14688. this.peerconnection.createAnswer(
  14689. function (answer) {
  14690. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14691. // if we're running on FF, transform to Plan A first.
  14692. if (RTCBrowserType.usesUnifiedPlan()) {
  14693. answer = self.interop.toPlanB(answer);
  14694. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14695. }
  14696. // munge local video SSRC
  14697. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  14698. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14699. answer = self.simulcast.mungeLocalDescription(answer);
  14700. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14701. }
  14702. successCallback(answer);
  14703. },
  14704. function(err) {
  14705. self.trace('createAnswerOnFailure', err);
  14706. failureCallback(err);
  14707. },
  14708. constraints
  14709. );
  14710. };
  14711. TraceablePeerConnection.prototype.addIceCandidate
  14712. = function (candidate, successCallback, failureCallback) {
  14713. //var self = this;
  14714. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14715. this.peerconnection.addIceCandidate(candidate);
  14716. /* maybe later
  14717. this.peerconnection.addIceCandidate(candidate,
  14718. function () {
  14719. self.trace('addIceCandidateOnSuccess');
  14720. successCallback();
  14721. },
  14722. function (err) {
  14723. self.trace('addIceCandidateOnFailure', err);
  14724. failureCallback(err);
  14725. }
  14726. );
  14727. */
  14728. };
  14729. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14730. // TODO: Is this the correct way to handle Opera, Temasys?
  14731. if (RTCBrowserType.isFirefox()) {
  14732. // ignore for now...
  14733. if(!errback)
  14734. errback = function () {};
  14735. this.peerconnection.getStats(null, callback, errback);
  14736. } else {
  14737. this.peerconnection.getStats(callback);
  14738. }
  14739. };
  14740. module.exports = TraceablePeerConnection;
  14741. },{"../../service/xmpp/XMPPEvents":161,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"./LocalSSRCReplacement":55,"sdp-interop":92,"sdp-simulcast":95,"sdp-transform":98}],60:[function(require,module,exports){
  14742. /* global $, $iq, APP, config, messageHandler,
  14743. roomName, sessionTerminated, Strophe, Util */
  14744. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14745. var Settings = require("../settings/Settings");
  14746. var AuthenticationEvents
  14747. = require("../../service/authentication/AuthenticationEvents");
  14748. /**
  14749. * Contains logic responsible for enabling/disabling functionality available
  14750. * only to moderator users.
  14751. */
  14752. var connection = null;
  14753. var focusUserJid;
  14754. function createExpBackoffTimer(step) {
  14755. var count = 1;
  14756. return function (reset) {
  14757. // Reset call
  14758. if (reset) {
  14759. count = 1;
  14760. return;
  14761. }
  14762. // Calculate next timeout
  14763. var timeout = Math.pow(2, count - 1);
  14764. count += 1;
  14765. return timeout * step;
  14766. };
  14767. }
  14768. var getNextTimeout = createExpBackoffTimer(1000);
  14769. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14770. // External authentication stuff
  14771. var externalAuthEnabled = false;
  14772. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14773. // it will be enabled automatically if focus detects the component through
  14774. // service discovery.
  14775. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14776. var eventEmitter = null;
  14777. var Moderator = {
  14778. isModerator: function () {
  14779. return connection && connection.emuc.isModerator();
  14780. },
  14781. isPeerModerator: function (peerJid) {
  14782. return connection &&
  14783. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14784. },
  14785. isExternalAuthEnabled: function () {
  14786. return externalAuthEnabled;
  14787. },
  14788. isSipGatewayEnabled: function () {
  14789. return sipGatewayEnabled;
  14790. },
  14791. setConnection: function (con) {
  14792. connection = con;
  14793. },
  14794. init: function (xmpp, emitter) {
  14795. this.xmppService = xmpp;
  14796. eventEmitter = emitter;
  14797. // Message listener that talks to POPUP window
  14798. function listener(event) {
  14799. if (event.data && event.data.sessionId) {
  14800. if (event.origin !== window.location.origin) {
  14801. console.warn("Ignoring sessionId from different origin: " +
  14802. event.origin);
  14803. return;
  14804. }
  14805. localStorage.setItem('sessionId', event.data.sessionId);
  14806. // After popup is closed we will authenticate
  14807. }
  14808. }
  14809. // Register
  14810. if (window.addEventListener) {
  14811. window.addEventListener("message", listener, false);
  14812. } else {
  14813. window.attachEvent("onmessage", listener);
  14814. }
  14815. },
  14816. onMucMemberLeft: function (jid) {
  14817. console.info("Someone left is it focus ? " + jid);
  14818. var resource = Strophe.getResourceFromJid(jid);
  14819. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14820. console.info(
  14821. "Focus has left the room - leaving conference");
  14822. //hangUp();
  14823. // We'd rather reload to have everything re-initialized
  14824. // FIXME: show some message before reload
  14825. location.reload();
  14826. }
  14827. },
  14828. setFocusUserJid: function (focusJid) {
  14829. if (!focusUserJid) {
  14830. focusUserJid = focusJid;
  14831. console.info("Focus jid set to: " + focusUserJid);
  14832. }
  14833. },
  14834. getFocusUserJid: function () {
  14835. return focusUserJid;
  14836. },
  14837. getFocusComponent: function () {
  14838. // Get focus component address
  14839. var focusComponent = config.hosts.focus;
  14840. // If not specified use default: 'focus.domain'
  14841. if (!focusComponent) {
  14842. focusComponent = 'focus.' + config.hosts.domain;
  14843. }
  14844. return focusComponent;
  14845. },
  14846. createConferenceIq: function (roomName) {
  14847. // Generate create conference IQ
  14848. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14849. // Session Id used for authentication
  14850. var sessionId = localStorage.getItem('sessionId');
  14851. var machineUID = Settings.getSettings().uid;
  14852. console.info(
  14853. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14854. elem.c('conference', {
  14855. xmlns: 'http://jitsi.org/protocol/focus',
  14856. room: roomName,
  14857. 'machine-uid': machineUID
  14858. });
  14859. if (sessionId) {
  14860. elem.attrs({ 'session-id': sessionId});
  14861. }
  14862. if (config.hosts.bridge !== undefined) {
  14863. elem.c(
  14864. 'property',
  14865. { name: 'bridge', value: config.hosts.bridge})
  14866. .up();
  14867. }
  14868. // Tell the focus we have Jigasi configured
  14869. if (config.hosts.call_control !== undefined) {
  14870. elem.c(
  14871. 'property',
  14872. { name: 'call_control', value: config.hosts.call_control})
  14873. .up();
  14874. }
  14875. if (config.channelLastN !== undefined) {
  14876. elem.c(
  14877. 'property',
  14878. { name: 'channelLastN', value: config.channelLastN})
  14879. .up();
  14880. }
  14881. if (config.adaptiveLastN !== undefined) {
  14882. elem.c(
  14883. 'property',
  14884. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14885. .up();
  14886. }
  14887. if (config.adaptiveSimulcast !== undefined) {
  14888. elem.c(
  14889. 'property',
  14890. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14891. .up();
  14892. }
  14893. if (config.openSctp !== undefined) {
  14894. elem.c(
  14895. 'property',
  14896. { name: 'openSctp', value: config.openSctp})
  14897. .up();
  14898. }
  14899. if(config.startAudioMuted !== undefined)
  14900. {
  14901. elem.c(
  14902. 'property',
  14903. { name: 'startAudioMuted', value: config.startAudioMuted})
  14904. .up();
  14905. }
  14906. if(config.startVideoMuted !== undefined)
  14907. {
  14908. elem.c(
  14909. 'property',
  14910. { name: 'startVideoMuted', value: config.startVideoMuted})
  14911. .up();
  14912. }
  14913. elem.c(
  14914. 'property',
  14915. { name: 'simulcastMode', value: 'rewriting'})
  14916. .up();
  14917. elem.up();
  14918. return elem;
  14919. },
  14920. parseSessionId: function (resultIq) {
  14921. var sessionId = $(resultIq).find('conference').attr('session-id');
  14922. if (sessionId) {
  14923. console.info('Received sessionId: ' + sessionId);
  14924. localStorage.setItem('sessionId', sessionId);
  14925. }
  14926. },
  14927. parseConfigOptions: function (resultIq) {
  14928. Moderator.setFocusUserJid(
  14929. $(resultIq).find('conference').attr('focusjid'));
  14930. var authenticationEnabled
  14931. = $(resultIq).find(
  14932. '>conference>property' +
  14933. '[name=\'authentication\'][value=\'true\']').length > 0;
  14934. console.info("Authentication enabled: " + authenticationEnabled);
  14935. externalAuthEnabled = $(resultIq).find(
  14936. '>conference>property' +
  14937. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14938. console.info('External authentication enabled: ' + externalAuthEnabled);
  14939. if (!externalAuthEnabled) {
  14940. // We expect to receive sessionId in 'internal' authentication mode
  14941. Moderator.parseSessionId(resultIq);
  14942. }
  14943. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14944. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14945. authenticationEnabled, authIdentity);
  14946. // Check if focus has auto-detected Jigasi component(this will be also
  14947. // included if we have passed our host from the config)
  14948. if ($(resultIq).find(
  14949. '>conference>property' +
  14950. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14951. sipGatewayEnabled = true;
  14952. }
  14953. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14954. },
  14955. // FIXME: we need to show the fact that we're waiting for the focus
  14956. // to the user(or that focus is not available)
  14957. allocateConferenceFocus: function (roomName, callback) {
  14958. // Try to use focus user JID from the config
  14959. Moderator.setFocusUserJid(config.focusUserJid);
  14960. // Send create conference IQ
  14961. var iq = Moderator.createConferenceIq(roomName);
  14962. var self = this;
  14963. connection.sendIQ(
  14964. iq,
  14965. function (result) {
  14966. // Setup config options
  14967. Moderator.parseConfigOptions(result);
  14968. if ('true' === $(result).find('conference').attr('ready')) {
  14969. // Reset both timers
  14970. getNextTimeout(true);
  14971. getNextErrorTimeout(true);
  14972. // Exec callback
  14973. callback();
  14974. } else {
  14975. var waitMs = getNextTimeout();
  14976. console.info("Waiting for the focus... " + waitMs);
  14977. // Reset error timeout
  14978. getNextErrorTimeout(true);
  14979. window.setTimeout(
  14980. function () {
  14981. Moderator.allocateConferenceFocus(
  14982. roomName, callback);
  14983. }, waitMs);
  14984. }
  14985. },
  14986. function (error) {
  14987. // Invalid session ? remove and try again
  14988. // without session ID to get a new one
  14989. var invalidSession
  14990. = $(error).find('>error>session-invalid').length;
  14991. if (invalidSession) {
  14992. console.info("Session expired! - removing");
  14993. localStorage.removeItem("sessionId");
  14994. }
  14995. if ($(error).find('>error>graceful-shutdown').length) {
  14996. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14997. return;
  14998. }
  14999. // Check for error returned by the reservation system
  15000. var reservationErr = $(error).find('>error>reservation-error');
  15001. if (reservationErr.length) {
  15002. // Trigger error event
  15003. var errorCode = reservationErr.attr('error-code');
  15004. var errorMsg;
  15005. if ($(error).find('>error>text')) {
  15006. errorMsg = $(error).find('>error>text').text();
  15007. }
  15008. eventEmitter.emit(
  15009. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  15010. return;
  15011. }
  15012. // Not authorized to create new room
  15013. if ($(error).find('>error>not-authorized').length) {
  15014. console.warn("Unauthorized to start the conference", error);
  15015. var toDomain
  15016. = Strophe.getDomainFromJid(error.getAttribute('to'));
  15017. if (toDomain !== config.hosts.anonymousdomain) {
  15018. // FIXME: "is external" should come either from
  15019. // the focus or config.js
  15020. externalAuthEnabled = true;
  15021. }
  15022. eventEmitter.emit(
  15023. XMPPEvents.AUTHENTICATION_REQUIRED,
  15024. function () {
  15025. Moderator.allocateConferenceFocus(
  15026. roomName, callback);
  15027. });
  15028. return;
  15029. }
  15030. var waitMs = getNextErrorTimeout();
  15031. console.error("Focus error, retry after " + waitMs, error);
  15032. // Show message
  15033. var focusComponent = Moderator.getFocusComponent();
  15034. var retrySec = waitMs / 1000;
  15035. // FIXME: message is duplicated ?
  15036. // Do not show in case of session invalid
  15037. // which means just a retry
  15038. if (!invalidSession) {
  15039. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  15040. focusComponent, retrySec);
  15041. }
  15042. // Reset response timeout
  15043. getNextTimeout(true);
  15044. window.setTimeout(
  15045. function () {
  15046. Moderator.allocateConferenceFocus(roomName, callback);
  15047. }, waitMs);
  15048. }
  15049. );
  15050. },
  15051. getLoginUrl: function (roomName, urlCallback) {
  15052. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15053. iq.c('login-url', {
  15054. xmlns: 'http://jitsi.org/protocol/focus',
  15055. room: roomName,
  15056. 'machine-uid': Settings.getSettings().uid
  15057. });
  15058. connection.sendIQ(
  15059. iq,
  15060. function (result) {
  15061. var url = $(result).find('login-url').attr('url');
  15062. url = url = decodeURIComponent(url);
  15063. if (url) {
  15064. console.info("Got auth url: " + url);
  15065. urlCallback(url);
  15066. } else {
  15067. console.error(
  15068. "Failed to get auth url from the focus", result);
  15069. }
  15070. },
  15071. function (error) {
  15072. console.error("Get auth url error", error);
  15073. }
  15074. );
  15075. },
  15076. getPopupLoginUrl: function (roomName, urlCallback) {
  15077. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15078. iq.c('login-url', {
  15079. xmlns: 'http://jitsi.org/protocol/focus',
  15080. room: roomName,
  15081. 'machine-uid': Settings.getSettings().uid,
  15082. popup: true
  15083. });
  15084. connection.sendIQ(
  15085. iq,
  15086. function (result) {
  15087. var url = $(result).find('login-url').attr('url');
  15088. url = url = decodeURIComponent(url);
  15089. if (url) {
  15090. console.info("Got POPUP auth url: " + url);
  15091. urlCallback(url);
  15092. } else {
  15093. console.error(
  15094. "Failed to get POPUP auth url from the focus", result);
  15095. }
  15096. },
  15097. function (error) {
  15098. console.error('Get POPUP auth url error', error);
  15099. }
  15100. );
  15101. },
  15102. logout: function (callback) {
  15103. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15104. var sessionId = localStorage.getItem('sessionId');
  15105. if (!sessionId) {
  15106. callback();
  15107. return;
  15108. }
  15109. iq.c('logout', {
  15110. xmlns: 'http://jitsi.org/protocol/focus',
  15111. 'session-id': sessionId
  15112. });
  15113. connection.sendIQ(
  15114. iq,
  15115. function (result) {
  15116. var logoutUrl = $(result).find('logout').attr('logout-url');
  15117. if (logoutUrl) {
  15118. logoutUrl = decodeURIComponent(logoutUrl);
  15119. }
  15120. console.info("Log out OK, url: " + logoutUrl, result);
  15121. localStorage.removeItem('sessionId');
  15122. callback(logoutUrl);
  15123. },
  15124. function (error) {
  15125. console.error("Logout error", error);
  15126. }
  15127. );
  15128. }
  15129. };
  15130. module.exports = Moderator;
  15131. },{"../../service/authentication/AuthenticationEvents":156,"../../service/xmpp/XMPPEvents":161,"../settings/Settings":47}],61:[function(require,module,exports){
  15132. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  15133. Toolbar, Util */
  15134. var Moderator = require("./moderator");
  15135. var recordingToken = null;
  15136. var recordingEnabled;
  15137. /**
  15138. * Whether to use a jirecon component for recording, or use the videobridge
  15139. * through COLIBRI.
  15140. */
  15141. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  15142. /**
  15143. * The ID of the jirecon recording session. Jirecon generates it when we
  15144. * initially start recording, and it needs to be used in subsequent requests
  15145. * to jirecon.
  15146. */
  15147. var jireconRid = null;
  15148. /**
  15149. * The callback to update the recording button. Currently used from colibri
  15150. * after receiving a pending status.
  15151. */
  15152. var recordingStateChangeCallback = null;
  15153. function setRecordingToken(token) {
  15154. recordingToken = token;
  15155. }
  15156. function setRecordingJirecon(state, token, callback, connection) {
  15157. if (state == recordingEnabled){
  15158. return;
  15159. }
  15160. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  15161. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  15162. action: (state === 'on') ? 'start' : 'stop',
  15163. mucjid: connection.emuc.roomjid});
  15164. if (state === 'off'){
  15165. iq.attrs({rid: jireconRid});
  15166. }
  15167. console.log('Start recording');
  15168. connection.sendIQ(
  15169. iq,
  15170. function (result) {
  15171. // TODO wait for an IQ with the real status, since this is
  15172. // provisional?
  15173. jireconRid = $(result).find('recording').attr('rid');
  15174. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  15175. '(jirecon)' + result);
  15176. recordingEnabled = state;
  15177. if (state === 'off'){
  15178. jireconRid = null;
  15179. }
  15180. callback(state);
  15181. },
  15182. function (error) {
  15183. console.log('Failed to start recording, error: ', error);
  15184. callback(recordingEnabled);
  15185. });
  15186. }
  15187. // Sends a COLIBRI message which enables or disables (according to 'state')
  15188. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  15189. // with the new recording state, according to the IQ.
  15190. function setRecordingColibri(state, token, callback, connection) {
  15191. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  15192. elem.c('conference', {
  15193. xmlns: 'http://jitsi.org/protocol/colibri'
  15194. });
  15195. elem.c('recording', {state: state, token: token});
  15196. connection.sendIQ(elem,
  15197. function (result) {
  15198. console.log('Set recording "', state, '". Result:', result);
  15199. var recordingElem = $(result).find('>conference>recording');
  15200. var newState = recordingElem.attr('state');
  15201. recordingEnabled = newState;
  15202. callback(newState);
  15203. if (newState === 'pending' && recordingStateChangeCallback == null) {
  15204. recordingStateChangeCallback = callback;
  15205. connection.addHandler(function(iq){
  15206. var state = $(iq).find('recording').attr('state');
  15207. if (state)
  15208. recordingStateChangeCallback(state);
  15209. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  15210. }
  15211. },
  15212. function (error) {
  15213. console.warn(error);
  15214. callback(recordingEnabled);
  15215. }
  15216. );
  15217. }
  15218. function setRecording(state, token, callback, connection) {
  15219. if (useJirecon){
  15220. setRecordingJirecon(state, token, callback, connection);
  15221. } else {
  15222. setRecordingColibri(state, token, callback, connection);
  15223. }
  15224. }
  15225. var Recording = {
  15226. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  15227. if (!Moderator.isModerator()) {
  15228. console.log(
  15229. 'non-focus, or conference not yet organized:' +
  15230. ' not enabling recording');
  15231. return;
  15232. }
  15233. var self = this;
  15234. // Jirecon does not (currently) support a token.
  15235. if (!recordingToken && !useJirecon) {
  15236. tokenEmptyCallback(function (value) {
  15237. setRecordingToken(value);
  15238. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  15239. });
  15240. return;
  15241. }
  15242. var oldState = recordingEnabled;
  15243. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  15244. setRecording(newState,
  15245. recordingToken,
  15246. function (state) {
  15247. console.log("New recording state: ", state);
  15248. if (state === oldState) {
  15249. // FIXME: new focus:
  15250. // this will not work when moderator changes
  15251. // during active session. Then it will assume that
  15252. // recording status has changed to true, but it might have
  15253. // been already true(and we only received actual status from
  15254. // the focus).
  15255. //
  15256. // SO we start with status null, so that it is initialized
  15257. // here and will fail only after second click, so if invalid
  15258. // token was used we have to press the button twice before
  15259. // current status will be fetched and token will be reset.
  15260. //
  15261. // Reliable way would be to return authentication error.
  15262. // Or status update when moderator connects.
  15263. // Or we have to stop recording session when current
  15264. // moderator leaves the room.
  15265. // Failed to change, reset the token because it might
  15266. // have been wrong
  15267. setRecordingToken(null);
  15268. }
  15269. recordingStateChangeCallback(state);
  15270. },
  15271. connection
  15272. );
  15273. }
  15274. };
  15275. module.exports = Recording;
  15276. },{"./moderator":60}],62:[function(require,module,exports){
  15277. /* jshint -W117 */
  15278. /* a simple MUC connection plugin
  15279. * can only handle a single MUC room
  15280. */
  15281. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15282. var Moderator = require("./moderator");
  15283. module.exports = function(XMPP, eventEmitter) {
  15284. Strophe.addConnectionPlugin('emuc', {
  15285. connection: null,
  15286. roomjid: null,
  15287. myroomjid: null,
  15288. members: {},
  15289. list_members: [], // so we can elect a new focus
  15290. presMap: {},
  15291. preziMap: {},
  15292. joined: false,
  15293. isOwner: false,
  15294. role: null,
  15295. focusMucJid: null,
  15296. bridgeIsDown: false,
  15297. init: function (conn) {
  15298. this.connection = conn;
  15299. },
  15300. initPresenceMap: function (myroomjid) {
  15301. this.presMap['to'] = myroomjid;
  15302. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15303. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15304. this.addAudioInfoToPresence(true);
  15305. }
  15306. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15307. this.addVideoInfoToPresence(true);
  15308. }
  15309. },
  15310. doJoin: function (jid, password) {
  15311. this.myroomjid = jid;
  15312. console.info("Joined MUC as " + this.myroomjid);
  15313. this.initPresenceMap(this.myroomjid);
  15314. if (!this.roomjid) {
  15315. this.roomjid = Strophe.getBareJidFromJid(jid);
  15316. // add handlers (just once)
  15317. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15318. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15319. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15320. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15321. }
  15322. if (password !== undefined) {
  15323. this.presMap['password'] = password;
  15324. }
  15325. this.sendPresence();
  15326. },
  15327. doLeave: function () {
  15328. console.log("do leave", this.myroomjid);
  15329. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15330. this.presMap.length = 0;
  15331. this.connection.send(pres);
  15332. },
  15333. createNonAnonymousRoom: function () {
  15334. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15335. var getForm = $iq({type: 'get', to: this.roomjid})
  15336. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15337. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15338. var self = this;
  15339. this.connection.sendIQ(getForm, function (form) {
  15340. if (!$(form).find(
  15341. '>query>x[xmlns="jabber:x:data"]' +
  15342. '>field[var="muc#roomconfig_whois"]').length) {
  15343. console.error('non-anonymous rooms not supported');
  15344. return;
  15345. }
  15346. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15347. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15348. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15349. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15350. .c('value')
  15351. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15352. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15353. .c('value').t('anyone').up().up();
  15354. self.connection.sendIQ(formSubmit);
  15355. }, function (error) {
  15356. console.error("Error getting room configuration form");
  15357. });
  15358. },
  15359. onPresence: function (pres) {
  15360. var from = pres.getAttribute('from');
  15361. // What is this for? A workaround for something?
  15362. if (pres.getAttribute('type')) {
  15363. return true;
  15364. }
  15365. // Parse etherpad tag.
  15366. var etherpad = $(pres).find('>etherpad');
  15367. if (etherpad.length) {
  15368. if (config.etherpad_base) {
  15369. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15370. }
  15371. }
  15372. // Parse prezi tag.
  15373. var presentation = $(pres).find('>prezi');
  15374. if (presentation.length) {
  15375. var url = presentation.attr('url');
  15376. var current = presentation.find('>current').text();
  15377. console.log('presentation info received from', from, url);
  15378. if (this.preziMap[from] == null) {
  15379. this.preziMap[from] = url;
  15380. $(document).trigger('presentationadded.muc', [from, url, current]);
  15381. }
  15382. else {
  15383. $(document).trigger('gotoslide.muc', [from, url, current]);
  15384. }
  15385. }
  15386. else if (this.preziMap[from] != null) {
  15387. var url = this.preziMap[from];
  15388. delete this.preziMap[from];
  15389. $(document).trigger('presentationremoved.muc', [from, url]);
  15390. }
  15391. // Parse audio info tag.
  15392. var audioMuted = $(pres).find('>audiomuted');
  15393. if (audioMuted.length) {
  15394. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  15395. from, (audioMuted.text() === "true"));
  15396. }
  15397. // Parse video info tag.
  15398. var videoMuted = $(pres).find('>videomuted');
  15399. if (videoMuted.length) {
  15400. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  15401. from, (videoMuted.text() === "true"));
  15402. }
  15403. var startMuted = $(pres).find('>startmuted');
  15404. if (startMuted.length)
  15405. {
  15406. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15407. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  15408. }
  15409. var devices = $(pres).find('>devices');
  15410. if(devices.length)
  15411. {
  15412. var audio = devices.find('>audio');
  15413. var video = devices.find('>video');
  15414. var devicesValues = {audio: false, video: false};
  15415. if(audio.length && audio.text() === "true")
  15416. {
  15417. devicesValues.audio = true;
  15418. }
  15419. if(video.length && video.text() === "true")
  15420. {
  15421. devicesValues.video = true;
  15422. }
  15423. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15424. Strophe.getResourceFromJid(from), devicesValues);
  15425. }
  15426. var videoType = $(pres).find('>videoType');
  15427. if (videoType.length)
  15428. {
  15429. if (videoType.text().length)
  15430. {
  15431. eventEmitter.emit(XMPPEvents.VIDEO_TYPE,
  15432. Strophe.getResourceFromJid(from), videoType.text());
  15433. }
  15434. }
  15435. var stats = $(pres).find('>stats');
  15436. if (stats.length) {
  15437. var statsObj = {};
  15438. Strophe.forEachChild(stats[0], "stat", function (el) {
  15439. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15440. });
  15441. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15442. }
  15443. // Parse status.
  15444. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15445. this.isOwner = true;
  15446. this.createNonAnonymousRoom();
  15447. }
  15448. // Parse roles.
  15449. var member = {};
  15450. member.show = $(pres).find('>show').text();
  15451. member.status = $(pres).find('>status').text();
  15452. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15453. member.affiliation = tmp.attr('affiliation');
  15454. member.role = tmp.attr('role');
  15455. // Focus recognition
  15456. member.jid = tmp.attr('jid');
  15457. member.isFocus = false;
  15458. if (member.jid
  15459. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15460. member.isFocus = true;
  15461. }
  15462. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15463. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  15464. if (from == this.myroomjid) {
  15465. if (member.affiliation == 'owner') this.isOwner = true;
  15466. if (this.role !== member.role) {
  15467. this.role = member.role;
  15468. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15469. from, member, pres, Moderator.isModerator());
  15470. }
  15471. if (!this.joined) {
  15472. this.joined = true;
  15473. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15474. this.list_members.push(from);
  15475. }
  15476. } else if (this.members[from] === undefined) {
  15477. // new participant
  15478. this.members[from] = member;
  15479. this.list_members.push(from);
  15480. console.log('entered', from, member);
  15481. if (member.isFocus) {
  15482. this.focusMucJid = from;
  15483. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15484. }
  15485. else {
  15486. var id = $(pres).find('>userId').text();
  15487. var email = $(pres).find('>email');
  15488. if (email.length > 0) {
  15489. id = email.text();
  15490. }
  15491. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15492. }
  15493. } else {
  15494. // Presence update for existing participant
  15495. // Watch role change:
  15496. if (this.members[from].role != member.role) {
  15497. this.members[from].role = member.role;
  15498. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15499. member.role, member.displayName);
  15500. }
  15501. }
  15502. // Always trigger presence to update bindings
  15503. this.parsePresence(from, member, pres);
  15504. // Trigger status message update
  15505. if (member.status) {
  15506. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15507. }
  15508. return true;
  15509. },
  15510. onPresenceUnavailable: function (pres) {
  15511. var from = pres.getAttribute('from');
  15512. // room destroyed ?
  15513. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15514. '>destroy').length) {
  15515. var reason;
  15516. var reasonSelect = $(pres).find(
  15517. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15518. '>destroy>reason');
  15519. if (reasonSelect.length) {
  15520. reason = reasonSelect.text();
  15521. }
  15522. XMPP.disposeConference(false);
  15523. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15524. return true;
  15525. }
  15526. // Status code 110 indicates that this notification is "self-presence".
  15527. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15528. delete this.members[from];
  15529. this.list_members.splice(this.list_members.indexOf(from), 1);
  15530. this.onParticipantLeft(from);
  15531. }
  15532. // If the status code is 110 this means we're leaving and we would like
  15533. // to remove everyone else from our view, so we trigger the event.
  15534. else if (this.list_members.length > 1) {
  15535. for (var i = 0; i < this.list_members.length; i++) {
  15536. var member = this.list_members[i];
  15537. delete this.members[i];
  15538. this.list_members.splice(i, 1);
  15539. this.onParticipantLeft(member);
  15540. }
  15541. }
  15542. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15543. $(document).trigger('kicked.muc', [from]);
  15544. if (this.myroomjid === from) {
  15545. XMPP.disposeConference(false);
  15546. eventEmitter.emit(XMPPEvents.KICKED);
  15547. }
  15548. }
  15549. return true;
  15550. },
  15551. onPresenceError: function (pres) {
  15552. var from = pres.getAttribute('from');
  15553. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15554. console.log('on password required', from);
  15555. var self = this;
  15556. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15557. self.doJoin(from, value);
  15558. });
  15559. } else if ($(pres).find(
  15560. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15561. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15562. if (toDomain === config.hosts.anonymousdomain) {
  15563. // enter the room by replying with 'not-authorized'. This would
  15564. // result in reconnection from authorized domain.
  15565. // We're either missing Jicofo/Prosody config for anonymous
  15566. // domains or something is wrong.
  15567. // XMPP.promptLogin();
  15568. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15569. } else {
  15570. console.warn('onPresError ', pres);
  15571. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15572. }
  15573. } else {
  15574. console.warn('onPresError ', pres);
  15575. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15576. }
  15577. return true;
  15578. },
  15579. sendMessage: function (body, nickname) {
  15580. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15581. msg.c('body', body).up();
  15582. if (nickname) {
  15583. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15584. }
  15585. this.connection.send(msg);
  15586. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15587. },
  15588. setSubject: function (subject) {
  15589. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15590. msg.c('subject', subject);
  15591. this.connection.send(msg);
  15592. console.log("topic changed to " + subject);
  15593. },
  15594. onMessage: function (msg) {
  15595. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15596. var from = msg.getAttribute('from');
  15597. var nick =
  15598. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15599. .text() ||
  15600. Strophe.getResourceFromJid(from);
  15601. var txt = $(msg).find('>body').text();
  15602. var type = msg.getAttribute("type");
  15603. if (type == "error") {
  15604. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15605. $(msg).find('>text').text(), txt);
  15606. return true;
  15607. }
  15608. var subject = $(msg).find('>subject');
  15609. if (subject.length) {
  15610. var subjectText = subject.text();
  15611. if (subjectText || subjectText == "") {
  15612. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15613. console.log("Subject is changed to " + subjectText);
  15614. }
  15615. }
  15616. // xep-0203 delay
  15617. var stamp = $(msg).find('>delay').attr('stamp');
  15618. if (!stamp) {
  15619. // or xep-0091 delay, UTC timestamp
  15620. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15621. if (stamp) {
  15622. // the format is CCYYMMDDThh:mm:ss
  15623. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15624. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15625. }
  15626. }
  15627. if (txt) {
  15628. console.log('chat', nick, txt);
  15629. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15630. from, nick, txt, this.myroomjid, stamp);
  15631. }
  15632. return true;
  15633. },
  15634. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15635. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15636. var ob = this;
  15637. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15638. function (res) {
  15639. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15640. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15641. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15642. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15643. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15644. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15645. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15646. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15647. ob.connection.sendIQ(formsubmit,
  15648. onSuccess,
  15649. onError);
  15650. } else {
  15651. onNotSupported();
  15652. }
  15653. }, onError);
  15654. },
  15655. kick: function (jid) {
  15656. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15657. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15658. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15659. .c('reason').t('You have been kicked.').up().up().up();
  15660. this.connection.sendIQ(
  15661. kickIQ,
  15662. function (result) {
  15663. console.log('Kick participant with jid: ', jid, result);
  15664. },
  15665. function (error) {
  15666. console.log('Kick participant error: ', error);
  15667. });
  15668. },
  15669. sendPresence: function () {
  15670. if (!this.presMap['to']) {
  15671. // Too early to send presence - not initialized
  15672. return;
  15673. }
  15674. var pres = $pres({to: this.presMap['to'] });
  15675. pres.c('x', {xmlns: this.presMap['xns']});
  15676. if (this.presMap['password']) {
  15677. pres.c('password').t(this.presMap['password']).up();
  15678. }
  15679. pres.up();
  15680. // Send XEP-0115 'c' stanza that contains our capabilities info
  15681. if (this.connection.caps) {
  15682. this.connection.caps.node = config.clientNode;
  15683. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15684. }
  15685. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15686. .t(navigator.userAgent).up();
  15687. if (this.presMap['bridgeIsDown']) {
  15688. pres.c('bridgeIsDown').up();
  15689. }
  15690. if (this.presMap['email']) {
  15691. pres.c('email').t(this.presMap['email']).up();
  15692. }
  15693. if (this.presMap['userId']) {
  15694. pres.c('userId').t(this.presMap['userId']).up();
  15695. }
  15696. if (this.presMap['displayName']) {
  15697. // XEP-0172
  15698. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15699. .t(this.presMap['displayName']).up();
  15700. }
  15701. if(this.presMap["devices"])
  15702. {
  15703. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15704. .c('video').t(this.presMap['devices'].video).up().up();
  15705. }
  15706. if (this.presMap['audions']) {
  15707. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15708. .t(this.presMap['audiomuted']).up();
  15709. }
  15710. if (this.presMap['videons']) {
  15711. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15712. .t(this.presMap['videomuted']).up();
  15713. }
  15714. if (this.presMap['videoTypeNs']) {
  15715. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  15716. .t(this.presMap['videoType']).up();
  15717. }
  15718. if (this.presMap['statsns']) {
  15719. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15720. for (var stat in this.presMap["stats"])
  15721. if (this.presMap["stats"][stat] != null)
  15722. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15723. pres.up();
  15724. }
  15725. if (this.presMap['prezins']) {
  15726. pres.c('prezi',
  15727. {xmlns: this.presMap['prezins'],
  15728. 'url': this.presMap['preziurl']})
  15729. .c('current').t(this.presMap['prezicurrent']).up().up();
  15730. }
  15731. if(this.presMap["startMuted"] !== undefined)
  15732. {
  15733. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15734. video: this.presMap["startMuted"].video,
  15735. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15736. delete this.presMap["startMuted"];
  15737. }
  15738. pres.up();
  15739. this.connection.send(pres);
  15740. },
  15741. addDisplayNameToPresence: function (displayName) {
  15742. this.presMap['displayName'] = displayName;
  15743. },
  15744. addDevicesToPresence: function (devices) {
  15745. this.presMap['devices'] = devices;
  15746. },
  15747. /**
  15748. * Adds the info about the type of our video stream.
  15749. * @param videoType 'camera' or 'screen'
  15750. */
  15751. addVideoTypeToPresence: function (videoType) {
  15752. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  15753. this.presMap['videoType'] = videoType;
  15754. },
  15755. addPreziToPresence: function (url, currentSlide) {
  15756. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15757. this.presMap['preziurl'] = url;
  15758. this.presMap['prezicurrent'] = currentSlide;
  15759. },
  15760. removePreziFromPresence: function () {
  15761. delete this.presMap['prezins'];
  15762. delete this.presMap['preziurl'];
  15763. delete this.presMap['prezicurrent'];
  15764. },
  15765. addCurrentSlideToPresence: function (currentSlide) {
  15766. this.presMap['prezicurrent'] = currentSlide;
  15767. },
  15768. getPrezi: function (roomjid) {
  15769. return this.preziMap[roomjid];
  15770. },
  15771. addAudioInfoToPresence: function (isMuted) {
  15772. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15773. this.presMap['audiomuted'] = isMuted.toString();
  15774. },
  15775. addVideoInfoToPresence: function (isMuted) {
  15776. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15777. this.presMap['videomuted'] = isMuted.toString();
  15778. },
  15779. addConnectionInfoToPresence: function (stats) {
  15780. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15781. this.presMap['stats'] = stats;
  15782. },
  15783. findJidFromResource: function (resourceJid) {
  15784. if (resourceJid &&
  15785. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15786. return this.myroomjid;
  15787. }
  15788. var peerJid = null;
  15789. Object.keys(this.members).some(function (jid) {
  15790. peerJid = jid;
  15791. return Strophe.getResourceFromJid(jid) === resourceJid;
  15792. });
  15793. return peerJid;
  15794. },
  15795. addBridgeIsDownToPresence: function () {
  15796. this.presMap['bridgeIsDown'] = true;
  15797. },
  15798. addEmailToPresence: function (email) {
  15799. this.presMap['email'] = email;
  15800. },
  15801. addUserIdToPresence: function (userId) {
  15802. this.presMap['userId'] = userId;
  15803. },
  15804. addStartMutedToPresence: function (audio, video) {
  15805. this.presMap["startMuted"] = {audio: audio, video: video};
  15806. },
  15807. isModerator: function () {
  15808. return this.role === 'moderator';
  15809. },
  15810. getMemberRole: function (peerJid) {
  15811. if (this.members[peerJid]) {
  15812. return this.members[peerJid].role;
  15813. }
  15814. return null;
  15815. },
  15816. onParticipantLeft: function (jid) {
  15817. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15818. this.connection.jingle.terminateByJid(jid);
  15819. if (this.getPrezi(jid)) {
  15820. $(document).trigger('presentationremoved.muc',
  15821. [jid, this.getPrezi(jid)]);
  15822. }
  15823. Moderator.onMucMemberLeft(jid);
  15824. },
  15825. parsePresence: function (from, member, pres) {
  15826. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  15827. this.bridgeIsDown = true;
  15828. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15829. }
  15830. if(member.isFocus)
  15831. return;
  15832. var displayName = !config.displayJids
  15833. ? member.displayName : Strophe.getResourceFromJid(from);
  15834. if (displayName && displayName.length > 0) {
  15835. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15836. }
  15837. var id = $(pres).find('>userID').text();
  15838. var email = $(pres).find('>email');
  15839. if (email.length > 0) {
  15840. id = email.text();
  15841. }
  15842. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15843. }
  15844. });
  15845. };
  15846. },{"../../service/xmpp/XMPPEvents":161,"./moderator":60}],63:[function(require,module,exports){
  15847. /* jshint -W117 */
  15848. var JingleSession = require("./JingleSessionPC");
  15849. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15850. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15851. module.exports = function(XMPP, eventEmitter) {
  15852. Strophe.addConnectionPlugin('jingle', {
  15853. connection: null,
  15854. sessions: {},
  15855. jid2session: {},
  15856. ice_config: {iceServers: []},
  15857. pc_constraints: {},
  15858. activecall: null,
  15859. media_constraints: {
  15860. mandatory: {
  15861. 'OfferToReceiveAudio': true,
  15862. 'OfferToReceiveVideo': true
  15863. }
  15864. // MozDontOfferDataChannel: true when this is firefox
  15865. },
  15866. init: function (conn) {
  15867. this.connection = conn;
  15868. if (this.connection.disco) {
  15869. // http://xmpp.org/extensions/xep-0167.html#support
  15870. // http://xmpp.org/extensions/xep-0176.html#support
  15871. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15872. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15873. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15874. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15875. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15876. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15877. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15878. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15879. || RTCBrowserType.isTemasysPluginUsed()) {
  15880. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15881. }
  15882. // this is dealt with by SDP O/A so we don't need to announce this
  15883. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15884. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15885. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15886. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15887. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15888. }
  15889. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15890. },
  15891. onJingle: function (iq) {
  15892. var sid = $(iq).find('jingle').attr('sid');
  15893. var action = $(iq).find('jingle').attr('action');
  15894. var fromJid = iq.getAttribute('from');
  15895. // send ack first
  15896. var ack = $iq({type: 'result',
  15897. to: fromJid,
  15898. id: iq.getAttribute('id')
  15899. });
  15900. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15901. var sess = this.sessions[sid];
  15902. if ('session-initiate' != action) {
  15903. if (sess === null) {
  15904. ack.type = 'error';
  15905. ack.c('error', {type: 'cancel'})
  15906. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15907. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15908. this.connection.send(ack);
  15909. return true;
  15910. }
  15911. // local jid is not checked
  15912. if (fromJid != sess.peerjid) {
  15913. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15914. ack.type = 'error';
  15915. ack.c('error', {type: 'cancel'})
  15916. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15917. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15918. this.connection.send(ack);
  15919. return true;
  15920. }
  15921. } else if (sess !== undefined) {
  15922. // existing session with same session id
  15923. // this might be out-of-order if the sess.peerjid is the same as from
  15924. ack.type = 'error';
  15925. ack.c('error', {type: 'cancel'})
  15926. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15927. console.warn('duplicate session id', sid);
  15928. this.connection.send(ack);
  15929. return true;
  15930. }
  15931. // FIXME: check for a defined action
  15932. this.connection.send(ack);
  15933. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15934. switch (action) {
  15935. case 'session-initiate':
  15936. var startMuted = $(iq).find('jingle>startmuted');
  15937. if (startMuted && startMuted.length > 0) {
  15938. var audioMuted = startMuted.attr("audio");
  15939. var videoMuted = startMuted.attr("video");
  15940. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15941. audioMuted === "true", videoMuted === "true");
  15942. }
  15943. sess = new JingleSession(
  15944. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15945. this.connection, XMPP, eventEmitter);
  15946. // configure session
  15947. sess.media_constraints = this.media_constraints;
  15948. sess.pc_constraints = this.pc_constraints;
  15949. sess.ice_config = this.ice_config;
  15950. sess.initialize(fromJid, false);
  15951. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15952. sess.setOffer($(iq).find('>jingle'));
  15953. this.sessions[sess.sid] = sess;
  15954. this.jid2session[sess.peerjid] = sess;
  15955. // the callback should either
  15956. // .sendAnswer and .accept
  15957. // or .sendTerminate -- not necessarily synchronous
  15958. // TODO: do we check activecall == null?
  15959. this.connection.jingle.activecall = sess;
  15960. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15961. // TODO: check affiliation and/or role
  15962. console.log('emuc data for', sess.peerjid,
  15963. this.connection.emuc.members[sess.peerjid]);
  15964. sess.sendAnswer();
  15965. sess.accept();
  15966. break;
  15967. case 'session-accept':
  15968. sess.setAnswer($(iq).find('>jingle'));
  15969. sess.accept();
  15970. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15971. break;
  15972. case 'session-terminate':
  15973. // If this is not the focus sending the terminate, we have
  15974. // nothing more to do here.
  15975. if (Object.keys(this.sessions).length < 1
  15976. || !(this.sessions[Object.keys(this.sessions)[0]]
  15977. instanceof JingleSession))
  15978. {
  15979. break;
  15980. }
  15981. console.log('terminating...', sess.sid);
  15982. sess.terminate();
  15983. this.terminate(sess.sid);
  15984. if ($(iq).find('>jingle>reason').length) {
  15985. $(document).trigger('callterminated.jingle', [
  15986. sess.sid,
  15987. sess.peerjid,
  15988. $(iq).find('>jingle>reason>:first')[0].tagName,
  15989. $(iq).find('>jingle>reason>text').text()
  15990. ]);
  15991. } else {
  15992. $(document).trigger('callterminated.jingle',
  15993. [sess.sid, sess.peerjid]);
  15994. }
  15995. break;
  15996. case 'transport-info':
  15997. sess.addIceCandidate($(iq).find('>jingle>content'));
  15998. break;
  15999. case 'session-info':
  16000. var affected;
  16001. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16002. $(document).trigger('ringing.jingle', [sess.sid]);
  16003. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16004. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16005. $(document).trigger('mute.jingle', [sess.sid, affected]);
  16006. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16007. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16008. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  16009. }
  16010. break;
  16011. case 'addsource': // FIXME: proprietary, un-jingleish
  16012. case 'source-add': // FIXME: proprietary
  16013. sess.addSource($(iq).find('>jingle>content'), fromJid);
  16014. break;
  16015. case 'removesource': // FIXME: proprietary, un-jingleish
  16016. case 'source-remove': // FIXME: proprietary
  16017. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  16018. break;
  16019. default:
  16020. console.warn('jingle action not implemented', action);
  16021. break;
  16022. }
  16023. return true;
  16024. },
  16025. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  16026. var sess = new JingleSession(myjid || this.connection.jid,
  16027. Math.random().toString(36).substr(2, 12), // random string
  16028. this.connection, XMPP, eventEmitter);
  16029. // configure session
  16030. sess.media_constraints = this.media_constraints;
  16031. sess.pc_constraints = this.pc_constraints;
  16032. sess.ice_config = this.ice_config;
  16033. sess.initialize(peerjid, true);
  16034. this.sessions[sess.sid] = sess;
  16035. this.jid2session[sess.peerjid] = sess;
  16036. sess.sendOffer();
  16037. return sess;
  16038. },
  16039. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  16040. if (sid === null || sid === undefined) {
  16041. for (sid in this.sessions) {
  16042. if (this.sessions[sid].state != 'ended') {
  16043. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16044. this.sessions[sid].terminate();
  16045. }
  16046. delete this.jid2session[this.sessions[sid].peerjid];
  16047. delete this.sessions[sid];
  16048. }
  16049. } else if (this.sessions.hasOwnProperty(sid)) {
  16050. if (this.sessions[sid].state != 'ended') {
  16051. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16052. this.sessions[sid].terminate();
  16053. }
  16054. delete this.jid2session[this.sessions[sid].peerjid];
  16055. delete this.sessions[sid];
  16056. }
  16057. },
  16058. // Used to terminate a session when an unavailable presence is received.
  16059. terminateByJid: function (jid) {
  16060. if (this.jid2session.hasOwnProperty(jid)) {
  16061. var sess = this.jid2session[jid];
  16062. if (sess) {
  16063. sess.terminate();
  16064. console.log('peer went away silently', jid);
  16065. delete this.sessions[sess.sid];
  16066. delete this.jid2session[jid];
  16067. $(document).trigger('callterminated.jingle',
  16068. [sess.sid, jid], 'gone');
  16069. }
  16070. }
  16071. },
  16072. terminateRemoteByJid: function (jid, reason) {
  16073. if (this.jid2session.hasOwnProperty(jid)) {
  16074. var sess = this.jid2session[jid];
  16075. if (sess) {
  16076. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  16077. sess.terminate();
  16078. console.log('terminate peer with jid', sess.sid, jid);
  16079. delete this.sessions[sess.sid];
  16080. delete this.jid2session[jid];
  16081. $(document).trigger('callterminated.jingle',
  16082. [sess.sid, jid, 'kicked']);
  16083. }
  16084. }
  16085. },
  16086. getStunAndTurnCredentials: function () {
  16087. // get stun and turn configuration from server via xep-0215
  16088. // uses time-limited credentials as described in
  16089. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  16090. //
  16091. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  16092. // for a prosody module which implements this
  16093. //
  16094. // currently, this doesn't work with updateIce and therefore credentials with a long
  16095. // validity have to be fetched before creating the peerconnection
  16096. // TODO: implement refresh via updateIce as described in
  16097. // https://code.google.com/p/webrtc/issues/detail?id=1650
  16098. var self = this;
  16099. this.connection.sendIQ(
  16100. $iq({type: 'get', to: this.connection.domain})
  16101. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  16102. function (res) {
  16103. var iceservers = [];
  16104. $(res).find('>services>service').each(function (idx, el) {
  16105. el = $(el);
  16106. var dict = {};
  16107. var type = el.attr('type');
  16108. switch (type) {
  16109. case 'stun':
  16110. dict.url = 'stun:' + el.attr('host');
  16111. if (el.attr('port')) {
  16112. dict.url += ':' + el.attr('port');
  16113. }
  16114. iceservers.push(dict);
  16115. break;
  16116. case 'turn':
  16117. case 'turns':
  16118. dict.url = type + ':';
  16119. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  16120. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  16121. dict.url += el.attr('username') + '@';
  16122. } else {
  16123. dict.username = el.attr('username'); // only works in M28
  16124. }
  16125. }
  16126. dict.url += el.attr('host');
  16127. if (el.attr('port') && el.attr('port') != '3478') {
  16128. dict.url += ':' + el.attr('port');
  16129. }
  16130. if (el.attr('transport') && el.attr('transport') != 'udp') {
  16131. dict.url += '?transport=' + el.attr('transport');
  16132. }
  16133. if (el.attr('password')) {
  16134. dict.credential = el.attr('password');
  16135. }
  16136. iceservers.push(dict);
  16137. break;
  16138. }
  16139. });
  16140. self.ice_config.iceServers = iceservers;
  16141. },
  16142. function (err) {
  16143. console.warn('getting turn credentials failed', err);
  16144. console.warn('is mod_turncredentials or similar installed?');
  16145. }
  16146. );
  16147. // implement push?
  16148. },
  16149. /**
  16150. * Returns the data saved in 'updateLog' in a format to be logged.
  16151. */
  16152. getLog: function () {
  16153. var data = {};
  16154. var self = this;
  16155. Object.keys(this.sessions).forEach(function (sid) {
  16156. var session = self.sessions[sid];
  16157. if (session.peerconnection && session.peerconnection.updateLog) {
  16158. // FIXME: should probably be a .dump call
  16159. data["jingle_" + session.sid] = {
  16160. updateLog: session.peerconnection.updateLog,
  16161. stats: session.peerconnection.stats,
  16162. url: window.location.href
  16163. };
  16164. }
  16165. });
  16166. return data;
  16167. }
  16168. });
  16169. };
  16170. },{"../../service/xmpp/XMPPEvents":161,"../RTC/RTCBrowserType":8,"./JingleSessionPC":54}],64:[function(require,module,exports){
  16171. /* global Strophe */
  16172. module.exports = function () {
  16173. Strophe.addConnectionPlugin('logger', {
  16174. // logs raw stanzas and makes them available for download as JSON
  16175. connection: null,
  16176. log: [],
  16177. init: function (conn) {
  16178. this.connection = conn;
  16179. this.connection.rawInput = this.log_incoming.bind(this);
  16180. this.connection.rawOutput = this.log_outgoing.bind(this);
  16181. },
  16182. log_incoming: function (stanza) {
  16183. this.log.push([new Date().getTime(), 'incoming', stanza]);
  16184. },
  16185. log_outgoing: function (stanza) {
  16186. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  16187. }
  16188. });
  16189. };
  16190. },{}],65:[function(require,module,exports){
  16191. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  16192. setAudioMuted, Strophe */
  16193. /**
  16194. * Moderate connection plugin.
  16195. */
  16196. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16197. module.exports = function (XMPP, eventEmitter) {
  16198. Strophe.addConnectionPlugin('moderate', {
  16199. connection: null,
  16200. init: function (conn) {
  16201. this.connection = conn;
  16202. this.connection.addHandler(this.onMute.bind(this),
  16203. 'http://jitsi.org/jitmeet/audio',
  16204. 'iq',
  16205. 'set',
  16206. null,
  16207. null);
  16208. },
  16209. setMute: function (jid, mute) {
  16210. console.info("set mute", mute);
  16211. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  16212. .c('mute', {
  16213. xmlns: 'http://jitsi.org/jitmeet/audio',
  16214. jid: jid
  16215. })
  16216. .t(mute.toString())
  16217. .up();
  16218. this.connection.sendIQ(
  16219. iqToFocus,
  16220. function (result) {
  16221. console.log('set mute', result);
  16222. },
  16223. function (error) {
  16224. console.log('set mute error', error);
  16225. });
  16226. },
  16227. onMute: function (iq) {
  16228. var from = iq.getAttribute('from');
  16229. if (from !== this.connection.emuc.focusMucJid) {
  16230. console.warn("Ignored mute from non focus peer");
  16231. return false;
  16232. }
  16233. var mute = $(iq).find('mute');
  16234. if (mute.length) {
  16235. var doMuteAudio = mute.text() === "true";
  16236. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16237. XMPP.forceMuted = doMuteAudio;
  16238. }
  16239. return true;
  16240. },
  16241. eject: function (jid) {
  16242. // We're not the focus, so can't terminate
  16243. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16244. this.connection.emuc.kick(jid);
  16245. }
  16246. });
  16247. }
  16248. },{"../../service/xmpp/XMPPEvents":161}],66:[function(require,module,exports){
  16249. /* jshint -W117 */
  16250. module.exports = function() {
  16251. Strophe.addConnectionPlugin('rayo',
  16252. {
  16253. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16254. connection: null,
  16255. init: function (conn) {
  16256. this.connection = conn;
  16257. if (this.connection.disco) {
  16258. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16259. }
  16260. this.connection.addHandler(
  16261. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16262. },
  16263. onRayo: function (iq) {
  16264. console.info("Rayo IQ", iq);
  16265. },
  16266. dial: function (to, from, roomName, roomPass) {
  16267. var self = this;
  16268. var req = $iq(
  16269. {
  16270. type: 'set',
  16271. to: this.connection.emuc.focusMucJid
  16272. }
  16273. );
  16274. req.c('dial',
  16275. {
  16276. xmlns: this.RAYO_XMLNS,
  16277. to: to,
  16278. from: from
  16279. });
  16280. req.c('header',
  16281. {
  16282. name: 'JvbRoomName',
  16283. value: roomName
  16284. }).up();
  16285. if (roomPass !== null && roomPass.length) {
  16286. req.c('header',
  16287. {
  16288. name: 'JvbRoomPassword',
  16289. value: roomPass
  16290. }).up();
  16291. }
  16292. this.connection.sendIQ(
  16293. req,
  16294. function (result) {
  16295. console.info('Dial result ', result);
  16296. var resource = $(result).find('ref').attr('uri');
  16297. this.call_resource = resource.substr('xmpp:'.length);
  16298. console.info(
  16299. "Received call resource: " + this.call_resource);
  16300. },
  16301. function (error) {
  16302. console.info('Dial error ', error);
  16303. }
  16304. );
  16305. },
  16306. hang_up: function () {
  16307. if (!this.call_resource) {
  16308. console.warn("No call in progress");
  16309. return;
  16310. }
  16311. var self = this;
  16312. var req = $iq(
  16313. {
  16314. type: 'set',
  16315. to: this.call_resource
  16316. }
  16317. );
  16318. req.c('hangup',
  16319. {
  16320. xmlns: this.RAYO_XMLNS
  16321. });
  16322. this.connection.sendIQ(
  16323. req,
  16324. function (result) {
  16325. console.info('Hangup result ', result);
  16326. self.call_resource = null;
  16327. },
  16328. function (error) {
  16329. console.info('Hangup error ', error);
  16330. self.call_resource = null;
  16331. }
  16332. );
  16333. }
  16334. }
  16335. );
  16336. };
  16337. },{}],67:[function(require,module,exports){
  16338. /**
  16339. * Strophe logger implementation. Logs from level WARN and above.
  16340. */
  16341. module.exports = function () {
  16342. Strophe.log = function (level, msg) {
  16343. switch (level) {
  16344. case Strophe.LogLevel.WARN:
  16345. console.warn("Strophe: " + msg);
  16346. break;
  16347. case Strophe.LogLevel.ERROR:
  16348. case Strophe.LogLevel.FATAL:
  16349. console.error("Strophe: " + msg);
  16350. break;
  16351. }
  16352. };
  16353. Strophe.getStatusString = function (status) {
  16354. switch (status) {
  16355. case Strophe.Status.ERROR:
  16356. return "ERROR";
  16357. case Strophe.Status.CONNECTING:
  16358. return "CONNECTING";
  16359. case Strophe.Status.CONNFAIL:
  16360. return "CONNFAIL";
  16361. case Strophe.Status.AUTHENTICATING:
  16362. return "AUTHENTICATING";
  16363. case Strophe.Status.AUTHFAIL:
  16364. return "AUTHFAIL";
  16365. case Strophe.Status.CONNECTED:
  16366. return "CONNECTED";
  16367. case Strophe.Status.DISCONNECTED:
  16368. return "DISCONNECTED";
  16369. case Strophe.Status.DISCONNECTING:
  16370. return "DISCONNECTING";
  16371. case Strophe.Status.ATTACHED:
  16372. return "ATTACHED";
  16373. default:
  16374. return "unknown";
  16375. }
  16376. };
  16377. };
  16378. },{}],68:[function(require,module,exports){
  16379. /* global $, APP, config, Strophe*/
  16380. var Moderator = require("./moderator");
  16381. var EventEmitter = require("events");
  16382. var Recording = require("./recording");
  16383. var SDP = require("./SDP");
  16384. var Settings = require("../settings/Settings");
  16385. var Pako = require("pako");
  16386. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16387. var RTCEvents = require("../../service/RTC/RTCEvents");
  16388. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16389. var retry = require('retry');
  16390. var eventEmitter = new EventEmitter();
  16391. var connection = null;
  16392. var authenticatedUser = false;
  16393. function connect(jid, password) {
  16394. var faultTolerantConnect = retry.operation({
  16395. retries: 3
  16396. });
  16397. // fault tolerant connect
  16398. faultTolerantConnect.attempt(function () {
  16399. connection = XMPP.createConnection();
  16400. Moderator.setConnection(connection);
  16401. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16402. if (config.useIPv6) {
  16403. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16404. if (!connection.jingle.pc_constraints.optional)
  16405. connection.jingle.pc_constraints.optional = [];
  16406. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16407. }
  16408. // Include user info in MUC presence
  16409. var settings = Settings.getSettings();
  16410. if (settings.email) {
  16411. connection.emuc.addEmailToPresence(settings.email);
  16412. }
  16413. if (settings.uid) {
  16414. connection.emuc.addUserIdToPresence(settings.uid);
  16415. }
  16416. if (settings.displayName) {
  16417. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16418. }
  16419. // connection.connect() starts the connection process.
  16420. //
  16421. // As the connection process proceeds, the user supplied callback will
  16422. // be triggered multiple times with status updates. The callback should
  16423. // take two arguments - the status code and the error condition.
  16424. //
  16425. // The status code will be one of the values in the Strophe.Status
  16426. // constants. The error condition will be one of the conditions defined
  16427. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16428. //
  16429. // The Parameters wait, hold and route are optional and only relevant
  16430. // for BOSH connections. Please see XEP 124 for a more detailed
  16431. // explanation of the optional parameters.
  16432. //
  16433. // Connection status constants for use by the connection handler
  16434. // callback.
  16435. //
  16436. // Status.ERROR - An error has occurred (websockets specific)
  16437. // Status.CONNECTING - The connection is currently being made
  16438. // Status.CONNFAIL - The connection attempt failed
  16439. // Status.AUTHENTICATING - The connection is authenticating
  16440. // Status.AUTHFAIL - The authentication attempt failed
  16441. // Status.CONNECTED - The connection has succeeded
  16442. // Status.DISCONNECTED - The connection has been terminated
  16443. // Status.DISCONNECTING - The connection is currently being terminated
  16444. // Status.ATTACHED - The connection has been attached
  16445. var anonymousConnectionFailed = false;
  16446. var connectionFailed = false;
  16447. var lastErrorMsg;
  16448. connection.connect(jid, password, function (status, msg) {
  16449. console.log('Strophe status changed to',
  16450. Strophe.getStatusString(status), msg);
  16451. if (status === Strophe.Status.CONNECTED) {
  16452. if (config.useStunTurn) {
  16453. connection.jingle.getStunAndTurnCredentials();
  16454. }
  16455. console.info("My Jabber ID: " + connection.jid);
  16456. if (password)
  16457. authenticatedUser = true;
  16458. maybeDoJoin();
  16459. } else if (status === Strophe.Status.CONNFAIL) {
  16460. if (msg === 'x-strophe-bad-non-anon-jid') {
  16461. anonymousConnectionFailed = true;
  16462. } else {
  16463. connectionFailed = true;
  16464. }
  16465. lastErrorMsg = msg;
  16466. } else if (status === Strophe.Status.DISCONNECTED) {
  16467. if (anonymousConnectionFailed) {
  16468. // prompt user for username and password
  16469. XMPP.promptLogin();
  16470. } else {
  16471. // Strophe already has built-in HTTP/BOSH error handling and
  16472. // request retry logic. Requests are resent automatically
  16473. // until their error count reaches 5. Strophe.js disconnects
  16474. // if the error count is > 5. We are not replicating this
  16475. // here.
  16476. //
  16477. // The "problem" is that failed HTTP/BOSH requests don't
  16478. // trigger a callback with a status update, so when a
  16479. // callback with status Strophe.Status.DISCONNECTED arrives,
  16480. // we can't be sure if it's a graceful disconnect or if it's
  16481. // triggered by some HTTP/BOSH error.
  16482. //
  16483. // But that's a minor issue in Jitsi Meet as we never
  16484. // disconnect anyway, not even when the user closes the
  16485. // browser window (which is kind of wrong, but the point is
  16486. // that we should never ever get disconnected).
  16487. //
  16488. // On the other hand, failed connections due to XMPP layer
  16489. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16490. //
  16491. // Here we implement retry logic for failed connections due
  16492. // to XMPP layer errors and we display an error to the user
  16493. // if we get disconnected from the XMPP server permanently.
  16494. // If the connection failed, retry.
  16495. if (connectionFailed &&
  16496. faultTolerantConnect.retry("connection-failed")) {
  16497. return;
  16498. }
  16499. // If we failed to connect to the XMPP server, fire an event
  16500. // to let all the interested module now about it.
  16501. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16502. msg ? msg : lastErrorMsg);
  16503. }
  16504. } else if (status === Strophe.Status.AUTHFAIL) {
  16505. // wrong password or username, prompt user
  16506. XMPP.promptLogin();
  16507. }
  16508. });
  16509. });
  16510. }
  16511. function maybeDoJoin() {
  16512. if (connection && connection.connected &&
  16513. Strophe.getResourceFromJid(connection.jid) &&
  16514. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16515. // .connected is true while connecting?
  16516. doJoin();
  16517. }
  16518. }
  16519. function doJoin() {
  16520. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16521. }
  16522. function initStrophePlugins()
  16523. {
  16524. require("./strophe.emuc")(XMPP, eventEmitter);
  16525. require("./strophe.jingle")(XMPP, eventEmitter);
  16526. require("./strophe.moderate")(XMPP, eventEmitter);
  16527. require("./strophe.util")();
  16528. require("./strophe.rayo")();
  16529. require("./strophe.logger")();
  16530. }
  16531. /**
  16532. * If given <tt>localStream</tt> is video one this method will advertise it's
  16533. * video type in MUC presence.
  16534. * @param localStream new or modified <tt>LocalStream</tt>.
  16535. */
  16536. function broadcastLocalVideoType(localStream) {
  16537. if (localStream.videoType)
  16538. XMPP.addToPresence('videoType', localStream.videoType);
  16539. }
  16540. function registerListeners() {
  16541. APP.RTC.addStreamListener(
  16542. function (localStream) {
  16543. maybeDoJoin();
  16544. broadcastLocalVideoType(localStream);
  16545. },
  16546. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16547. );
  16548. APP.RTC.addStreamListener(
  16549. broadcastLocalVideoType,
  16550. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16551. );
  16552. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16553. XMPP.addToPresence("devices", devices);
  16554. });
  16555. }
  16556. var unload = (function () {
  16557. var unloaded = false;
  16558. return function () {
  16559. if (unloaded) { return; }
  16560. unloaded = true;
  16561. if (connection && connection.connected) {
  16562. // ensure signout
  16563. $.ajax({
  16564. type: 'POST',
  16565. url: config.bosh,
  16566. async: false,
  16567. cache: false,
  16568. contentType: 'application/xml',
  16569. data: "<body rid='" +
  16570. (connection.rid || connection._proto.rid) +
  16571. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16572. (connection.sid || connection._proto.sid) +
  16573. "' type='terminate'>" +
  16574. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16575. "</body>",
  16576. success: function (data) {
  16577. console.log('signed out');
  16578. console.log(data);
  16579. },
  16580. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16581. console.log('signout error',
  16582. textStatus + ' (' + errorThrown + ')');
  16583. }
  16584. });
  16585. }
  16586. XMPP.disposeConference(true);
  16587. };
  16588. })();
  16589. function setupEvents() {
  16590. // In recent versions of FF the 'beforeunload' event is not fired when the
  16591. // window or the tab is closed. It is only fired when we leave the page
  16592. // (change URL). If this participant doesn't unload properly, then it
  16593. // becomes a ghost for the rest of the participants that stay in the
  16594. // conference. Thankfully handling the 'unload' event in addition to the
  16595. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16596. // method at least once.
  16597. //
  16598. // The 'unload' method can safely be run multiple times, it will actually do
  16599. // something only the first time that it's run, so we're don't have to worry
  16600. // about browsers that fire both events.
  16601. $(window).bind('beforeunload', unload);
  16602. $(window).bind('unload', unload);
  16603. }
  16604. var XMPP = {
  16605. getConnection: function(){ return connection; },
  16606. sessionTerminated: false,
  16607. /**
  16608. * XMPP connection status
  16609. */
  16610. Status: Strophe.Status,
  16611. /**
  16612. * Remembers if we were muted by the focus.
  16613. * @type {boolean}
  16614. */
  16615. forceMuted: false,
  16616. start: function () {
  16617. setupEvents();
  16618. initStrophePlugins();
  16619. registerListeners();
  16620. Moderator.init(this, eventEmitter);
  16621. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16622. // Force authenticated domain if room is appended with '?login=true'
  16623. if (config.hosts.anonymousdomain &&
  16624. window.location.search.indexOf("login=true") !== -1) {
  16625. configDomain = config.hosts.domain;
  16626. }
  16627. var jid = configDomain || window.location.hostname;
  16628. connect(jid, null);
  16629. },
  16630. createConnection: function () {
  16631. var bosh = config.bosh || '/http-bind';
  16632. return new Strophe.Connection(bosh);
  16633. },
  16634. getStatusString: function (status) {
  16635. return Strophe.getStatusString(status);
  16636. },
  16637. promptLogin: function () {
  16638. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16639. },
  16640. joinRoom: function(roomName, useNicks, nick) {
  16641. var roomjid = roomName;
  16642. if (useNicks) {
  16643. if (nick) {
  16644. roomjid += '/' + nick;
  16645. } else {
  16646. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16647. }
  16648. } else {
  16649. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16650. if(!authenticatedUser)
  16651. tmpJid = tmpJid.substr(0, 8);
  16652. roomjid += '/' + tmpJid;
  16653. }
  16654. connection.emuc.doJoin(roomjid);
  16655. },
  16656. myJid: function () {
  16657. if(!connection)
  16658. return null;
  16659. return connection.emuc.myroomjid;
  16660. },
  16661. myResource: function () {
  16662. if(!connection || ! connection.emuc.myroomjid)
  16663. return null;
  16664. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16665. },
  16666. disposeConference: function (onUnload) {
  16667. var handler = connection.jingle.activecall;
  16668. if (handler && handler.peerconnection) {
  16669. // FIXME: probably removing streams is not required and close() should
  16670. // be enough
  16671. if (APP.RTC.localAudio) {
  16672. handler.peerconnection.removeStream(
  16673. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16674. }
  16675. if (APP.RTC.localVideo) {
  16676. handler.peerconnection.removeStream(
  16677. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16678. }
  16679. handler.peerconnection.close();
  16680. }
  16681. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16682. connection.jingle.activecall = null;
  16683. if (!onUnload) {
  16684. this.sessionTerminated = true;
  16685. connection.emuc.doLeave();
  16686. }
  16687. },
  16688. addListener: function(type, listener) {
  16689. eventEmitter.on(type, listener);
  16690. },
  16691. removeListener: function (type, listener) {
  16692. eventEmitter.removeListener(type, listener);
  16693. },
  16694. allocateConferenceFocus: function(roomName, callback) {
  16695. Moderator.allocateConferenceFocus(roomName, callback);
  16696. },
  16697. getLoginUrl: function (roomName, callback) {
  16698. Moderator.getLoginUrl(roomName, callback);
  16699. },
  16700. getPopupLoginUrl: function (roomName, callback) {
  16701. Moderator.getPopupLoginUrl(roomName, callback);
  16702. },
  16703. isModerator: function () {
  16704. return Moderator.isModerator();
  16705. },
  16706. isSipGatewayEnabled: function () {
  16707. return Moderator.isSipGatewayEnabled();
  16708. },
  16709. isExternalAuthEnabled: function () {
  16710. return Moderator.isExternalAuthEnabled();
  16711. },
  16712. isConferenceInProgress: function () {
  16713. return connection && connection.jingle.activecall &&
  16714. connection.jingle.activecall.peerconnection;
  16715. },
  16716. switchStreams: function (stream, oldStream, callback, isAudio) {
  16717. if (this.isConferenceInProgress()) {
  16718. // FIXME: will block switchInProgress on true value in case of exception
  16719. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16720. } else {
  16721. // We are done immediately
  16722. console.warn("No conference handler or conference not started yet");
  16723. callback();
  16724. }
  16725. },
  16726. sendVideoInfoPresence: function (mute) {
  16727. if(!connection)
  16728. return;
  16729. connection.emuc.addVideoInfoToPresence(mute);
  16730. connection.emuc.sendPresence();
  16731. },
  16732. setVideoMute: function (mute, callback, options) {
  16733. if(!connection)
  16734. return;
  16735. var self = this;
  16736. var localCallback = function (mute) {
  16737. self.sendVideoInfoPresence(mute);
  16738. return callback(mute);
  16739. };
  16740. if(connection.jingle.activecall)
  16741. {
  16742. connection.jingle.activecall.setVideoMute(
  16743. mute, localCallback, options);
  16744. }
  16745. else {
  16746. localCallback(mute);
  16747. }
  16748. },
  16749. setAudioMute: function (mute, callback) {
  16750. if (!(connection && APP.RTC.localAudio)) {
  16751. return false;
  16752. }
  16753. if (this.forceMuted && !mute) {
  16754. console.info("Asking focus for unmute");
  16755. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16756. // FIXME: wait for result before resetting muted status
  16757. this.forceMuted = false;
  16758. }
  16759. if (mute == APP.RTC.localAudio.isMuted()) {
  16760. // Nothing to do
  16761. return true;
  16762. }
  16763. APP.RTC.localAudio.setMute(mute);
  16764. this.sendAudioInfoPresence(mute, callback);
  16765. return true;
  16766. },
  16767. sendAudioInfoPresence: function(mute, callback) {
  16768. if(connection) {
  16769. connection.emuc.addAudioInfoToPresence(mute);
  16770. connection.emuc.sendPresence();
  16771. }
  16772. callback();
  16773. return true;
  16774. },
  16775. toggleRecording: function (tokenEmptyCallback,
  16776. recordingStateChangeCallback) {
  16777. Recording.toggleRecording(tokenEmptyCallback,
  16778. recordingStateChangeCallback, connection);
  16779. },
  16780. addToPresence: function (name, value, dontSend) {
  16781. switch (name) {
  16782. case "displayName":
  16783. connection.emuc.addDisplayNameToPresence(value);
  16784. break;
  16785. case "prezi":
  16786. connection.emuc.addPreziToPresence(value, 0);
  16787. break;
  16788. case "preziSlide":
  16789. connection.emuc.addCurrentSlideToPresence(value);
  16790. break;
  16791. case "connectionQuality":
  16792. connection.emuc.addConnectionInfoToPresence(value);
  16793. break;
  16794. case "email":
  16795. connection.emuc.addEmailToPresence(value);
  16796. break;
  16797. case "devices":
  16798. connection.emuc.addDevicesToPresence(value);
  16799. break;
  16800. case "videoType":
  16801. connection.emuc.addVideoTypeToPresence(value);
  16802. break;
  16803. case "startMuted":
  16804. if(!Moderator.isModerator())
  16805. return;
  16806. connection.emuc.addStartMutedToPresence(value[0],
  16807. value[1]);
  16808. break;
  16809. default :
  16810. console.log("Unknown tag for presence: " + name);
  16811. return;
  16812. }
  16813. if (!dontSend)
  16814. connection.emuc.sendPresence();
  16815. },
  16816. /**
  16817. * Sends 'data' as a log message to the focus. Returns true iff a message
  16818. * was sent.
  16819. * @param data
  16820. * @returns {boolean} true iff a message was sent.
  16821. */
  16822. sendLogs: function (data) {
  16823. if(!connection.emuc.focusMucJid)
  16824. return false;
  16825. var deflate = true;
  16826. var content = JSON.stringify(data);
  16827. if (deflate) {
  16828. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16829. }
  16830. content = Base64.encode(content);
  16831. // XEP-0337-ish
  16832. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16833. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16834. id: 'PeerConnectionStats'});
  16835. message.c('message').t(content).up();
  16836. if (deflate) {
  16837. message.c('tag', {name: "deflated", value: "true"}).up();
  16838. }
  16839. message.up();
  16840. connection.send(message);
  16841. return true;
  16842. },
  16843. // Gets the logs from strophe.jingle.
  16844. getJingleLog: function () {
  16845. return connection.jingle ? connection.jingle.getLog() : {};
  16846. },
  16847. // Gets the logs from strophe.
  16848. getXmppLog: function () {
  16849. return connection.logger ? connection.logger.log : null;
  16850. },
  16851. getPrezi: function () {
  16852. return connection.emuc.getPrezi(this.myJid());
  16853. },
  16854. removePreziFromPresence: function () {
  16855. connection.emuc.removePreziFromPresence();
  16856. connection.emuc.sendPresence();
  16857. },
  16858. sendChatMessage: function (message, nickname) {
  16859. connection.emuc.sendMessage(message, nickname);
  16860. },
  16861. setSubject: function (topic) {
  16862. connection.emuc.setSubject(topic);
  16863. },
  16864. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16865. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16866. },
  16867. dial: function (to, from, roomName,roomPass) {
  16868. connection.rayo.dial(to, from, roomName,roomPass);
  16869. },
  16870. setMute: function (jid, mute) {
  16871. connection.moderate.setMute(jid, mute);
  16872. },
  16873. eject: function (jid) {
  16874. connection.moderate.eject(jid);
  16875. },
  16876. logout: function (callback) {
  16877. Moderator.logout(callback);
  16878. },
  16879. findJidFromResource: function (resource) {
  16880. return connection.emuc.findJidFromResource(resource);
  16881. },
  16882. getMembers: function () {
  16883. return connection.emuc.members;
  16884. },
  16885. getJidFromSSRC: function (ssrc) {
  16886. if (!this.isConferenceInProgress())
  16887. return null;
  16888. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16889. },
  16890. // Returns true iff we have joined the MUC.
  16891. isMUCJoined: function () {
  16892. return connection.emuc.joined;
  16893. },
  16894. getSessions: function () {
  16895. return connection.jingle.sessions;
  16896. },
  16897. removeStream: function (stream) {
  16898. if (!this.isConferenceInProgress())
  16899. return;
  16900. connection.jingle.activecall.peerconnection.removeStream(stream);
  16901. }
  16902. };
  16903. module.exports = XMPP;
  16904. },{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes":154,"../../service/xmpp/XMPPEvents":161,"../settings/Settings":47,"./SDP":56,"./moderator":60,"./recording":61,"./strophe.emuc":62,"./strophe.jingle":63,"./strophe.logger":64,"./strophe.moderate":65,"./strophe.rayo":66,"./strophe.util":67,"events":162,"pako":72,"retry":88}],69:[function(require,module,exports){
  16905. (function (process){
  16906. /*!
  16907. * async
  16908. * https://github.com/caolan/async
  16909. *
  16910. * Copyright 2010-2014 Caolan McMahon
  16911. * Released under the MIT license
  16912. */
  16913. /*jshint onevar: false, indent:4 */
  16914. /*global setImmediate: false, setTimeout: false, console: false */
  16915. (function () {
  16916. var async = {};
  16917. // global on the server, window in the browser
  16918. var root, previous_async;
  16919. root = this;
  16920. if (root != null) {
  16921. previous_async = root.async;
  16922. }
  16923. async.noConflict = function () {
  16924. root.async = previous_async;
  16925. return async;
  16926. };
  16927. function only_once(fn) {
  16928. var called = false;
  16929. return function() {
  16930. if (called) throw new Error("Callback was already called.");
  16931. called = true;
  16932. fn.apply(root, arguments);
  16933. }
  16934. }
  16935. //// cross-browser compatiblity functions ////
  16936. var _toString = Object.prototype.toString;
  16937. var _isArray = Array.isArray || function (obj) {
  16938. return _toString.call(obj) === '[object Array]';
  16939. };
  16940. var _each = function (arr, iterator) {
  16941. if (arr.forEach) {
  16942. return arr.forEach(iterator);
  16943. }
  16944. for (var i = 0; i < arr.length; i += 1) {
  16945. iterator(arr[i], i, arr);
  16946. }
  16947. };
  16948. var _map = function (arr, iterator) {
  16949. if (arr.map) {
  16950. return arr.map(iterator);
  16951. }
  16952. var results = [];
  16953. _each(arr, function (x, i, a) {
  16954. results.push(iterator(x, i, a));
  16955. });
  16956. return results;
  16957. };
  16958. var _reduce = function (arr, iterator, memo) {
  16959. if (arr.reduce) {
  16960. return arr.reduce(iterator, memo);
  16961. }
  16962. _each(arr, function (x, i, a) {
  16963. memo = iterator(memo, x, i, a);
  16964. });
  16965. return memo;
  16966. };
  16967. var _keys = function (obj) {
  16968. if (Object.keys) {
  16969. return Object.keys(obj);
  16970. }
  16971. var keys = [];
  16972. for (var k in obj) {
  16973. if (obj.hasOwnProperty(k)) {
  16974. keys.push(k);
  16975. }
  16976. }
  16977. return keys;
  16978. };
  16979. //// exported async module functions ////
  16980. //// nextTick implementation with browser-compatible fallback ////
  16981. if (typeof process === 'undefined' || !(process.nextTick)) {
  16982. if (typeof setImmediate === 'function') {
  16983. async.nextTick = function (fn) {
  16984. // not a direct alias for IE10 compatibility
  16985. setImmediate(fn);
  16986. };
  16987. async.setImmediate = async.nextTick;
  16988. }
  16989. else {
  16990. async.nextTick = function (fn) {
  16991. setTimeout(fn, 0);
  16992. };
  16993. async.setImmediate = async.nextTick;
  16994. }
  16995. }
  16996. else {
  16997. async.nextTick = process.nextTick;
  16998. if (typeof setImmediate !== 'undefined') {
  16999. async.setImmediate = function (fn) {
  17000. // not a direct alias for IE10 compatibility
  17001. setImmediate(fn);
  17002. };
  17003. }
  17004. else {
  17005. async.setImmediate = async.nextTick;
  17006. }
  17007. }
  17008. async.each = function (arr, iterator, callback) {
  17009. callback = callback || function () {};
  17010. if (!arr.length) {
  17011. return callback();
  17012. }
  17013. var completed = 0;
  17014. _each(arr, function (x) {
  17015. iterator(x, only_once(done) );
  17016. });
  17017. function done(err) {
  17018. if (err) {
  17019. callback(err);
  17020. callback = function () {};
  17021. }
  17022. else {
  17023. completed += 1;
  17024. if (completed >= arr.length) {
  17025. callback();
  17026. }
  17027. }
  17028. }
  17029. };
  17030. async.forEach = async.each;
  17031. async.eachSeries = function (arr, iterator, callback) {
  17032. callback = callback || function () {};
  17033. if (!arr.length) {
  17034. return callback();
  17035. }
  17036. var completed = 0;
  17037. var iterate = function () {
  17038. iterator(arr[completed], function (err) {
  17039. if (err) {
  17040. callback(err);
  17041. callback = function () {};
  17042. }
  17043. else {
  17044. completed += 1;
  17045. if (completed >= arr.length) {
  17046. callback();
  17047. }
  17048. else {
  17049. iterate();
  17050. }
  17051. }
  17052. });
  17053. };
  17054. iterate();
  17055. };
  17056. async.forEachSeries = async.eachSeries;
  17057. async.eachLimit = function (arr, limit, iterator, callback) {
  17058. var fn = _eachLimit(limit);
  17059. fn.apply(null, [arr, iterator, callback]);
  17060. };
  17061. async.forEachLimit = async.eachLimit;
  17062. var _eachLimit = function (limit) {
  17063. return function (arr, iterator, callback) {
  17064. callback = callback || function () {};
  17065. if (!arr.length || limit <= 0) {
  17066. return callback();
  17067. }
  17068. var completed = 0;
  17069. var started = 0;
  17070. var running = 0;
  17071. (function replenish () {
  17072. if (completed >= arr.length) {
  17073. return callback();
  17074. }
  17075. while (running < limit && started < arr.length) {
  17076. started += 1;
  17077. running += 1;
  17078. iterator(arr[started - 1], function (err) {
  17079. if (err) {
  17080. callback(err);
  17081. callback = function () {};
  17082. }
  17083. else {
  17084. completed += 1;
  17085. running -= 1;
  17086. if (completed >= arr.length) {
  17087. callback();
  17088. }
  17089. else {
  17090. replenish();
  17091. }
  17092. }
  17093. });
  17094. }
  17095. })();
  17096. };
  17097. };
  17098. var doParallel = function (fn) {
  17099. return function () {
  17100. var args = Array.prototype.slice.call(arguments);
  17101. return fn.apply(null, [async.each].concat(args));
  17102. };
  17103. };
  17104. var doParallelLimit = function(limit, fn) {
  17105. return function () {
  17106. var args = Array.prototype.slice.call(arguments);
  17107. return fn.apply(null, [_eachLimit(limit)].concat(args));
  17108. };
  17109. };
  17110. var doSeries = function (fn) {
  17111. return function () {
  17112. var args = Array.prototype.slice.call(arguments);
  17113. return fn.apply(null, [async.eachSeries].concat(args));
  17114. };
  17115. };
  17116. var _asyncMap = function (eachfn, arr, iterator, callback) {
  17117. arr = _map(arr, function (x, i) {
  17118. return {index: i, value: x};
  17119. });
  17120. if (!callback) {
  17121. eachfn(arr, function (x, callback) {
  17122. iterator(x.value, function (err) {
  17123. callback(err);
  17124. });
  17125. });
  17126. } else {
  17127. var results = [];
  17128. eachfn(arr, function (x, callback) {
  17129. iterator(x.value, function (err, v) {
  17130. results[x.index] = v;
  17131. callback(err);
  17132. });
  17133. }, function (err) {
  17134. callback(err, results);
  17135. });
  17136. }
  17137. };
  17138. async.map = doParallel(_asyncMap);
  17139. async.mapSeries = doSeries(_asyncMap);
  17140. async.mapLimit = function (arr, limit, iterator, callback) {
  17141. return _mapLimit(limit)(arr, iterator, callback);
  17142. };
  17143. var _mapLimit = function(limit) {
  17144. return doParallelLimit(limit, _asyncMap);
  17145. };
  17146. // reduce only has a series version, as doing reduce in parallel won't
  17147. // work in many situations.
  17148. async.reduce = function (arr, memo, iterator, callback) {
  17149. async.eachSeries(arr, function (x, callback) {
  17150. iterator(memo, x, function (err, v) {
  17151. memo = v;
  17152. callback(err);
  17153. });
  17154. }, function (err) {
  17155. callback(err, memo);
  17156. });
  17157. };
  17158. // inject alias
  17159. async.inject = async.reduce;
  17160. // foldl alias
  17161. async.foldl = async.reduce;
  17162. async.reduceRight = function (arr, memo, iterator, callback) {
  17163. var reversed = _map(arr, function (x) {
  17164. return x;
  17165. }).reverse();
  17166. async.reduce(reversed, memo, iterator, callback);
  17167. };
  17168. // foldr alias
  17169. async.foldr = async.reduceRight;
  17170. var _filter = function (eachfn, arr, iterator, callback) {
  17171. var results = [];
  17172. arr = _map(arr, function (x, i) {
  17173. return {index: i, value: x};
  17174. });
  17175. eachfn(arr, function (x, callback) {
  17176. iterator(x.value, function (v) {
  17177. if (v) {
  17178. results.push(x);
  17179. }
  17180. callback();
  17181. });
  17182. }, function (err) {
  17183. callback(_map(results.sort(function (a, b) {
  17184. return a.index - b.index;
  17185. }), function (x) {
  17186. return x.value;
  17187. }));
  17188. });
  17189. };
  17190. async.filter = doParallel(_filter);
  17191. async.filterSeries = doSeries(_filter);
  17192. // select alias
  17193. async.select = async.filter;
  17194. async.selectSeries = async.filterSeries;
  17195. var _reject = function (eachfn, arr, iterator, callback) {
  17196. var results = [];
  17197. arr = _map(arr, function (x, i) {
  17198. return {index: i, value: x};
  17199. });
  17200. eachfn(arr, function (x, callback) {
  17201. iterator(x.value, function (v) {
  17202. if (!v) {
  17203. results.push(x);
  17204. }
  17205. callback();
  17206. });
  17207. }, function (err) {
  17208. callback(_map(results.sort(function (a, b) {
  17209. return a.index - b.index;
  17210. }), function (x) {
  17211. return x.value;
  17212. }));
  17213. });
  17214. };
  17215. async.reject = doParallel(_reject);
  17216. async.rejectSeries = doSeries(_reject);
  17217. var _detect = function (eachfn, arr, iterator, main_callback) {
  17218. eachfn(arr, function (x, callback) {
  17219. iterator(x, function (result) {
  17220. if (result) {
  17221. main_callback(x);
  17222. main_callback = function () {};
  17223. }
  17224. else {
  17225. callback();
  17226. }
  17227. });
  17228. }, function (err) {
  17229. main_callback();
  17230. });
  17231. };
  17232. async.detect = doParallel(_detect);
  17233. async.detectSeries = doSeries(_detect);
  17234. async.some = function (arr, iterator, main_callback) {
  17235. async.each(arr, function (x, callback) {
  17236. iterator(x, function (v) {
  17237. if (v) {
  17238. main_callback(true);
  17239. main_callback = function () {};
  17240. }
  17241. callback();
  17242. });
  17243. }, function (err) {
  17244. main_callback(false);
  17245. });
  17246. };
  17247. // any alias
  17248. async.any = async.some;
  17249. async.every = function (arr, iterator, main_callback) {
  17250. async.each(arr, function (x, callback) {
  17251. iterator(x, function (v) {
  17252. if (!v) {
  17253. main_callback(false);
  17254. main_callback = function () {};
  17255. }
  17256. callback();
  17257. });
  17258. }, function (err) {
  17259. main_callback(true);
  17260. });
  17261. };
  17262. // all alias
  17263. async.all = async.every;
  17264. async.sortBy = function (arr, iterator, callback) {
  17265. async.map(arr, function (x, callback) {
  17266. iterator(x, function (err, criteria) {
  17267. if (err) {
  17268. callback(err);
  17269. }
  17270. else {
  17271. callback(null, {value: x, criteria: criteria});
  17272. }
  17273. });
  17274. }, function (err, results) {
  17275. if (err) {
  17276. return callback(err);
  17277. }
  17278. else {
  17279. var fn = function (left, right) {
  17280. var a = left.criteria, b = right.criteria;
  17281. return a < b ? -1 : a > b ? 1 : 0;
  17282. };
  17283. callback(null, _map(results.sort(fn), function (x) {
  17284. return x.value;
  17285. }));
  17286. }
  17287. });
  17288. };
  17289. async.auto = function (tasks, callback) {
  17290. callback = callback || function () {};
  17291. var keys = _keys(tasks);
  17292. var remainingTasks = keys.length
  17293. if (!remainingTasks) {
  17294. return callback();
  17295. }
  17296. var results = {};
  17297. var listeners = [];
  17298. var addListener = function (fn) {
  17299. listeners.unshift(fn);
  17300. };
  17301. var removeListener = function (fn) {
  17302. for (var i = 0; i < listeners.length; i += 1) {
  17303. if (listeners[i] === fn) {
  17304. listeners.splice(i, 1);
  17305. return;
  17306. }
  17307. }
  17308. };
  17309. var taskComplete = function () {
  17310. remainingTasks--
  17311. _each(listeners.slice(0), function (fn) {
  17312. fn();
  17313. });
  17314. };
  17315. addListener(function () {
  17316. if (!remainingTasks) {
  17317. var theCallback = callback;
  17318. // prevent final callback from calling itself if it errors
  17319. callback = function () {};
  17320. theCallback(null, results);
  17321. }
  17322. });
  17323. _each(keys, function (k) {
  17324. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17325. var taskCallback = function (err) {
  17326. var args = Array.prototype.slice.call(arguments, 1);
  17327. if (args.length <= 1) {
  17328. args = args[0];
  17329. }
  17330. if (err) {
  17331. var safeResults = {};
  17332. _each(_keys(results), function(rkey) {
  17333. safeResults[rkey] = results[rkey];
  17334. });
  17335. safeResults[k] = args;
  17336. callback(err, safeResults);
  17337. // stop subsequent errors hitting callback multiple times
  17338. callback = function () {};
  17339. }
  17340. else {
  17341. results[k] = args;
  17342. async.setImmediate(taskComplete);
  17343. }
  17344. };
  17345. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17346. var ready = function () {
  17347. return _reduce(requires, function (a, x) {
  17348. return (a && results.hasOwnProperty(x));
  17349. }, true) && !results.hasOwnProperty(k);
  17350. };
  17351. if (ready()) {
  17352. task[task.length - 1](taskCallback, results);
  17353. }
  17354. else {
  17355. var listener = function () {
  17356. if (ready()) {
  17357. removeListener(listener);
  17358. task[task.length - 1](taskCallback, results);
  17359. }
  17360. };
  17361. addListener(listener);
  17362. }
  17363. });
  17364. };
  17365. async.retry = function(times, task, callback) {
  17366. var DEFAULT_TIMES = 5;
  17367. var attempts = [];
  17368. // Use defaults if times not passed
  17369. if (typeof times === 'function') {
  17370. callback = task;
  17371. task = times;
  17372. times = DEFAULT_TIMES;
  17373. }
  17374. // Make sure times is a number
  17375. times = parseInt(times, 10) || DEFAULT_TIMES;
  17376. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17377. var retryAttempt = function(task, finalAttempt) {
  17378. return function(seriesCallback) {
  17379. task(function(err, result){
  17380. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17381. }, wrappedResults);
  17382. };
  17383. };
  17384. while (times) {
  17385. attempts.push(retryAttempt(task, !(times-=1)));
  17386. }
  17387. async.series(attempts, function(done, data){
  17388. data = data[data.length - 1];
  17389. (wrappedCallback || callback)(data.err, data.result);
  17390. });
  17391. }
  17392. // If a callback is passed, run this as a controll flow
  17393. return callback ? wrappedTask() : wrappedTask
  17394. };
  17395. async.waterfall = function (tasks, callback) {
  17396. callback = callback || function () {};
  17397. if (!_isArray(tasks)) {
  17398. var err = new Error('First argument to waterfall must be an array of functions');
  17399. return callback(err);
  17400. }
  17401. if (!tasks.length) {
  17402. return callback();
  17403. }
  17404. var wrapIterator = function (iterator) {
  17405. return function (err) {
  17406. if (err) {
  17407. callback.apply(null, arguments);
  17408. callback = function () {};
  17409. }
  17410. else {
  17411. var args = Array.prototype.slice.call(arguments, 1);
  17412. var next = iterator.next();
  17413. if (next) {
  17414. args.push(wrapIterator(next));
  17415. }
  17416. else {
  17417. args.push(callback);
  17418. }
  17419. async.setImmediate(function () {
  17420. iterator.apply(null, args);
  17421. });
  17422. }
  17423. };
  17424. };
  17425. wrapIterator(async.iterator(tasks))();
  17426. };
  17427. var _parallel = function(eachfn, tasks, callback) {
  17428. callback = callback || function () {};
  17429. if (_isArray(tasks)) {
  17430. eachfn.map(tasks, function (fn, callback) {
  17431. if (fn) {
  17432. fn(function (err) {
  17433. var args = Array.prototype.slice.call(arguments, 1);
  17434. if (args.length <= 1) {
  17435. args = args[0];
  17436. }
  17437. callback.call(null, err, args);
  17438. });
  17439. }
  17440. }, callback);
  17441. }
  17442. else {
  17443. var results = {};
  17444. eachfn.each(_keys(tasks), function (k, callback) {
  17445. tasks[k](function (err) {
  17446. var args = Array.prototype.slice.call(arguments, 1);
  17447. if (args.length <= 1) {
  17448. args = args[0];
  17449. }
  17450. results[k] = args;
  17451. callback(err);
  17452. });
  17453. }, function (err) {
  17454. callback(err, results);
  17455. });
  17456. }
  17457. };
  17458. async.parallel = function (tasks, callback) {
  17459. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17460. };
  17461. async.parallelLimit = function(tasks, limit, callback) {
  17462. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17463. };
  17464. async.series = function (tasks, callback) {
  17465. callback = callback || function () {};
  17466. if (_isArray(tasks)) {
  17467. async.mapSeries(tasks, function (fn, callback) {
  17468. if (fn) {
  17469. fn(function (err) {
  17470. var args = Array.prototype.slice.call(arguments, 1);
  17471. if (args.length <= 1) {
  17472. args = args[0];
  17473. }
  17474. callback.call(null, err, args);
  17475. });
  17476. }
  17477. }, callback);
  17478. }
  17479. else {
  17480. var results = {};
  17481. async.eachSeries(_keys(tasks), function (k, callback) {
  17482. tasks[k](function (err) {
  17483. var args = Array.prototype.slice.call(arguments, 1);
  17484. if (args.length <= 1) {
  17485. args = args[0];
  17486. }
  17487. results[k] = args;
  17488. callback(err);
  17489. });
  17490. }, function (err) {
  17491. callback(err, results);
  17492. });
  17493. }
  17494. };
  17495. async.iterator = function (tasks) {
  17496. var makeCallback = function (index) {
  17497. var fn = function () {
  17498. if (tasks.length) {
  17499. tasks[index].apply(null, arguments);
  17500. }
  17501. return fn.next();
  17502. };
  17503. fn.next = function () {
  17504. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17505. };
  17506. return fn;
  17507. };
  17508. return makeCallback(0);
  17509. };
  17510. async.apply = function (fn) {
  17511. var args = Array.prototype.slice.call(arguments, 1);
  17512. return function () {
  17513. return fn.apply(
  17514. null, args.concat(Array.prototype.slice.call(arguments))
  17515. );
  17516. };
  17517. };
  17518. var _concat = function (eachfn, arr, fn, callback) {
  17519. var r = [];
  17520. eachfn(arr, function (x, cb) {
  17521. fn(x, function (err, y) {
  17522. r = r.concat(y || []);
  17523. cb(err);
  17524. });
  17525. }, function (err) {
  17526. callback(err, r);
  17527. });
  17528. };
  17529. async.concat = doParallel(_concat);
  17530. async.concatSeries = doSeries(_concat);
  17531. async.whilst = function (test, iterator, callback) {
  17532. if (test()) {
  17533. iterator(function (err) {
  17534. if (err) {
  17535. return callback(err);
  17536. }
  17537. async.whilst(test, iterator, callback);
  17538. });
  17539. }
  17540. else {
  17541. callback();
  17542. }
  17543. };
  17544. async.doWhilst = function (iterator, test, callback) {
  17545. iterator(function (err) {
  17546. if (err) {
  17547. return callback(err);
  17548. }
  17549. var args = Array.prototype.slice.call(arguments, 1);
  17550. if (test.apply(null, args)) {
  17551. async.doWhilst(iterator, test, callback);
  17552. }
  17553. else {
  17554. callback();
  17555. }
  17556. });
  17557. };
  17558. async.until = function (test, iterator, callback) {
  17559. if (!test()) {
  17560. iterator(function (err) {
  17561. if (err) {
  17562. return callback(err);
  17563. }
  17564. async.until(test, iterator, callback);
  17565. });
  17566. }
  17567. else {
  17568. callback();
  17569. }
  17570. };
  17571. async.doUntil = function (iterator, test, callback) {
  17572. iterator(function (err) {
  17573. if (err) {
  17574. return callback(err);
  17575. }
  17576. var args = Array.prototype.slice.call(arguments, 1);
  17577. if (!test.apply(null, args)) {
  17578. async.doUntil(iterator, test, callback);
  17579. }
  17580. else {
  17581. callback();
  17582. }
  17583. });
  17584. };
  17585. async.queue = function (worker, concurrency) {
  17586. if (concurrency === undefined) {
  17587. concurrency = 1;
  17588. }
  17589. function _insert(q, data, pos, callback) {
  17590. if (!q.started){
  17591. q.started = true;
  17592. }
  17593. if (!_isArray(data)) {
  17594. data = [data];
  17595. }
  17596. if(data.length == 0) {
  17597. // call drain immediately if there are no tasks
  17598. return async.setImmediate(function() {
  17599. if (q.drain) {
  17600. q.drain();
  17601. }
  17602. });
  17603. }
  17604. _each(data, function(task) {
  17605. var item = {
  17606. data: task,
  17607. callback: typeof callback === 'function' ? callback : null
  17608. };
  17609. if (pos) {
  17610. q.tasks.unshift(item);
  17611. } else {
  17612. q.tasks.push(item);
  17613. }
  17614. if (q.saturated && q.tasks.length === q.concurrency) {
  17615. q.saturated();
  17616. }
  17617. async.setImmediate(q.process);
  17618. });
  17619. }
  17620. var workers = 0;
  17621. var q = {
  17622. tasks: [],
  17623. concurrency: concurrency,
  17624. saturated: null,
  17625. empty: null,
  17626. drain: null,
  17627. started: false,
  17628. paused: false,
  17629. push: function (data, callback) {
  17630. _insert(q, data, false, callback);
  17631. },
  17632. kill: function () {
  17633. q.drain = null;
  17634. q.tasks = [];
  17635. },
  17636. unshift: function (data, callback) {
  17637. _insert(q, data, true, callback);
  17638. },
  17639. process: function () {
  17640. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17641. var task = q.tasks.shift();
  17642. if (q.empty && q.tasks.length === 0) {
  17643. q.empty();
  17644. }
  17645. workers += 1;
  17646. var next = function () {
  17647. workers -= 1;
  17648. if (task.callback) {
  17649. task.callback.apply(task, arguments);
  17650. }
  17651. if (q.drain && q.tasks.length + workers === 0) {
  17652. q.drain();
  17653. }
  17654. q.process();
  17655. };
  17656. var cb = only_once(next);
  17657. worker(task.data, cb);
  17658. }
  17659. },
  17660. length: function () {
  17661. return q.tasks.length;
  17662. },
  17663. running: function () {
  17664. return workers;
  17665. },
  17666. idle: function() {
  17667. return q.tasks.length + workers === 0;
  17668. },
  17669. pause: function () {
  17670. if (q.paused === true) { return; }
  17671. q.paused = true;
  17672. q.process();
  17673. },
  17674. resume: function () {
  17675. if (q.paused === false) { return; }
  17676. q.paused = false;
  17677. q.process();
  17678. }
  17679. };
  17680. return q;
  17681. };
  17682. async.priorityQueue = function (worker, concurrency) {
  17683. function _compareTasks(a, b){
  17684. return a.priority - b.priority;
  17685. };
  17686. function _binarySearch(sequence, item, compare) {
  17687. var beg = -1,
  17688. end = sequence.length - 1;
  17689. while (beg < end) {
  17690. var mid = beg + ((end - beg + 1) >>> 1);
  17691. if (compare(item, sequence[mid]) >= 0) {
  17692. beg = mid;
  17693. } else {
  17694. end = mid - 1;
  17695. }
  17696. }
  17697. return beg;
  17698. }
  17699. function _insert(q, data, priority, callback) {
  17700. if (!q.started){
  17701. q.started = true;
  17702. }
  17703. if (!_isArray(data)) {
  17704. data = [data];
  17705. }
  17706. if(data.length == 0) {
  17707. // call drain immediately if there are no tasks
  17708. return async.setImmediate(function() {
  17709. if (q.drain) {
  17710. q.drain();
  17711. }
  17712. });
  17713. }
  17714. _each(data, function(task) {
  17715. var item = {
  17716. data: task,
  17717. priority: priority,
  17718. callback: typeof callback === 'function' ? callback : null
  17719. };
  17720. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17721. if (q.saturated && q.tasks.length === q.concurrency) {
  17722. q.saturated();
  17723. }
  17724. async.setImmediate(q.process);
  17725. });
  17726. }
  17727. // Start with a normal queue
  17728. var q = async.queue(worker, concurrency);
  17729. // Override push to accept second parameter representing priority
  17730. q.push = function (data, priority, callback) {
  17731. _insert(q, data, priority, callback);
  17732. };
  17733. // Remove unshift function
  17734. delete q.unshift;
  17735. return q;
  17736. };
  17737. async.cargo = function (worker, payload) {
  17738. var working = false,
  17739. tasks = [];
  17740. var cargo = {
  17741. tasks: tasks,
  17742. payload: payload,
  17743. saturated: null,
  17744. empty: null,
  17745. drain: null,
  17746. drained: true,
  17747. push: function (data, callback) {
  17748. if (!_isArray(data)) {
  17749. data = [data];
  17750. }
  17751. _each(data, function(task) {
  17752. tasks.push({
  17753. data: task,
  17754. callback: typeof callback === 'function' ? callback : null
  17755. });
  17756. cargo.drained = false;
  17757. if (cargo.saturated && tasks.length === payload) {
  17758. cargo.saturated();
  17759. }
  17760. });
  17761. async.setImmediate(cargo.process);
  17762. },
  17763. process: function process() {
  17764. if (working) return;
  17765. if (tasks.length === 0) {
  17766. if(cargo.drain && !cargo.drained) cargo.drain();
  17767. cargo.drained = true;
  17768. return;
  17769. }
  17770. var ts = typeof payload === 'number'
  17771. ? tasks.splice(0, payload)
  17772. : tasks.splice(0, tasks.length);
  17773. var ds = _map(ts, function (task) {
  17774. return task.data;
  17775. });
  17776. if(cargo.empty) cargo.empty();
  17777. working = true;
  17778. worker(ds, function () {
  17779. working = false;
  17780. var args = arguments;
  17781. _each(ts, function (data) {
  17782. if (data.callback) {
  17783. data.callback.apply(null, args);
  17784. }
  17785. });
  17786. process();
  17787. });
  17788. },
  17789. length: function () {
  17790. return tasks.length;
  17791. },
  17792. running: function () {
  17793. return working;
  17794. }
  17795. };
  17796. return cargo;
  17797. };
  17798. var _console_fn = function (name) {
  17799. return function (fn) {
  17800. var args = Array.prototype.slice.call(arguments, 1);
  17801. fn.apply(null, args.concat([function (err) {
  17802. var args = Array.prototype.slice.call(arguments, 1);
  17803. if (typeof console !== 'undefined') {
  17804. if (err) {
  17805. if (console.error) {
  17806. console.error(err);
  17807. }
  17808. }
  17809. else if (console[name]) {
  17810. _each(args, function (x) {
  17811. console[name](x);
  17812. });
  17813. }
  17814. }
  17815. }]));
  17816. };
  17817. };
  17818. async.log = _console_fn('log');
  17819. async.dir = _console_fn('dir');
  17820. /*async.info = _console_fn('info');
  17821. async.warn = _console_fn('warn');
  17822. async.error = _console_fn('error');*/
  17823. async.memoize = function (fn, hasher) {
  17824. var memo = {};
  17825. var queues = {};
  17826. hasher = hasher || function (x) {
  17827. return x;
  17828. };
  17829. var memoized = function () {
  17830. var args = Array.prototype.slice.call(arguments);
  17831. var callback = args.pop();
  17832. var key = hasher.apply(null, args);
  17833. if (key in memo) {
  17834. async.nextTick(function () {
  17835. callback.apply(null, memo[key]);
  17836. });
  17837. }
  17838. else if (key in queues) {
  17839. queues[key].push(callback);
  17840. }
  17841. else {
  17842. queues[key] = [callback];
  17843. fn.apply(null, args.concat([function () {
  17844. memo[key] = arguments;
  17845. var q = queues[key];
  17846. delete queues[key];
  17847. for (var i = 0, l = q.length; i < l; i++) {
  17848. q[i].apply(null, arguments);
  17849. }
  17850. }]));
  17851. }
  17852. };
  17853. memoized.memo = memo;
  17854. memoized.unmemoized = fn;
  17855. return memoized;
  17856. };
  17857. async.unmemoize = function (fn) {
  17858. return function () {
  17859. return (fn.unmemoized || fn).apply(null, arguments);
  17860. };
  17861. };
  17862. async.times = function (count, iterator, callback) {
  17863. var counter = [];
  17864. for (var i = 0; i < count; i++) {
  17865. counter.push(i);
  17866. }
  17867. return async.map(counter, iterator, callback);
  17868. };
  17869. async.timesSeries = function (count, iterator, callback) {
  17870. var counter = [];
  17871. for (var i = 0; i < count; i++) {
  17872. counter.push(i);
  17873. }
  17874. return async.mapSeries(counter, iterator, callback);
  17875. };
  17876. async.seq = function (/* functions... */) {
  17877. var fns = arguments;
  17878. return function () {
  17879. var that = this;
  17880. var args = Array.prototype.slice.call(arguments);
  17881. var callback = args.pop();
  17882. async.reduce(fns, args, function (newargs, fn, cb) {
  17883. fn.apply(that, newargs.concat([function () {
  17884. var err = arguments[0];
  17885. var nextargs = Array.prototype.slice.call(arguments, 1);
  17886. cb(err, nextargs);
  17887. }]))
  17888. },
  17889. function (err, results) {
  17890. callback.apply(that, [err].concat(results));
  17891. });
  17892. };
  17893. };
  17894. async.compose = function (/* functions... */) {
  17895. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17896. };
  17897. var _applyEach = function (eachfn, fns /*args...*/) {
  17898. var go = function () {
  17899. var that = this;
  17900. var args = Array.prototype.slice.call(arguments);
  17901. var callback = args.pop();
  17902. return eachfn(fns, function (fn, cb) {
  17903. fn.apply(that, args.concat([cb]));
  17904. },
  17905. callback);
  17906. };
  17907. if (arguments.length > 2) {
  17908. var args = Array.prototype.slice.call(arguments, 2);
  17909. return go.apply(this, args);
  17910. }
  17911. else {
  17912. return go;
  17913. }
  17914. };
  17915. async.applyEach = doParallel(_applyEach);
  17916. async.applyEachSeries = doSeries(_applyEach);
  17917. async.forever = function (fn, callback) {
  17918. function next(err) {
  17919. if (err) {
  17920. if (callback) {
  17921. return callback(err);
  17922. }
  17923. throw err;
  17924. }
  17925. fn(next);
  17926. }
  17927. next();
  17928. };
  17929. // Node.js
  17930. if (typeof module !== 'undefined' && module.exports) {
  17931. module.exports = async;
  17932. }
  17933. // AMD / RequireJS
  17934. else if (typeof define !== 'undefined' && define.amd) {
  17935. define([], function () {
  17936. return async;
  17937. });
  17938. }
  17939. // included directly via <script> tag
  17940. else {
  17941. root.async = async;
  17942. }
  17943. }());
  17944. }).call(this,require('_process'))
  17945. },{"_process":163}],70:[function(require,module,exports){
  17946. // i18next, v1.7.7
  17947. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17948. // Distributed under MIT license
  17949. // http://i18next.com
  17950. (function() {
  17951. // add indexOf to non ECMA-262 standard compliant browsers
  17952. if (!Array.prototype.indexOf) {
  17953. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17954. "use strict";
  17955. if (this == null) {
  17956. throw new TypeError();
  17957. }
  17958. var t = Object(this);
  17959. var len = t.length >>> 0;
  17960. if (len === 0) {
  17961. return -1;
  17962. }
  17963. var n = 0;
  17964. if (arguments.length > 0) {
  17965. n = Number(arguments[1]);
  17966. if (n != n) { // shortcut for verifying if it's NaN
  17967. n = 0;
  17968. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17969. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17970. }
  17971. }
  17972. if (n >= len) {
  17973. return -1;
  17974. }
  17975. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17976. for (; k < len; k++) {
  17977. if (k in t && t[k] === searchElement) {
  17978. return k;
  17979. }
  17980. }
  17981. return -1;
  17982. }
  17983. }
  17984. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17985. if (!Array.prototype.lastIndexOf) {
  17986. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17987. "use strict";
  17988. if (this == null) {
  17989. throw new TypeError();
  17990. }
  17991. var t = Object(this);
  17992. var len = t.length >>> 0;
  17993. if (len === 0) {
  17994. return -1;
  17995. }
  17996. var n = len;
  17997. if (arguments.length > 1) {
  17998. n = Number(arguments[1]);
  17999. if (n != n) {
  18000. n = 0;
  18001. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  18002. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18003. }
  18004. }
  18005. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  18006. for (; k >= 0; k--) {
  18007. if (k in t && t[k] === searchElement) {
  18008. return k;
  18009. }
  18010. }
  18011. return -1;
  18012. };
  18013. }
  18014. // Add string trim for IE8.
  18015. if (typeof String.prototype.trim !== 'function') {
  18016. String.prototype.trim = function() {
  18017. return this.replace(/^\s+|\s+$/g, '');
  18018. }
  18019. }
  18020. var root = this
  18021. , $ = root.jQuery || root.Zepto
  18022. , i18n = {}
  18023. , resStore = {}
  18024. , currentLng
  18025. , replacementCounter = 0
  18026. , languages = []
  18027. , initialized = false
  18028. , sync = {};
  18029. // Export the i18next object for **CommonJS**.
  18030. // If we're not in CommonJS, add `i18n` to the
  18031. // global object or to jquery.
  18032. if (typeof module !== 'undefined' && module.exports) {
  18033. if (!$) {
  18034. try {
  18035. $ = require('jquery');
  18036. } catch(e) {
  18037. // just ignore
  18038. }
  18039. }
  18040. if ($) {
  18041. $.i18n = $.i18n || i18n;
  18042. }
  18043. module.exports = i18n;
  18044. } else {
  18045. if ($) {
  18046. $.i18n = $.i18n || i18n;
  18047. }
  18048. root.i18n = root.i18n || i18n;
  18049. }
  18050. sync = {
  18051. load: function(lngs, options, cb) {
  18052. if (options.useLocalStorage) {
  18053. sync._loadLocal(lngs, options, function(err, store) {
  18054. var missingLngs = [];
  18055. for (var i = 0, len = lngs.length; i < len; i++) {
  18056. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  18057. }
  18058. if (missingLngs.length > 0) {
  18059. sync._fetch(missingLngs, options, function(err, fetched) {
  18060. f.extend(store, fetched);
  18061. sync._storeLocal(fetched);
  18062. cb(null, store);
  18063. });
  18064. } else {
  18065. cb(null, store);
  18066. }
  18067. });
  18068. } else {
  18069. sync._fetch(lngs, options, function(err, store){
  18070. cb(null, store);
  18071. });
  18072. }
  18073. },
  18074. _loadLocal: function(lngs, options, cb) {
  18075. var store = {}
  18076. , nowMS = new Date().getTime();
  18077. if(window.localStorage) {
  18078. var todo = lngs.length;
  18079. f.each(lngs, function(key, lng) {
  18080. var local = window.localStorage.getItem('res_' + lng);
  18081. if (local) {
  18082. local = JSON.parse(local);
  18083. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  18084. store[lng] = local;
  18085. }
  18086. }
  18087. todo--; // wait for all done befor callback
  18088. if (todo === 0) cb(null, store);
  18089. });
  18090. }
  18091. },
  18092. _storeLocal: function(store) {
  18093. if(window.localStorage) {
  18094. for (var m in store) {
  18095. store[m].i18nStamp = new Date().getTime();
  18096. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  18097. }
  18098. }
  18099. return;
  18100. },
  18101. _fetch: function(lngs, options, cb) {
  18102. var ns = options.ns
  18103. , store = {};
  18104. if (!options.dynamicLoad) {
  18105. var todo = ns.namespaces.length * lngs.length
  18106. , errors;
  18107. // load each file individual
  18108. f.each(ns.namespaces, function(nsIndex, nsValue) {
  18109. f.each(lngs, function(lngIndex, lngValue) {
  18110. // Call this once our translation has returned.
  18111. var loadComplete = function(err, data) {
  18112. if (err) {
  18113. errors = errors || [];
  18114. errors.push(err);
  18115. }
  18116. store[lngValue] = store[lngValue] || {};
  18117. store[lngValue][nsValue] = data;
  18118. todo--; // wait for all done befor callback
  18119. if (todo === 0) cb(errors, store);
  18120. };
  18121. if(typeof options.customLoad == 'function'){
  18122. // Use the specified custom callback.
  18123. options.customLoad(lngValue, nsValue, options, loadComplete);
  18124. } else {
  18125. //~ // Use our inbuilt sync.
  18126. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  18127. }
  18128. });
  18129. });
  18130. } else {
  18131. // Call this once our translation has returned.
  18132. var loadComplete = function(err, data) {
  18133. cb(null, data);
  18134. };
  18135. if(typeof options.customLoad == 'function'){
  18136. // Use the specified custom callback.
  18137. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  18138. } else {
  18139. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  18140. // load all needed stuff once
  18141. f.ajax({
  18142. url: url,
  18143. success: function(data, status, xhr) {
  18144. f.log('loaded: ' + url);
  18145. loadComplete(null, data);
  18146. },
  18147. error : function(xhr, status, error) {
  18148. f.log('failed loading: ' + url);
  18149. loadComplete('failed loading resource.json error: ' + error);
  18150. },
  18151. dataType: "json",
  18152. async : options.getAsync
  18153. });
  18154. }
  18155. }
  18156. },
  18157. _fetchOne: function(lng, ns, options, done) {
  18158. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  18159. f.ajax({
  18160. url: url,
  18161. success: function(data, status, xhr) {
  18162. f.log('loaded: ' + url);
  18163. done(null, data);
  18164. },
  18165. error : function(xhr, status, error) {
  18166. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  18167. // file loaded but invalid json, stop waste time !
  18168. f.error('There is a typo in: ' + url);
  18169. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  18170. f.log('Does not exist: ' + url);
  18171. } else {
  18172. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  18173. f.log(theStatus + ' when loading ' + url);
  18174. }
  18175. done(error, {});
  18176. },
  18177. dataType: "json",
  18178. async : options.getAsync
  18179. });
  18180. },
  18181. postMissing: function(lng, ns, key, defaultValue, lngs) {
  18182. var payload = {};
  18183. payload[key] = defaultValue;
  18184. var urls = [];
  18185. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  18186. for (var i = 0; i < o.fallbackLng.length; i++) {
  18187. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  18188. }
  18189. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  18190. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  18191. } else if (o.sendMissingTo === 'all') {
  18192. for (var i = 0, l = lngs.length; i < l; i++) {
  18193. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  18194. }
  18195. }
  18196. for (var y = 0, len = urls.length; y < len; y++) {
  18197. var item = urls[y];
  18198. f.ajax({
  18199. url: item.url,
  18200. type: o.sendType,
  18201. data: payload,
  18202. success: function(data, status, xhr) {
  18203. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18204. // add key to resStore
  18205. var keys = key.split('.');
  18206. var x = 0;
  18207. var value = resStore[item.lng][ns];
  18208. while (keys[x]) {
  18209. if (x === keys.length - 1) {
  18210. value = value[keys[x]] = defaultValue;
  18211. } else {
  18212. value = value[keys[x]] = value[keys[x]] || {};
  18213. }
  18214. x++;
  18215. }
  18216. },
  18217. error : function(xhr, status, error) {
  18218. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18219. },
  18220. dataType: "json",
  18221. async : o.postAsync
  18222. });
  18223. }
  18224. },
  18225. reload: reload
  18226. };
  18227. // defaults
  18228. var o = {
  18229. lng: undefined,
  18230. load: 'all',
  18231. preload: [],
  18232. lowerCaseLng: false,
  18233. returnObjectTrees: false,
  18234. fallbackLng: ['dev'],
  18235. fallbackNS: [],
  18236. detectLngQS: 'setLng',
  18237. detectLngFromLocalStorage: false,
  18238. ns: 'translation',
  18239. fallbackOnNull: true,
  18240. fallbackOnEmpty: false,
  18241. fallbackToDefaultNS: false,
  18242. nsseparator: ':',
  18243. keyseparator: '.',
  18244. selectorAttr: 'data-i18n',
  18245. debug: false,
  18246. resGetPath: 'locales/__lng__/__ns__.json',
  18247. resPostPath: 'locales/add/__lng__/__ns__',
  18248. getAsync: true,
  18249. postAsync: true,
  18250. resStore: undefined,
  18251. useLocalStorage: false,
  18252. localStorageExpirationTime: 7*24*60*60*1000,
  18253. dynamicLoad: false,
  18254. sendMissing: false,
  18255. sendMissingTo: 'fallback', // current | all
  18256. sendType: 'POST',
  18257. interpolationPrefix: '__',
  18258. interpolationSuffix: '__',
  18259. defaultVariables: false,
  18260. reusePrefix: '$t(',
  18261. reuseSuffix: ')',
  18262. pluralSuffix: '_plural',
  18263. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18264. contextNotFound: ['context_not_found', Math.random()].join(''),
  18265. escapeInterpolation: false,
  18266. indefiniteSuffix: '_indefinite',
  18267. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18268. setJqueryExt: true,
  18269. defaultValueFromContent: true,
  18270. useDataAttrOptions: false,
  18271. cookieExpirationTime: undefined,
  18272. useCookie: true,
  18273. cookieName: 'i18next',
  18274. cookieDomain: undefined,
  18275. objectTreeKeyHandler: undefined,
  18276. postProcess: undefined,
  18277. parseMissingKey: undefined,
  18278. missingKeyHandler: sync.postMissing,
  18279. shortcutFunction: 'sprintf' // or: defaultValue
  18280. };
  18281. function _extend(target, source) {
  18282. if (!source || typeof source === 'function') {
  18283. return target;
  18284. }
  18285. for (var attr in source) { target[attr] = source[attr]; }
  18286. return target;
  18287. }
  18288. function _deepExtend(target, source) {
  18289. for (var prop in source)
  18290. if (prop in target)
  18291. _deepExtend(target[prop], source[prop]);
  18292. else
  18293. target[prop] = source[prop];
  18294. return target;
  18295. }
  18296. function _each(object, callback, args) {
  18297. var name, i = 0,
  18298. length = object.length,
  18299. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18300. if (args) {
  18301. if (isObj) {
  18302. for (name in object) {
  18303. if (callback.apply(object[name], args) === false) {
  18304. break;
  18305. }
  18306. }
  18307. } else {
  18308. for ( ; i < length; ) {
  18309. if (callback.apply(object[i++], args) === false) {
  18310. break;
  18311. }
  18312. }
  18313. }
  18314. // A special, fast, case for the most common use of each
  18315. } else {
  18316. if (isObj) {
  18317. for (name in object) {
  18318. if (callback.call(object[name], name, object[name]) === false) {
  18319. break;
  18320. }
  18321. }
  18322. } else {
  18323. for ( ; i < length; ) {
  18324. if (callback.call(object[i], i, object[i++]) === false) {
  18325. break;
  18326. }
  18327. }
  18328. }
  18329. }
  18330. return object;
  18331. }
  18332. var _entityMap = {
  18333. "&": "&amp;",
  18334. "<": "&lt;",
  18335. ">": "&gt;",
  18336. '"': '&quot;',
  18337. "'": '&#39;',
  18338. "/": '&#x2F;'
  18339. };
  18340. function _escape(data) {
  18341. if (typeof data === 'string') {
  18342. return data.replace(/[&<>"'\/]/g, function (s) {
  18343. return _entityMap[s];
  18344. });
  18345. }else{
  18346. return data;
  18347. }
  18348. }
  18349. function _ajax(options) {
  18350. // v0.5.0 of https://github.com/goloroden/http.js
  18351. var getXhr = function (callback) {
  18352. // Use the native XHR object if the browser supports it.
  18353. if (window.XMLHttpRequest) {
  18354. return callback(null, new XMLHttpRequest());
  18355. } else if (window.ActiveXObject) {
  18356. // In Internet Explorer check for ActiveX versions of the XHR object.
  18357. try {
  18358. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18359. } catch (e) {
  18360. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18361. }
  18362. }
  18363. // If no XHR support was found, throw an error.
  18364. return callback(new Error());
  18365. };
  18366. var encodeUsingUrlEncoding = function (data) {
  18367. if(typeof data === 'string') {
  18368. return data;
  18369. }
  18370. var result = [];
  18371. for(var dataItem in data) {
  18372. if(data.hasOwnProperty(dataItem)) {
  18373. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18374. }
  18375. }
  18376. return result.join('&');
  18377. };
  18378. var utf8 = function (text) {
  18379. text = text.replace(/\r\n/g, '\n');
  18380. var result = '';
  18381. for(var i = 0; i < text.length; i++) {
  18382. var c = text.charCodeAt(i);
  18383. if(c < 128) {
  18384. result += String.fromCharCode(c);
  18385. } else if((c > 127) && (c < 2048)) {
  18386. result += String.fromCharCode((c >> 6) | 192);
  18387. result += String.fromCharCode((c & 63) | 128);
  18388. } else {
  18389. result += String.fromCharCode((c >> 12) | 224);
  18390. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18391. result += String.fromCharCode((c & 63) | 128);
  18392. }
  18393. }
  18394. return result;
  18395. };
  18396. var base64 = function (text) {
  18397. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18398. text = utf8(text);
  18399. var result = '',
  18400. chr1, chr2, chr3,
  18401. enc1, enc2, enc3, enc4,
  18402. i = 0;
  18403. do {
  18404. chr1 = text.charCodeAt(i++);
  18405. chr2 = text.charCodeAt(i++);
  18406. chr3 = text.charCodeAt(i++);
  18407. enc1 = chr1 >> 2;
  18408. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18409. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18410. enc4 = chr3 & 63;
  18411. if(isNaN(chr2)) {
  18412. enc3 = enc4 = 64;
  18413. } else if(isNaN(chr3)) {
  18414. enc4 = 64;
  18415. }
  18416. result +=
  18417. keyStr.charAt(enc1) +
  18418. keyStr.charAt(enc2) +
  18419. keyStr.charAt(enc3) +
  18420. keyStr.charAt(enc4);
  18421. chr1 = chr2 = chr3 = '';
  18422. enc1 = enc2 = enc3 = enc4 = '';
  18423. } while(i < text.length);
  18424. return result;
  18425. };
  18426. var mergeHeaders = function () {
  18427. // Use the first header object as base.
  18428. var result = arguments[0];
  18429. // Iterate through the remaining header objects and add them.
  18430. for(var i = 1; i < arguments.length; i++) {
  18431. var currentHeaders = arguments[i];
  18432. for(var header in currentHeaders) {
  18433. if(currentHeaders.hasOwnProperty(header)) {
  18434. result[header] = currentHeaders[header];
  18435. }
  18436. }
  18437. }
  18438. // Return the merged headers.
  18439. return result;
  18440. };
  18441. var ajax = function (method, url, options, callback) {
  18442. // Adjust parameters.
  18443. if(typeof options === 'function') {
  18444. callback = options;
  18445. options = {};
  18446. }
  18447. // Set default parameter values.
  18448. options.cache = options.cache || false;
  18449. options.data = options.data || {};
  18450. options.headers = options.headers || {};
  18451. options.jsonp = options.jsonp || false;
  18452. options.async = options.async === undefined ? true : options.async;
  18453. // Merge the various header objects.
  18454. var headers = mergeHeaders({
  18455. 'accept': '*/*',
  18456. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18457. }, ajax.headers, options.headers);
  18458. // Encode the data according to the content-type.
  18459. var payload;
  18460. if (headers['content-type'] === 'application/json') {
  18461. payload = JSON.stringify(options.data);
  18462. } else {
  18463. payload = encodeUsingUrlEncoding(options.data);
  18464. }
  18465. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18466. // if neccessary.
  18467. if(method === 'GET') {
  18468. // Setup the query string.
  18469. var queryString = [];
  18470. if(payload) {
  18471. queryString.push(payload);
  18472. payload = null;
  18473. }
  18474. // Handle caching.
  18475. if(!options.cache) {
  18476. queryString.push('_=' + (new Date()).getTime());
  18477. }
  18478. // If neccessary prepare the query string for a JSONP call.
  18479. if(options.jsonp) {
  18480. queryString.push('callback=' + options.jsonp);
  18481. queryString.push('jsonp=' + options.jsonp);
  18482. }
  18483. // Merge the query string and attach it to the url.
  18484. queryString = queryString.join('&');
  18485. if (queryString.length > 1) {
  18486. if (url.indexOf('?') > -1) {
  18487. url += '&' + queryString;
  18488. } else {
  18489. url += '?' + queryString;
  18490. }
  18491. }
  18492. // Make a JSONP call if neccessary.
  18493. if(options.jsonp) {
  18494. var head = document.getElementsByTagName('head')[0];
  18495. var script = document.createElement('script');
  18496. script.type = 'text/javascript';
  18497. script.src = url;
  18498. head.appendChild(script);
  18499. return;
  18500. }
  18501. }
  18502. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18503. getXhr(function (err, xhr) {
  18504. if(err) return callback(err);
  18505. // Open the request.
  18506. xhr.open(method, url, options.async);
  18507. // Set the request headers.
  18508. for(var header in headers) {
  18509. if(headers.hasOwnProperty(header)) {
  18510. xhr.setRequestHeader(header, headers[header]);
  18511. }
  18512. }
  18513. // Handle the request events.
  18514. xhr.onreadystatechange = function () {
  18515. if(xhr.readyState === 4) {
  18516. var data = xhr.responseText || '';
  18517. // If no callback is given, return.
  18518. if(!callback) {
  18519. return;
  18520. }
  18521. // Return an object that provides access to the data as text and JSON.
  18522. callback(xhr.status, {
  18523. text: function () {
  18524. return data;
  18525. },
  18526. json: function () {
  18527. try {
  18528. return JSON.parse(data)
  18529. } catch (e) {
  18530. f.error('Can not parse JSON. URL: ' + url);
  18531. return {};
  18532. }
  18533. }
  18534. });
  18535. }
  18536. };
  18537. // Actually send the XHR request.
  18538. xhr.send(payload);
  18539. });
  18540. };
  18541. // Define the external interface.
  18542. var http = {
  18543. authBasic: function (username, password) {
  18544. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18545. },
  18546. connect: function (url, options, callback) {
  18547. return ajax('CONNECT', url, options, callback);
  18548. },
  18549. del: function (url, options, callback) {
  18550. return ajax('DELETE', url, options, callback);
  18551. },
  18552. get: function (url, options, callback) {
  18553. return ajax('GET', url, options, callback);
  18554. },
  18555. head: function (url, options, callback) {
  18556. return ajax('HEAD', url, options, callback);
  18557. },
  18558. headers: function (headers) {
  18559. ajax.headers = headers || {};
  18560. },
  18561. isAllowed: function (url, verb, callback) {
  18562. this.options(url, function (status, data) {
  18563. callback(data.text().indexOf(verb) !== -1);
  18564. });
  18565. },
  18566. options: function (url, options, callback) {
  18567. return ajax('OPTIONS', url, options, callback);
  18568. },
  18569. patch: function (url, options, callback) {
  18570. return ajax('PATCH', url, options, callback);
  18571. },
  18572. post: function (url, options, callback) {
  18573. return ajax('POST', url, options, callback);
  18574. },
  18575. put: function (url, options, callback) {
  18576. return ajax('PUT', url, options, callback);
  18577. },
  18578. trace: function (url, options, callback) {
  18579. return ajax('TRACE', url, options, callback);
  18580. }
  18581. };
  18582. var methode = options.type ? options.type.toLowerCase() : 'get';
  18583. http[methode](options.url, options, function (status, data) {
  18584. // file: protocol always gives status code 0, so check for data
  18585. if (status === 200 || (status === 0 && data.text())) {
  18586. options.success(data.json(), status, null);
  18587. } else {
  18588. options.error(data.text(), status, null);
  18589. }
  18590. });
  18591. }
  18592. var _cookie = {
  18593. create: function(name,value,minutes,domain) {
  18594. var expires;
  18595. if (minutes) {
  18596. var date = new Date();
  18597. date.setTime(date.getTime()+(minutes*60*1000));
  18598. expires = "; expires="+date.toGMTString();
  18599. }
  18600. else expires = "";
  18601. domain = (domain)? "domain="+domain+";" : "";
  18602. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18603. },
  18604. read: function(name) {
  18605. var nameEQ = name + "=";
  18606. var ca = document.cookie.split(';');
  18607. for(var i=0;i < ca.length;i++) {
  18608. var c = ca[i];
  18609. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18610. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18611. }
  18612. return null;
  18613. },
  18614. remove: function(name) {
  18615. this.create(name,"",-1);
  18616. }
  18617. };
  18618. var cookie_noop = {
  18619. create: function(name,value,minutes,domain) {},
  18620. read: function(name) { return null; },
  18621. remove: function(name) {}
  18622. };
  18623. // move dependent functions to a container so that
  18624. // they can be overriden easier in no jquery environment (node.js)
  18625. var f = {
  18626. extend: $ ? $.extend : _extend,
  18627. deepExtend: _deepExtend,
  18628. each: $ ? $.each : _each,
  18629. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18630. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18631. detectLanguage: detectLanguage,
  18632. escape: _escape,
  18633. log: function(str) {
  18634. if (o.debug && typeof console !== "undefined") console.log(str);
  18635. },
  18636. error: function(str) {
  18637. if (typeof console !== "undefined") console.error(str);
  18638. },
  18639. getCountyIndexOfLng: function(lng) {
  18640. var lng_index = 0;
  18641. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18642. return lng_index;
  18643. },
  18644. toLanguages: function(lng) {
  18645. var log = this.log;
  18646. function applyCase(l) {
  18647. var ret = l;
  18648. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18649. var parts = l.split('-');
  18650. ret = o.lowerCaseLng ?
  18651. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18652. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18653. } else {
  18654. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18655. }
  18656. return ret;
  18657. }
  18658. var languages = [];
  18659. var whitelist = o.lngWhitelist || false;
  18660. var addLanguage = function(language){
  18661. //reject langs not whitelisted
  18662. if(!whitelist || whitelist.indexOf(language) > -1){
  18663. languages.push(language);
  18664. }else{
  18665. log('rejecting non-whitelisted language: ' + language);
  18666. }
  18667. };
  18668. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18669. var parts = lng.split('-');
  18670. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18671. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18672. } else {
  18673. addLanguage(applyCase(lng));
  18674. }
  18675. for (var i = 0; i < o.fallbackLng.length; i++) {
  18676. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18677. }
  18678. return languages;
  18679. },
  18680. regexEscape: function(str) {
  18681. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18682. },
  18683. regexReplacementEscape: function(strOrFn) {
  18684. if (typeof strOrFn === 'string') {
  18685. return strOrFn.replace(/\$/g, "$$$$");
  18686. } else {
  18687. return strOrFn;
  18688. }
  18689. },
  18690. localStorage: {
  18691. setItem: function(key, value) {
  18692. if (window.localStorage) {
  18693. try {
  18694. window.localStorage.setItem(key, value);
  18695. } catch (e) {
  18696. f.log('failed to set value for key "' + key + '" to localStorage.');
  18697. }
  18698. }
  18699. }
  18700. }
  18701. };
  18702. function init(options, cb) {
  18703. if (typeof options === 'function') {
  18704. cb = options;
  18705. options = {};
  18706. }
  18707. options = options || {};
  18708. // override defaults with passed in options
  18709. f.extend(o, options);
  18710. delete o.fixLng; /* passed in each time */
  18711. // override functions: .log(), .detectLanguage(), etc
  18712. if (o.functions) {
  18713. delete o.functions;
  18714. f.extend(f, options.functions);
  18715. }
  18716. // create namespace object if namespace is passed in as string
  18717. if (typeof o.ns == 'string') {
  18718. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18719. }
  18720. // fallback namespaces
  18721. if (typeof o.fallbackNS == 'string') {
  18722. o.fallbackNS = [o.fallbackNS];
  18723. }
  18724. // fallback languages
  18725. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18726. o.fallbackLng = [o.fallbackLng];
  18727. }
  18728. // escape prefix/suffix
  18729. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18730. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18731. if (!o.lng) o.lng = f.detectLanguage();
  18732. languages = f.toLanguages(o.lng);
  18733. currentLng = languages[0];
  18734. f.log('currentLng set to: ' + currentLng);
  18735. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18736. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18737. }
  18738. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18739. f.localStorage.setItem('i18next_lng', currentLng);
  18740. }
  18741. var lngTranslate = translate;
  18742. if (options.fixLng) {
  18743. lngTranslate = function(key, options) {
  18744. options = options || {};
  18745. options.lng = options.lng || lngTranslate.lng;
  18746. return translate(key, options);
  18747. };
  18748. lngTranslate.lng = currentLng;
  18749. }
  18750. pluralExtensions.setCurrentLng(currentLng);
  18751. // add JQuery extensions
  18752. if ($ && o.setJqueryExt) addJqueryFunct();
  18753. // jQuery deferred
  18754. var deferred;
  18755. if ($ && $.Deferred) {
  18756. deferred = $.Deferred();
  18757. }
  18758. // return immidiatly if res are passed in
  18759. if (o.resStore) {
  18760. resStore = o.resStore;
  18761. initialized = true;
  18762. if (cb) cb(lngTranslate);
  18763. if (deferred) deferred.resolve(lngTranslate);
  18764. if (deferred) return deferred.promise();
  18765. return;
  18766. }
  18767. // languages to load
  18768. var lngsToLoad = f.toLanguages(o.lng);
  18769. if (typeof o.preload === 'string') o.preload = [o.preload];
  18770. for (var i = 0, l = o.preload.length; i < l; i++) {
  18771. var pres = f.toLanguages(o.preload[i]);
  18772. for (var y = 0, len = pres.length; y < len; y++) {
  18773. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18774. lngsToLoad.push(pres[y]);
  18775. }
  18776. }
  18777. }
  18778. // else load them
  18779. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18780. resStore = store;
  18781. initialized = true;
  18782. if (cb) cb(lngTranslate);
  18783. if (deferred) deferred.resolve(lngTranslate);
  18784. });
  18785. if (deferred) return deferred.promise();
  18786. }
  18787. function preload(lngs, cb) {
  18788. if (typeof lngs === 'string') lngs = [lngs];
  18789. for (var i = 0, l = lngs.length; i < l; i++) {
  18790. if (o.preload.indexOf(lngs[i]) < 0) {
  18791. o.preload.push(lngs[i]);
  18792. }
  18793. }
  18794. return init(cb);
  18795. }
  18796. function addResourceBundle(lng, ns, resources, deep) {
  18797. if (typeof ns !== 'string') {
  18798. resources = ns;
  18799. ns = o.ns.defaultNs;
  18800. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18801. o.ns.namespaces.push(ns);
  18802. }
  18803. resStore[lng] = resStore[lng] || {};
  18804. resStore[lng][ns] = resStore[lng][ns] || {};
  18805. if (deep) {
  18806. f.deepExtend(resStore[lng][ns], resources);
  18807. } else {
  18808. f.extend(resStore[lng][ns], resources);
  18809. }
  18810. }
  18811. function hasResourceBundle(lng, ns) {
  18812. if (typeof ns !== 'string') {
  18813. ns = o.ns.defaultNs;
  18814. }
  18815. resStore[lng] = resStore[lng] || {};
  18816. var res = resStore[lng][ns] || {};
  18817. var hasValues = false;
  18818. for(var prop in res) {
  18819. if (res.hasOwnProperty(prop)) {
  18820. hasValues = true;
  18821. }
  18822. }
  18823. return hasValues;
  18824. }
  18825. function removeResourceBundle(lng, ns) {
  18826. if (typeof ns !== 'string') {
  18827. ns = o.ns.defaultNs;
  18828. }
  18829. resStore[lng] = resStore[lng] || {};
  18830. resStore[lng][ns] = {};
  18831. }
  18832. function addResource(lng, ns, key, value) {
  18833. if (typeof ns !== 'string') {
  18834. resource = ns;
  18835. ns = o.ns.defaultNs;
  18836. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18837. o.ns.namespaces.push(ns);
  18838. }
  18839. resStore[lng] = resStore[lng] || {};
  18840. resStore[lng][ns] = resStore[lng][ns] || {};
  18841. var keys = key.split(o.keyseparator);
  18842. var x = 0;
  18843. var node = resStore[lng][ns];
  18844. var origRef = node;
  18845. while (keys[x]) {
  18846. if (x == keys.length - 1)
  18847. node[keys[x]] = value;
  18848. else {
  18849. if (node[keys[x]] == null)
  18850. node[keys[x]] = {};
  18851. node = node[keys[x]];
  18852. }
  18853. x++;
  18854. }
  18855. }
  18856. function addResources(lng, ns, resources) {
  18857. if (typeof ns !== 'string') {
  18858. resource = ns;
  18859. ns = o.ns.defaultNs;
  18860. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18861. o.ns.namespaces.push(ns);
  18862. }
  18863. for (var m in resources) {
  18864. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18865. }
  18866. }
  18867. function setDefaultNamespace(ns) {
  18868. o.ns.defaultNs = ns;
  18869. }
  18870. function loadNamespace(namespace, cb) {
  18871. loadNamespaces([namespace], cb);
  18872. }
  18873. function loadNamespaces(namespaces, cb) {
  18874. var opts = {
  18875. dynamicLoad: o.dynamicLoad,
  18876. resGetPath: o.resGetPath,
  18877. getAsync: o.getAsync,
  18878. customLoad: o.customLoad,
  18879. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18880. };
  18881. // languages to load
  18882. var lngsToLoad = f.toLanguages(o.lng);
  18883. if (typeof o.preload === 'string') o.preload = [o.preload];
  18884. for (var i = 0, l = o.preload.length; i < l; i++) {
  18885. var pres = f.toLanguages(o.preload[i]);
  18886. for (var y = 0, len = pres.length; y < len; y++) {
  18887. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18888. lngsToLoad.push(pres[y]);
  18889. }
  18890. }
  18891. }
  18892. // check if we have to load
  18893. var lngNeedLoad = [];
  18894. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18895. var needLoad = false;
  18896. var resSet = resStore[lngsToLoad[a]];
  18897. if (resSet) {
  18898. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18899. if (!resSet[namespaces[b]]) needLoad = true;
  18900. }
  18901. } else {
  18902. needLoad = true;
  18903. }
  18904. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18905. }
  18906. if (lngNeedLoad.length) {
  18907. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18908. var todo = namespaces.length * lngNeedLoad.length;
  18909. // load each file individual
  18910. f.each(namespaces, function(nsIndex, nsValue) {
  18911. // append namespace to namespace array
  18912. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18913. o.ns.namespaces.push(nsValue);
  18914. }
  18915. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18916. resStore[lngValue] = resStore[lngValue] || {};
  18917. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18918. todo--; // wait for all done befor callback
  18919. if (todo === 0 && cb) {
  18920. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18921. cb();
  18922. }
  18923. });
  18924. });
  18925. });
  18926. } else {
  18927. if (cb) cb();
  18928. }
  18929. }
  18930. function setLng(lng, options, cb) {
  18931. if (typeof options === 'function') {
  18932. cb = options;
  18933. options = {};
  18934. } else if (!options) {
  18935. options = {};
  18936. }
  18937. options.lng = lng;
  18938. return init(options, cb);
  18939. }
  18940. function lng() {
  18941. return currentLng;
  18942. }
  18943. function reload(cb) {
  18944. resStore = {};
  18945. setLng(currentLng, cb);
  18946. }
  18947. function addJqueryFunct() {
  18948. // $.t shortcut
  18949. $.t = $.t || translate;
  18950. function parse(ele, key, options) {
  18951. if (key.length === 0) return;
  18952. var attr = 'text';
  18953. if (key.indexOf('[') === 0) {
  18954. var parts = key.split(']');
  18955. key = parts[1];
  18956. attr = parts[0].substr(1, parts[0].length-1);
  18957. }
  18958. if (key.indexOf(';') === key.length-1) {
  18959. key = key.substr(0, key.length-2);
  18960. }
  18961. var optionsToUse;
  18962. if (attr === 'html') {
  18963. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18964. ele.html($.t(key, optionsToUse));
  18965. } else if (attr === 'text') {
  18966. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18967. ele.text($.t(key, optionsToUse));
  18968. } else if (attr === 'prepend') {
  18969. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18970. ele.prepend($.t(key, optionsToUse));
  18971. } else if (attr === 'append') {
  18972. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18973. ele.append($.t(key, optionsToUse));
  18974. } else if (attr.indexOf("data-") === 0) {
  18975. var dataAttr = attr.substr(("data-").length);
  18976. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18977. var translated = $.t(key, optionsToUse);
  18978. //we change into the data cache
  18979. ele.data(dataAttr, translated);
  18980. //we change into the dom
  18981. ele.attr(attr, translated);
  18982. } else {
  18983. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18984. ele.attr(attr, $.t(key, optionsToUse));
  18985. }
  18986. }
  18987. function localize(ele, options) {
  18988. var key = ele.attr(o.selectorAttr);
  18989. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18990. if (!key) return;
  18991. var target = ele
  18992. , targetSelector = ele.data("i18n-target");
  18993. if (targetSelector) {
  18994. target = ele.find(targetSelector) || ele;
  18995. }
  18996. if (!options && o.useDataAttrOptions === true) {
  18997. options = ele.data("i18n-options");
  18998. }
  18999. options = options || {};
  19000. if (key.indexOf(';') >= 0) {
  19001. var keys = key.split(';');
  19002. $.each(keys, function(m, k) {
  19003. if (k !== '') parse(target, k, options);
  19004. });
  19005. } else {
  19006. parse(target, key, options);
  19007. }
  19008. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  19009. }
  19010. // fn
  19011. $.fn.i18n = function (options) {
  19012. return this.each(function() {
  19013. // localize element itself
  19014. localize($(this), options);
  19015. // localize childs
  19016. var elements = $(this).find('[' + o.selectorAttr + ']');
  19017. elements.each(function() {
  19018. localize($(this), options);
  19019. });
  19020. });
  19021. };
  19022. }
  19023. function applyReplacement(str, replacementHash, nestedKey, options) {
  19024. if (!str) return str;
  19025. options = options || replacementHash; // first call uses replacement hash combined with options
  19026. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  19027. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  19028. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  19029. , unEscapingSuffix = 'HTML'+suffix;
  19030. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  19031. f.each(hash, function(key, value) {
  19032. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  19033. if (typeof value === 'object' && value !== null) {
  19034. str = applyReplacement(str, value, nextKey, options);
  19035. } else {
  19036. if (options.escapeInterpolation || o.escapeInterpolation) {
  19037. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  19038. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  19039. } else {
  19040. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  19041. }
  19042. // str = options.escapeInterpolation;
  19043. }
  19044. });
  19045. return str;
  19046. }
  19047. // append it to functions
  19048. f.applyReplacement = applyReplacement;
  19049. function applyReuse(translated, options) {
  19050. var comma = ',';
  19051. var options_open = '{';
  19052. var options_close = '}';
  19053. var opts = f.extend({}, options);
  19054. delete opts.postProcess;
  19055. while (translated.indexOf(o.reusePrefix) != -1) {
  19056. replacementCounter++;
  19057. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  19058. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  19059. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  19060. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  19061. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  19062. if (index_of_end_of_closing <= index_of_opening) {
  19063. f.error('there is an missing closing in following translation value', translated);
  19064. return '';
  19065. }
  19066. if (token_without_symbols.indexOf(comma) != -1) {
  19067. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  19068. 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) {
  19069. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  19070. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  19071. try {
  19072. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  19073. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  19074. } catch (e) {
  19075. }
  19076. }
  19077. }
  19078. var translated_token = _translate(token_without_symbols, opts);
  19079. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  19080. }
  19081. return translated;
  19082. }
  19083. function hasContext(options) {
  19084. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  19085. }
  19086. function needsPlural(options, lng) {
  19087. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  19088. }
  19089. function needsIndefiniteArticle(options) {
  19090. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  19091. }
  19092. function exists(key, options) {
  19093. options = options || {};
  19094. var notFound = _getDefaultValue(key, options)
  19095. , found = _find(key, options);
  19096. return found !== undefined || found === notFound;
  19097. }
  19098. function translate(key, options) {
  19099. options = options || {};
  19100. if (!initialized) {
  19101. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  19102. return options.defaultValue || '';
  19103. };
  19104. replacementCounter = 0;
  19105. return _translate.apply(null, arguments);
  19106. }
  19107. function _getDefaultValue(key, options) {
  19108. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  19109. }
  19110. function _injectSprintfProcessor() {
  19111. var values = [];
  19112. // mh: build array from second argument onwards
  19113. for (var i = 1; i < arguments.length; i++) {
  19114. values.push(arguments[i]);
  19115. }
  19116. return {
  19117. postProcess: 'sprintf',
  19118. sprintf: values
  19119. };
  19120. }
  19121. function _translate(potentialKeys, options) {
  19122. if (options && typeof options !== 'object') {
  19123. if (o.shortcutFunction === 'sprintf') {
  19124. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  19125. options = _injectSprintfProcessor.apply(null, arguments);
  19126. } else if (o.shortcutFunction === 'defaultValue') {
  19127. options = {
  19128. defaultValue: options
  19129. }
  19130. }
  19131. } else {
  19132. options = options || {};
  19133. }
  19134. if (typeof o.defaultVariables === 'object') {
  19135. options = f.extend({}, o.defaultVariables, options);
  19136. }
  19137. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  19138. if (typeof potentialKeys === 'string') {
  19139. potentialKeys = [potentialKeys];
  19140. }
  19141. var key = potentialKeys[0];
  19142. if (potentialKeys.length > 1) {
  19143. for (var i = 0; i < potentialKeys.length; i++) {
  19144. key = potentialKeys[i];
  19145. if (exists(key, options)) {
  19146. break;
  19147. }
  19148. }
  19149. }
  19150. var notFound = _getDefaultValue(key, options)
  19151. , found = _find(key, options)
  19152. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  19153. , ns = options.ns || o.ns.defaultNs
  19154. , parts;
  19155. // split ns and key
  19156. if (key.indexOf(o.nsseparator) > -1) {
  19157. parts = key.split(o.nsseparator);
  19158. ns = parts[0];
  19159. key = parts[1];
  19160. }
  19161. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  19162. if (options.lng) {
  19163. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  19164. } else {
  19165. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  19166. }
  19167. }
  19168. var postProcessor = options.postProcess || o.postProcess;
  19169. if (found !== undefined && postProcessor) {
  19170. if (postProcessors[postProcessor]) {
  19171. found = postProcessors[postProcessor](found, key, options);
  19172. }
  19173. }
  19174. // process notFound if function exists
  19175. var splitNotFound = notFound;
  19176. if (notFound.indexOf(o.nsseparator) > -1) {
  19177. parts = notFound.split(o.nsseparator);
  19178. splitNotFound = parts[1];
  19179. }
  19180. if (splitNotFound === key && o.parseMissingKey) {
  19181. notFound = o.parseMissingKey(notFound);
  19182. }
  19183. if (found === undefined) {
  19184. notFound = applyReplacement(notFound, options);
  19185. notFound = applyReuse(notFound, options);
  19186. if (postProcessor && postProcessors[postProcessor]) {
  19187. var val = _getDefaultValue(key, options);
  19188. found = postProcessors[postProcessor](val, key, options);
  19189. }
  19190. }
  19191. return (found !== undefined) ? found : notFound;
  19192. }
  19193. function _find(key, options) {
  19194. options = options || {};
  19195. var optionWithoutCount, translated
  19196. , notFound = _getDefaultValue(key, options)
  19197. , lngs = languages;
  19198. if (!resStore) { return notFound; } // no resStore to translate from
  19199. // CI mode
  19200. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19201. // passed in lng
  19202. if (options.lngs) lngs = options.lngs;
  19203. if (options.lng) {
  19204. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19205. if (!resStore[lngs[0]]) {
  19206. var oldAsync = o.getAsync;
  19207. o.getAsync = false;
  19208. i18n.sync.load(lngs, o, function(err, store) {
  19209. f.extend(resStore, store);
  19210. o.getAsync = oldAsync;
  19211. });
  19212. }
  19213. }
  19214. var ns = options.ns || o.ns.defaultNs;
  19215. if (key.indexOf(o.nsseparator) > -1) {
  19216. var parts = key.split(o.nsseparator);
  19217. ns = parts[0];
  19218. key = parts[1];
  19219. }
  19220. if (hasContext(options)) {
  19221. optionWithoutCount = f.extend({}, options);
  19222. delete optionWithoutCount.context;
  19223. optionWithoutCount.defaultValue = o.contextNotFound;
  19224. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19225. translated = translate(contextKey, optionWithoutCount);
  19226. if (translated != o.contextNotFound) {
  19227. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19228. } // else continue translation with original/nonContext key
  19229. }
  19230. if (needsPlural(options, lngs[0])) {
  19231. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19232. delete optionWithoutCount.count;
  19233. delete optionWithoutCount.lng;
  19234. optionWithoutCount.defaultValue = o.pluralNotFound;
  19235. var pluralKey;
  19236. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19237. pluralKey = ns + o.nsseparator + key;
  19238. } else {
  19239. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19240. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19241. if (pluralExtension >= 0) {
  19242. pluralKey = pluralKey + '_' + pluralExtension;
  19243. } else if (pluralExtension === 1) {
  19244. pluralKey = ns + o.nsseparator + key; // singular
  19245. }
  19246. }
  19247. translated = translate(pluralKey, optionWithoutCount);
  19248. if (translated != o.pluralNotFound) {
  19249. return applyReplacement(translated, {
  19250. count: options.count,
  19251. interpolationPrefix: options.interpolationPrefix,
  19252. interpolationSuffix: options.interpolationSuffix
  19253. }); // apply replacement for count only
  19254. } else if (lngs.length > 1) {
  19255. // remove failed lng
  19256. var clone = lngs.slice();
  19257. clone.shift();
  19258. options = f.extend(options, { lngs: clone });
  19259. delete options.lng;
  19260. // retry with fallbacks
  19261. translated = translate(ns + o.nsseparator + key, options);
  19262. if (translated != o.pluralNotFound) return translated;
  19263. } else {
  19264. return translated;
  19265. }
  19266. }
  19267. if (needsIndefiniteArticle(options)) {
  19268. var optionsWithoutIndef = f.extend({}, options);
  19269. delete optionsWithoutIndef.indefinite_article;
  19270. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19271. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19272. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19273. translated = translate(indefiniteKey, optionsWithoutIndef);
  19274. if (translated != o.indefiniteNotFound) {
  19275. return translated;
  19276. }
  19277. }
  19278. var found;
  19279. var keys = key.split(o.keyseparator);
  19280. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19281. if (found !== undefined) break;
  19282. var l = lngs[i];
  19283. var x = 0;
  19284. var value = resStore[l] && resStore[l][ns];
  19285. while (keys[x]) {
  19286. value = value && value[keys[x]];
  19287. x++;
  19288. }
  19289. if (value !== undefined) {
  19290. var valueType = Object.prototype.toString.apply(value);
  19291. if (typeof value === 'string') {
  19292. value = applyReplacement(value, options);
  19293. value = applyReuse(value, options);
  19294. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19295. value = value.join('\n');
  19296. value = applyReplacement(value, options);
  19297. value = applyReuse(value, options);
  19298. } else if (value === null && o.fallbackOnNull === true) {
  19299. value = undefined;
  19300. } else if (value !== null) {
  19301. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19302. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19303. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19304. } else {
  19305. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19306. 'returned an object instead of string.';
  19307. f.log(value);
  19308. }
  19309. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19310. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19311. f.each(value, function(m) {
  19312. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19313. });
  19314. value = copy;
  19315. }
  19316. }
  19317. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19318. value = undefined;
  19319. found = value;
  19320. }
  19321. }
  19322. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19323. // set flag for fallback lookup - avoid recursion
  19324. options.isFallbackLookup = true;
  19325. if (o.fallbackNS.length) {
  19326. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19327. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19328. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19329. /* compare value without namespace */
  19330. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19331. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19332. if (foundValue !== notFoundValue) break;
  19333. }
  19334. }
  19335. } else {
  19336. found = _find(key, options); // fallback to default NS
  19337. }
  19338. options.isFallbackLookup = false;
  19339. }
  19340. return found;
  19341. }
  19342. function detectLanguage() {
  19343. var detectedLng;
  19344. var whitelist = o.lngWhitelist || [];
  19345. var userLngChoices = [];
  19346. // get from qs
  19347. var qsParm = [];
  19348. if (typeof window !== 'undefined') {
  19349. (function() {
  19350. var query = window.location.search.substring(1);
  19351. var params = query.split('&');
  19352. for (var i=0; i<params.length; i++) {
  19353. var pos = params[i].indexOf('=');
  19354. if (pos > 0) {
  19355. var key = params[i].substring(0,pos);
  19356. if (key == o.detectLngQS) {
  19357. userLngChoices.push(params[i].substring(pos+1));
  19358. }
  19359. }
  19360. }
  19361. })();
  19362. }
  19363. // get from cookie
  19364. if (o.useCookie && typeof document !== 'undefined') {
  19365. var c = f.cookie.read(o.cookieName);
  19366. if (c) userLngChoices.push(c);
  19367. }
  19368. // get from localStorage
  19369. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19370. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19371. }
  19372. // get from navigator
  19373. if (typeof navigator !== 'undefined') {
  19374. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19375. for (var i=0;i<navigator.languages.length;i++) {
  19376. userLngChoices.push(navigator.languages[i]);
  19377. }
  19378. }
  19379. if (navigator.userLanguage) {
  19380. userLngChoices.push(navigator.userLanguage);
  19381. }
  19382. if (navigator.language) {
  19383. userLngChoices.push(navigator.language);
  19384. }
  19385. }
  19386. (function() {
  19387. for (var i=0;i<userLngChoices.length;i++) {
  19388. var lng = userLngChoices[i];
  19389. if (lng.indexOf('-') > -1) {
  19390. var parts = lng.split('-');
  19391. lng = o.lowerCaseLng ?
  19392. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19393. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19394. }
  19395. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19396. detectedLng = lng;
  19397. break;
  19398. }
  19399. }
  19400. })();
  19401. //fallback
  19402. if (!detectedLng){
  19403. detectedLng = o.fallbackLng[0];
  19404. }
  19405. return detectedLng;
  19406. }
  19407. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19408. /* [code, name, numbers, pluralsType] */
  19409. var _rules = [
  19410. ["ach", "Acholi", [1,2], 1],
  19411. ["af", "Afrikaans",[1,2], 2],
  19412. ["ak", "Akan", [1,2], 1],
  19413. ["am", "Amharic", [1,2], 1],
  19414. ["an", "Aragonese",[1,2], 2],
  19415. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19416. ["arn", "Mapudungun",[1,2], 1],
  19417. ["ast", "Asturian", [1,2], 2],
  19418. ["ay", "Aymará", [1], 3],
  19419. ["az", "Azerbaijani",[1,2],2],
  19420. ["be", "Belarusian",[1,2,5],4],
  19421. ["bg", "Bulgarian",[1,2], 2],
  19422. ["bn", "Bengali", [1,2], 2],
  19423. ["bo", "Tibetan", [1], 3],
  19424. ["br", "Breton", [1,2], 1],
  19425. ["bs", "Bosnian", [1,2,5],4],
  19426. ["ca", "Catalan", [1,2], 2],
  19427. ["cgg", "Chiga", [1], 3],
  19428. ["cs", "Czech", [1,2,5],6],
  19429. ["csb", "Kashubian",[1,2,5],7],
  19430. ["cy", "Welsh", [1,2,3,8],8],
  19431. ["da", "Danish", [1,2], 2],
  19432. ["de", "German", [1,2], 2],
  19433. ["dev", "Development Fallback", [1,2], 2],
  19434. ["dz", "Dzongkha", [1], 3],
  19435. ["el", "Greek", [1,2], 2],
  19436. ["en", "English", [1,2], 2],
  19437. ["eo", "Esperanto",[1,2], 2],
  19438. ["es", "Spanish", [1,2], 2],
  19439. ["es_ar","Argentinean Spanish", [1,2], 2],
  19440. ["et", "Estonian", [1,2], 2],
  19441. ["eu", "Basque", [1,2], 2],
  19442. ["fa", "Persian", [1], 3],
  19443. ["fi", "Finnish", [1,2], 2],
  19444. ["fil", "Filipino", [1,2], 1],
  19445. ["fo", "Faroese", [1,2], 2],
  19446. ["fr", "French", [1,2], 9],
  19447. ["fur", "Friulian", [1,2], 2],
  19448. ["fy", "Frisian", [1,2], 2],
  19449. ["ga", "Irish", [1,2,3,7,11],10],
  19450. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19451. ["gl", "Galician", [1,2], 2],
  19452. ["gu", "Gujarati", [1,2], 2],
  19453. ["gun", "Gun", [1,2], 1],
  19454. ["ha", "Hausa", [1,2], 2],
  19455. ["he", "Hebrew", [1,2], 2],
  19456. ["hi", "Hindi", [1,2], 2],
  19457. ["hr", "Croatian", [1,2,5],4],
  19458. ["hu", "Hungarian",[1,2], 2],
  19459. ["hy", "Armenian", [1,2], 2],
  19460. ["ia", "Interlingua",[1,2],2],
  19461. ["id", "Indonesian",[1], 3],
  19462. ["is", "Icelandic",[1,2], 12],
  19463. ["it", "Italian", [1,2], 2],
  19464. ["ja", "Japanese", [1], 3],
  19465. ["jbo", "Lojban", [1], 3],
  19466. ["jv", "Javanese", [0,1], 13],
  19467. ["ka", "Georgian", [1], 3],
  19468. ["kk", "Kazakh", [1], 3],
  19469. ["km", "Khmer", [1], 3],
  19470. ["kn", "Kannada", [1,2], 2],
  19471. ["ko", "Korean", [1], 3],
  19472. ["ku", "Kurdish", [1,2], 2],
  19473. ["kw", "Cornish", [1,2,3,4],14],
  19474. ["ky", "Kyrgyz", [1], 3],
  19475. ["lb", "Letzeburgesch",[1,2],2],
  19476. ["ln", "Lingala", [1,2], 1],
  19477. ["lo", "Lao", [1], 3],
  19478. ["lt", "Lithuanian",[1,2,10],15],
  19479. ["lv", "Latvian", [1,2,0],16],
  19480. ["mai", "Maithili", [1,2], 2],
  19481. ["mfe", "Mauritian Creole",[1,2],1],
  19482. ["mg", "Malagasy", [1,2], 1],
  19483. ["mi", "Maori", [1,2], 1],
  19484. ["mk", "Macedonian",[1,2],17],
  19485. ["ml", "Malayalam",[1,2], 2],
  19486. ["mn", "Mongolian",[1,2], 2],
  19487. ["mnk", "Mandinka", [0,1,2],18],
  19488. ["mr", "Marathi", [1,2], 2],
  19489. ["ms", "Malay", [1], 3],
  19490. ["mt", "Maltese", [1,2,11,20],19],
  19491. ["nah", "Nahuatl", [1,2], 2],
  19492. ["nap", "Neapolitan",[1,2], 2],
  19493. ["nb", "Norwegian Bokmal",[1,2],2],
  19494. ["ne", "Nepali", [1,2], 2],
  19495. ["nl", "Dutch", [1,2], 2],
  19496. ["nn", "Norwegian Nynorsk",[1,2],2],
  19497. ["no", "Norwegian",[1,2], 2],
  19498. ["nso", "Northern Sotho",[1,2],2],
  19499. ["oc", "Occitan", [1,2], 1],
  19500. ["or", "Oriya", [2,1], 2],
  19501. ["pa", "Punjabi", [1,2], 2],
  19502. ["pap", "Papiamento",[1,2], 2],
  19503. ["pl", "Polish", [1,2,5],7],
  19504. ["pms", "Piemontese",[1,2], 2],
  19505. ["ps", "Pashto", [1,2], 2],
  19506. ["pt", "Portuguese",[1,2], 2],
  19507. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19508. ["rm", "Romansh", [1,2], 2],
  19509. ["ro", "Romanian", [1,2,20],20],
  19510. ["ru", "Russian", [1,2,5],4],
  19511. ["sah", "Yakut", [1], 3],
  19512. ["sco", "Scots", [1,2], 2],
  19513. ["se", "Northern Sami",[1,2], 2],
  19514. ["si", "Sinhala", [1,2], 2],
  19515. ["sk", "Slovak", [1,2,5],6],
  19516. ["sl", "Slovenian",[5,1,2,3],21],
  19517. ["so", "Somali", [1,2], 2],
  19518. ["son", "Songhay", [1,2], 2],
  19519. ["sq", "Albanian", [1,2], 2],
  19520. ["sr", "Serbian", [1,2,5],4],
  19521. ["su", "Sundanese",[1], 3],
  19522. ["sv", "Swedish", [1,2], 2],
  19523. ["sw", "Swahili", [1,2], 2],
  19524. ["ta", "Tamil", [1,2], 2],
  19525. ["te", "Telugu", [1,2], 2],
  19526. ["tg", "Tajik", [1,2], 1],
  19527. ["th", "Thai", [1], 3],
  19528. ["ti", "Tigrinya", [1,2], 1],
  19529. ["tk", "Turkmen", [1,2], 2],
  19530. ["tr", "Turkish", [1,2], 1],
  19531. ["tt", "Tatar", [1], 3],
  19532. ["ug", "Uyghur", [1], 3],
  19533. ["uk", "Ukrainian",[1,2,5],4],
  19534. ["ur", "Urdu", [1,2], 2],
  19535. ["uz", "Uzbek", [1,2], 1],
  19536. ["vi", "Vietnamese",[1], 3],
  19537. ["wa", "Walloon", [1,2], 1],
  19538. ["wo", "Wolof", [1], 3],
  19539. ["yo", "Yoruba", [1,2], 2],
  19540. ["zh", "Chinese", [1], 3]
  19541. ];
  19542. var _rulesPluralsTypes = {
  19543. 1: function(n) {return Number(n > 1);},
  19544. 2: function(n) {return Number(n != 1);},
  19545. 3: function(n) {return 0;},
  19546. 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);},
  19547. 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);},
  19548. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19549. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19550. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19551. 9: function(n) {return Number(n >= 2);},
  19552. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19553. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19554. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19555. 13: function(n) {return Number(n !== 0);},
  19556. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19557. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19558. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19559. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19560. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19561. 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);},
  19562. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19563. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19564. };
  19565. var pluralExtensions = {
  19566. rules: (function () {
  19567. var l, rules = {};
  19568. for (l=_rules.length; l-- ;) {
  19569. rules[_rules[l][0]] = {
  19570. name: _rules[l][1],
  19571. numbers: _rules[l][2],
  19572. plurals: _rulesPluralsTypes[_rules[l][3]]
  19573. }
  19574. }
  19575. return rules;
  19576. }()),
  19577. // you can add your own pluralExtensions
  19578. addRule: function(lng, obj) {
  19579. pluralExtensions.rules[lng] = obj;
  19580. },
  19581. setCurrentLng: function(lng) {
  19582. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19583. var parts = lng.split('-');
  19584. pluralExtensions.currentRule = {
  19585. lng: lng,
  19586. rule: pluralExtensions.rules[parts[0]]
  19587. };
  19588. }
  19589. },
  19590. needsPlural: function(lng, count) {
  19591. var parts = lng.split('-');
  19592. var ext;
  19593. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19594. ext = pluralExtensions.currentRule.rule;
  19595. } else {
  19596. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19597. }
  19598. if (ext && ext.numbers.length <= 1) {
  19599. return false;
  19600. } else {
  19601. return this.get(lng, count) !== 1;
  19602. }
  19603. },
  19604. get: function(lng, count) {
  19605. var parts = lng.split('-');
  19606. function getResult(l, c) {
  19607. var ext;
  19608. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19609. ext = pluralExtensions.currentRule.rule;
  19610. } else {
  19611. ext = pluralExtensions.rules[l];
  19612. }
  19613. if (ext) {
  19614. var i;
  19615. if (ext.noAbs) {
  19616. i = ext.plurals(c);
  19617. } else {
  19618. i = ext.plurals(Math.abs(c));
  19619. }
  19620. var number = ext.numbers[i];
  19621. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19622. if (number === 2) {
  19623. number = -1; // regular plural
  19624. } else if (number === 1) {
  19625. number = 1; // singular
  19626. }
  19627. }//console.log(count + '-' + number);
  19628. return number;
  19629. } else {
  19630. return c === 1 ? '1' : '-1';
  19631. }
  19632. }
  19633. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19634. }
  19635. };
  19636. var postProcessors = {};
  19637. var addPostProcessor = function(name, fc) {
  19638. postProcessors[name] = fc;
  19639. };
  19640. // sprintf support
  19641. var sprintf = (function() {
  19642. function get_type(variable) {
  19643. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19644. }
  19645. function str_repeat(input, multiplier) {
  19646. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19647. return output.join('');
  19648. }
  19649. var str_format = function() {
  19650. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19651. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19652. }
  19653. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19654. };
  19655. str_format.format = function(parse_tree, argv) {
  19656. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19657. for (i = 0; i < tree_length; i++) {
  19658. node_type = get_type(parse_tree[i]);
  19659. if (node_type === 'string') {
  19660. output.push(parse_tree[i]);
  19661. }
  19662. else if (node_type === 'array') {
  19663. match = parse_tree[i]; // convenience purposes only
  19664. if (match[2]) { // keyword argument
  19665. arg = argv[cursor];
  19666. for (k = 0; k < match[2].length; k++) {
  19667. if (!arg.hasOwnProperty(match[2][k])) {
  19668. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19669. }
  19670. arg = arg[match[2][k]];
  19671. }
  19672. }
  19673. else if (match[1]) { // positional argument (explicit)
  19674. arg = argv[match[1]];
  19675. }
  19676. else { // positional argument (implicit)
  19677. arg = argv[cursor++];
  19678. }
  19679. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19680. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19681. }
  19682. switch (match[8]) {
  19683. case 'b': arg = arg.toString(2); break;
  19684. case 'c': arg = String.fromCharCode(arg); break;
  19685. case 'd': arg = parseInt(arg, 10); break;
  19686. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19687. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19688. case 'o': arg = arg.toString(8); break;
  19689. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19690. case 'u': arg = Math.abs(arg); break;
  19691. case 'x': arg = arg.toString(16); break;
  19692. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19693. }
  19694. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19695. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19696. pad_length = match[6] - String(arg).length;
  19697. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19698. output.push(match[5] ? arg + pad : pad + arg);
  19699. }
  19700. }
  19701. return output.join('');
  19702. };
  19703. str_format.cache = {};
  19704. str_format.parse = function(fmt) {
  19705. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19706. while (_fmt) {
  19707. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19708. parse_tree.push(match[0]);
  19709. }
  19710. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19711. parse_tree.push('%');
  19712. }
  19713. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19714. if (match[2]) {
  19715. arg_names |= 1;
  19716. var field_list = [], replacement_field = match[2], field_match = [];
  19717. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19718. field_list.push(field_match[1]);
  19719. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19720. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19721. field_list.push(field_match[1]);
  19722. }
  19723. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19724. field_list.push(field_match[1]);
  19725. }
  19726. else {
  19727. throw('[sprintf] huh?');
  19728. }
  19729. }
  19730. }
  19731. else {
  19732. throw('[sprintf] huh?');
  19733. }
  19734. match[2] = field_list;
  19735. }
  19736. else {
  19737. arg_names |= 2;
  19738. }
  19739. if (arg_names === 3) {
  19740. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19741. }
  19742. parse_tree.push(match);
  19743. }
  19744. else {
  19745. throw('[sprintf] huh?');
  19746. }
  19747. _fmt = _fmt.substring(match[0].length);
  19748. }
  19749. return parse_tree;
  19750. };
  19751. return str_format;
  19752. })();
  19753. var vsprintf = function(fmt, argv) {
  19754. argv.unshift(fmt);
  19755. return sprintf.apply(null, argv);
  19756. };
  19757. addPostProcessor("sprintf", function(val, key, opts) {
  19758. if (!opts.sprintf) return val;
  19759. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19760. return vsprintf(val, opts.sprintf);
  19761. } else if (typeof opts.sprintf === 'object') {
  19762. return sprintf(val, opts.sprintf);
  19763. }
  19764. return val;
  19765. });
  19766. // public api interface
  19767. i18n.init = init;
  19768. i18n.setLng = setLng;
  19769. i18n.preload = preload;
  19770. i18n.addResourceBundle = addResourceBundle;
  19771. i18n.hasResourceBundle = hasResourceBundle;
  19772. i18n.addResource = addResource;
  19773. i18n.addResources = addResources;
  19774. i18n.removeResourceBundle = removeResourceBundle;
  19775. i18n.loadNamespace = loadNamespace;
  19776. i18n.loadNamespaces = loadNamespaces;
  19777. i18n.setDefaultNamespace = setDefaultNamespace;
  19778. i18n.t = translate;
  19779. i18n.translate = translate;
  19780. i18n.exists = exists;
  19781. i18n.detectLanguage = f.detectLanguage;
  19782. i18n.pluralExtensions = pluralExtensions;
  19783. i18n.sync = sync;
  19784. i18n.functions = f;
  19785. i18n.lng = lng;
  19786. i18n.addPostProcessor = addPostProcessor;
  19787. i18n.options = o;
  19788. })();
  19789. },{"jquery":"jquery"}],71:[function(require,module,exports){
  19790. /*
  19791. A JavaScript implementation of the SHA family of hashes, as
  19792. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  19793. as defined in FIPS PUB 198a
  19794. Copyright Brian Turek 2008-2013
  19795. Distributed under the BSD License
  19796. See http://caligatio.github.com/jsSHA/ for more information
  19797. Several functions taken from Paul Johnston
  19798. */
  19799. (function(T){function z(a,c,b){var g=0,f=[0],h="",l=null,h=b||"UTF8";if("UTF8"!==h&&"UTF16"!==h)throw"encoding must be UTF8 or UTF16";if("HEX"===c){if(0!==a.length%2)throw"srcString of HEX type must be in byte increments";l=B(a);g=l.binLen;f=l.value}else if("ASCII"===c||"TEXT"===c)l=J(a,h),g=l.binLen,f=l.value;else if("B64"===c)l=K(a),g=l.binLen,f=l.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";this.getHash=function(a,c,b,h){var l=null,d=f.slice(),n=g,p;3===arguments.length?"number"!==
  19800. typeof b&&(h=b,b=1):2===arguments.length&&(b=1);if(b!==parseInt(b,10)||1>b)throw"numRounds must a integer >= 1";switch(c){case "HEX":l=L;break;case "B64":l=M;break;default:throw"format must be HEX or B64";}if("SHA-1"===a)for(p=0;p<b;p++)d=y(d,n),n=160;else if("SHA-224"===a)for(p=0;p<b;p++)d=v(d,n,a),n=224;else if("SHA-256"===a)for(p=0;p<b;p++)d=v(d,n,a),n=256;else if("SHA-384"===a)for(p=0;p<b;p++)d=v(d,n,a),n=384;else if("SHA-512"===a)for(p=0;p<b;p++)d=v(d,n,a),n=512;else throw"Chosen SHA variant is not supported";
  19801. return l(d,N(h))};this.getHMAC=function(a,b,c,l,s){var d,n,p,m,w=[],x=[];d=null;switch(l){case "HEX":l=L;break;case "B64":l=M;break;default:throw"outputFormat must be HEX or B64";}if("SHA-1"===c)n=64,m=160;else if("SHA-224"===c)n=64,m=224;else if("SHA-256"===c)n=64,m=256;else if("SHA-384"===c)n=128,m=384;else if("SHA-512"===c)n=128,m=512;else throw"Chosen SHA variant is not supported";if("HEX"===b)d=B(a),p=d.binLen,d=d.value;else if("ASCII"===b||"TEXT"===b)d=J(a,h),p=d.binLen,d=d.value;else if("B64"===
  19802. b)d=K(a),p=d.binLen,d=d.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";a=8*n;b=n/4-1;n<p/8?(d="SHA-1"===c?y(d,p):v(d,p,c),d[b]&=4294967040):n>p/8&&(d[b]&=4294967040);for(n=0;n<=b;n+=1)w[n]=d[n]^909522486,x[n]=d[n]^1549556828;c="SHA-1"===c?y(x.concat(y(w.concat(f),a+g)),a+m):v(x.concat(v(w.concat(f),a+g,c)),a+m,c);return l(c,N(s))}}function s(a,c){this.a=a;this.b=c}function J(a,c){var b=[],g,f=[],h=0,l;if("UTF8"===c)for(l=0;l<a.length;l+=1)for(g=a.charCodeAt(l),f=[],2048<g?(f[0]=224|
  19803. (g&61440)>>>12,f[1]=128|(g&4032)>>>6,f[2]=128|g&63):128<g?(f[0]=192|(g&1984)>>>6,f[1]=128|g&63):f[0]=g,g=0;g<f.length;g+=1)b[h>>>2]|=f[g]<<24-h%4*8,h+=1;else if("UTF16"===c)for(l=0;l<a.length;l+=1)b[h>>>2]|=a.charCodeAt(l)<<16-h%4*8,h+=2;return{value:b,binLen:8*h}}function B(a){var c=[],b=a.length,g,f;if(0!==b%2)throw"String of HEX type must be in byte increments";for(g=0;g<b;g+=2){f=parseInt(a.substr(g,2),16);if(isNaN(f))throw"String of HEX type contains invalid characters";c[g>>>3]|=f<<24-g%8*4}return{value:c,
  19804. binLen:4*b}}function K(a){var c=[],b=0,g,f,h,l,r;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw"Invalid character in base-64 string";g=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==g&&g<a.length)throw"Invalid '=' found in base-64 string";for(f=0;f<a.length;f+=4){r=a.substr(f,4);for(h=l=0;h<r.length;h+=1)g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(r[h]),l|=g<<18-6*h;for(h=0;h<r.length-1;h+=1)c[b>>2]|=(l>>>16-8*h&255)<<24-b%4*8,b+=1}return{value:c,binLen:8*b}}function L(a,
  19805. c){var b="",g=4*a.length,f,h;for(f=0;f<g;f+=1)h=a[f>>>2]>>>8*(3-f%4),b+="0123456789abcdef".charAt(h>>>4&15)+"0123456789abcdef".charAt(h&15);return c.outputUpper?b.toUpperCase():b}function M(a,c){var b="",g=4*a.length,f,h,l;for(f=0;f<g;f+=3)for(l=(a[f>>>2]>>>8*(3-f%4)&255)<<16|(a[f+1>>>2]>>>8*(3-(f+1)%4)&255)<<8|a[f+2>>>2]>>>8*(3-(f+2)%4)&255,h=0;4>h;h+=1)b=8*f+6*h<=32*a.length?b+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(l>>>6*(3-h)&63):b+c.b64Pad;return b}function N(a){var c=
  19806. {outputUpper:!1,b64Pad:"="};try{a.hasOwnProperty("outputUpper")&&(c.outputUpper=a.outputUpper),a.hasOwnProperty("b64Pad")&&(c.b64Pad=a.b64Pad)}catch(b){}if("boolean"!==typeof c.outputUpper)throw"Invalid outputUpper formatting option";if("string"!==typeof c.b64Pad)throw"Invalid b64Pad formatting option";return c}function U(a,c){return a<<c|a>>>32-c}function u(a,c){return a>>>c|a<<32-c}function t(a,c){var b=null,b=new s(a.a,a.b);return b=32>=c?new s(b.a>>>c|b.b<<32-c&4294967295,b.b>>>c|b.a<<32-c&4294967295):
  19807. new s(b.b>>>c-32|b.a<<64-c&4294967295,b.a>>>c-32|b.b<<64-c&4294967295)}function O(a,c){var b=null;return b=32>=c?new s(a.a>>>c,a.b>>>c|a.a<<32-c&4294967295):new s(0,a.a>>>c-32)}function V(a,c,b){return a^c^b}function P(a,c,b){return a&c^~a&b}function W(a,c,b){return new s(a.a&c.a^~a.a&b.a,a.b&c.b^~a.b&b.b)}function Q(a,c,b){return a&c^a&b^c&b}function X(a,c,b){return new s(a.a&c.a^a.a&b.a^c.a&b.a,a.b&c.b^a.b&b.b^c.b&b.b)}function Y(a){return u(a,2)^u(a,13)^u(a,22)}function Z(a){var c=t(a,28),b=t(a,
  19808. 34);a=t(a,39);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function $(a){return u(a,6)^u(a,11)^u(a,25)}function aa(a){var c=t(a,14),b=t(a,18);a=t(a,41);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function ba(a){return u(a,7)^u(a,18)^a>>>3}function ca(a){var c=t(a,1),b=t(a,8);a=O(a,7);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function da(a){return u(a,17)^u(a,19)^a>>>10}function ea(a){var c=t(a,19),b=t(a,61);a=O(a,6);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function R(a,c){var b=(a&65535)+(c&65535);return((a>>>16)+(c>>>
  19809. 16)+(b>>>16)&65535)<<16|b&65535}function fa(a,c,b,g){var f=(a&65535)+(c&65535)+(b&65535)+(g&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)&65535)<<16|f&65535}function S(a,c,b,g,f){var h=(a&65535)+(c&65535)+(b&65535)+(g&65535)+(f&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)+(h>>>16)&65535)<<16|h&65535}function ga(a,c){var b,g,f;b=(a.b&65535)+(c.b&65535);g=(a.b>>>16)+(c.b>>>16)+(b>>>16);f=(g&65535)<<16|b&65535;b=(a.a&65535)+(c.a&65535)+(g>>>16);g=(a.a>>>16)+(c.a>>>16)+(b>>>
  19810. 16);return new s((g&65535)<<16|b&65535,f)}function ha(a,c,b,g){var f,h,l;f=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535);h=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f>>>16);l=(h&65535)<<16|f&65535;f=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(h>>>16);h=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f>>>16);return new s((h&65535)<<16|f&65535,l)}function ia(a,c,b,g,f){var h,l,r;h=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535)+(f.b&65535);l=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f.b>>>
  19811. 16)+(h>>>16);r=(l&65535)<<16|h&65535;h=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(f.a&65535)+(l>>>16);l=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f.a>>>16)+(h>>>16);return new s((l&65535)<<16|h&65535,r)}function y(a,c){var b=[],g,f,h,l,r,s,u=P,t=V,v=Q,d=U,n=R,p,m,w=S,x,q=[1732584193,4023233417,2562383102,271733878,3285377520];a[c>>>5]|=128<<24-c%32;a[(c+65>>>9<<4)+15]=c;x=a.length;for(p=0;p<x;p+=16){g=q[0];f=q[1];h=q[2];l=q[3];r=q[4];for(m=0;80>m;m+=1)b[m]=16>m?a[m+p]:d(b[m-3]^b[m-8]^b[m-
  19812. 14]^b[m-16],1),s=20>m?w(d(g,5),u(f,h,l),r,1518500249,b[m]):40>m?w(d(g,5),t(f,h,l),r,1859775393,b[m]):60>m?w(d(g,5),v(f,h,l),r,2400959708,b[m]):w(d(g,5),t(f,h,l),r,3395469782,b[m]),r=l,l=h,h=d(f,30),f=g,g=s;q[0]=n(g,q[0]);q[1]=n(f,q[1]);q[2]=n(h,q[2]);q[3]=n(l,q[3]);q[4]=n(r,q[4])}return q}function v(a,c,b){var g,f,h,l,r,t,u,v,z,d,n,p,m,w,x,q,y,C,D,E,F,G,H,I,e,A=[],B,k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,
  19813. 1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,
  19814. 2361852424,2428436474,2756734187,3204031479,3329325298];d=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428];f=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];if("SHA-224"===b||"SHA-256"===b)n=64,g=(c+65>>>9<<4)+15,w=16,x=1,e=Number,q=R,y=fa,C=S,D=ba,E=da,F=Y,G=$,I=Q,H=P,d="SHA-224"===b?d:f;else if("SHA-384"===b||"SHA-512"===b)n=80,g=(c+128>>>10<<5)+31,w=32,x=2,e=s,q=ga,y=ha,C=ia,D=ca,E=ea,F=Z,G=aa,I=X,H=W,k=[new e(k[0],
  19815. 3609767458),new e(k[1],602891725),new e(k[2],3964484399),new e(k[3],2173295548),new e(k[4],4081628472),new e(k[5],3053834265),new e(k[6],2937671579),new e(k[7],3664609560),new e(k[8],2734883394),new e(k[9],1164996542),new e(k[10],1323610764),new e(k[11],3590304994),new e(k[12],4068182383),new e(k[13],991336113),new e(k[14],633803317),new e(k[15],3479774868),new e(k[16],2666613458),new e(k[17],944711139),new e(k[18],2341262773),new e(k[19],2007800933),new e(k[20],1495990901),new e(k[21],1856431235),
  19816. new e(k[22],3175218132),new e(k[23],2198950837),new e(k[24],3999719339),new e(k[25],766784016),new e(k[26],2566594879),new e(k[27],3203337956),new e(k[28],1034457026),new e(k[29],2466948901),new e(k[30],3758326383),new e(k[31],168717936),new e(k[32],1188179964),new e(k[33],1546045734),new e(k[34],1522805485),new e(k[35],2643833823),new e(k[36],2343527390),new e(k[37],1014477480),new e(k[38],1206759142),new e(k[39],344077627),new e(k[40],1290863460),new e(k[41],3158454273),new e(k[42],3505952657),
  19817. new e(k[43],106217008),new e(k[44],3606008344),new e(k[45],1432725776),new e(k[46],1467031594),new e(k[47],851169720),new e(k[48],3100823752),new e(k[49],1363258195),new e(k[50],3750685593),new e(k[51],3785050280),new e(k[52],3318307427),new e(k[53],3812723403),new e(k[54],2003034995),new e(k[55],3602036899),new e(k[56],1575990012),new e(k[57],1125592928),new e(k[58],2716904306),new e(k[59],442776044),new e(k[60],593698344),new e(k[61],3733110249),new e(k[62],2999351573),new e(k[63],3815920427),new e(3391569614,
  19818. 3928383900),new e(3515267271,566280711),new e(3940187606,3454069534),new e(4118630271,4000239992),new e(116418474,1914138554),new e(174292421,2731055270),new e(289380356,3203993006),new e(460393269,320620315),new e(685471733,587496836),new e(852142971,1086792851),new e(1017036298,365543100),new e(1126000580,2618297676),new e(1288033470,3409855158),new e(1501505948,4234509866),new e(1607167915,987167468),new e(1816402316,1246189591)],d="SHA-384"===b?[new e(3418070365,d[0]),new e(1654270250,d[1]),new e(2438529370,
  19819. d[2]),new e(355462360,d[3]),new e(1731405415,d[4]),new e(41048885895,d[5]),new e(3675008525,d[6]),new e(1203062813,d[7])]:[new e(f[0],4089235720),new e(f[1],2227873595),new e(f[2],4271175723),new e(f[3],1595750129),new e(f[4],2917565137),new e(f[5],725511199),new e(f[6],4215389547),new e(f[7],327033209)];else throw"Unexpected error in SHA-2 implementation";a[c>>>5]|=128<<24-c%32;a[g]=c;B=a.length;for(p=0;p<B;p+=w){c=d[0];g=d[1];f=d[2];h=d[3];l=d[4];r=d[5];t=d[6];u=d[7];for(m=0;m<n;m+=1)A[m]=16>m?
  19820. new e(a[m*x+p],a[m*x+p+1]):y(E(A[m-2]),A[m-7],D(A[m-15]),A[m-16]),v=C(u,G(l),H(l,r,t),k[m],A[m]),z=q(F(c),I(c,g,f)),u=t,t=r,r=l,l=q(h,v),h=f,f=g,g=c,c=q(v,z);d[0]=q(c,d[0]);d[1]=q(g,d[1]);d[2]=q(f,d[2]);d[3]=q(h,d[3]);d[4]=q(l,d[4]);d[5]=q(r,d[5]);d[6]=q(t,d[6]);d[7]=q(u,d[7])}if("SHA-224"===b)a=[d[0],d[1],d[2],d[3],d[4],d[5],d[6]];else if("SHA-256"===b)a=d;else if("SHA-384"===b)a=[d[0].a,d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b];else if("SHA-512"===b)a=[d[0].a,
  19821. d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b,d[6].a,d[6].b,d[7].a,d[7].b];else throw"Unexpected error in SHA-2 implementation";return a}"function"===typeof define&&typeof define.amd?define(function(){return z}):"undefined"!==typeof exports?"undefined"!==typeof module&&module.exports?module.exports=exports=z:exports=z:T.jsSHA=z})(this);
  19822. },{}],72:[function(require,module,exports){
  19823. // Top level file is just a mixin of submodules & constants
  19824. 'use strict';
  19825. var assign = require('./lib/utils/common').assign;
  19826. var deflate = require('./lib/deflate');
  19827. var inflate = require('./lib/inflate');
  19828. var constants = require('./lib/zlib/constants');
  19829. var pako = {};
  19830. assign(pako, deflate, inflate, constants);
  19831. module.exports = pako;
  19832. },{"./lib/deflate":73,"./lib/inflate":74,"./lib/utils/common":75,"./lib/zlib/constants":78}],73:[function(require,module,exports){
  19833. 'use strict';
  19834. var zlib_deflate = require('./zlib/deflate.js');
  19835. var utils = require('./utils/common');
  19836. var strings = require('./utils/strings');
  19837. var msg = require('./zlib/messages');
  19838. var zstream = require('./zlib/zstream');
  19839. var toString = Object.prototype.toString;
  19840. /* Public constants ==========================================================*/
  19841. /* ===========================================================================*/
  19842. var Z_NO_FLUSH = 0;
  19843. var Z_FINISH = 4;
  19844. var Z_OK = 0;
  19845. var Z_STREAM_END = 1;
  19846. var Z_SYNC_FLUSH = 2;
  19847. var Z_DEFAULT_COMPRESSION = -1;
  19848. var Z_DEFAULT_STRATEGY = 0;
  19849. var Z_DEFLATED = 8;
  19850. /* ===========================================================================*/
  19851. /**
  19852. * class Deflate
  19853. *
  19854. * Generic JS-style wrapper for zlib calls. If you don't need
  19855. * streaming behaviour - use more simple functions: [[deflate]],
  19856. * [[deflateRaw]] and [[gzip]].
  19857. **/
  19858. /* internal
  19859. * Deflate.chunks -> Array
  19860. *
  19861. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19862. **/
  19863. /**
  19864. * Deflate.result -> Uint8Array|Array
  19865. *
  19866. * Compressed result, generated by default [[Deflate#onData]]
  19867. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19868. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19869. * push a chunk with explicit flush (call [[Deflate#push]] with
  19870. * `Z_SYNC_FLUSH` param).
  19871. **/
  19872. /**
  19873. * Deflate.err -> Number
  19874. *
  19875. * Error code after deflate finished. 0 (Z_OK) on success.
  19876. * You will not need it in real life, because deflate errors
  19877. * are possible only on wrong options or bad `onData` / `onEnd`
  19878. * custom handlers.
  19879. **/
  19880. /**
  19881. * Deflate.msg -> String
  19882. *
  19883. * Error message, if [[Deflate.err]] != 0
  19884. **/
  19885. /**
  19886. * new Deflate(options)
  19887. * - options (Object): zlib deflate options.
  19888. *
  19889. * Creates new deflator instance with specified params. Throws exception
  19890. * on bad params. Supported options:
  19891. *
  19892. * - `level`
  19893. * - `windowBits`
  19894. * - `memLevel`
  19895. * - `strategy`
  19896. *
  19897. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19898. * for more information on these.
  19899. *
  19900. * Additional options, for internal needs:
  19901. *
  19902. * - `chunkSize` - size of generated data chunks (16K by default)
  19903. * - `raw` (Boolean) - do raw deflate
  19904. * - `gzip` (Boolean) - create gzip wrapper
  19905. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19906. * (each char code [0..255])
  19907. * - `header` (Object) - custom header for gzip
  19908. * - `text` (Boolean) - true if compressed data believed to be text
  19909. * - `time` (Number) - modification time, unix timestamp
  19910. * - `os` (Number) - operation system code
  19911. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19912. * - `name` (String) - file name (binary string)
  19913. * - `comment` (String) - comment (binary string)
  19914. * - `hcrc` (Boolean) - true if header crc should be added
  19915. *
  19916. * ##### Example:
  19917. *
  19918. * ```javascript
  19919. * var pako = require('pako')
  19920. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19921. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19922. *
  19923. * var deflate = new pako.Deflate({ level: 3});
  19924. *
  19925. * deflate.push(chunk1, false);
  19926. * deflate.push(chunk2, true); // true -> last chunk
  19927. *
  19928. * if (deflate.err) { throw new Error(deflate.err); }
  19929. *
  19930. * console.log(deflate.result);
  19931. * ```
  19932. **/
  19933. var Deflate = function(options) {
  19934. this.options = utils.assign({
  19935. level: Z_DEFAULT_COMPRESSION,
  19936. method: Z_DEFLATED,
  19937. chunkSize: 16384,
  19938. windowBits: 15,
  19939. memLevel: 8,
  19940. strategy: Z_DEFAULT_STRATEGY,
  19941. to: ''
  19942. }, options || {});
  19943. var opt = this.options;
  19944. if (opt.raw && (opt.windowBits > 0)) {
  19945. opt.windowBits = -opt.windowBits;
  19946. }
  19947. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19948. opt.windowBits += 16;
  19949. }
  19950. this.err = 0; // error code, if happens (0 = Z_OK)
  19951. this.msg = ''; // error message
  19952. this.ended = false; // used to avoid multiple onEnd() calls
  19953. this.chunks = []; // chunks of compressed data
  19954. this.strm = new zstream();
  19955. this.strm.avail_out = 0;
  19956. var status = zlib_deflate.deflateInit2(
  19957. this.strm,
  19958. opt.level,
  19959. opt.method,
  19960. opt.windowBits,
  19961. opt.memLevel,
  19962. opt.strategy
  19963. );
  19964. if (status !== Z_OK) {
  19965. throw new Error(msg[status]);
  19966. }
  19967. if (opt.header) {
  19968. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19969. }
  19970. };
  19971. /**
  19972. * Deflate#push(data[, mode]) -> Boolean
  19973. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19974. * converted to utf8 byte sequence.
  19975. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19976. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19977. *
  19978. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19979. * new compressed chunks. Returns `true` on success. The last data block must have
  19980. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19981. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19982. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19983. *
  19984. * On fail call [[Deflate#onEnd]] with error code and return false.
  19985. *
  19986. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19987. * array format is detected automatically). Also, don't skip last param and always
  19988. * use the same type in your code (boolean or number). That will improve JS speed.
  19989. *
  19990. * For regular `Array`-s make sure all elements are [0..255].
  19991. *
  19992. * ##### Example
  19993. *
  19994. * ```javascript
  19995. * push(chunk, false); // push one of data chunks
  19996. * ...
  19997. * push(chunk, true); // push last chunk
  19998. * ```
  19999. **/
  20000. Deflate.prototype.push = function(data, mode) {
  20001. var strm = this.strm;
  20002. var chunkSize = this.options.chunkSize;
  20003. var status, _mode;
  20004. if (this.ended) { return false; }
  20005. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  20006. // Convert data if needed
  20007. if (typeof data === 'string') {
  20008. // If we need to compress text, change encoding to utf8.
  20009. strm.input = strings.string2buf(data);
  20010. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20011. strm.input = new Uint8Array(data);
  20012. } else {
  20013. strm.input = data;
  20014. }
  20015. strm.next_in = 0;
  20016. strm.avail_in = strm.input.length;
  20017. do {
  20018. if (strm.avail_out === 0) {
  20019. strm.output = new utils.Buf8(chunkSize);
  20020. strm.next_out = 0;
  20021. strm.avail_out = chunkSize;
  20022. }
  20023. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  20024. if (status !== Z_STREAM_END && status !== Z_OK) {
  20025. this.onEnd(status);
  20026. this.ended = true;
  20027. return false;
  20028. }
  20029. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  20030. if (this.options.to === 'string') {
  20031. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  20032. } else {
  20033. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20034. }
  20035. }
  20036. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  20037. // Finalize on the last chunk.
  20038. if (_mode === Z_FINISH) {
  20039. status = zlib_deflate.deflateEnd(this.strm);
  20040. this.onEnd(status);
  20041. this.ended = true;
  20042. return status === Z_OK;
  20043. }
  20044. // callback interim results if Z_SYNC_FLUSH.
  20045. if (_mode === Z_SYNC_FLUSH) {
  20046. this.onEnd(Z_OK);
  20047. strm.avail_out = 0;
  20048. return true;
  20049. }
  20050. return true;
  20051. };
  20052. /**
  20053. * Deflate#onData(chunk) -> Void
  20054. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20055. * on js engine support. When string output requested, each chunk
  20056. * will be string.
  20057. *
  20058. * By default, stores data blocks in `chunks[]` property and glue
  20059. * those in `onEnd`. Override this handler, if you need another behaviour.
  20060. **/
  20061. Deflate.prototype.onData = function(chunk) {
  20062. this.chunks.push(chunk);
  20063. };
  20064. /**
  20065. * Deflate#onEnd(status) -> Void
  20066. * - status (Number): deflate status. 0 (Z_OK) on success,
  20067. * other if not.
  20068. *
  20069. * Called once after you tell deflate that the input stream is
  20070. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20071. * or if an error happened. By default - join collected chunks,
  20072. * free memory and fill `results` / `err` properties.
  20073. **/
  20074. Deflate.prototype.onEnd = function(status) {
  20075. // On success - join
  20076. if (status === Z_OK) {
  20077. if (this.options.to === 'string') {
  20078. this.result = this.chunks.join('');
  20079. } else {
  20080. this.result = utils.flattenChunks(this.chunks);
  20081. }
  20082. }
  20083. this.chunks = [];
  20084. this.err = status;
  20085. this.msg = this.strm.msg;
  20086. };
  20087. /**
  20088. * deflate(data[, options]) -> Uint8Array|Array|String
  20089. * - data (Uint8Array|Array|String): input data to compress.
  20090. * - options (Object): zlib deflate options.
  20091. *
  20092. * Compress `data` with deflate alrorythm and `options`.
  20093. *
  20094. * Supported options are:
  20095. *
  20096. * - level
  20097. * - windowBits
  20098. * - memLevel
  20099. * - strategy
  20100. *
  20101. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20102. * for more information on these.
  20103. *
  20104. * Sugar (options):
  20105. *
  20106. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20107. * negative windowBits implicitly.
  20108. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20109. * (each char code [0..255])
  20110. *
  20111. * ##### Example:
  20112. *
  20113. * ```javascript
  20114. * var pako = require('pako')
  20115. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  20116. *
  20117. * console.log(pako.deflate(data));
  20118. * ```
  20119. **/
  20120. function deflate(input, options) {
  20121. var deflator = new Deflate(options);
  20122. deflator.push(input, true);
  20123. // That will never happens, if you don't cheat with options :)
  20124. if (deflator.err) { throw deflator.msg; }
  20125. return deflator.result;
  20126. }
  20127. /**
  20128. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  20129. * - data (Uint8Array|Array|String): input data to compress.
  20130. * - options (Object): zlib deflate options.
  20131. *
  20132. * The same as [[deflate]], but creates raw data, without wrapper
  20133. * (header and adler32 crc).
  20134. **/
  20135. function deflateRaw(input, options) {
  20136. options = options || {};
  20137. options.raw = true;
  20138. return deflate(input, options);
  20139. }
  20140. /**
  20141. * gzip(data[, options]) -> Uint8Array|Array|String
  20142. * - data (Uint8Array|Array|String): input data to compress.
  20143. * - options (Object): zlib deflate options.
  20144. *
  20145. * The same as [[deflate]], but create gzip wrapper instead of
  20146. * deflate one.
  20147. **/
  20148. function gzip(input, options) {
  20149. options = options || {};
  20150. options.gzip = true;
  20151. return deflate(input, options);
  20152. }
  20153. exports.Deflate = Deflate;
  20154. exports.deflate = deflate;
  20155. exports.deflateRaw = deflateRaw;
  20156. exports.gzip = gzip;
  20157. },{"./utils/common":75,"./utils/strings":76,"./zlib/deflate.js":80,"./zlib/messages":85,"./zlib/zstream":87}],74:[function(require,module,exports){
  20158. 'use strict';
  20159. var zlib_inflate = require('./zlib/inflate.js');
  20160. var utils = require('./utils/common');
  20161. var strings = require('./utils/strings');
  20162. var c = require('./zlib/constants');
  20163. var msg = require('./zlib/messages');
  20164. var zstream = require('./zlib/zstream');
  20165. var gzheader = require('./zlib/gzheader');
  20166. var toString = Object.prototype.toString;
  20167. /**
  20168. * class Inflate
  20169. *
  20170. * Generic JS-style wrapper for zlib calls. If you don't need
  20171. * streaming behaviour - use more simple functions: [[inflate]]
  20172. * and [[inflateRaw]].
  20173. **/
  20174. /* internal
  20175. * inflate.chunks -> Array
  20176. *
  20177. * Chunks of output data, if [[Inflate#onData]] not overriden.
  20178. **/
  20179. /**
  20180. * Inflate.result -> Uint8Array|Array|String
  20181. *
  20182. * Uncompressed result, generated by default [[Inflate#onData]]
  20183. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  20184. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  20185. * push a chunk with explicit flush (call [[Inflate#push]] with
  20186. * `Z_SYNC_FLUSH` param).
  20187. **/
  20188. /**
  20189. * Inflate.err -> Number
  20190. *
  20191. * Error code after inflate finished. 0 (Z_OK) on success.
  20192. * Should be checked if broken data possible.
  20193. **/
  20194. /**
  20195. * Inflate.msg -> String
  20196. *
  20197. * Error message, if [[Inflate.err]] != 0
  20198. **/
  20199. /**
  20200. * new Inflate(options)
  20201. * - options (Object): zlib inflate options.
  20202. *
  20203. * Creates new inflator instance with specified params. Throws exception
  20204. * on bad params. Supported options:
  20205. *
  20206. * - `windowBits`
  20207. *
  20208. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20209. * for more information on these.
  20210. *
  20211. * Additional options, for internal needs:
  20212. *
  20213. * - `chunkSize` - size of generated data chunks (16K by default)
  20214. * - `raw` (Boolean) - do raw inflate
  20215. * - `to` (String) - if equal to 'string', then result will be converted
  20216. * from utf8 to utf16 (javascript) string. When string output requested,
  20217. * chunk length can differ from `chunkSize`, depending on content.
  20218. *
  20219. * By default, when no options set, autodetect deflate/gzip data format via
  20220. * wrapper header.
  20221. *
  20222. * ##### Example:
  20223. *
  20224. * ```javascript
  20225. * var pako = require('pako')
  20226. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20227. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20228. *
  20229. * var inflate = new pako.Inflate({ level: 3});
  20230. *
  20231. * inflate.push(chunk1, false);
  20232. * inflate.push(chunk2, true); // true -> last chunk
  20233. *
  20234. * if (inflate.err) { throw new Error(inflate.err); }
  20235. *
  20236. * console.log(inflate.result);
  20237. * ```
  20238. **/
  20239. var Inflate = function(options) {
  20240. this.options = utils.assign({
  20241. chunkSize: 16384,
  20242. windowBits: 0,
  20243. to: ''
  20244. }, options || {});
  20245. var opt = this.options;
  20246. // Force window size for `raw` data, if not set directly,
  20247. // because we have no header for autodetect.
  20248. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20249. opt.windowBits = -opt.windowBits;
  20250. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20251. }
  20252. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20253. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20254. !(options && options.windowBits)) {
  20255. opt.windowBits += 32;
  20256. }
  20257. // Gzip header has no info about windows size, we can do autodetect only
  20258. // for deflate. So, if window size not set, force it to max when gzip possible
  20259. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20260. // bit 3 (16) -> gzipped data
  20261. // bit 4 (32) -> autodetect gzip/deflate
  20262. if ((opt.windowBits & 15) === 0) {
  20263. opt.windowBits |= 15;
  20264. }
  20265. }
  20266. this.err = 0; // error code, if happens (0 = Z_OK)
  20267. this.msg = ''; // error message
  20268. this.ended = false; // used to avoid multiple onEnd() calls
  20269. this.chunks = []; // chunks of compressed data
  20270. this.strm = new zstream();
  20271. this.strm.avail_out = 0;
  20272. var status = zlib_inflate.inflateInit2(
  20273. this.strm,
  20274. opt.windowBits
  20275. );
  20276. if (status !== c.Z_OK) {
  20277. throw new Error(msg[status]);
  20278. }
  20279. this.header = new gzheader();
  20280. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20281. };
  20282. /**
  20283. * Inflate#push(data[, mode]) -> Boolean
  20284. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20285. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20286. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20287. *
  20288. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20289. * new output chunks. Returns `true` on success. The last data block must have
  20290. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20291. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20292. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20293. *
  20294. * On fail call [[Inflate#onEnd]] with error code and return false.
  20295. *
  20296. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20297. * format is detected automatically). Also, don't skip last param and always
  20298. * use the same type in your code (boolean or number). That will improve JS speed.
  20299. *
  20300. * For regular `Array`-s make sure all elements are [0..255].
  20301. *
  20302. * ##### Example
  20303. *
  20304. * ```javascript
  20305. * push(chunk, false); // push one of data chunks
  20306. * ...
  20307. * push(chunk, true); // push last chunk
  20308. * ```
  20309. **/
  20310. Inflate.prototype.push = function(data, mode) {
  20311. var strm = this.strm;
  20312. var chunkSize = this.options.chunkSize;
  20313. var status, _mode;
  20314. var next_out_utf8, tail, utf8str;
  20315. if (this.ended) { return false; }
  20316. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20317. // Convert data if needed
  20318. if (typeof data === 'string') {
  20319. // Only binary strings can be decompressed on practice
  20320. strm.input = strings.binstring2buf(data);
  20321. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20322. strm.input = new Uint8Array(data);
  20323. } else {
  20324. strm.input = data;
  20325. }
  20326. strm.next_in = 0;
  20327. strm.avail_in = strm.input.length;
  20328. do {
  20329. if (strm.avail_out === 0) {
  20330. strm.output = new utils.Buf8(chunkSize);
  20331. strm.next_out = 0;
  20332. strm.avail_out = chunkSize;
  20333. }
  20334. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20335. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20336. this.onEnd(status);
  20337. this.ended = true;
  20338. return false;
  20339. }
  20340. if (strm.next_out) {
  20341. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20342. if (this.options.to === 'string') {
  20343. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20344. tail = strm.next_out - next_out_utf8;
  20345. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20346. // move tail
  20347. strm.next_out = tail;
  20348. strm.avail_out = chunkSize - tail;
  20349. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20350. this.onData(utf8str);
  20351. } else {
  20352. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20353. }
  20354. }
  20355. }
  20356. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20357. if (status === c.Z_STREAM_END) {
  20358. _mode = c.Z_FINISH;
  20359. }
  20360. // Finalize on the last chunk.
  20361. if (_mode === c.Z_FINISH) {
  20362. status = zlib_inflate.inflateEnd(this.strm);
  20363. this.onEnd(status);
  20364. this.ended = true;
  20365. return status === c.Z_OK;
  20366. }
  20367. // callback interim results if Z_SYNC_FLUSH.
  20368. if (_mode === c.Z_SYNC_FLUSH) {
  20369. this.onEnd(c.Z_OK);
  20370. strm.avail_out = 0;
  20371. return true;
  20372. }
  20373. return true;
  20374. };
  20375. /**
  20376. * Inflate#onData(chunk) -> Void
  20377. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20378. * on js engine support. When string output requested, each chunk
  20379. * will be string.
  20380. *
  20381. * By default, stores data blocks in `chunks[]` property and glue
  20382. * those in `onEnd`. Override this handler, if you need another behaviour.
  20383. **/
  20384. Inflate.prototype.onData = function(chunk) {
  20385. this.chunks.push(chunk);
  20386. };
  20387. /**
  20388. * Inflate#onEnd(status) -> Void
  20389. * - status (Number): inflate status. 0 (Z_OK) on success,
  20390. * other if not.
  20391. *
  20392. * Called either after you tell inflate that the input stream is
  20393. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20394. * or if an error happened. By default - join collected chunks,
  20395. * free memory and fill `results` / `err` properties.
  20396. **/
  20397. Inflate.prototype.onEnd = function(status) {
  20398. // On success - join
  20399. if (status === c.Z_OK) {
  20400. if (this.options.to === 'string') {
  20401. // Glue & convert here, until we teach pako to send
  20402. // utf8 alligned strings to onData
  20403. this.result = this.chunks.join('');
  20404. } else {
  20405. this.result = utils.flattenChunks(this.chunks);
  20406. }
  20407. }
  20408. this.chunks = [];
  20409. this.err = status;
  20410. this.msg = this.strm.msg;
  20411. };
  20412. /**
  20413. * inflate(data[, options]) -> Uint8Array|Array|String
  20414. * - data (Uint8Array|Array|String): input data to decompress.
  20415. * - options (Object): zlib inflate options.
  20416. *
  20417. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20418. * format via wrapper header by default. That's why we don't provide
  20419. * separate `ungzip` method.
  20420. *
  20421. * Supported options are:
  20422. *
  20423. * - windowBits
  20424. *
  20425. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20426. * for more information.
  20427. *
  20428. * Sugar (options):
  20429. *
  20430. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20431. * negative windowBits implicitly.
  20432. * - `to` (String) - if equal to 'string', then result will be converted
  20433. * from utf8 to utf16 (javascript) string. When string output requested,
  20434. * chunk length can differ from `chunkSize`, depending on content.
  20435. *
  20436. *
  20437. * ##### Example:
  20438. *
  20439. * ```javascript
  20440. * var pako = require('pako')
  20441. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20442. * , output;
  20443. *
  20444. * try {
  20445. * output = pako.inflate(input);
  20446. * } catch (err)
  20447. * console.log(err);
  20448. * }
  20449. * ```
  20450. **/
  20451. function inflate(input, options) {
  20452. var inflator = new Inflate(options);
  20453. inflator.push(input, true);
  20454. // That will never happens, if you don't cheat with options :)
  20455. if (inflator.err) { throw inflator.msg; }
  20456. return inflator.result;
  20457. }
  20458. /**
  20459. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20460. * - data (Uint8Array|Array|String): input data to decompress.
  20461. * - options (Object): zlib inflate options.
  20462. *
  20463. * The same as [[inflate]], but creates raw data, without wrapper
  20464. * (header and adler32 crc).
  20465. **/
  20466. function inflateRaw(input, options) {
  20467. options = options || {};
  20468. options.raw = true;
  20469. return inflate(input, options);
  20470. }
  20471. /**
  20472. * ungzip(data[, options]) -> Uint8Array|Array|String
  20473. * - data (Uint8Array|Array|String): input data to decompress.
  20474. * - options (Object): zlib inflate options.
  20475. *
  20476. * Just shortcut to [[inflate]], because it autodetects format
  20477. * by header.content. Done for convenience.
  20478. **/
  20479. exports.Inflate = Inflate;
  20480. exports.inflate = inflate;
  20481. exports.inflateRaw = inflateRaw;
  20482. exports.ungzip = inflate;
  20483. },{"./utils/common":75,"./utils/strings":76,"./zlib/constants":78,"./zlib/gzheader":81,"./zlib/inflate.js":83,"./zlib/messages":85,"./zlib/zstream":87}],75:[function(require,module,exports){
  20484. 'use strict';
  20485. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20486. (typeof Uint16Array !== 'undefined') &&
  20487. (typeof Int32Array !== 'undefined');
  20488. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20489. var sources = Array.prototype.slice.call(arguments, 1);
  20490. while (sources.length) {
  20491. var source = sources.shift();
  20492. if (!source) { continue; }
  20493. if (typeof source !== 'object') {
  20494. throw new TypeError(source + 'must be non-object');
  20495. }
  20496. for (var p in source) {
  20497. if (source.hasOwnProperty(p)) {
  20498. obj[p] = source[p];
  20499. }
  20500. }
  20501. }
  20502. return obj;
  20503. };
  20504. // reduce buffer size, avoiding mem copy
  20505. exports.shrinkBuf = function (buf, size) {
  20506. if (buf.length === size) { return buf; }
  20507. if (buf.subarray) { return buf.subarray(0, size); }
  20508. buf.length = size;
  20509. return buf;
  20510. };
  20511. var fnTyped = {
  20512. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20513. if (src.subarray && dest.subarray) {
  20514. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20515. return;
  20516. }
  20517. // Fallback to ordinary array
  20518. for (var i=0; i<len; i++) {
  20519. dest[dest_offs + i] = src[src_offs + i];
  20520. }
  20521. },
  20522. // Join array of chunks to single array.
  20523. flattenChunks: function(chunks) {
  20524. var i, l, len, pos, chunk, result;
  20525. // calculate data length
  20526. len = 0;
  20527. for (i=0, l=chunks.length; i<l; i++) {
  20528. len += chunks[i].length;
  20529. }
  20530. // join chunks
  20531. result = new Uint8Array(len);
  20532. pos = 0;
  20533. for (i=0, l=chunks.length; i<l; i++) {
  20534. chunk = chunks[i];
  20535. result.set(chunk, pos);
  20536. pos += chunk.length;
  20537. }
  20538. return result;
  20539. }
  20540. };
  20541. var fnUntyped = {
  20542. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20543. for (var i=0; i<len; i++) {
  20544. dest[dest_offs + i] = src[src_offs + i];
  20545. }
  20546. },
  20547. // Join array of chunks to single array.
  20548. flattenChunks: function(chunks) {
  20549. return [].concat.apply([], chunks);
  20550. }
  20551. };
  20552. // Enable/Disable typed arrays use, for testing
  20553. //
  20554. exports.setTyped = function (on) {
  20555. if (on) {
  20556. exports.Buf8 = Uint8Array;
  20557. exports.Buf16 = Uint16Array;
  20558. exports.Buf32 = Int32Array;
  20559. exports.assign(exports, fnTyped);
  20560. } else {
  20561. exports.Buf8 = Array;
  20562. exports.Buf16 = Array;
  20563. exports.Buf32 = Array;
  20564. exports.assign(exports, fnUntyped);
  20565. }
  20566. };
  20567. exports.setTyped(TYPED_OK);
  20568. },{}],76:[function(require,module,exports){
  20569. // String encode/decode helpers
  20570. 'use strict';
  20571. var utils = require('./common');
  20572. // Quick check if we can use fast array to bin string conversion
  20573. //
  20574. // - apply(Array) can fail on Android 2.2
  20575. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20576. //
  20577. var STR_APPLY_OK = true;
  20578. var STR_APPLY_UIA_OK = true;
  20579. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20580. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20581. // Table with utf8 lengths (calculated by first byte of sequence)
  20582. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20583. // because max possible codepoint is 0x10ffff
  20584. var _utf8len = new utils.Buf8(256);
  20585. for (var q=0; q<256; q++) {
  20586. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20587. }
  20588. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20589. // convert string to array (typed, when possible)
  20590. exports.string2buf = function (str) {
  20591. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20592. // count binary size
  20593. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20594. c = str.charCodeAt(m_pos);
  20595. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20596. c2 = str.charCodeAt(m_pos+1);
  20597. if ((c2 & 0xfc00) === 0xdc00) {
  20598. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20599. m_pos++;
  20600. }
  20601. }
  20602. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20603. }
  20604. // allocate buffer
  20605. buf = new utils.Buf8(buf_len);
  20606. // convert
  20607. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20608. c = str.charCodeAt(m_pos);
  20609. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20610. c2 = str.charCodeAt(m_pos+1);
  20611. if ((c2 & 0xfc00) === 0xdc00) {
  20612. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20613. m_pos++;
  20614. }
  20615. }
  20616. if (c < 0x80) {
  20617. /* one byte */
  20618. buf[i++] = c;
  20619. } else if (c < 0x800) {
  20620. /* two bytes */
  20621. buf[i++] = 0xC0 | (c >>> 6);
  20622. buf[i++] = 0x80 | (c & 0x3f);
  20623. } else if (c < 0x10000) {
  20624. /* three bytes */
  20625. buf[i++] = 0xE0 | (c >>> 12);
  20626. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20627. buf[i++] = 0x80 | (c & 0x3f);
  20628. } else {
  20629. /* four bytes */
  20630. buf[i++] = 0xf0 | (c >>> 18);
  20631. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20632. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20633. buf[i++] = 0x80 | (c & 0x3f);
  20634. }
  20635. }
  20636. return buf;
  20637. };
  20638. // Helper (used in 2 places)
  20639. function buf2binstring(buf, len) {
  20640. // use fallback for big arrays to avoid stack overflow
  20641. if (len < 65537) {
  20642. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20643. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20644. }
  20645. }
  20646. var result = '';
  20647. for (var i=0; i < len; i++) {
  20648. result += String.fromCharCode(buf[i]);
  20649. }
  20650. return result;
  20651. }
  20652. // Convert byte array to binary string
  20653. exports.buf2binstring = function(buf) {
  20654. return buf2binstring(buf, buf.length);
  20655. };
  20656. // Convert binary string (typed, when possible)
  20657. exports.binstring2buf = function(str) {
  20658. var buf = new utils.Buf8(str.length);
  20659. for (var i=0, len=buf.length; i < len; i++) {
  20660. buf[i] = str.charCodeAt(i);
  20661. }
  20662. return buf;
  20663. };
  20664. // convert array to string
  20665. exports.buf2string = function (buf, max) {
  20666. var i, out, c, c_len;
  20667. var len = max || buf.length;
  20668. // Reserve max possible length (2 words per char)
  20669. // NB: by unknown reasons, Array is significantly faster for
  20670. // String.fromCharCode.apply than Uint16Array.
  20671. var utf16buf = new Array(len*2);
  20672. for (out=0, i=0; i<len;) {
  20673. c = buf[i++];
  20674. // quick process ascii
  20675. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20676. c_len = _utf8len[c];
  20677. // skip 5 & 6 byte codes
  20678. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20679. // apply mask on first byte
  20680. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20681. // join the rest
  20682. while (c_len > 1 && i < len) {
  20683. c = (c << 6) | (buf[i++] & 0x3f);
  20684. c_len--;
  20685. }
  20686. // terminated by end of string?
  20687. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20688. if (c < 0x10000) {
  20689. utf16buf[out++] = c;
  20690. } else {
  20691. c -= 0x10000;
  20692. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20693. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20694. }
  20695. }
  20696. return buf2binstring(utf16buf, out);
  20697. };
  20698. // Calculate max possible position in utf8 buffer,
  20699. // that will not break sequence. If that's not possible
  20700. // - (very small limits) return max size as is.
  20701. //
  20702. // buf[] - utf8 bytes array
  20703. // max - length limit (mandatory);
  20704. exports.utf8border = function(buf, max) {
  20705. var pos;
  20706. max = max || buf.length;
  20707. if (max > buf.length) { max = buf.length; }
  20708. // go back from last position, until start of sequence found
  20709. pos = max-1;
  20710. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20711. // Fuckup - very small and broken sequence,
  20712. // return max, because we should return something anyway.
  20713. if (pos < 0) { return max; }
  20714. // If we came to start of buffer - that means vuffer is too small,
  20715. // return max too.
  20716. if (pos === 0) { return max; }
  20717. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20718. };
  20719. },{"./common":75}],77:[function(require,module,exports){
  20720. 'use strict';
  20721. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20722. // It doesn't worth to make additional optimizationa as in original.
  20723. // Small size is preferable.
  20724. function adler32(adler, buf, len, pos) {
  20725. var s1 = (adler & 0xffff) |0,
  20726. s2 = ((adler >>> 16) & 0xffff) |0,
  20727. n = 0;
  20728. while (len !== 0) {
  20729. // Set limit ~ twice less than 5552, to keep
  20730. // s2 in 31-bits, because we force signed ints.
  20731. // in other case %= will fail.
  20732. n = len > 2000 ? 2000 : len;
  20733. len -= n;
  20734. do {
  20735. s1 = (s1 + buf[pos++]) |0;
  20736. s2 = (s2 + s1) |0;
  20737. } while (--n);
  20738. s1 %= 65521;
  20739. s2 %= 65521;
  20740. }
  20741. return (s1 | (s2 << 16)) |0;
  20742. }
  20743. module.exports = adler32;
  20744. },{}],78:[function(require,module,exports){
  20745. module.exports = {
  20746. /* Allowed flush values; see deflate() and inflate() below for details */
  20747. Z_NO_FLUSH: 0,
  20748. Z_PARTIAL_FLUSH: 1,
  20749. Z_SYNC_FLUSH: 2,
  20750. Z_FULL_FLUSH: 3,
  20751. Z_FINISH: 4,
  20752. Z_BLOCK: 5,
  20753. Z_TREES: 6,
  20754. /* Return codes for the compression/decompression functions. Negative values
  20755. * are errors, positive values are used for special but normal events.
  20756. */
  20757. Z_OK: 0,
  20758. Z_STREAM_END: 1,
  20759. Z_NEED_DICT: 2,
  20760. Z_ERRNO: -1,
  20761. Z_STREAM_ERROR: -2,
  20762. Z_DATA_ERROR: -3,
  20763. //Z_MEM_ERROR: -4,
  20764. Z_BUF_ERROR: -5,
  20765. //Z_VERSION_ERROR: -6,
  20766. /* compression levels */
  20767. Z_NO_COMPRESSION: 0,
  20768. Z_BEST_SPEED: 1,
  20769. Z_BEST_COMPRESSION: 9,
  20770. Z_DEFAULT_COMPRESSION: -1,
  20771. Z_FILTERED: 1,
  20772. Z_HUFFMAN_ONLY: 2,
  20773. Z_RLE: 3,
  20774. Z_FIXED: 4,
  20775. Z_DEFAULT_STRATEGY: 0,
  20776. /* Possible values of the data_type field (though see inflate()) */
  20777. Z_BINARY: 0,
  20778. Z_TEXT: 1,
  20779. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20780. Z_UNKNOWN: 2,
  20781. /* The deflate compression method */
  20782. Z_DEFLATED: 8
  20783. //Z_NULL: null // Use -1 or null inline, depending on var type
  20784. };
  20785. },{}],79:[function(require,module,exports){
  20786. 'use strict';
  20787. // Note: we can't get significant speed boost here.
  20788. // So write code to minimize size - no pregenerated tables
  20789. // and array tools dependencies.
  20790. // Use ordinary array, since untyped makes no boost here
  20791. function makeTable() {
  20792. var c, table = [];
  20793. for (var n =0; n < 256; n++) {
  20794. c = n;
  20795. for (var k =0; k < 8; k++) {
  20796. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20797. }
  20798. table[n] = c;
  20799. }
  20800. return table;
  20801. }
  20802. // Create table on load. Just 255 signed longs. Not a problem.
  20803. var crcTable = makeTable();
  20804. function crc32(crc, buf, len, pos) {
  20805. var t = crcTable,
  20806. end = pos + len;
  20807. crc = crc ^ (-1);
  20808. for (var i = pos; i < end; i++) {
  20809. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20810. }
  20811. return (crc ^ (-1)); // >>> 0;
  20812. }
  20813. module.exports = crc32;
  20814. },{}],80:[function(require,module,exports){
  20815. 'use strict';
  20816. var utils = require('../utils/common');
  20817. var trees = require('./trees');
  20818. var adler32 = require('./adler32');
  20819. var crc32 = require('./crc32');
  20820. var msg = require('./messages');
  20821. /* Public constants ==========================================================*/
  20822. /* ===========================================================================*/
  20823. /* Allowed flush values; see deflate() and inflate() below for details */
  20824. var Z_NO_FLUSH = 0;
  20825. var Z_PARTIAL_FLUSH = 1;
  20826. //var Z_SYNC_FLUSH = 2;
  20827. var Z_FULL_FLUSH = 3;
  20828. var Z_FINISH = 4;
  20829. var Z_BLOCK = 5;
  20830. //var Z_TREES = 6;
  20831. /* Return codes for the compression/decompression functions. Negative values
  20832. * are errors, positive values are used for special but normal events.
  20833. */
  20834. var Z_OK = 0;
  20835. var Z_STREAM_END = 1;
  20836. //var Z_NEED_DICT = 2;
  20837. //var Z_ERRNO = -1;
  20838. var Z_STREAM_ERROR = -2;
  20839. var Z_DATA_ERROR = -3;
  20840. //var Z_MEM_ERROR = -4;
  20841. var Z_BUF_ERROR = -5;
  20842. //var Z_VERSION_ERROR = -6;
  20843. /* compression levels */
  20844. //var Z_NO_COMPRESSION = 0;
  20845. //var Z_BEST_SPEED = 1;
  20846. //var Z_BEST_COMPRESSION = 9;
  20847. var Z_DEFAULT_COMPRESSION = -1;
  20848. var Z_FILTERED = 1;
  20849. var Z_HUFFMAN_ONLY = 2;
  20850. var Z_RLE = 3;
  20851. var Z_FIXED = 4;
  20852. var Z_DEFAULT_STRATEGY = 0;
  20853. /* Possible values of the data_type field (though see inflate()) */
  20854. //var Z_BINARY = 0;
  20855. //var Z_TEXT = 1;
  20856. //var Z_ASCII = 1; // = Z_TEXT
  20857. var Z_UNKNOWN = 2;
  20858. /* The deflate compression method */
  20859. var Z_DEFLATED = 8;
  20860. /*============================================================================*/
  20861. var MAX_MEM_LEVEL = 9;
  20862. /* Maximum value for memLevel in deflateInit2 */
  20863. var MAX_WBITS = 15;
  20864. /* 32K LZ77 window */
  20865. var DEF_MEM_LEVEL = 8;
  20866. var LENGTH_CODES = 29;
  20867. /* number of length codes, not counting the special END_BLOCK code */
  20868. var LITERALS = 256;
  20869. /* number of literal bytes 0..255 */
  20870. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20871. /* number of Literal or Length codes, including the END_BLOCK code */
  20872. var D_CODES = 30;
  20873. /* number of distance codes */
  20874. var BL_CODES = 19;
  20875. /* number of codes used to transfer the bit lengths */
  20876. var HEAP_SIZE = 2*L_CODES + 1;
  20877. /* maximum heap size */
  20878. var MAX_BITS = 15;
  20879. /* All codes must not exceed MAX_BITS bits */
  20880. var MIN_MATCH = 3;
  20881. var MAX_MATCH = 258;
  20882. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20883. var PRESET_DICT = 0x20;
  20884. var INIT_STATE = 42;
  20885. var EXTRA_STATE = 69;
  20886. var NAME_STATE = 73;
  20887. var COMMENT_STATE = 91;
  20888. var HCRC_STATE = 103;
  20889. var BUSY_STATE = 113;
  20890. var FINISH_STATE = 666;
  20891. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20892. var BS_BLOCK_DONE = 2; /* block flush performed */
  20893. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20894. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20895. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20896. function err(strm, errorCode) {
  20897. strm.msg = msg[errorCode];
  20898. return errorCode;
  20899. }
  20900. function rank(f) {
  20901. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20902. }
  20903. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20904. /* =========================================================================
  20905. * Flush as much pending output as possible. All deflate() output goes
  20906. * through this function so some applications may wish to modify it
  20907. * to avoid allocating a large strm->output buffer and copying into it.
  20908. * (See also read_buf()).
  20909. */
  20910. function flush_pending(strm) {
  20911. var s = strm.state;
  20912. //_tr_flush_bits(s);
  20913. var len = s.pending;
  20914. if (len > strm.avail_out) {
  20915. len = strm.avail_out;
  20916. }
  20917. if (len === 0) { return; }
  20918. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20919. strm.next_out += len;
  20920. s.pending_out += len;
  20921. strm.total_out += len;
  20922. strm.avail_out -= len;
  20923. s.pending -= len;
  20924. if (s.pending === 0) {
  20925. s.pending_out = 0;
  20926. }
  20927. }
  20928. function flush_block_only (s, last) {
  20929. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20930. s.block_start = s.strstart;
  20931. flush_pending(s.strm);
  20932. }
  20933. function put_byte(s, b) {
  20934. s.pending_buf[s.pending++] = b;
  20935. }
  20936. /* =========================================================================
  20937. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20938. * IN assertion: the stream state is correct and there is enough room in
  20939. * pending_buf.
  20940. */
  20941. function putShortMSB(s, b) {
  20942. // put_byte(s, (Byte)(b >> 8));
  20943. // put_byte(s, (Byte)(b & 0xff));
  20944. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20945. s.pending_buf[s.pending++] = b & 0xff;
  20946. }
  20947. /* ===========================================================================
  20948. * Read a new buffer from the current input stream, update the adler32
  20949. * and total number of bytes read. All deflate() input goes through
  20950. * this function so some applications may wish to modify it to avoid
  20951. * allocating a large strm->input buffer and copying from it.
  20952. * (See also flush_pending()).
  20953. */
  20954. function read_buf(strm, buf, start, size) {
  20955. var len = strm.avail_in;
  20956. if (len > size) { len = size; }
  20957. if (len === 0) { return 0; }
  20958. strm.avail_in -= len;
  20959. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20960. if (strm.state.wrap === 1) {
  20961. strm.adler = adler32(strm.adler, buf, len, start);
  20962. }
  20963. else if (strm.state.wrap === 2) {
  20964. strm.adler = crc32(strm.adler, buf, len, start);
  20965. }
  20966. strm.next_in += len;
  20967. strm.total_in += len;
  20968. return len;
  20969. }
  20970. /* ===========================================================================
  20971. * Set match_start to the longest match starting at the given string and
  20972. * return its length. Matches shorter or equal to prev_length are discarded,
  20973. * in which case the result is equal to prev_length and match_start is
  20974. * garbage.
  20975. * IN assertions: cur_match is the head of the hash chain for the current
  20976. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20977. * OUT assertion: the match length is not greater than s->lookahead.
  20978. */
  20979. function longest_match(s, cur_match) {
  20980. var chain_length = s.max_chain_length; /* max hash chain length */
  20981. var scan = s.strstart; /* current string */
  20982. var match; /* matched string */
  20983. var len; /* length of current match */
  20984. var best_len = s.prev_length; /* best match length so far */
  20985. var nice_match = s.nice_match; /* stop if match long enough */
  20986. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20987. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20988. var _win = s.window; // shortcut
  20989. var wmask = s.w_mask;
  20990. var prev = s.prev;
  20991. /* Stop when cur_match becomes <= limit. To simplify the code,
  20992. * we prevent matches with the string of window index 0.
  20993. */
  20994. var strend = s.strstart + MAX_MATCH;
  20995. var scan_end1 = _win[scan + best_len - 1];
  20996. var scan_end = _win[scan + best_len];
  20997. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20998. * It is easy to get rid of this optimization if necessary.
  20999. */
  21000. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  21001. /* Do not waste too much time if we already have a good match: */
  21002. if (s.prev_length >= s.good_match) {
  21003. chain_length >>= 2;
  21004. }
  21005. /* Do not look for matches beyond the end of the input. This is necessary
  21006. * to make deflate deterministic.
  21007. */
  21008. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  21009. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  21010. do {
  21011. // Assert(cur_match < s->strstart, "no future");
  21012. match = cur_match;
  21013. /* Skip to next match if the match length cannot increase
  21014. * or if the match length is less than 2. Note that the checks below
  21015. * for insufficient lookahead only occur occasionally for performance
  21016. * reasons. Therefore uninitialized memory will be accessed, and
  21017. * conditional jumps will be made that depend on those values.
  21018. * However the length of the match is limited to the lookahead, so
  21019. * the output of deflate is not affected by the uninitialized values.
  21020. */
  21021. if (_win[match + best_len] !== scan_end ||
  21022. _win[match + best_len - 1] !== scan_end1 ||
  21023. _win[match] !== _win[scan] ||
  21024. _win[++match] !== _win[scan + 1]) {
  21025. continue;
  21026. }
  21027. /* The check at best_len-1 can be removed because it will be made
  21028. * again later. (This heuristic is not always a win.)
  21029. * It is not necessary to compare scan[2] and match[2] since they
  21030. * are always equal when the other bytes match, given that
  21031. * the hash keys are equal and that HASH_BITS >= 8.
  21032. */
  21033. scan += 2;
  21034. match++;
  21035. // Assert(*scan == *match, "match[2]?");
  21036. /* We check for insufficient lookahead only every 8th comparison;
  21037. * the 256th check will be made at strstart+258.
  21038. */
  21039. do {
  21040. /*jshint noempty:false*/
  21041. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21042. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21043. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21044. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21045. scan < strend);
  21046. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  21047. len = MAX_MATCH - (strend - scan);
  21048. scan = strend - MAX_MATCH;
  21049. if (len > best_len) {
  21050. s.match_start = cur_match;
  21051. best_len = len;
  21052. if (len >= nice_match) {
  21053. break;
  21054. }
  21055. scan_end1 = _win[scan + best_len - 1];
  21056. scan_end = _win[scan + best_len];
  21057. }
  21058. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  21059. if (best_len <= s.lookahead) {
  21060. return best_len;
  21061. }
  21062. return s.lookahead;
  21063. }
  21064. /* ===========================================================================
  21065. * Fill the window when the lookahead becomes insufficient.
  21066. * Updates strstart and lookahead.
  21067. *
  21068. * IN assertion: lookahead < MIN_LOOKAHEAD
  21069. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  21070. * At least one byte has been read, or avail_in == 0; reads are
  21071. * performed for at least two bytes (required for the zip translate_eol
  21072. * option -- not supported here).
  21073. */
  21074. function fill_window(s) {
  21075. var _w_size = s.w_size;
  21076. var p, n, m, more, str;
  21077. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  21078. do {
  21079. more = s.window_size - s.lookahead - s.strstart;
  21080. // JS ints have 32 bit, block below not needed
  21081. /* Deal with !@#$% 64K limit: */
  21082. //if (sizeof(int) <= 2) {
  21083. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  21084. // more = wsize;
  21085. //
  21086. // } else if (more == (unsigned)(-1)) {
  21087. // /* Very unlikely, but possible on 16 bit machine if
  21088. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  21089. // */
  21090. // more--;
  21091. // }
  21092. //}
  21093. /* If the window is almost full and there is insufficient lookahead,
  21094. * move the upper half to the lower one to make room in the upper half.
  21095. */
  21096. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  21097. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  21098. s.match_start -= _w_size;
  21099. s.strstart -= _w_size;
  21100. /* we now have strstart >= MAX_DIST */
  21101. s.block_start -= _w_size;
  21102. /* Slide the hash table (could be avoided with 32 bit values
  21103. at the expense of memory usage). We slide even when level == 0
  21104. to keep the hash table consistent if we switch back to level > 0
  21105. later. (Using level 0 permanently is not an optimal usage of
  21106. zlib, so we don't care about this pathological case.)
  21107. */
  21108. n = s.hash_size;
  21109. p = n;
  21110. do {
  21111. m = s.head[--p];
  21112. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  21113. } while (--n);
  21114. n = _w_size;
  21115. p = n;
  21116. do {
  21117. m = s.prev[--p];
  21118. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  21119. /* If n is not on any hash chain, prev[n] is garbage but
  21120. * its value will never be used.
  21121. */
  21122. } while (--n);
  21123. more += _w_size;
  21124. }
  21125. if (s.strm.avail_in === 0) {
  21126. break;
  21127. }
  21128. /* If there was no sliding:
  21129. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  21130. * more == window_size - lookahead - strstart
  21131. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  21132. * => more >= window_size - 2*WSIZE + 2
  21133. * In the BIG_MEM or MMAP case (not yet supported),
  21134. * window_size == input_size + MIN_LOOKAHEAD &&
  21135. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  21136. * Otherwise, window_size == 2*WSIZE so more >= 2.
  21137. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  21138. */
  21139. //Assert(more >= 2, "more < 2");
  21140. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  21141. s.lookahead += n;
  21142. /* Initialize the hash value now that we have some input: */
  21143. if (s.lookahead + s.insert >= MIN_MATCH) {
  21144. str = s.strstart - s.insert;
  21145. s.ins_h = s.window[str];
  21146. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  21147. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  21148. //#if MIN_MATCH != 3
  21149. // Call update_hash() MIN_MATCH-3 more times
  21150. //#endif
  21151. while (s.insert) {
  21152. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21153. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  21154. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21155. s.head[s.ins_h] = str;
  21156. str++;
  21157. s.insert--;
  21158. if (s.lookahead + s.insert < MIN_MATCH) {
  21159. break;
  21160. }
  21161. }
  21162. }
  21163. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  21164. * but this is not important since only literal bytes will be emitted.
  21165. */
  21166. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  21167. /* If the WIN_INIT bytes after the end of the current data have never been
  21168. * written, then zero those bytes in order to avoid memory check reports of
  21169. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  21170. * the longest match routines. Update the high water mark for the next
  21171. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  21172. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  21173. */
  21174. // if (s.high_water < s.window_size) {
  21175. // var curr = s.strstart + s.lookahead;
  21176. // var init = 0;
  21177. //
  21178. // if (s.high_water < curr) {
  21179. // /* Previous high water mark below current data -- zero WIN_INIT
  21180. // * bytes or up to end of window, whichever is less.
  21181. // */
  21182. // init = s.window_size - curr;
  21183. // if (init > WIN_INIT)
  21184. // init = WIN_INIT;
  21185. // zmemzero(s->window + curr, (unsigned)init);
  21186. // s->high_water = curr + init;
  21187. // }
  21188. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  21189. // /* High water mark at or above current data, but below current data
  21190. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  21191. // * to end of window, whichever is less.
  21192. // */
  21193. // init = (ulg)curr + WIN_INIT - s->high_water;
  21194. // if (init > s->window_size - s->high_water)
  21195. // init = s->window_size - s->high_water;
  21196. // zmemzero(s->window + s->high_water, (unsigned)init);
  21197. // s->high_water += init;
  21198. // }
  21199. // }
  21200. //
  21201. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  21202. // "not enough room for search");
  21203. }
  21204. /* ===========================================================================
  21205. * Copy without compression as much as possible from the input stream, return
  21206. * the current block state.
  21207. * This function does not insert new strings in the dictionary since
  21208. * uncompressible data is probably not useful. This function is used
  21209. * only for the level=0 compression option.
  21210. * NOTE: this function should be optimized to avoid extra copying from
  21211. * window to pending_buf.
  21212. */
  21213. function deflate_stored(s, flush) {
  21214. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  21215. * to pending_buf_size, and each stored block has a 5 byte header:
  21216. */
  21217. var max_block_size = 0xffff;
  21218. if (max_block_size > s.pending_buf_size - 5) {
  21219. max_block_size = s.pending_buf_size - 5;
  21220. }
  21221. /* Copy as much as possible from input to output: */
  21222. for (;;) {
  21223. /* Fill the window as much as possible: */
  21224. if (s.lookahead <= 1) {
  21225. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  21226. // s->block_start >= (long)s->w_size, "slide too late");
  21227. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21228. // s.block_start >= s.w_size)) {
  21229. // throw new Error("slide too late");
  21230. // }
  21231. fill_window(s);
  21232. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21233. return BS_NEED_MORE;
  21234. }
  21235. if (s.lookahead === 0) {
  21236. break;
  21237. }
  21238. /* flush the current block */
  21239. }
  21240. //Assert(s->block_start >= 0L, "block gone");
  21241. // if (s.block_start < 0) throw new Error("block gone");
  21242. s.strstart += s.lookahead;
  21243. s.lookahead = 0;
  21244. /* Emit a stored block if pending_buf will be full: */
  21245. var max_start = s.block_start + max_block_size;
  21246. if (s.strstart === 0 || s.strstart >= max_start) {
  21247. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21248. s.lookahead = s.strstart - max_start;
  21249. s.strstart = max_start;
  21250. /*** FLUSH_BLOCK(s, 0); ***/
  21251. flush_block_only(s, false);
  21252. if (s.strm.avail_out === 0) {
  21253. return BS_NEED_MORE;
  21254. }
  21255. /***/
  21256. }
  21257. /* Flush if we may have to slide, otherwise block_start may become
  21258. * negative and the data will be gone:
  21259. */
  21260. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21261. /*** FLUSH_BLOCK(s, 0); ***/
  21262. flush_block_only(s, false);
  21263. if (s.strm.avail_out === 0) {
  21264. return BS_NEED_MORE;
  21265. }
  21266. /***/
  21267. }
  21268. }
  21269. s.insert = 0;
  21270. if (flush === Z_FINISH) {
  21271. /*** FLUSH_BLOCK(s, 1); ***/
  21272. flush_block_only(s, true);
  21273. if (s.strm.avail_out === 0) {
  21274. return BS_FINISH_STARTED;
  21275. }
  21276. /***/
  21277. return BS_FINISH_DONE;
  21278. }
  21279. if (s.strstart > s.block_start) {
  21280. /*** FLUSH_BLOCK(s, 0); ***/
  21281. flush_block_only(s, false);
  21282. if (s.strm.avail_out === 0) {
  21283. return BS_NEED_MORE;
  21284. }
  21285. /***/
  21286. }
  21287. return BS_NEED_MORE;
  21288. }
  21289. /* ===========================================================================
  21290. * Compress as much as possible from the input stream, return the current
  21291. * block state.
  21292. * This function does not perform lazy evaluation of matches and inserts
  21293. * new strings in the dictionary only for unmatched strings or for short
  21294. * matches. It is used only for the fast compression options.
  21295. */
  21296. function deflate_fast(s, flush) {
  21297. var hash_head; /* head of the hash chain */
  21298. var bflush; /* set if current block must be flushed */
  21299. for (;;) {
  21300. /* Make sure that we always have enough lookahead, except
  21301. * at the end of the input file. We need MAX_MATCH bytes
  21302. * for the next match, plus MIN_MATCH bytes to insert the
  21303. * string following the next match.
  21304. */
  21305. if (s.lookahead < MIN_LOOKAHEAD) {
  21306. fill_window(s);
  21307. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21308. return BS_NEED_MORE;
  21309. }
  21310. if (s.lookahead === 0) {
  21311. break; /* flush the current block */
  21312. }
  21313. }
  21314. /* Insert the string window[strstart .. strstart+2] in the
  21315. * dictionary, and set hash_head to the head of the hash chain:
  21316. */
  21317. hash_head = 0/*NIL*/;
  21318. if (s.lookahead >= MIN_MATCH) {
  21319. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21320. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21321. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21322. s.head[s.ins_h] = s.strstart;
  21323. /***/
  21324. }
  21325. /* Find the longest match, discarding those <= prev_length.
  21326. * At this point we have always match_length < MIN_MATCH
  21327. */
  21328. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21329. /* To simplify the code, we prevent matches with the string
  21330. * of window index 0 (in particular we have to avoid a match
  21331. * of the string with itself at the start of the input file).
  21332. */
  21333. s.match_length = longest_match(s, hash_head);
  21334. /* longest_match() sets match_start */
  21335. }
  21336. if (s.match_length >= MIN_MATCH) {
  21337. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21338. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21339. s.match_length - MIN_MATCH, bflush); ***/
  21340. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21341. s.lookahead -= s.match_length;
  21342. /* Insert new strings in the hash table only if the match length
  21343. * is not too large. This saves time but degrades compression.
  21344. */
  21345. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21346. s.match_length--; /* string at strstart already in table */
  21347. do {
  21348. s.strstart++;
  21349. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21350. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21351. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21352. s.head[s.ins_h] = s.strstart;
  21353. /***/
  21354. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21355. * always MIN_MATCH bytes ahead.
  21356. */
  21357. } while (--s.match_length !== 0);
  21358. s.strstart++;
  21359. } else
  21360. {
  21361. s.strstart += s.match_length;
  21362. s.match_length = 0;
  21363. s.ins_h = s.window[s.strstart];
  21364. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21365. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21366. //#if MIN_MATCH != 3
  21367. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21368. //#endif
  21369. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21370. * matter since it will be recomputed at next deflate call.
  21371. */
  21372. }
  21373. } else {
  21374. /* No match, output a literal byte */
  21375. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21376. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21377. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21378. s.lookahead--;
  21379. s.strstart++;
  21380. }
  21381. if (bflush) {
  21382. /*** FLUSH_BLOCK(s, 0); ***/
  21383. flush_block_only(s, false);
  21384. if (s.strm.avail_out === 0) {
  21385. return BS_NEED_MORE;
  21386. }
  21387. /***/
  21388. }
  21389. }
  21390. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21391. if (flush === Z_FINISH) {
  21392. /*** FLUSH_BLOCK(s, 1); ***/
  21393. flush_block_only(s, true);
  21394. if (s.strm.avail_out === 0) {
  21395. return BS_FINISH_STARTED;
  21396. }
  21397. /***/
  21398. return BS_FINISH_DONE;
  21399. }
  21400. if (s.last_lit) {
  21401. /*** FLUSH_BLOCK(s, 0); ***/
  21402. flush_block_only(s, false);
  21403. if (s.strm.avail_out === 0) {
  21404. return BS_NEED_MORE;
  21405. }
  21406. /***/
  21407. }
  21408. return BS_BLOCK_DONE;
  21409. }
  21410. /* ===========================================================================
  21411. * Same as above, but achieves better compression. We use a lazy
  21412. * evaluation for matches: a match is finally adopted only if there is
  21413. * no better match at the next window position.
  21414. */
  21415. function deflate_slow(s, flush) {
  21416. var hash_head; /* head of hash chain */
  21417. var bflush; /* set if current block must be flushed */
  21418. var max_insert;
  21419. /* Process the input block. */
  21420. for (;;) {
  21421. /* Make sure that we always have enough lookahead, except
  21422. * at the end of the input file. We need MAX_MATCH bytes
  21423. * for the next match, plus MIN_MATCH bytes to insert the
  21424. * string following the next match.
  21425. */
  21426. if (s.lookahead < MIN_LOOKAHEAD) {
  21427. fill_window(s);
  21428. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21429. return BS_NEED_MORE;
  21430. }
  21431. if (s.lookahead === 0) { break; } /* flush the current block */
  21432. }
  21433. /* Insert the string window[strstart .. strstart+2] in the
  21434. * dictionary, and set hash_head to the head of the hash chain:
  21435. */
  21436. hash_head = 0/*NIL*/;
  21437. if (s.lookahead >= MIN_MATCH) {
  21438. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21439. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21440. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21441. s.head[s.ins_h] = s.strstart;
  21442. /***/
  21443. }
  21444. /* Find the longest match, discarding those <= prev_length.
  21445. */
  21446. s.prev_length = s.match_length;
  21447. s.prev_match = s.match_start;
  21448. s.match_length = MIN_MATCH-1;
  21449. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21450. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21451. /* To simplify the code, we prevent matches with the string
  21452. * of window index 0 (in particular we have to avoid a match
  21453. * of the string with itself at the start of the input file).
  21454. */
  21455. s.match_length = longest_match(s, hash_head);
  21456. /* longest_match() sets match_start */
  21457. if (s.match_length <= 5 &&
  21458. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21459. /* If prev_match is also MIN_MATCH, match_start is garbage
  21460. * but we will ignore the current match anyway.
  21461. */
  21462. s.match_length = MIN_MATCH-1;
  21463. }
  21464. }
  21465. /* If there was a match at the previous step and the current
  21466. * match is not better, output the previous match:
  21467. */
  21468. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21469. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21470. /* Do not insert strings in hash table beyond this. */
  21471. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21472. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21473. s.prev_length - MIN_MATCH, bflush);***/
  21474. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21475. /* Insert in hash table all strings up to the end of the match.
  21476. * strstart-1 and strstart are already inserted. If there is not
  21477. * enough lookahead, the last two strings are not inserted in
  21478. * the hash table.
  21479. */
  21480. s.lookahead -= s.prev_length-1;
  21481. s.prev_length -= 2;
  21482. do {
  21483. if (++s.strstart <= max_insert) {
  21484. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21485. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21486. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21487. s.head[s.ins_h] = s.strstart;
  21488. /***/
  21489. }
  21490. } while (--s.prev_length !== 0);
  21491. s.match_available = 0;
  21492. s.match_length = MIN_MATCH-1;
  21493. s.strstart++;
  21494. if (bflush) {
  21495. /*** FLUSH_BLOCK(s, 0); ***/
  21496. flush_block_only(s, false);
  21497. if (s.strm.avail_out === 0) {
  21498. return BS_NEED_MORE;
  21499. }
  21500. /***/
  21501. }
  21502. } else if (s.match_available) {
  21503. /* If there was no match at the previous position, output a
  21504. * single literal. If there was a match but the current match
  21505. * is longer, truncate the previous match to a single literal.
  21506. */
  21507. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21508. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21509. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21510. if (bflush) {
  21511. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21512. flush_block_only(s, false);
  21513. /***/
  21514. }
  21515. s.strstart++;
  21516. s.lookahead--;
  21517. if (s.strm.avail_out === 0) {
  21518. return BS_NEED_MORE;
  21519. }
  21520. } else {
  21521. /* There is no previous match to compare with, wait for
  21522. * the next step to decide.
  21523. */
  21524. s.match_available = 1;
  21525. s.strstart++;
  21526. s.lookahead--;
  21527. }
  21528. }
  21529. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21530. if (s.match_available) {
  21531. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21532. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21533. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21534. s.match_available = 0;
  21535. }
  21536. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21537. if (flush === Z_FINISH) {
  21538. /*** FLUSH_BLOCK(s, 1); ***/
  21539. flush_block_only(s, true);
  21540. if (s.strm.avail_out === 0) {
  21541. return BS_FINISH_STARTED;
  21542. }
  21543. /***/
  21544. return BS_FINISH_DONE;
  21545. }
  21546. if (s.last_lit) {
  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. return BS_BLOCK_DONE;
  21555. }
  21556. /* ===========================================================================
  21557. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21558. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21559. * deflate switches away from Z_RLE.)
  21560. */
  21561. function deflate_rle(s, flush) {
  21562. var bflush; /* set if current block must be flushed */
  21563. var prev; /* byte at distance one to match */
  21564. var scan, strend; /* scan goes up to strend for length of run */
  21565. var _win = s.window;
  21566. for (;;) {
  21567. /* Make sure that we always have enough lookahead, except
  21568. * at the end of the input file. We need MAX_MATCH bytes
  21569. * for the longest run, plus one for the unrolled loop.
  21570. */
  21571. if (s.lookahead <= MAX_MATCH) {
  21572. fill_window(s);
  21573. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21574. return BS_NEED_MORE;
  21575. }
  21576. if (s.lookahead === 0) { break; } /* flush the current block */
  21577. }
  21578. /* See how many times the previous byte repeats */
  21579. s.match_length = 0;
  21580. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21581. scan = s.strstart - 1;
  21582. prev = _win[scan];
  21583. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21584. strend = s.strstart + MAX_MATCH;
  21585. do {
  21586. /*jshint noempty:false*/
  21587. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21588. prev === _win[++scan] && prev === _win[++scan] &&
  21589. prev === _win[++scan] && prev === _win[++scan] &&
  21590. prev === _win[++scan] && prev === _win[++scan] &&
  21591. scan < strend);
  21592. s.match_length = MAX_MATCH - (strend - scan);
  21593. if (s.match_length > s.lookahead) {
  21594. s.match_length = s.lookahead;
  21595. }
  21596. }
  21597. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21598. }
  21599. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21600. if (s.match_length >= MIN_MATCH) {
  21601. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21602. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21603. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21604. s.lookahead -= s.match_length;
  21605. s.strstart += s.match_length;
  21606. s.match_length = 0;
  21607. } else {
  21608. /* No match, output a literal byte */
  21609. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21610. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21611. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21612. s.lookahead--;
  21613. s.strstart++;
  21614. }
  21615. if (bflush) {
  21616. /*** FLUSH_BLOCK(s, 0); ***/
  21617. flush_block_only(s, false);
  21618. if (s.strm.avail_out === 0) {
  21619. return BS_NEED_MORE;
  21620. }
  21621. /***/
  21622. }
  21623. }
  21624. s.insert = 0;
  21625. if (flush === Z_FINISH) {
  21626. /*** FLUSH_BLOCK(s, 1); ***/
  21627. flush_block_only(s, true);
  21628. if (s.strm.avail_out === 0) {
  21629. return BS_FINISH_STARTED;
  21630. }
  21631. /***/
  21632. return BS_FINISH_DONE;
  21633. }
  21634. if (s.last_lit) {
  21635. /*** FLUSH_BLOCK(s, 0); ***/
  21636. flush_block_only(s, false);
  21637. if (s.strm.avail_out === 0) {
  21638. return BS_NEED_MORE;
  21639. }
  21640. /***/
  21641. }
  21642. return BS_BLOCK_DONE;
  21643. }
  21644. /* ===========================================================================
  21645. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21646. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21647. */
  21648. function deflate_huff(s, flush) {
  21649. var bflush; /* set if current block must be flushed */
  21650. for (;;) {
  21651. /* Make sure that we have a literal to write. */
  21652. if (s.lookahead === 0) {
  21653. fill_window(s);
  21654. if (s.lookahead === 0) {
  21655. if (flush === Z_NO_FLUSH) {
  21656. return BS_NEED_MORE;
  21657. }
  21658. break; /* flush the current block */
  21659. }
  21660. }
  21661. /* Output a literal byte */
  21662. s.match_length = 0;
  21663. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21664. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21665. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21666. s.lookahead--;
  21667. s.strstart++;
  21668. if (bflush) {
  21669. /*** FLUSH_BLOCK(s, 0); ***/
  21670. flush_block_only(s, false);
  21671. if (s.strm.avail_out === 0) {
  21672. return BS_NEED_MORE;
  21673. }
  21674. /***/
  21675. }
  21676. }
  21677. s.insert = 0;
  21678. if (flush === Z_FINISH) {
  21679. /*** FLUSH_BLOCK(s, 1); ***/
  21680. flush_block_only(s, true);
  21681. if (s.strm.avail_out === 0) {
  21682. return BS_FINISH_STARTED;
  21683. }
  21684. /***/
  21685. return BS_FINISH_DONE;
  21686. }
  21687. if (s.last_lit) {
  21688. /*** FLUSH_BLOCK(s, 0); ***/
  21689. flush_block_only(s, false);
  21690. if (s.strm.avail_out === 0) {
  21691. return BS_NEED_MORE;
  21692. }
  21693. /***/
  21694. }
  21695. return BS_BLOCK_DONE;
  21696. }
  21697. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21698. * the desired pack level (0..9). The values given below have been tuned to
  21699. * exclude worst case performance for pathological files. Better values may be
  21700. * found for specific files.
  21701. */
  21702. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21703. this.good_length = good_length;
  21704. this.max_lazy = max_lazy;
  21705. this.nice_length = nice_length;
  21706. this.max_chain = max_chain;
  21707. this.func = func;
  21708. };
  21709. var configuration_table;
  21710. configuration_table = [
  21711. /* good lazy nice chain */
  21712. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21713. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21714. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21715. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21716. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21717. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21718. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21719. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21720. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21721. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21722. ];
  21723. /* ===========================================================================
  21724. * Initialize the "longest match" routines for a new zlib stream
  21725. */
  21726. function lm_init(s) {
  21727. s.window_size = 2 * s.w_size;
  21728. /*** CLEAR_HASH(s); ***/
  21729. zero(s.head); // Fill with NIL (= 0);
  21730. /* Set the default configuration parameters:
  21731. */
  21732. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21733. s.good_match = configuration_table[s.level].good_length;
  21734. s.nice_match = configuration_table[s.level].nice_length;
  21735. s.max_chain_length = configuration_table[s.level].max_chain;
  21736. s.strstart = 0;
  21737. s.block_start = 0;
  21738. s.lookahead = 0;
  21739. s.insert = 0;
  21740. s.match_length = s.prev_length = MIN_MATCH - 1;
  21741. s.match_available = 0;
  21742. s.ins_h = 0;
  21743. }
  21744. function DeflateState() {
  21745. this.strm = null; /* pointer back to this zlib stream */
  21746. this.status = 0; /* as the name implies */
  21747. this.pending_buf = null; /* output still pending */
  21748. this.pending_buf_size = 0; /* size of pending_buf */
  21749. this.pending_out = 0; /* next pending byte to output to the stream */
  21750. this.pending = 0; /* nb of bytes in the pending buffer */
  21751. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21752. this.gzhead = null; /* gzip header information to write */
  21753. this.gzindex = 0; /* where in extra, name, or comment */
  21754. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21755. this.last_flush = -1; /* value of flush param for previous deflate call */
  21756. this.w_size = 0; /* LZ77 window size (32K by default) */
  21757. this.w_bits = 0; /* log2(w_size) (8..16) */
  21758. this.w_mask = 0; /* w_size - 1 */
  21759. this.window = null;
  21760. /* Sliding window. Input bytes are read into the second half of the window,
  21761. * and move to the first half later to keep a dictionary of at least wSize
  21762. * bytes. With this organization, matches are limited to a distance of
  21763. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21764. * performed with a length multiple of the block size.
  21765. */
  21766. this.window_size = 0;
  21767. /* Actual size of window: 2*wSize, except when the user input buffer
  21768. * is directly used as sliding window.
  21769. */
  21770. this.prev = null;
  21771. /* Link to older string with same hash index. To limit the size of this
  21772. * array to 64K, this link is maintained only for the last 32K strings.
  21773. * An index in this array is thus a window index modulo 32K.
  21774. */
  21775. this.head = null; /* Heads of the hash chains or NIL. */
  21776. this.ins_h = 0; /* hash index of string to be inserted */
  21777. this.hash_size = 0; /* number of elements in hash table */
  21778. this.hash_bits = 0; /* log2(hash_size) */
  21779. this.hash_mask = 0; /* hash_size-1 */
  21780. this.hash_shift = 0;
  21781. /* Number of bits by which ins_h must be shifted at each input
  21782. * step. It must be such that after MIN_MATCH steps, the oldest
  21783. * byte no longer takes part in the hash key, that is:
  21784. * hash_shift * MIN_MATCH >= hash_bits
  21785. */
  21786. this.block_start = 0;
  21787. /* Window position at the beginning of the current output block. Gets
  21788. * negative when the window is moved backwards.
  21789. */
  21790. this.match_length = 0; /* length of best match */
  21791. this.prev_match = 0; /* previous match */
  21792. this.match_available = 0; /* set if previous match exists */
  21793. this.strstart = 0; /* start of string to insert */
  21794. this.match_start = 0; /* start of matching string */
  21795. this.lookahead = 0; /* number of valid bytes ahead in window */
  21796. this.prev_length = 0;
  21797. /* Length of the best match at previous step. Matches not greater than this
  21798. * are discarded. This is used in the lazy match evaluation.
  21799. */
  21800. this.max_chain_length = 0;
  21801. /* To speed up deflation, hash chains are never searched beyond this
  21802. * length. A higher limit improves compression ratio but degrades the
  21803. * speed.
  21804. */
  21805. this.max_lazy_match = 0;
  21806. /* Attempt to find a better match only when the current match is strictly
  21807. * smaller than this value. This mechanism is used only for compression
  21808. * levels >= 4.
  21809. */
  21810. // That's alias to max_lazy_match, don't use directly
  21811. //this.max_insert_length = 0;
  21812. /* Insert new strings in the hash table only if the match length is not
  21813. * greater than this length. This saves time but degrades compression.
  21814. * max_insert_length is used only for compression levels <= 3.
  21815. */
  21816. this.level = 0; /* compression level (1..9) */
  21817. this.strategy = 0; /* favor or force Huffman coding*/
  21818. this.good_match = 0;
  21819. /* Use a faster search when the previous match is longer than this */
  21820. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21821. /* used by trees.c: */
  21822. /* Didn't use ct_data typedef below to suppress compiler warning */
  21823. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21824. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21825. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21826. // Use flat array of DOUBLE size, with interleaved fata,
  21827. // because JS does not support effective
  21828. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21829. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21830. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21831. zero(this.dyn_ltree);
  21832. zero(this.dyn_dtree);
  21833. zero(this.bl_tree);
  21834. this.l_desc = null; /* desc. for literal tree */
  21835. this.d_desc = null; /* desc. for distance tree */
  21836. this.bl_desc = null; /* desc. for bit length tree */
  21837. //ush bl_count[MAX_BITS+1];
  21838. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21839. /* number of codes at each bit length for an optimal tree */
  21840. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21841. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21842. zero(this.heap);
  21843. this.heap_len = 0; /* number of elements in the heap */
  21844. this.heap_max = 0; /* element of largest frequency */
  21845. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21846. * The same heap array is used to build all trees.
  21847. */
  21848. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21849. zero(this.depth);
  21850. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21851. */
  21852. this.l_buf = 0; /* buffer index for literals or lengths */
  21853. this.lit_bufsize = 0;
  21854. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21855. * limiting lit_bufsize to 64K:
  21856. * - frequencies can be kept in 16 bit counters
  21857. * - if compression is not successful for the first block, all input
  21858. * data is still in the window so we can still emit a stored block even
  21859. * when input comes from standard input. (This can also be done for
  21860. * all blocks if lit_bufsize is not greater than 32K.)
  21861. * - if compression is not successful for a file smaller than 64K, we can
  21862. * even emit a stored file instead of a stored block (saving 5 bytes).
  21863. * This is applicable only for zip (not gzip or zlib).
  21864. * - creating new Huffman trees less frequently may not provide fast
  21865. * adaptation to changes in the input data statistics. (Take for
  21866. * example a binary file with poorly compressible code followed by
  21867. * a highly compressible string table.) Smaller buffer sizes give
  21868. * fast adaptation but have of course the overhead of transmitting
  21869. * trees more frequently.
  21870. * - I can't count above 4
  21871. */
  21872. this.last_lit = 0; /* running index in l_buf */
  21873. this.d_buf = 0;
  21874. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21875. * the same number of elements. To use different lengths, an extra flag
  21876. * array would be necessary.
  21877. */
  21878. this.opt_len = 0; /* bit length of current block with optimal trees */
  21879. this.static_len = 0; /* bit length of current block with static trees */
  21880. this.matches = 0; /* number of string matches in current block */
  21881. this.insert = 0; /* bytes at end of window left to insert */
  21882. this.bi_buf = 0;
  21883. /* Output buffer. bits are inserted starting at the bottom (least
  21884. * significant bits).
  21885. */
  21886. this.bi_valid = 0;
  21887. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21888. * are always zero.
  21889. */
  21890. // Used for window memory init. We safely ignore it for JS. That makes
  21891. // sense only for pointers and memory check tools.
  21892. //this.high_water = 0;
  21893. /* High water mark offset in window for initialized bytes -- bytes above
  21894. * this are set to zero in order to avoid memory check warnings when
  21895. * longest match routines access bytes past the input. This is then
  21896. * updated to the new high water mark.
  21897. */
  21898. }
  21899. function deflateResetKeep(strm) {
  21900. var s;
  21901. if (!strm || !strm.state) {
  21902. return err(strm, Z_STREAM_ERROR);
  21903. }
  21904. strm.total_in = strm.total_out = 0;
  21905. strm.data_type = Z_UNKNOWN;
  21906. s = strm.state;
  21907. s.pending = 0;
  21908. s.pending_out = 0;
  21909. if (s.wrap < 0) {
  21910. s.wrap = -s.wrap;
  21911. /* was made negative by deflate(..., Z_FINISH); */
  21912. }
  21913. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21914. strm.adler = (s.wrap === 2) ?
  21915. 0 // crc32(0, Z_NULL, 0)
  21916. :
  21917. 1; // adler32(0, Z_NULL, 0)
  21918. s.last_flush = Z_NO_FLUSH;
  21919. trees._tr_init(s);
  21920. return Z_OK;
  21921. }
  21922. function deflateReset(strm) {
  21923. var ret = deflateResetKeep(strm);
  21924. if (ret === Z_OK) {
  21925. lm_init(strm.state);
  21926. }
  21927. return ret;
  21928. }
  21929. function deflateSetHeader(strm, head) {
  21930. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21931. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21932. strm.state.gzhead = head;
  21933. return Z_OK;
  21934. }
  21935. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21936. if (!strm) { // === Z_NULL
  21937. return Z_STREAM_ERROR;
  21938. }
  21939. var wrap = 1;
  21940. if (level === Z_DEFAULT_COMPRESSION) {
  21941. level = 6;
  21942. }
  21943. if (windowBits < 0) { /* suppress zlib wrapper */
  21944. wrap = 0;
  21945. windowBits = -windowBits;
  21946. }
  21947. else if (windowBits > 15) {
  21948. wrap = 2; /* write gzip wrapper instead */
  21949. windowBits -= 16;
  21950. }
  21951. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21952. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21953. strategy < 0 || strategy > Z_FIXED) {
  21954. return err(strm, Z_STREAM_ERROR);
  21955. }
  21956. if (windowBits === 8) {
  21957. windowBits = 9;
  21958. }
  21959. /* until 256-byte window bug fixed */
  21960. var s = new DeflateState();
  21961. strm.state = s;
  21962. s.strm = strm;
  21963. s.wrap = wrap;
  21964. s.gzhead = null;
  21965. s.w_bits = windowBits;
  21966. s.w_size = 1 << s.w_bits;
  21967. s.w_mask = s.w_size - 1;
  21968. s.hash_bits = memLevel + 7;
  21969. s.hash_size = 1 << s.hash_bits;
  21970. s.hash_mask = s.hash_size - 1;
  21971. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21972. s.window = new utils.Buf8(s.w_size * 2);
  21973. s.head = new utils.Buf16(s.hash_size);
  21974. s.prev = new utils.Buf16(s.w_size);
  21975. // Don't need mem init magic for JS.
  21976. //s.high_water = 0; /* nothing written to s->window yet */
  21977. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21978. s.pending_buf_size = s.lit_bufsize * 4;
  21979. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21980. s.d_buf = s.lit_bufsize >> 1;
  21981. s.l_buf = (1 + 2) * s.lit_bufsize;
  21982. s.level = level;
  21983. s.strategy = strategy;
  21984. s.method = method;
  21985. return deflateReset(strm);
  21986. }
  21987. function deflateInit(strm, level) {
  21988. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21989. }
  21990. function deflate(strm, flush) {
  21991. var old_flush, s;
  21992. var beg, val; // for gzip header write only
  21993. if (!strm || !strm.state ||
  21994. flush > Z_BLOCK || flush < 0) {
  21995. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21996. }
  21997. s = strm.state;
  21998. if (!strm.output ||
  21999. (!strm.input && strm.avail_in !== 0) ||
  22000. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  22001. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  22002. }
  22003. s.strm = strm; /* just in case */
  22004. old_flush = s.last_flush;
  22005. s.last_flush = flush;
  22006. /* Write the header */
  22007. if (s.status === INIT_STATE) {
  22008. if (s.wrap === 2) { // GZIP header
  22009. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22010. put_byte(s, 31);
  22011. put_byte(s, 139);
  22012. put_byte(s, 8);
  22013. if (!s.gzhead) { // s->gzhead == Z_NULL
  22014. put_byte(s, 0);
  22015. put_byte(s, 0);
  22016. put_byte(s, 0);
  22017. put_byte(s, 0);
  22018. put_byte(s, 0);
  22019. put_byte(s, s.level === 9 ? 2 :
  22020. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22021. 4 : 0));
  22022. put_byte(s, OS_CODE);
  22023. s.status = BUSY_STATE;
  22024. }
  22025. else {
  22026. put_byte(s, (s.gzhead.text ? 1 : 0) +
  22027. (s.gzhead.hcrc ? 2 : 0) +
  22028. (!s.gzhead.extra ? 0 : 4) +
  22029. (!s.gzhead.name ? 0 : 8) +
  22030. (!s.gzhead.comment ? 0 : 16)
  22031. );
  22032. put_byte(s, s.gzhead.time & 0xff);
  22033. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  22034. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  22035. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  22036. put_byte(s, s.level === 9 ? 2 :
  22037. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22038. 4 : 0));
  22039. put_byte(s, s.gzhead.os & 0xff);
  22040. if (s.gzhead.extra && s.gzhead.extra.length) {
  22041. put_byte(s, s.gzhead.extra.length & 0xff);
  22042. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  22043. }
  22044. if (s.gzhead.hcrc) {
  22045. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  22046. }
  22047. s.gzindex = 0;
  22048. s.status = EXTRA_STATE;
  22049. }
  22050. }
  22051. else // DEFLATE header
  22052. {
  22053. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  22054. var level_flags = -1;
  22055. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  22056. level_flags = 0;
  22057. } else if (s.level < 6) {
  22058. level_flags = 1;
  22059. } else if (s.level === 6) {
  22060. level_flags = 2;
  22061. } else {
  22062. level_flags = 3;
  22063. }
  22064. header |= (level_flags << 6);
  22065. if (s.strstart !== 0) { header |= PRESET_DICT; }
  22066. header += 31 - (header % 31);
  22067. s.status = BUSY_STATE;
  22068. putShortMSB(s, header);
  22069. /* Save the adler32 of the preset dictionary: */
  22070. if (s.strstart !== 0) {
  22071. putShortMSB(s, strm.adler >>> 16);
  22072. putShortMSB(s, strm.adler & 0xffff);
  22073. }
  22074. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  22075. }
  22076. }
  22077. //#ifdef GZIP
  22078. if (s.status === EXTRA_STATE) {
  22079. if (s.gzhead.extra/* != Z_NULL*/) {
  22080. beg = s.pending; /* start of bytes to update crc */
  22081. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  22082. if (s.pending === s.pending_buf_size) {
  22083. if (s.gzhead.hcrc && s.pending > beg) {
  22084. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22085. }
  22086. flush_pending(strm);
  22087. beg = s.pending;
  22088. if (s.pending === s.pending_buf_size) {
  22089. break;
  22090. }
  22091. }
  22092. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  22093. s.gzindex++;
  22094. }
  22095. if (s.gzhead.hcrc && s.pending > beg) {
  22096. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22097. }
  22098. if (s.gzindex === s.gzhead.extra.length) {
  22099. s.gzindex = 0;
  22100. s.status = NAME_STATE;
  22101. }
  22102. }
  22103. else {
  22104. s.status = NAME_STATE;
  22105. }
  22106. }
  22107. if (s.status === NAME_STATE) {
  22108. if (s.gzhead.name/* != Z_NULL*/) {
  22109. beg = s.pending; /* start of bytes to update crc */
  22110. //int val;
  22111. do {
  22112. if (s.pending === s.pending_buf_size) {
  22113. if (s.gzhead.hcrc && s.pending > beg) {
  22114. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22115. }
  22116. flush_pending(strm);
  22117. beg = s.pending;
  22118. if (s.pending === s.pending_buf_size) {
  22119. val = 1;
  22120. break;
  22121. }
  22122. }
  22123. // JS specific: little magic to add zero terminator to end of string
  22124. if (s.gzindex < s.gzhead.name.length) {
  22125. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  22126. } else {
  22127. val = 0;
  22128. }
  22129. put_byte(s, val);
  22130. } while (val !== 0);
  22131. if (s.gzhead.hcrc && s.pending > beg) {
  22132. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22133. }
  22134. if (val === 0) {
  22135. s.gzindex = 0;
  22136. s.status = COMMENT_STATE;
  22137. }
  22138. }
  22139. else {
  22140. s.status = COMMENT_STATE;
  22141. }
  22142. }
  22143. if (s.status === COMMENT_STATE) {
  22144. if (s.gzhead.comment/* != Z_NULL*/) {
  22145. beg = s.pending; /* start of bytes to update crc */
  22146. //int val;
  22147. do {
  22148. if (s.pending === s.pending_buf_size) {
  22149. if (s.gzhead.hcrc && s.pending > beg) {
  22150. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22151. }
  22152. flush_pending(strm);
  22153. beg = s.pending;
  22154. if (s.pending === s.pending_buf_size) {
  22155. val = 1;
  22156. break;
  22157. }
  22158. }
  22159. // JS specific: little magic to add zero terminator to end of string
  22160. if (s.gzindex < s.gzhead.comment.length) {
  22161. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  22162. } else {
  22163. val = 0;
  22164. }
  22165. put_byte(s, val);
  22166. } while (val !== 0);
  22167. if (s.gzhead.hcrc && s.pending > beg) {
  22168. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22169. }
  22170. if (val === 0) {
  22171. s.status = HCRC_STATE;
  22172. }
  22173. }
  22174. else {
  22175. s.status = HCRC_STATE;
  22176. }
  22177. }
  22178. if (s.status === HCRC_STATE) {
  22179. if (s.gzhead.hcrc) {
  22180. if (s.pending + 2 > s.pending_buf_size) {
  22181. flush_pending(strm);
  22182. }
  22183. if (s.pending + 2 <= s.pending_buf_size) {
  22184. put_byte(s, strm.adler & 0xff);
  22185. put_byte(s, (strm.adler >> 8) & 0xff);
  22186. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22187. s.status = BUSY_STATE;
  22188. }
  22189. }
  22190. else {
  22191. s.status = BUSY_STATE;
  22192. }
  22193. }
  22194. //#endif
  22195. /* Flush as much pending output as possible */
  22196. if (s.pending !== 0) {
  22197. flush_pending(strm);
  22198. if (strm.avail_out === 0) {
  22199. /* Since avail_out is 0, deflate will be called again with
  22200. * more output space, but possibly with both pending and
  22201. * avail_in equal to zero. There won't be anything to do,
  22202. * but this is not an error situation so make sure we
  22203. * return OK instead of BUF_ERROR at next call of deflate:
  22204. */
  22205. s.last_flush = -1;
  22206. return Z_OK;
  22207. }
  22208. /* Make sure there is something to do and avoid duplicate consecutive
  22209. * flushes. For repeated and useless calls with Z_FINISH, we keep
  22210. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  22211. */
  22212. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  22213. flush !== Z_FINISH) {
  22214. return err(strm, Z_BUF_ERROR);
  22215. }
  22216. /* User must not provide more input after the first FINISH: */
  22217. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  22218. return err(strm, Z_BUF_ERROR);
  22219. }
  22220. /* Start a new block or continue the current one.
  22221. */
  22222. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  22223. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  22224. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  22225. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  22226. configuration_table[s.level].func(s, flush));
  22227. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22228. s.status = FINISH_STATE;
  22229. }
  22230. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22231. if (strm.avail_out === 0) {
  22232. s.last_flush = -1;
  22233. /* avoid BUF_ERROR next call, see above */
  22234. }
  22235. return Z_OK;
  22236. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22237. * of deflate should use the same flush parameter to make sure
  22238. * that the flush is complete. So we don't have to output an
  22239. * empty block here, this will be done at next call. This also
  22240. * ensures that for a very small output buffer, we emit at most
  22241. * one empty block.
  22242. */
  22243. }
  22244. if (bstate === BS_BLOCK_DONE) {
  22245. if (flush === Z_PARTIAL_FLUSH) {
  22246. trees._tr_align(s);
  22247. }
  22248. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22249. trees._tr_stored_block(s, 0, 0, false);
  22250. /* For a full flush, this empty block will be recognized
  22251. * as a special marker by inflate_sync().
  22252. */
  22253. if (flush === Z_FULL_FLUSH) {
  22254. /*** CLEAR_HASH(s); ***/ /* forget history */
  22255. zero(s.head); // Fill with NIL (= 0);
  22256. if (s.lookahead === 0) {
  22257. s.strstart = 0;
  22258. s.block_start = 0;
  22259. s.insert = 0;
  22260. }
  22261. }
  22262. }
  22263. flush_pending(strm);
  22264. if (strm.avail_out === 0) {
  22265. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22266. return Z_OK;
  22267. }
  22268. }
  22269. }
  22270. //Assert(strm->avail_out > 0, "bug2");
  22271. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22272. if (flush !== Z_FINISH) { return Z_OK; }
  22273. if (s.wrap <= 0) { return Z_STREAM_END; }
  22274. /* Write the trailer */
  22275. if (s.wrap === 2) {
  22276. put_byte(s, strm.adler & 0xff);
  22277. put_byte(s, (strm.adler >> 8) & 0xff);
  22278. put_byte(s, (strm.adler >> 16) & 0xff);
  22279. put_byte(s, (strm.adler >> 24) & 0xff);
  22280. put_byte(s, strm.total_in & 0xff);
  22281. put_byte(s, (strm.total_in >> 8) & 0xff);
  22282. put_byte(s, (strm.total_in >> 16) & 0xff);
  22283. put_byte(s, (strm.total_in >> 24) & 0xff);
  22284. }
  22285. else
  22286. {
  22287. putShortMSB(s, strm.adler >>> 16);
  22288. putShortMSB(s, strm.adler & 0xffff);
  22289. }
  22290. flush_pending(strm);
  22291. /* If avail_out is zero, the application will call deflate again
  22292. * to flush the rest.
  22293. */
  22294. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22295. /* write the trailer only once! */
  22296. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22297. }
  22298. function deflateEnd(strm) {
  22299. var status;
  22300. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22301. return Z_STREAM_ERROR;
  22302. }
  22303. status = strm.state.status;
  22304. if (status !== INIT_STATE &&
  22305. status !== EXTRA_STATE &&
  22306. status !== NAME_STATE &&
  22307. status !== COMMENT_STATE &&
  22308. status !== HCRC_STATE &&
  22309. status !== BUSY_STATE &&
  22310. status !== FINISH_STATE
  22311. ) {
  22312. return err(strm, Z_STREAM_ERROR);
  22313. }
  22314. strm.state = null;
  22315. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22316. }
  22317. /* =========================================================================
  22318. * Copy the source state to the destination state
  22319. */
  22320. //function deflateCopy(dest, source) {
  22321. //
  22322. //}
  22323. exports.deflateInit = deflateInit;
  22324. exports.deflateInit2 = deflateInit2;
  22325. exports.deflateReset = deflateReset;
  22326. exports.deflateResetKeep = deflateResetKeep;
  22327. exports.deflateSetHeader = deflateSetHeader;
  22328. exports.deflate = deflate;
  22329. exports.deflateEnd = deflateEnd;
  22330. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22331. /* Not implemented
  22332. exports.deflateBound = deflateBound;
  22333. exports.deflateCopy = deflateCopy;
  22334. exports.deflateSetDictionary = deflateSetDictionary;
  22335. exports.deflateParams = deflateParams;
  22336. exports.deflatePending = deflatePending;
  22337. exports.deflatePrime = deflatePrime;
  22338. exports.deflateTune = deflateTune;
  22339. */
  22340. },{"../utils/common":75,"./adler32":77,"./crc32":79,"./messages":85,"./trees":86}],81:[function(require,module,exports){
  22341. 'use strict';
  22342. function GZheader() {
  22343. /* true if compressed data believed to be text */
  22344. this.text = 0;
  22345. /* modification time */
  22346. this.time = 0;
  22347. /* extra flags (not used when writing a gzip file) */
  22348. this.xflags = 0;
  22349. /* operating system */
  22350. this.os = 0;
  22351. /* pointer to extra field or Z_NULL if none */
  22352. this.extra = null;
  22353. /* extra field length (valid if extra != Z_NULL) */
  22354. this.extra_len = 0; // Actually, we don't need it in JS,
  22355. // but leave for few code modifications
  22356. //
  22357. // Setup limits is not necessary because in js we should not preallocate memory
  22358. // for inflate use constant limit in 65536 bytes
  22359. //
  22360. /* space at extra (only when reading header) */
  22361. // this.extra_max = 0;
  22362. /* pointer to zero-terminated file name or Z_NULL */
  22363. this.name = '';
  22364. /* space at name (only when reading header) */
  22365. // this.name_max = 0;
  22366. /* pointer to zero-terminated comment or Z_NULL */
  22367. this.comment = '';
  22368. /* space at comment (only when reading header) */
  22369. // this.comm_max = 0;
  22370. /* true if there was or will be a header crc */
  22371. this.hcrc = 0;
  22372. /* true when done reading gzip header (not used when writing a gzip file) */
  22373. this.done = false;
  22374. }
  22375. module.exports = GZheader;
  22376. },{}],82:[function(require,module,exports){
  22377. 'use strict';
  22378. // See state defs from inflate.js
  22379. var BAD = 30; /* got a data error -- remain here until reset */
  22380. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22381. /*
  22382. Decode literal, length, and distance codes and write out the resulting
  22383. literal and match bytes until either not enough input or output is
  22384. available, an end-of-block is encountered, or a data error is encountered.
  22385. When large enough input and output buffers are supplied to inflate(), for
  22386. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22387. inflate execution time is spent in this routine.
  22388. Entry assumptions:
  22389. state.mode === LEN
  22390. strm.avail_in >= 6
  22391. strm.avail_out >= 258
  22392. start >= strm.avail_out
  22393. state.bits < 8
  22394. On return, state.mode is one of:
  22395. LEN -- ran out of enough output space or enough available input
  22396. TYPE -- reached end of block code, inflate() to interpret next block
  22397. BAD -- error in block data
  22398. Notes:
  22399. - The maximum input bits used by a length/distance pair is 15 bits for the
  22400. length code, 5 bits for the length extra, 15 bits for the distance code,
  22401. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22402. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22403. checking for available input while decoding.
  22404. - The maximum bytes that a single length/distance pair can output is 258
  22405. bytes, which is the maximum length that can be coded. inflate_fast()
  22406. requires strm.avail_out >= 258 for each loop to avoid checking for
  22407. output space.
  22408. */
  22409. module.exports = function inflate_fast(strm, start) {
  22410. var state;
  22411. var _in; /* local strm.input */
  22412. var last; /* have enough input while in < last */
  22413. var _out; /* local strm.output */
  22414. var beg; /* inflate()'s initial strm.output */
  22415. var end; /* while out < end, enough space available */
  22416. //#ifdef INFLATE_STRICT
  22417. var dmax; /* maximum distance from zlib header */
  22418. //#endif
  22419. var wsize; /* window size or zero if not using window */
  22420. var whave; /* valid bytes in the window */
  22421. var wnext; /* window write index */
  22422. var window; /* allocated sliding window, if wsize != 0 */
  22423. var hold; /* local strm.hold */
  22424. var bits; /* local strm.bits */
  22425. var lcode; /* local strm.lencode */
  22426. var dcode; /* local strm.distcode */
  22427. var lmask; /* mask for first level of length codes */
  22428. var dmask; /* mask for first level of distance codes */
  22429. var here; /* retrieved table entry */
  22430. var op; /* code bits, operation, extra bits, or */
  22431. /* window position, window bytes to copy */
  22432. var len; /* match length, unused bytes */
  22433. var dist; /* match distance */
  22434. var from; /* where to copy match from */
  22435. var from_source;
  22436. var input, output; // JS specific, because we have no pointers
  22437. /* copy state to local variables */
  22438. state = strm.state;
  22439. //here = state.here;
  22440. _in = strm.next_in;
  22441. input = strm.input;
  22442. last = _in + (strm.avail_in - 5);
  22443. _out = strm.next_out;
  22444. output = strm.output;
  22445. beg = _out - (start - strm.avail_out);
  22446. end = _out + (strm.avail_out - 257);
  22447. //#ifdef INFLATE_STRICT
  22448. dmax = state.dmax;
  22449. //#endif
  22450. wsize = state.wsize;
  22451. whave = state.whave;
  22452. wnext = state.wnext;
  22453. window = state.window;
  22454. hold = state.hold;
  22455. bits = state.bits;
  22456. lcode = state.lencode;
  22457. dcode = state.distcode;
  22458. lmask = (1 << state.lenbits) - 1;
  22459. dmask = (1 << state.distbits) - 1;
  22460. /* decode literals and length/distances until end-of-block or not enough
  22461. input data or output space */
  22462. top:
  22463. do {
  22464. if (bits < 15) {
  22465. hold += input[_in++] << bits;
  22466. bits += 8;
  22467. hold += input[_in++] << bits;
  22468. bits += 8;
  22469. }
  22470. here = lcode[hold & lmask];
  22471. dolen:
  22472. for (;;) { // Goto emulation
  22473. op = here >>> 24/*here.bits*/;
  22474. hold >>>= op;
  22475. bits -= op;
  22476. op = (here >>> 16) & 0xff/*here.op*/;
  22477. if (op === 0) { /* literal */
  22478. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22479. // "inflate: literal '%c'\n" :
  22480. // "inflate: literal 0x%02x\n", here.val));
  22481. output[_out++] = here & 0xffff/*here.val*/;
  22482. }
  22483. else if (op & 16) { /* length base */
  22484. len = here & 0xffff/*here.val*/;
  22485. op &= 15; /* number of extra bits */
  22486. if (op) {
  22487. if (bits < op) {
  22488. hold += input[_in++] << bits;
  22489. bits += 8;
  22490. }
  22491. len += hold & ((1 << op) - 1);
  22492. hold >>>= op;
  22493. bits -= op;
  22494. }
  22495. //Tracevv((stderr, "inflate: length %u\n", len));
  22496. if (bits < 15) {
  22497. hold += input[_in++] << bits;
  22498. bits += 8;
  22499. hold += input[_in++] << bits;
  22500. bits += 8;
  22501. }
  22502. here = dcode[hold & dmask];
  22503. dodist:
  22504. for (;;) { // goto emulation
  22505. op = here >>> 24/*here.bits*/;
  22506. hold >>>= op;
  22507. bits -= op;
  22508. op = (here >>> 16) & 0xff/*here.op*/;
  22509. if (op & 16) { /* distance base */
  22510. dist = here & 0xffff/*here.val*/;
  22511. op &= 15; /* number of extra bits */
  22512. if (bits < op) {
  22513. hold += input[_in++] << bits;
  22514. bits += 8;
  22515. if (bits < op) {
  22516. hold += input[_in++] << bits;
  22517. bits += 8;
  22518. }
  22519. }
  22520. dist += hold & ((1 << op) - 1);
  22521. //#ifdef INFLATE_STRICT
  22522. if (dist > dmax) {
  22523. strm.msg = 'invalid distance too far back';
  22524. state.mode = BAD;
  22525. break top;
  22526. }
  22527. //#endif
  22528. hold >>>= op;
  22529. bits -= op;
  22530. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22531. op = _out - beg; /* max distance in output */
  22532. if (dist > op) { /* see if copy from window */
  22533. op = dist - op; /* distance back in window */
  22534. if (op > whave) {
  22535. if (state.sane) {
  22536. strm.msg = 'invalid distance too far back';
  22537. state.mode = BAD;
  22538. break top;
  22539. }
  22540. // (!) This block is disabled in zlib defailts,
  22541. // don't enable it for binary compatibility
  22542. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22543. // if (len <= op - whave) {
  22544. // do {
  22545. // output[_out++] = 0;
  22546. // } while (--len);
  22547. // continue top;
  22548. // }
  22549. // len -= op - whave;
  22550. // do {
  22551. // output[_out++] = 0;
  22552. // } while (--op > whave);
  22553. // if (op === 0) {
  22554. // from = _out - dist;
  22555. // do {
  22556. // output[_out++] = output[from++];
  22557. // } while (--len);
  22558. // continue top;
  22559. // }
  22560. //#endif
  22561. }
  22562. from = 0; // window index
  22563. from_source = window;
  22564. if (wnext === 0) { /* very common case */
  22565. from += wsize - op;
  22566. if (op < len) { /* some from window */
  22567. len -= op;
  22568. do {
  22569. output[_out++] = window[from++];
  22570. } while (--op);
  22571. from = _out - dist; /* rest from output */
  22572. from_source = output;
  22573. }
  22574. }
  22575. else if (wnext < op) { /* wrap around window */
  22576. from += wsize + wnext - op;
  22577. op -= wnext;
  22578. if (op < len) { /* some from end of window */
  22579. len -= op;
  22580. do {
  22581. output[_out++] = window[from++];
  22582. } while (--op);
  22583. from = 0;
  22584. if (wnext < len) { /* some from start of window */
  22585. op = wnext;
  22586. len -= op;
  22587. do {
  22588. output[_out++] = window[from++];
  22589. } while (--op);
  22590. from = _out - dist; /* rest from output */
  22591. from_source = output;
  22592. }
  22593. }
  22594. }
  22595. else { /* contiguous in window */
  22596. from += wnext - op;
  22597. if (op < len) { /* some from window */
  22598. len -= op;
  22599. do {
  22600. output[_out++] = window[from++];
  22601. } while (--op);
  22602. from = _out - dist; /* rest from output */
  22603. from_source = output;
  22604. }
  22605. }
  22606. while (len > 2) {
  22607. output[_out++] = from_source[from++];
  22608. output[_out++] = from_source[from++];
  22609. output[_out++] = from_source[from++];
  22610. len -= 3;
  22611. }
  22612. if (len) {
  22613. output[_out++] = from_source[from++];
  22614. if (len > 1) {
  22615. output[_out++] = from_source[from++];
  22616. }
  22617. }
  22618. }
  22619. else {
  22620. from = _out - dist; /* copy direct from output */
  22621. do { /* minimum length is three */
  22622. output[_out++] = output[from++];
  22623. output[_out++] = output[from++];
  22624. output[_out++] = output[from++];
  22625. len -= 3;
  22626. } while (len > 2);
  22627. if (len) {
  22628. output[_out++] = output[from++];
  22629. if (len > 1) {
  22630. output[_out++] = output[from++];
  22631. }
  22632. }
  22633. }
  22634. }
  22635. else if ((op & 64) === 0) { /* 2nd level distance code */
  22636. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22637. continue dodist;
  22638. }
  22639. else {
  22640. strm.msg = 'invalid distance code';
  22641. state.mode = BAD;
  22642. break top;
  22643. }
  22644. break; // need to emulate goto via "continue"
  22645. }
  22646. }
  22647. else if ((op & 64) === 0) { /* 2nd level length code */
  22648. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22649. continue dolen;
  22650. }
  22651. else if (op & 32) { /* end-of-block */
  22652. //Tracevv((stderr, "inflate: end of block\n"));
  22653. state.mode = TYPE;
  22654. break top;
  22655. }
  22656. else {
  22657. strm.msg = 'invalid literal/length code';
  22658. state.mode = BAD;
  22659. break top;
  22660. }
  22661. break; // need to emulate goto via "continue"
  22662. }
  22663. } while (_in < last && _out < end);
  22664. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22665. len = bits >> 3;
  22666. _in -= len;
  22667. bits -= len << 3;
  22668. hold &= (1 << bits) - 1;
  22669. /* update state and return */
  22670. strm.next_in = _in;
  22671. strm.next_out = _out;
  22672. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22673. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22674. state.hold = hold;
  22675. state.bits = bits;
  22676. return;
  22677. };
  22678. },{}],83:[function(require,module,exports){
  22679. 'use strict';
  22680. var utils = require('../utils/common');
  22681. var adler32 = require('./adler32');
  22682. var crc32 = require('./crc32');
  22683. var inflate_fast = require('./inffast');
  22684. var inflate_table = require('./inftrees');
  22685. var CODES = 0;
  22686. var LENS = 1;
  22687. var DISTS = 2;
  22688. /* Public constants ==========================================================*/
  22689. /* ===========================================================================*/
  22690. /* Allowed flush values; see deflate() and inflate() below for details */
  22691. //var Z_NO_FLUSH = 0;
  22692. //var Z_PARTIAL_FLUSH = 1;
  22693. //var Z_SYNC_FLUSH = 2;
  22694. //var Z_FULL_FLUSH = 3;
  22695. var Z_FINISH = 4;
  22696. var Z_BLOCK = 5;
  22697. var Z_TREES = 6;
  22698. /* Return codes for the compression/decompression functions. Negative values
  22699. * are errors, positive values are used for special but normal events.
  22700. */
  22701. var Z_OK = 0;
  22702. var Z_STREAM_END = 1;
  22703. var Z_NEED_DICT = 2;
  22704. //var Z_ERRNO = -1;
  22705. var Z_STREAM_ERROR = -2;
  22706. var Z_DATA_ERROR = -3;
  22707. var Z_MEM_ERROR = -4;
  22708. var Z_BUF_ERROR = -5;
  22709. //var Z_VERSION_ERROR = -6;
  22710. /* The deflate compression method */
  22711. var Z_DEFLATED = 8;
  22712. /* STATES ====================================================================*/
  22713. /* ===========================================================================*/
  22714. var HEAD = 1; /* i: waiting for magic header */
  22715. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22716. var TIME = 3; /* i: waiting for modification time (gzip) */
  22717. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22718. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22719. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22720. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22721. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22722. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22723. var DICTID = 10; /* i: waiting for dictionary check value */
  22724. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22725. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22726. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22727. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22728. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22729. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22730. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22731. var LENLENS = 18; /* i: waiting for code length code lengths */
  22732. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22733. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22734. var LEN = 21; /* i: waiting for length/lit/eob code */
  22735. var LENEXT = 22; /* i: waiting for length extra bits */
  22736. var DIST = 23; /* i: waiting for distance code */
  22737. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22738. var MATCH = 25; /* o: waiting for output space to copy string */
  22739. var LIT = 26; /* o: waiting for output space to write literal */
  22740. var CHECK = 27; /* i: waiting for 32-bit check value */
  22741. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22742. var DONE = 29; /* finished check, done -- remain here until reset */
  22743. var BAD = 30; /* got a data error -- remain here until reset */
  22744. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22745. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22746. /* ===========================================================================*/
  22747. var ENOUGH_LENS = 852;
  22748. var ENOUGH_DISTS = 592;
  22749. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22750. var MAX_WBITS = 15;
  22751. /* 32K LZ77 window */
  22752. var DEF_WBITS = MAX_WBITS;
  22753. function ZSWAP32(q) {
  22754. return (((q >>> 24) & 0xff) +
  22755. ((q >>> 8) & 0xff00) +
  22756. ((q & 0xff00) << 8) +
  22757. ((q & 0xff) << 24));
  22758. }
  22759. function InflateState() {
  22760. this.mode = 0; /* current inflate mode */
  22761. this.last = false; /* true if processing last block */
  22762. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22763. this.havedict = false; /* true if dictionary provided */
  22764. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22765. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22766. this.check = 0; /* protected copy of check value */
  22767. this.total = 0; /* protected copy of output count */
  22768. // TODO: may be {}
  22769. this.head = null; /* where to save gzip header information */
  22770. /* sliding window */
  22771. this.wbits = 0; /* log base 2 of requested window size */
  22772. this.wsize = 0; /* window size or zero if not using window */
  22773. this.whave = 0; /* valid bytes in the window */
  22774. this.wnext = 0; /* window write index */
  22775. this.window = null; /* allocated sliding window, if needed */
  22776. /* bit accumulator */
  22777. this.hold = 0; /* input bit accumulator */
  22778. this.bits = 0; /* number of bits in "in" */
  22779. /* for string and stored block copying */
  22780. this.length = 0; /* literal or length of data to copy */
  22781. this.offset = 0; /* distance back to copy string from */
  22782. /* for table and code decoding */
  22783. this.extra = 0; /* extra bits needed */
  22784. /* fixed and dynamic code tables */
  22785. this.lencode = null; /* starting table for length/literal codes */
  22786. this.distcode = null; /* starting table for distance codes */
  22787. this.lenbits = 0; /* index bits for lencode */
  22788. this.distbits = 0; /* index bits for distcode */
  22789. /* dynamic table building */
  22790. this.ncode = 0; /* number of code length code lengths */
  22791. this.nlen = 0; /* number of length code lengths */
  22792. this.ndist = 0; /* number of distance code lengths */
  22793. this.have = 0; /* number of code lengths in lens[] */
  22794. this.next = null; /* next available space in codes[] */
  22795. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22796. this.work = new utils.Buf16(288); /* work area for code table building */
  22797. /*
  22798. because we don't have pointers in js, we use lencode and distcode directly
  22799. as buffers so we don't need codes
  22800. */
  22801. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22802. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22803. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22804. this.sane = 0; /* if false, allow invalid distance too far */
  22805. this.back = 0; /* bits back of last unprocessed length/lit */
  22806. this.was = 0; /* initial length of match */
  22807. }
  22808. function inflateResetKeep(strm) {
  22809. var state;
  22810. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22811. state = strm.state;
  22812. strm.total_in = strm.total_out = state.total = 0;
  22813. strm.msg = ''; /*Z_NULL*/
  22814. if (state.wrap) { /* to support ill-conceived Java test suite */
  22815. strm.adler = state.wrap & 1;
  22816. }
  22817. state.mode = HEAD;
  22818. state.last = 0;
  22819. state.havedict = 0;
  22820. state.dmax = 32768;
  22821. state.head = null/*Z_NULL*/;
  22822. state.hold = 0;
  22823. state.bits = 0;
  22824. //state.lencode = state.distcode = state.next = state.codes;
  22825. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22826. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22827. state.sane = 1;
  22828. state.back = -1;
  22829. //Tracev((stderr, "inflate: reset\n"));
  22830. return Z_OK;
  22831. }
  22832. function inflateReset(strm) {
  22833. var state;
  22834. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22835. state = strm.state;
  22836. state.wsize = 0;
  22837. state.whave = 0;
  22838. state.wnext = 0;
  22839. return inflateResetKeep(strm);
  22840. }
  22841. function inflateReset2(strm, windowBits) {
  22842. var wrap;
  22843. var state;
  22844. /* get the state */
  22845. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22846. state = strm.state;
  22847. /* extract wrap request from windowBits parameter */
  22848. if (windowBits < 0) {
  22849. wrap = 0;
  22850. windowBits = -windowBits;
  22851. }
  22852. else {
  22853. wrap = (windowBits >> 4) + 1;
  22854. if (windowBits < 48) {
  22855. windowBits &= 15;
  22856. }
  22857. }
  22858. /* set number of window bits, free window if different */
  22859. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22860. return Z_STREAM_ERROR;
  22861. }
  22862. if (state.window !== null && state.wbits !== windowBits) {
  22863. state.window = null;
  22864. }
  22865. /* update state and reset the rest of it */
  22866. state.wrap = wrap;
  22867. state.wbits = windowBits;
  22868. return inflateReset(strm);
  22869. }
  22870. function inflateInit2(strm, windowBits) {
  22871. var ret;
  22872. var state;
  22873. if (!strm) { return Z_STREAM_ERROR; }
  22874. //strm.msg = Z_NULL; /* in case we return an error */
  22875. state = new InflateState();
  22876. //if (state === Z_NULL) return Z_MEM_ERROR;
  22877. //Tracev((stderr, "inflate: allocated\n"));
  22878. strm.state = state;
  22879. state.window = null/*Z_NULL*/;
  22880. ret = inflateReset2(strm, windowBits);
  22881. if (ret !== Z_OK) {
  22882. strm.state = null/*Z_NULL*/;
  22883. }
  22884. return ret;
  22885. }
  22886. function inflateInit(strm) {
  22887. return inflateInit2(strm, DEF_WBITS);
  22888. }
  22889. /*
  22890. Return state with length and distance decoding tables and index sizes set to
  22891. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22892. If BUILDFIXED is defined, then instead this routine builds the tables the
  22893. first time it's called, and returns those tables the first time and
  22894. thereafter. This reduces the size of the code by about 2K bytes, in
  22895. exchange for a little execution time. However, BUILDFIXED should not be
  22896. used for threaded applications, since the rewriting of the tables and virgin
  22897. may not be thread-safe.
  22898. */
  22899. var virgin = true;
  22900. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22901. function fixedtables(state) {
  22902. /* build fixed huffman tables if first call (may not be thread safe) */
  22903. if (virgin) {
  22904. var sym;
  22905. lenfix = new utils.Buf32(512);
  22906. distfix = new utils.Buf32(32);
  22907. /* literal/length table */
  22908. sym = 0;
  22909. while (sym < 144) { state.lens[sym++] = 8; }
  22910. while (sym < 256) { state.lens[sym++] = 9; }
  22911. while (sym < 280) { state.lens[sym++] = 7; }
  22912. while (sym < 288) { state.lens[sym++] = 8; }
  22913. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22914. /* distance table */
  22915. sym = 0;
  22916. while (sym < 32) { state.lens[sym++] = 5; }
  22917. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22918. /* do this just once */
  22919. virgin = false;
  22920. }
  22921. state.lencode = lenfix;
  22922. state.lenbits = 9;
  22923. state.distcode = distfix;
  22924. state.distbits = 5;
  22925. }
  22926. /*
  22927. Update the window with the last wsize (normally 32K) bytes written before
  22928. returning. If window does not exist yet, create it. This is only called
  22929. when a window is already in use, or when output has been written during this
  22930. inflate call, but the end of the deflate stream has not been reached yet.
  22931. It is also called to create a window for dictionary data when a dictionary
  22932. is loaded.
  22933. Providing output buffers larger than 32K to inflate() should provide a speed
  22934. advantage, since only the last 32K of output is copied to the sliding window
  22935. upon return from inflate(), and since all distances after the first 32K of
  22936. output will fall in the output data, making match copies simpler and faster.
  22937. The advantage may be dependent on the size of the processor's data caches.
  22938. */
  22939. function updatewindow(strm, src, end, copy) {
  22940. var dist;
  22941. var state = strm.state;
  22942. /* if it hasn't been done already, allocate space for the window */
  22943. if (state.window === null) {
  22944. state.wsize = 1 << state.wbits;
  22945. state.wnext = 0;
  22946. state.whave = 0;
  22947. state.window = new utils.Buf8(state.wsize);
  22948. }
  22949. /* copy state->wsize or less output bytes into the circular window */
  22950. if (copy >= state.wsize) {
  22951. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22952. state.wnext = 0;
  22953. state.whave = state.wsize;
  22954. }
  22955. else {
  22956. dist = state.wsize - state.wnext;
  22957. if (dist > copy) {
  22958. dist = copy;
  22959. }
  22960. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22961. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22962. copy -= dist;
  22963. if (copy) {
  22964. //zmemcpy(state->window, end - copy, copy);
  22965. utils.arraySet(state.window,src, end - copy, copy, 0);
  22966. state.wnext = copy;
  22967. state.whave = state.wsize;
  22968. }
  22969. else {
  22970. state.wnext += dist;
  22971. if (state.wnext === state.wsize) { state.wnext = 0; }
  22972. if (state.whave < state.wsize) { state.whave += dist; }
  22973. }
  22974. }
  22975. return 0;
  22976. }
  22977. function inflate(strm, flush) {
  22978. var state;
  22979. var input, output; // input/output buffers
  22980. var next; /* next input INDEX */
  22981. var put; /* next output INDEX */
  22982. var have, left; /* available input and output */
  22983. var hold; /* bit buffer */
  22984. var bits; /* bits in bit buffer */
  22985. var _in, _out; /* save starting available input and output */
  22986. var copy; /* number of stored or match bytes to copy */
  22987. var from; /* where to copy match bytes from */
  22988. var from_source;
  22989. var here = 0; /* current decoding table entry */
  22990. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22991. //var last; /* parent table entry */
  22992. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22993. var len; /* length to copy for repeats, bits to drop */
  22994. var ret; /* return code */
  22995. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22996. var opts;
  22997. var n; // temporary var for NEED_BITS
  22998. var order = /* permutation of code lengths */
  22999. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  23000. if (!strm || !strm.state || !strm.output ||
  23001. (!strm.input && strm.avail_in !== 0)) {
  23002. return Z_STREAM_ERROR;
  23003. }
  23004. state = strm.state;
  23005. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  23006. //--- LOAD() ---
  23007. put = strm.next_out;
  23008. output = strm.output;
  23009. left = strm.avail_out;
  23010. next = strm.next_in;
  23011. input = strm.input;
  23012. have = strm.avail_in;
  23013. hold = state.hold;
  23014. bits = state.bits;
  23015. //---
  23016. _in = have;
  23017. _out = left;
  23018. ret = Z_OK;
  23019. inf_leave: // goto emulation
  23020. for (;;) {
  23021. switch (state.mode) {
  23022. case HEAD:
  23023. if (state.wrap === 0) {
  23024. state.mode = TYPEDO;
  23025. break;
  23026. }
  23027. //=== NEEDBITS(16);
  23028. while (bits < 16) {
  23029. if (have === 0) { break inf_leave; }
  23030. have--;
  23031. hold += input[next++] << bits;
  23032. bits += 8;
  23033. }
  23034. //===//
  23035. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  23036. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  23037. //=== CRC2(state.check, hold);
  23038. hbuf[0] = hold & 0xff;
  23039. hbuf[1] = (hold >>> 8) & 0xff;
  23040. state.check = crc32(state.check, hbuf, 2, 0);
  23041. //===//
  23042. //=== INITBITS();
  23043. hold = 0;
  23044. bits = 0;
  23045. //===//
  23046. state.mode = FLAGS;
  23047. break;
  23048. }
  23049. state.flags = 0; /* expect zlib header */
  23050. if (state.head) {
  23051. state.head.done = false;
  23052. }
  23053. if (!(state.wrap & 1) || /* check if zlib header allowed */
  23054. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  23055. strm.msg = 'incorrect header check';
  23056. state.mode = BAD;
  23057. break;
  23058. }
  23059. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  23060. strm.msg = 'unknown compression method';
  23061. state.mode = BAD;
  23062. break;
  23063. }
  23064. //--- DROPBITS(4) ---//
  23065. hold >>>= 4;
  23066. bits -= 4;
  23067. //---//
  23068. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  23069. if (state.wbits === 0) {
  23070. state.wbits = len;
  23071. }
  23072. else if (len > state.wbits) {
  23073. strm.msg = 'invalid window size';
  23074. state.mode = BAD;
  23075. break;
  23076. }
  23077. state.dmax = 1 << len;
  23078. //Tracev((stderr, "inflate: zlib header ok\n"));
  23079. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23080. state.mode = hold & 0x200 ? DICTID : TYPE;
  23081. //=== INITBITS();
  23082. hold = 0;
  23083. bits = 0;
  23084. //===//
  23085. break;
  23086. case FLAGS:
  23087. //=== NEEDBITS(16); */
  23088. while (bits < 16) {
  23089. if (have === 0) { break inf_leave; }
  23090. have--;
  23091. hold += input[next++] << bits;
  23092. bits += 8;
  23093. }
  23094. //===//
  23095. state.flags = hold;
  23096. if ((state.flags & 0xff) !== Z_DEFLATED) {
  23097. strm.msg = 'unknown compression method';
  23098. state.mode = BAD;
  23099. break;
  23100. }
  23101. if (state.flags & 0xe000) {
  23102. strm.msg = 'unknown header flags set';
  23103. state.mode = BAD;
  23104. break;
  23105. }
  23106. if (state.head) {
  23107. state.head.text = ((hold >> 8) & 1);
  23108. }
  23109. if (state.flags & 0x0200) {
  23110. //=== CRC2(state.check, hold);
  23111. hbuf[0] = hold & 0xff;
  23112. hbuf[1] = (hold >>> 8) & 0xff;
  23113. state.check = crc32(state.check, hbuf, 2, 0);
  23114. //===//
  23115. }
  23116. //=== INITBITS();
  23117. hold = 0;
  23118. bits = 0;
  23119. //===//
  23120. state.mode = TIME;
  23121. /* falls through */
  23122. case TIME:
  23123. //=== NEEDBITS(32); */
  23124. while (bits < 32) {
  23125. if (have === 0) { break inf_leave; }
  23126. have--;
  23127. hold += input[next++] << bits;
  23128. bits += 8;
  23129. }
  23130. //===//
  23131. if (state.head) {
  23132. state.head.time = hold;
  23133. }
  23134. if (state.flags & 0x0200) {
  23135. //=== CRC4(state.check, hold)
  23136. hbuf[0] = hold & 0xff;
  23137. hbuf[1] = (hold >>> 8) & 0xff;
  23138. hbuf[2] = (hold >>> 16) & 0xff;
  23139. hbuf[3] = (hold >>> 24) & 0xff;
  23140. state.check = crc32(state.check, hbuf, 4, 0);
  23141. //===
  23142. }
  23143. //=== INITBITS();
  23144. hold = 0;
  23145. bits = 0;
  23146. //===//
  23147. state.mode = OS;
  23148. /* falls through */
  23149. case OS:
  23150. //=== NEEDBITS(16); */
  23151. while (bits < 16) {
  23152. if (have === 0) { break inf_leave; }
  23153. have--;
  23154. hold += input[next++] << bits;
  23155. bits += 8;
  23156. }
  23157. //===//
  23158. if (state.head) {
  23159. state.head.xflags = (hold & 0xff);
  23160. state.head.os = (hold >> 8);
  23161. }
  23162. if (state.flags & 0x0200) {
  23163. //=== CRC2(state.check, hold);
  23164. hbuf[0] = hold & 0xff;
  23165. hbuf[1] = (hold >>> 8) & 0xff;
  23166. state.check = crc32(state.check, hbuf, 2, 0);
  23167. //===//
  23168. }
  23169. //=== INITBITS();
  23170. hold = 0;
  23171. bits = 0;
  23172. //===//
  23173. state.mode = EXLEN;
  23174. /* falls through */
  23175. case EXLEN:
  23176. if (state.flags & 0x0400) {
  23177. //=== NEEDBITS(16); */
  23178. while (bits < 16) {
  23179. if (have === 0) { break inf_leave; }
  23180. have--;
  23181. hold += input[next++] << bits;
  23182. bits += 8;
  23183. }
  23184. //===//
  23185. state.length = hold;
  23186. if (state.head) {
  23187. state.head.extra_len = hold;
  23188. }
  23189. if (state.flags & 0x0200) {
  23190. //=== CRC2(state.check, hold);
  23191. hbuf[0] = hold & 0xff;
  23192. hbuf[1] = (hold >>> 8) & 0xff;
  23193. state.check = crc32(state.check, hbuf, 2, 0);
  23194. //===//
  23195. }
  23196. //=== INITBITS();
  23197. hold = 0;
  23198. bits = 0;
  23199. //===//
  23200. }
  23201. else if (state.head) {
  23202. state.head.extra = null/*Z_NULL*/;
  23203. }
  23204. state.mode = EXTRA;
  23205. /* falls through */
  23206. case EXTRA:
  23207. if (state.flags & 0x0400) {
  23208. copy = state.length;
  23209. if (copy > have) { copy = have; }
  23210. if (copy) {
  23211. if (state.head) {
  23212. len = state.head.extra_len - state.length;
  23213. if (!state.head.extra) {
  23214. // Use untyped array for more conveniend processing later
  23215. state.head.extra = new Array(state.head.extra_len);
  23216. }
  23217. utils.arraySet(
  23218. state.head.extra,
  23219. input,
  23220. next,
  23221. // extra field is limited to 65536 bytes
  23222. // - no need for additional size check
  23223. copy,
  23224. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  23225. len
  23226. );
  23227. //zmemcpy(state.head.extra + len, next,
  23228. // len + copy > state.head.extra_max ?
  23229. // state.head.extra_max - len : copy);
  23230. }
  23231. if (state.flags & 0x0200) {
  23232. state.check = crc32(state.check, input, copy, next);
  23233. }
  23234. have -= copy;
  23235. next += copy;
  23236. state.length -= copy;
  23237. }
  23238. if (state.length) { break inf_leave; }
  23239. }
  23240. state.length = 0;
  23241. state.mode = NAME;
  23242. /* falls through */
  23243. case NAME:
  23244. if (state.flags & 0x0800) {
  23245. if (have === 0) { break inf_leave; }
  23246. copy = 0;
  23247. do {
  23248. // TODO: 2 or 1 bytes?
  23249. len = input[next + copy++];
  23250. /* use constant limit because in js we should not preallocate memory */
  23251. if (state.head && len &&
  23252. (state.length < 65536 /*state.head.name_max*/)) {
  23253. state.head.name += String.fromCharCode(len);
  23254. }
  23255. } while (len && copy < have);
  23256. if (state.flags & 0x0200) {
  23257. state.check = crc32(state.check, input, copy, next);
  23258. }
  23259. have -= copy;
  23260. next += copy;
  23261. if (len) { break inf_leave; }
  23262. }
  23263. else if (state.head) {
  23264. state.head.name = null;
  23265. }
  23266. state.length = 0;
  23267. state.mode = COMMENT;
  23268. /* falls through */
  23269. case COMMENT:
  23270. if (state.flags & 0x1000) {
  23271. if (have === 0) { break inf_leave; }
  23272. copy = 0;
  23273. do {
  23274. len = input[next + copy++];
  23275. /* use constant limit because in js we should not preallocate memory */
  23276. if (state.head && len &&
  23277. (state.length < 65536 /*state.head.comm_max*/)) {
  23278. state.head.comment += String.fromCharCode(len);
  23279. }
  23280. } while (len && copy < have);
  23281. if (state.flags & 0x0200) {
  23282. state.check = crc32(state.check, input, copy, next);
  23283. }
  23284. have -= copy;
  23285. next += copy;
  23286. if (len) { break inf_leave; }
  23287. }
  23288. else if (state.head) {
  23289. state.head.comment = null;
  23290. }
  23291. state.mode = HCRC;
  23292. /* falls through */
  23293. case HCRC:
  23294. if (state.flags & 0x0200) {
  23295. //=== NEEDBITS(16); */
  23296. while (bits < 16) {
  23297. if (have === 0) { break inf_leave; }
  23298. have--;
  23299. hold += input[next++] << bits;
  23300. bits += 8;
  23301. }
  23302. //===//
  23303. if (hold !== (state.check & 0xffff)) {
  23304. strm.msg = 'header crc mismatch';
  23305. state.mode = BAD;
  23306. break;
  23307. }
  23308. //=== INITBITS();
  23309. hold = 0;
  23310. bits = 0;
  23311. //===//
  23312. }
  23313. if (state.head) {
  23314. state.head.hcrc = ((state.flags >> 9) & 1);
  23315. state.head.done = true;
  23316. }
  23317. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23318. state.mode = TYPE;
  23319. break;
  23320. case DICTID:
  23321. //=== NEEDBITS(32); */
  23322. while (bits < 32) {
  23323. if (have === 0) { break inf_leave; }
  23324. have--;
  23325. hold += input[next++] << bits;
  23326. bits += 8;
  23327. }
  23328. //===//
  23329. strm.adler = state.check = ZSWAP32(hold);
  23330. //=== INITBITS();
  23331. hold = 0;
  23332. bits = 0;
  23333. //===//
  23334. state.mode = DICT;
  23335. /* falls through */
  23336. case DICT:
  23337. if (state.havedict === 0) {
  23338. //--- RESTORE() ---
  23339. strm.next_out = put;
  23340. strm.avail_out = left;
  23341. strm.next_in = next;
  23342. strm.avail_in = have;
  23343. state.hold = hold;
  23344. state.bits = bits;
  23345. //---
  23346. return Z_NEED_DICT;
  23347. }
  23348. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23349. state.mode = TYPE;
  23350. /* falls through */
  23351. case TYPE:
  23352. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23353. /* falls through */
  23354. case TYPEDO:
  23355. if (state.last) {
  23356. //--- BYTEBITS() ---//
  23357. hold >>>= bits & 7;
  23358. bits -= bits & 7;
  23359. //---//
  23360. state.mode = CHECK;
  23361. break;
  23362. }
  23363. //=== NEEDBITS(3); */
  23364. while (bits < 3) {
  23365. if (have === 0) { break inf_leave; }
  23366. have--;
  23367. hold += input[next++] << bits;
  23368. bits += 8;
  23369. }
  23370. //===//
  23371. state.last = (hold & 0x01)/*BITS(1)*/;
  23372. //--- DROPBITS(1) ---//
  23373. hold >>>= 1;
  23374. bits -= 1;
  23375. //---//
  23376. switch ((hold & 0x03)/*BITS(2)*/) {
  23377. case 0: /* stored block */
  23378. //Tracev((stderr, "inflate: stored block%s\n",
  23379. // state.last ? " (last)" : ""));
  23380. state.mode = STORED;
  23381. break;
  23382. case 1: /* fixed block */
  23383. fixedtables(state);
  23384. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23385. // state.last ? " (last)" : ""));
  23386. state.mode = LEN_; /* decode codes */
  23387. if (flush === Z_TREES) {
  23388. //--- DROPBITS(2) ---//
  23389. hold >>>= 2;
  23390. bits -= 2;
  23391. //---//
  23392. break inf_leave;
  23393. }
  23394. break;
  23395. case 2: /* dynamic block */
  23396. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23397. // state.last ? " (last)" : ""));
  23398. state.mode = TABLE;
  23399. break;
  23400. case 3:
  23401. strm.msg = 'invalid block type';
  23402. state.mode = BAD;
  23403. }
  23404. //--- DROPBITS(2) ---//
  23405. hold >>>= 2;
  23406. bits -= 2;
  23407. //---//
  23408. break;
  23409. case STORED:
  23410. //--- BYTEBITS() ---// /* go to byte boundary */
  23411. hold >>>= bits & 7;
  23412. bits -= bits & 7;
  23413. //---//
  23414. //=== NEEDBITS(32); */
  23415. while (bits < 32) {
  23416. if (have === 0) { break inf_leave; }
  23417. have--;
  23418. hold += input[next++] << bits;
  23419. bits += 8;
  23420. }
  23421. //===//
  23422. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23423. strm.msg = 'invalid stored block lengths';
  23424. state.mode = BAD;
  23425. break;
  23426. }
  23427. state.length = hold & 0xffff;
  23428. //Tracev((stderr, "inflate: stored length %u\n",
  23429. // state.length));
  23430. //=== INITBITS();
  23431. hold = 0;
  23432. bits = 0;
  23433. //===//
  23434. state.mode = COPY_;
  23435. if (flush === Z_TREES) { break inf_leave; }
  23436. /* falls through */
  23437. case COPY_:
  23438. state.mode = COPY;
  23439. /* falls through */
  23440. case COPY:
  23441. copy = state.length;
  23442. if (copy) {
  23443. if (copy > have) { copy = have; }
  23444. if (copy > left) { copy = left; }
  23445. if (copy === 0) { break inf_leave; }
  23446. //--- zmemcpy(put, next, copy); ---
  23447. utils.arraySet(output, input, next, copy, put);
  23448. //---//
  23449. have -= copy;
  23450. next += copy;
  23451. left -= copy;
  23452. put += copy;
  23453. state.length -= copy;
  23454. break;
  23455. }
  23456. //Tracev((stderr, "inflate: stored end\n"));
  23457. state.mode = TYPE;
  23458. break;
  23459. case TABLE:
  23460. //=== NEEDBITS(14); */
  23461. while (bits < 14) {
  23462. if (have === 0) { break inf_leave; }
  23463. have--;
  23464. hold += input[next++] << bits;
  23465. bits += 8;
  23466. }
  23467. //===//
  23468. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23469. //--- DROPBITS(5) ---//
  23470. hold >>>= 5;
  23471. bits -= 5;
  23472. //---//
  23473. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23474. //--- DROPBITS(5) ---//
  23475. hold >>>= 5;
  23476. bits -= 5;
  23477. //---//
  23478. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23479. //--- DROPBITS(4) ---//
  23480. hold >>>= 4;
  23481. bits -= 4;
  23482. //---//
  23483. //#ifndef PKZIP_BUG_WORKAROUND
  23484. if (state.nlen > 286 || state.ndist > 30) {
  23485. strm.msg = 'too many length or distance symbols';
  23486. state.mode = BAD;
  23487. break;
  23488. }
  23489. //#endif
  23490. //Tracev((stderr, "inflate: table sizes ok\n"));
  23491. state.have = 0;
  23492. state.mode = LENLENS;
  23493. /* falls through */
  23494. case LENLENS:
  23495. while (state.have < state.ncode) {
  23496. //=== NEEDBITS(3);
  23497. while (bits < 3) {
  23498. if (have === 0) { break inf_leave; }
  23499. have--;
  23500. hold += input[next++] << bits;
  23501. bits += 8;
  23502. }
  23503. //===//
  23504. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23505. //--- DROPBITS(3) ---//
  23506. hold >>>= 3;
  23507. bits -= 3;
  23508. //---//
  23509. }
  23510. while (state.have < 19) {
  23511. state.lens[order[state.have++]] = 0;
  23512. }
  23513. // We have separate tables & no pointers. 2 commented lines below not needed.
  23514. //state.next = state.codes;
  23515. //state.lencode = state.next;
  23516. // Switch to use dynamic table
  23517. state.lencode = state.lendyn;
  23518. state.lenbits = 7;
  23519. opts = {bits: state.lenbits};
  23520. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23521. state.lenbits = opts.bits;
  23522. if (ret) {
  23523. strm.msg = 'invalid code lengths set';
  23524. state.mode = BAD;
  23525. break;
  23526. }
  23527. //Tracev((stderr, "inflate: code lengths ok\n"));
  23528. state.have = 0;
  23529. state.mode = CODELENS;
  23530. /* falls through */
  23531. case CODELENS:
  23532. while (state.have < state.nlen + state.ndist) {
  23533. for (;;) {
  23534. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23535. here_bits = here >>> 24;
  23536. here_op = (here >>> 16) & 0xff;
  23537. here_val = here & 0xffff;
  23538. if ((here_bits) <= bits) { break; }
  23539. //--- PULLBYTE() ---//
  23540. if (have === 0) { break inf_leave; }
  23541. have--;
  23542. hold += input[next++] << bits;
  23543. bits += 8;
  23544. //---//
  23545. }
  23546. if (here_val < 16) {
  23547. //--- DROPBITS(here.bits) ---//
  23548. hold >>>= here_bits;
  23549. bits -= here_bits;
  23550. //---//
  23551. state.lens[state.have++] = here_val;
  23552. }
  23553. else {
  23554. if (here_val === 16) {
  23555. //=== NEEDBITS(here.bits + 2);
  23556. n = here_bits + 2;
  23557. while (bits < n) {
  23558. if (have === 0) { break inf_leave; }
  23559. have--;
  23560. hold += input[next++] << bits;
  23561. bits += 8;
  23562. }
  23563. //===//
  23564. //--- DROPBITS(here.bits) ---//
  23565. hold >>>= here_bits;
  23566. bits -= here_bits;
  23567. //---//
  23568. if (state.have === 0) {
  23569. strm.msg = 'invalid bit length repeat';
  23570. state.mode = BAD;
  23571. break;
  23572. }
  23573. len = state.lens[state.have - 1];
  23574. copy = 3 + (hold & 0x03);//BITS(2);
  23575. //--- DROPBITS(2) ---//
  23576. hold >>>= 2;
  23577. bits -= 2;
  23578. //---//
  23579. }
  23580. else if (here_val === 17) {
  23581. //=== NEEDBITS(here.bits + 3);
  23582. n = here_bits + 3;
  23583. while (bits < n) {
  23584. if (have === 0) { break inf_leave; }
  23585. have--;
  23586. hold += input[next++] << bits;
  23587. bits += 8;
  23588. }
  23589. //===//
  23590. //--- DROPBITS(here.bits) ---//
  23591. hold >>>= here_bits;
  23592. bits -= here_bits;
  23593. //---//
  23594. len = 0;
  23595. copy = 3 + (hold & 0x07);//BITS(3);
  23596. //--- DROPBITS(3) ---//
  23597. hold >>>= 3;
  23598. bits -= 3;
  23599. //---//
  23600. }
  23601. else {
  23602. //=== NEEDBITS(here.bits + 7);
  23603. n = here_bits + 7;
  23604. while (bits < n) {
  23605. if (have === 0) { break inf_leave; }
  23606. have--;
  23607. hold += input[next++] << bits;
  23608. bits += 8;
  23609. }
  23610. //===//
  23611. //--- DROPBITS(here.bits) ---//
  23612. hold >>>= here_bits;
  23613. bits -= here_bits;
  23614. //---//
  23615. len = 0;
  23616. copy = 11 + (hold & 0x7f);//BITS(7);
  23617. //--- DROPBITS(7) ---//
  23618. hold >>>= 7;
  23619. bits -= 7;
  23620. //---//
  23621. }
  23622. if (state.have + copy > state.nlen + state.ndist) {
  23623. strm.msg = 'invalid bit length repeat';
  23624. state.mode = BAD;
  23625. break;
  23626. }
  23627. while (copy--) {
  23628. state.lens[state.have++] = len;
  23629. }
  23630. }
  23631. }
  23632. /* handle error breaks in while */
  23633. if (state.mode === BAD) { break; }
  23634. /* check for end-of-block code (better have one) */
  23635. if (state.lens[256] === 0) {
  23636. strm.msg = 'invalid code -- missing end-of-block';
  23637. state.mode = BAD;
  23638. break;
  23639. }
  23640. /* build code tables -- note: do not change the lenbits or distbits
  23641. values here (9 and 6) without reading the comments in inftrees.h
  23642. concerning the ENOUGH constants, which depend on those values */
  23643. state.lenbits = 9;
  23644. opts = {bits: state.lenbits};
  23645. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23646. // We have separate tables & no pointers. 2 commented lines below not needed.
  23647. // state.next_index = opts.table_index;
  23648. state.lenbits = opts.bits;
  23649. // state.lencode = state.next;
  23650. if (ret) {
  23651. strm.msg = 'invalid literal/lengths set';
  23652. state.mode = BAD;
  23653. break;
  23654. }
  23655. state.distbits = 6;
  23656. //state.distcode.copy(state.codes);
  23657. // Switch to use dynamic table
  23658. state.distcode = state.distdyn;
  23659. opts = {bits: state.distbits};
  23660. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23661. // We have separate tables & no pointers. 2 commented lines below not needed.
  23662. // state.next_index = opts.table_index;
  23663. state.distbits = opts.bits;
  23664. // state.distcode = state.next;
  23665. if (ret) {
  23666. strm.msg = 'invalid distances set';
  23667. state.mode = BAD;
  23668. break;
  23669. }
  23670. //Tracev((stderr, 'inflate: codes ok\n'));
  23671. state.mode = LEN_;
  23672. if (flush === Z_TREES) { break inf_leave; }
  23673. /* falls through */
  23674. case LEN_:
  23675. state.mode = LEN;
  23676. /* falls through */
  23677. case LEN:
  23678. if (have >= 6 && left >= 258) {
  23679. //--- RESTORE() ---
  23680. strm.next_out = put;
  23681. strm.avail_out = left;
  23682. strm.next_in = next;
  23683. strm.avail_in = have;
  23684. state.hold = hold;
  23685. state.bits = bits;
  23686. //---
  23687. inflate_fast(strm, _out);
  23688. //--- LOAD() ---
  23689. put = strm.next_out;
  23690. output = strm.output;
  23691. left = strm.avail_out;
  23692. next = strm.next_in;
  23693. input = strm.input;
  23694. have = strm.avail_in;
  23695. hold = state.hold;
  23696. bits = state.bits;
  23697. //---
  23698. if (state.mode === TYPE) {
  23699. state.back = -1;
  23700. }
  23701. break;
  23702. }
  23703. state.back = 0;
  23704. for (;;) {
  23705. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23706. here_bits = here >>> 24;
  23707. here_op = (here >>> 16) & 0xff;
  23708. here_val = here & 0xffff;
  23709. if (here_bits <= bits) { break; }
  23710. //--- PULLBYTE() ---//
  23711. if (have === 0) { break inf_leave; }
  23712. have--;
  23713. hold += input[next++] << bits;
  23714. bits += 8;
  23715. //---//
  23716. }
  23717. if (here_op && (here_op & 0xf0) === 0) {
  23718. last_bits = here_bits;
  23719. last_op = here_op;
  23720. last_val = here_val;
  23721. for (;;) {
  23722. here = state.lencode[last_val +
  23723. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23724. here_bits = here >>> 24;
  23725. here_op = (here >>> 16) & 0xff;
  23726. here_val = here & 0xffff;
  23727. if ((last_bits + here_bits) <= bits) { break; }
  23728. //--- PULLBYTE() ---//
  23729. if (have === 0) { break inf_leave; }
  23730. have--;
  23731. hold += input[next++] << bits;
  23732. bits += 8;
  23733. //---//
  23734. }
  23735. //--- DROPBITS(last.bits) ---//
  23736. hold >>>= last_bits;
  23737. bits -= last_bits;
  23738. //---//
  23739. state.back += last_bits;
  23740. }
  23741. //--- DROPBITS(here.bits) ---//
  23742. hold >>>= here_bits;
  23743. bits -= here_bits;
  23744. //---//
  23745. state.back += here_bits;
  23746. state.length = here_val;
  23747. if (here_op === 0) {
  23748. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23749. // "inflate: literal '%c'\n" :
  23750. // "inflate: literal 0x%02x\n", here.val));
  23751. state.mode = LIT;
  23752. break;
  23753. }
  23754. if (here_op & 32) {
  23755. //Tracevv((stderr, "inflate: end of block\n"));
  23756. state.back = -1;
  23757. state.mode = TYPE;
  23758. break;
  23759. }
  23760. if (here_op & 64) {
  23761. strm.msg = 'invalid literal/length code';
  23762. state.mode = BAD;
  23763. break;
  23764. }
  23765. state.extra = here_op & 15;
  23766. state.mode = LENEXT;
  23767. /* falls through */
  23768. case LENEXT:
  23769. if (state.extra) {
  23770. //=== NEEDBITS(state.extra);
  23771. n = state.extra;
  23772. while (bits < n) {
  23773. if (have === 0) { break inf_leave; }
  23774. have--;
  23775. hold += input[next++] << bits;
  23776. bits += 8;
  23777. }
  23778. //===//
  23779. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23780. //--- DROPBITS(state.extra) ---//
  23781. hold >>>= state.extra;
  23782. bits -= state.extra;
  23783. //---//
  23784. state.back += state.extra;
  23785. }
  23786. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23787. state.was = state.length;
  23788. state.mode = DIST;
  23789. /* falls through */
  23790. case DIST:
  23791. for (;;) {
  23792. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23793. here_bits = here >>> 24;
  23794. here_op = (here >>> 16) & 0xff;
  23795. here_val = here & 0xffff;
  23796. if ((here_bits) <= bits) { break; }
  23797. //--- PULLBYTE() ---//
  23798. if (have === 0) { break inf_leave; }
  23799. have--;
  23800. hold += input[next++] << bits;
  23801. bits += 8;
  23802. //---//
  23803. }
  23804. if ((here_op & 0xf0) === 0) {
  23805. last_bits = here_bits;
  23806. last_op = here_op;
  23807. last_val = here_val;
  23808. for (;;) {
  23809. here = state.distcode[last_val +
  23810. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23811. here_bits = here >>> 24;
  23812. here_op = (here >>> 16) & 0xff;
  23813. here_val = here & 0xffff;
  23814. if ((last_bits + here_bits) <= bits) { break; }
  23815. //--- PULLBYTE() ---//
  23816. if (have === 0) { break inf_leave; }
  23817. have--;
  23818. hold += input[next++] << bits;
  23819. bits += 8;
  23820. //---//
  23821. }
  23822. //--- DROPBITS(last.bits) ---//
  23823. hold >>>= last_bits;
  23824. bits -= last_bits;
  23825. //---//
  23826. state.back += last_bits;
  23827. }
  23828. //--- DROPBITS(here.bits) ---//
  23829. hold >>>= here_bits;
  23830. bits -= here_bits;
  23831. //---//
  23832. state.back += here_bits;
  23833. if (here_op & 64) {
  23834. strm.msg = 'invalid distance code';
  23835. state.mode = BAD;
  23836. break;
  23837. }
  23838. state.offset = here_val;
  23839. state.extra = (here_op) & 15;
  23840. state.mode = DISTEXT;
  23841. /* falls through */
  23842. case DISTEXT:
  23843. if (state.extra) {
  23844. //=== NEEDBITS(state.extra);
  23845. n = state.extra;
  23846. while (bits < n) {
  23847. if (have === 0) { break inf_leave; }
  23848. have--;
  23849. hold += input[next++] << bits;
  23850. bits += 8;
  23851. }
  23852. //===//
  23853. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23854. //--- DROPBITS(state.extra) ---//
  23855. hold >>>= state.extra;
  23856. bits -= state.extra;
  23857. //---//
  23858. state.back += state.extra;
  23859. }
  23860. //#ifdef INFLATE_STRICT
  23861. if (state.offset > state.dmax) {
  23862. strm.msg = 'invalid distance too far back';
  23863. state.mode = BAD;
  23864. break;
  23865. }
  23866. //#endif
  23867. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23868. state.mode = MATCH;
  23869. /* falls through */
  23870. case MATCH:
  23871. if (left === 0) { break inf_leave; }
  23872. copy = _out - left;
  23873. if (state.offset > copy) { /* copy from window */
  23874. copy = state.offset - copy;
  23875. if (copy > state.whave) {
  23876. if (state.sane) {
  23877. strm.msg = 'invalid distance too far back';
  23878. state.mode = BAD;
  23879. break;
  23880. }
  23881. // (!) This block is disabled in zlib defailts,
  23882. // don't enable it for binary compatibility
  23883. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23884. // Trace((stderr, "inflate.c too far\n"));
  23885. // copy -= state.whave;
  23886. // if (copy > state.length) { copy = state.length; }
  23887. // if (copy > left) { copy = left; }
  23888. // left -= copy;
  23889. // state.length -= copy;
  23890. // do {
  23891. // output[put++] = 0;
  23892. // } while (--copy);
  23893. // if (state.length === 0) { state.mode = LEN; }
  23894. // break;
  23895. //#endif
  23896. }
  23897. if (copy > state.wnext) {
  23898. copy -= state.wnext;
  23899. from = state.wsize - copy;
  23900. }
  23901. else {
  23902. from = state.wnext - copy;
  23903. }
  23904. if (copy > state.length) { copy = state.length; }
  23905. from_source = state.window;
  23906. }
  23907. else { /* copy from output */
  23908. from_source = output;
  23909. from = put - state.offset;
  23910. copy = state.length;
  23911. }
  23912. if (copy > left) { copy = left; }
  23913. left -= copy;
  23914. state.length -= copy;
  23915. do {
  23916. output[put++] = from_source[from++];
  23917. } while (--copy);
  23918. if (state.length === 0) { state.mode = LEN; }
  23919. break;
  23920. case LIT:
  23921. if (left === 0) { break inf_leave; }
  23922. output[put++] = state.length;
  23923. left--;
  23924. state.mode = LEN;
  23925. break;
  23926. case CHECK:
  23927. if (state.wrap) {
  23928. //=== NEEDBITS(32);
  23929. while (bits < 32) {
  23930. if (have === 0) { break inf_leave; }
  23931. have--;
  23932. // Use '|' insdead of '+' to make sure that result is signed
  23933. hold |= input[next++] << bits;
  23934. bits += 8;
  23935. }
  23936. //===//
  23937. _out -= left;
  23938. strm.total_out += _out;
  23939. state.total += _out;
  23940. if (_out) {
  23941. strm.adler = state.check =
  23942. /*UPDATE(state.check, put - _out, _out);*/
  23943. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23944. }
  23945. _out = left;
  23946. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23947. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23948. strm.msg = 'incorrect data check';
  23949. state.mode = BAD;
  23950. break;
  23951. }
  23952. //=== INITBITS();
  23953. hold = 0;
  23954. bits = 0;
  23955. //===//
  23956. //Tracev((stderr, "inflate: check matches trailer\n"));
  23957. }
  23958. state.mode = LENGTH;
  23959. /* falls through */
  23960. case LENGTH:
  23961. if (state.wrap && state.flags) {
  23962. //=== NEEDBITS(32);
  23963. while (bits < 32) {
  23964. if (have === 0) { break inf_leave; }
  23965. have--;
  23966. hold += input[next++] << bits;
  23967. bits += 8;
  23968. }
  23969. //===//
  23970. if (hold !== (state.total & 0xffffffff)) {
  23971. strm.msg = 'incorrect length check';
  23972. state.mode = BAD;
  23973. break;
  23974. }
  23975. //=== INITBITS();
  23976. hold = 0;
  23977. bits = 0;
  23978. //===//
  23979. //Tracev((stderr, "inflate: length matches trailer\n"));
  23980. }
  23981. state.mode = DONE;
  23982. /* falls through */
  23983. case DONE:
  23984. ret = Z_STREAM_END;
  23985. break inf_leave;
  23986. case BAD:
  23987. ret = Z_DATA_ERROR;
  23988. break inf_leave;
  23989. case MEM:
  23990. return Z_MEM_ERROR;
  23991. case SYNC:
  23992. /* falls through */
  23993. default:
  23994. return Z_STREAM_ERROR;
  23995. }
  23996. }
  23997. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23998. /*
  23999. Return from inflate(), updating the total counts and the check value.
  24000. If there was no progress during the inflate() call, return a buffer
  24001. error. Call updatewindow() to create and/or update the window state.
  24002. Note: a memory error from inflate() is non-recoverable.
  24003. */
  24004. //--- RESTORE() ---
  24005. strm.next_out = put;
  24006. strm.avail_out = left;
  24007. strm.next_in = next;
  24008. strm.avail_in = have;
  24009. state.hold = hold;
  24010. state.bits = bits;
  24011. //---
  24012. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  24013. (state.mode < CHECK || flush !== Z_FINISH))) {
  24014. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  24015. state.mode = MEM;
  24016. return Z_MEM_ERROR;
  24017. }
  24018. }
  24019. _in -= strm.avail_in;
  24020. _out -= strm.avail_out;
  24021. strm.total_in += _in;
  24022. strm.total_out += _out;
  24023. state.total += _out;
  24024. if (state.wrap && _out) {
  24025. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  24026. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  24027. }
  24028. strm.data_type = state.bits + (state.last ? 64 : 0) +
  24029. (state.mode === TYPE ? 128 : 0) +
  24030. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  24031. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  24032. ret = Z_BUF_ERROR;
  24033. }
  24034. return ret;
  24035. }
  24036. function inflateEnd(strm) {
  24037. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  24038. return Z_STREAM_ERROR;
  24039. }
  24040. var state = strm.state;
  24041. if (state.window) {
  24042. state.window = null;
  24043. }
  24044. strm.state = null;
  24045. return Z_OK;
  24046. }
  24047. function inflateGetHeader(strm, head) {
  24048. var state;
  24049. /* check state */
  24050. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  24051. state = strm.state;
  24052. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  24053. /* save header structure */
  24054. state.head = head;
  24055. head.done = false;
  24056. return Z_OK;
  24057. }
  24058. exports.inflateReset = inflateReset;
  24059. exports.inflateReset2 = inflateReset2;
  24060. exports.inflateResetKeep = inflateResetKeep;
  24061. exports.inflateInit = inflateInit;
  24062. exports.inflateInit2 = inflateInit2;
  24063. exports.inflate = inflate;
  24064. exports.inflateEnd = inflateEnd;
  24065. exports.inflateGetHeader = inflateGetHeader;
  24066. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  24067. /* Not implemented
  24068. exports.inflateCopy = inflateCopy;
  24069. exports.inflateGetDictionary = inflateGetDictionary;
  24070. exports.inflateMark = inflateMark;
  24071. exports.inflatePrime = inflatePrime;
  24072. exports.inflateSetDictionary = inflateSetDictionary;
  24073. exports.inflateSync = inflateSync;
  24074. exports.inflateSyncPoint = inflateSyncPoint;
  24075. exports.inflateUndermine = inflateUndermine;
  24076. */
  24077. },{"../utils/common":75,"./adler32":77,"./crc32":79,"./inffast":82,"./inftrees":84}],84:[function(require,module,exports){
  24078. 'use strict';
  24079. var utils = require('../utils/common');
  24080. var MAXBITS = 15;
  24081. var ENOUGH_LENS = 852;
  24082. var ENOUGH_DISTS = 592;
  24083. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  24084. var CODES = 0;
  24085. var LENS = 1;
  24086. var DISTS = 2;
  24087. var lbase = [ /* Length codes 257..285 base */
  24088. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  24089. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  24090. ];
  24091. var lext = [ /* Length codes 257..285 extra */
  24092. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  24093. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  24094. ];
  24095. var dbase = [ /* Distance codes 0..29 base */
  24096. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  24097. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  24098. 8193, 12289, 16385, 24577, 0, 0
  24099. ];
  24100. var dext = [ /* Distance codes 0..29 extra */
  24101. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  24102. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  24103. 28, 28, 29, 29, 64, 64
  24104. ];
  24105. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  24106. {
  24107. var bits = opts.bits;
  24108. //here = opts.here; /* table entry for duplication */
  24109. var len = 0; /* a code's length in bits */
  24110. var sym = 0; /* index of code symbols */
  24111. var min = 0, max = 0; /* minimum and maximum code lengths */
  24112. var root = 0; /* number of index bits for root table */
  24113. var curr = 0; /* number of index bits for current table */
  24114. var drop = 0; /* code bits to drop for sub-table */
  24115. var left = 0; /* number of prefix codes available */
  24116. var used = 0; /* code entries in table used */
  24117. var huff = 0; /* Huffman code */
  24118. var incr; /* for incrementing code, index */
  24119. var fill; /* index for replicating entries */
  24120. var low; /* low bits for current root entry */
  24121. var mask; /* mask for low root bits */
  24122. var next; /* next available space in table */
  24123. var base = null; /* base value table to use */
  24124. var base_index = 0;
  24125. // var shoextra; /* extra bits table to use */
  24126. var end; /* use base and extra for symbol > end */
  24127. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  24128. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  24129. var extra = null;
  24130. var extra_index = 0;
  24131. var here_bits, here_op, here_val;
  24132. /*
  24133. Process a set of code lengths to create a canonical Huffman code. The
  24134. code lengths are lens[0..codes-1]. Each length corresponds to the
  24135. symbols 0..codes-1. The Huffman code is generated by first sorting the
  24136. symbols by length from short to long, and retaining the symbol order
  24137. for codes with equal lengths. Then the code starts with all zero bits
  24138. for the first code of the shortest length, and the codes are integer
  24139. increments for the same length, and zeros are appended as the length
  24140. increases. For the deflate format, these bits are stored backwards
  24141. from their more natural integer increment ordering, and so when the
  24142. decoding tables are built in the large loop below, the integer codes
  24143. are incremented backwards.
  24144. This routine assumes, but does not check, that all of the entries in
  24145. lens[] are in the range 0..MAXBITS. The caller must assure this.
  24146. 1..MAXBITS is interpreted as that code length. zero means that that
  24147. symbol does not occur in this code.
  24148. The codes are sorted by computing a count of codes for each length,
  24149. creating from that a table of starting indices for each length in the
  24150. sorted table, and then entering the symbols in order in the sorted
  24151. table. The sorted table is work[], with that space being provided by
  24152. the caller.
  24153. The length counts are used for other purposes as well, i.e. finding
  24154. the minimum and maximum length codes, determining if there are any
  24155. codes at all, checking for a valid set of lengths, and looking ahead
  24156. at length counts to determine sub-table sizes when building the
  24157. decoding tables.
  24158. */
  24159. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  24160. for (len = 0; len <= MAXBITS; len++) {
  24161. count[len] = 0;
  24162. }
  24163. for (sym = 0; sym < codes; sym++) {
  24164. count[lens[lens_index + sym]]++;
  24165. }
  24166. /* bound code lengths, force root to be within code lengths */
  24167. root = bits;
  24168. for (max = MAXBITS; max >= 1; max--) {
  24169. if (count[max] !== 0) { break; }
  24170. }
  24171. if (root > max) {
  24172. root = max;
  24173. }
  24174. if (max === 0) { /* no symbols to code at all */
  24175. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  24176. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  24177. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  24178. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24179. //table.op[opts.table_index] = 64;
  24180. //table.bits[opts.table_index] = 1;
  24181. //table.val[opts.table_index++] = 0;
  24182. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24183. opts.bits = 1;
  24184. return 0; /* no symbols, but wait for decoding to report error */
  24185. }
  24186. for (min = 1; min < max; min++) {
  24187. if (count[min] !== 0) { break; }
  24188. }
  24189. if (root < min) {
  24190. root = min;
  24191. }
  24192. /* check for an over-subscribed or incomplete set of lengths */
  24193. left = 1;
  24194. for (len = 1; len <= MAXBITS; len++) {
  24195. left <<= 1;
  24196. left -= count[len];
  24197. if (left < 0) {
  24198. return -1;
  24199. } /* over-subscribed */
  24200. }
  24201. if (left > 0 && (type === CODES || max !== 1)) {
  24202. return -1; /* incomplete set */
  24203. }
  24204. /* generate offsets into symbol table for each length for sorting */
  24205. offs[1] = 0;
  24206. for (len = 1; len < MAXBITS; len++) {
  24207. offs[len + 1] = offs[len] + count[len];
  24208. }
  24209. /* sort symbols by length, by symbol order within each length */
  24210. for (sym = 0; sym < codes; sym++) {
  24211. if (lens[lens_index + sym] !== 0) {
  24212. work[offs[lens[lens_index + sym]]++] = sym;
  24213. }
  24214. }
  24215. /*
  24216. Create and fill in decoding tables. In this loop, the table being
  24217. filled is at next and has curr index bits. The code being used is huff
  24218. with length len. That code is converted to an index by dropping drop
  24219. bits off of the bottom. For codes where len is less than drop + curr,
  24220. those top drop + curr - len bits are incremented through all values to
  24221. fill the table with replicated entries.
  24222. root is the number of index bits for the root table. When len exceeds
  24223. root, sub-tables are created pointed to by the root entry with an index
  24224. of the low root bits of huff. This is saved in low to check for when a
  24225. new sub-table should be started. drop is zero when the root table is
  24226. being filled, and drop is root when sub-tables are being filled.
  24227. When a new sub-table is needed, it is necessary to look ahead in the
  24228. code lengths to determine what size sub-table is needed. The length
  24229. counts are used for this, and so count[] is decremented as codes are
  24230. entered in the tables.
  24231. used keeps track of how many table entries have been allocated from the
  24232. provided *table space. It is checked for LENS and DIST tables against
  24233. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24234. the initial root table size constants. See the comments in inftrees.h
  24235. for more information.
  24236. sym increments through all symbols, and the loop terminates when
  24237. all codes of length max, i.e. all codes, have been processed. This
  24238. routine permits incomplete codes, so another loop after this one fills
  24239. in the rest of the decoding tables with invalid code markers.
  24240. */
  24241. /* set up for code type */
  24242. // poor man optimization - use if-else instead of switch,
  24243. // to avoid deopts in old v8
  24244. if (type === CODES) {
  24245. base = extra = work; /* dummy value--not used */
  24246. end = 19;
  24247. } else if (type === LENS) {
  24248. base = lbase;
  24249. base_index -= 257;
  24250. extra = lext;
  24251. extra_index -= 257;
  24252. end = 256;
  24253. } else { /* DISTS */
  24254. base = dbase;
  24255. extra = dext;
  24256. end = -1;
  24257. }
  24258. /* initialize opts for loop */
  24259. huff = 0; /* starting code */
  24260. sym = 0; /* starting code symbol */
  24261. len = min; /* starting code length */
  24262. next = table_index; /* current table to fill in */
  24263. curr = root; /* current table index bits */
  24264. drop = 0; /* current bits to drop from code for index */
  24265. low = -1; /* trigger new sub-table when len > root */
  24266. used = 1 << root; /* use root table entries */
  24267. mask = used - 1; /* mask for comparing low */
  24268. /* check available table space */
  24269. if ((type === LENS && used > ENOUGH_LENS) ||
  24270. (type === DISTS && used > ENOUGH_DISTS)) {
  24271. return 1;
  24272. }
  24273. var i=0;
  24274. /* process all codes and make table entries */
  24275. for (;;) {
  24276. i++;
  24277. /* create table entry */
  24278. here_bits = len - drop;
  24279. if (work[sym] < end) {
  24280. here_op = 0;
  24281. here_val = work[sym];
  24282. }
  24283. else if (work[sym] > end) {
  24284. here_op = extra[extra_index + work[sym]];
  24285. here_val = base[base_index + work[sym]];
  24286. }
  24287. else {
  24288. here_op = 32 + 64; /* end of block */
  24289. here_val = 0;
  24290. }
  24291. /* replicate for those indices with low len bits equal to huff */
  24292. incr = 1 << (len - drop);
  24293. fill = 1 << curr;
  24294. min = fill; /* save offset to next table */
  24295. do {
  24296. fill -= incr;
  24297. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24298. } while (fill !== 0);
  24299. /* backwards increment the len-bit code huff */
  24300. incr = 1 << (len - 1);
  24301. while (huff & incr) {
  24302. incr >>= 1;
  24303. }
  24304. if (incr !== 0) {
  24305. huff &= incr - 1;
  24306. huff += incr;
  24307. } else {
  24308. huff = 0;
  24309. }
  24310. /* go to next symbol, update count, len */
  24311. sym++;
  24312. if (--count[len] === 0) {
  24313. if (len === max) { break; }
  24314. len = lens[lens_index + work[sym]];
  24315. }
  24316. /* create new sub-table if needed */
  24317. if (len > root && (huff & mask) !== low) {
  24318. /* if first time, transition to sub-tables */
  24319. if (drop === 0) {
  24320. drop = root;
  24321. }
  24322. /* increment past last table */
  24323. next += min; /* here min is 1 << curr */
  24324. /* determine length of next table */
  24325. curr = len - drop;
  24326. left = 1 << curr;
  24327. while (curr + drop < max) {
  24328. left -= count[curr + drop];
  24329. if (left <= 0) { break; }
  24330. curr++;
  24331. left <<= 1;
  24332. }
  24333. /* check for enough space */
  24334. used += 1 << curr;
  24335. if ((type === LENS && used > ENOUGH_LENS) ||
  24336. (type === DISTS && used > ENOUGH_DISTS)) {
  24337. return 1;
  24338. }
  24339. /* point entry in root table to sub-table */
  24340. low = huff & mask;
  24341. /*table.op[low] = curr;
  24342. table.bits[low] = root;
  24343. table.val[low] = next - opts.table_index;*/
  24344. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24345. }
  24346. }
  24347. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24348. at most one remaining entry, since if the code is incomplete, the
  24349. maximum code length that was allowed to get this far is one bit) */
  24350. if (huff !== 0) {
  24351. //table.op[next + huff] = 64; /* invalid code marker */
  24352. //table.bits[next + huff] = len - drop;
  24353. //table.val[next + huff] = 0;
  24354. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24355. }
  24356. /* set return parameters */
  24357. //opts.table_index += used;
  24358. opts.bits = root;
  24359. return 0;
  24360. };
  24361. },{"../utils/common":75}],85:[function(require,module,exports){
  24362. 'use strict';
  24363. module.exports = {
  24364. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24365. '1': 'stream end', /* Z_STREAM_END 1 */
  24366. '0': '', /* Z_OK 0 */
  24367. '-1': 'file error', /* Z_ERRNO (-1) */
  24368. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24369. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24370. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24371. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24372. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24373. };
  24374. },{}],86:[function(require,module,exports){
  24375. 'use strict';
  24376. var utils = require('../utils/common');
  24377. /* Public constants ==========================================================*/
  24378. /* ===========================================================================*/
  24379. //var Z_FILTERED = 1;
  24380. //var Z_HUFFMAN_ONLY = 2;
  24381. //var Z_RLE = 3;
  24382. var Z_FIXED = 4;
  24383. //var Z_DEFAULT_STRATEGY = 0;
  24384. /* Possible values of the data_type field (though see inflate()) */
  24385. var Z_BINARY = 0;
  24386. var Z_TEXT = 1;
  24387. //var Z_ASCII = 1; // = Z_TEXT
  24388. var Z_UNKNOWN = 2;
  24389. /*============================================================================*/
  24390. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24391. // From zutil.h
  24392. var STORED_BLOCK = 0;
  24393. var STATIC_TREES = 1;
  24394. var DYN_TREES = 2;
  24395. /* The three kinds of block type */
  24396. var MIN_MATCH = 3;
  24397. var MAX_MATCH = 258;
  24398. /* The minimum and maximum match lengths */
  24399. // From deflate.h
  24400. /* ===========================================================================
  24401. * Internal compression state.
  24402. */
  24403. var LENGTH_CODES = 29;
  24404. /* number of length codes, not counting the special END_BLOCK code */
  24405. var LITERALS = 256;
  24406. /* number of literal bytes 0..255 */
  24407. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24408. /* number of Literal or Length codes, including the END_BLOCK code */
  24409. var D_CODES = 30;
  24410. /* number of distance codes */
  24411. var BL_CODES = 19;
  24412. /* number of codes used to transfer the bit lengths */
  24413. var HEAP_SIZE = 2*L_CODES + 1;
  24414. /* maximum heap size */
  24415. var MAX_BITS = 15;
  24416. /* All codes must not exceed MAX_BITS bits */
  24417. var Buf_size = 16;
  24418. /* size of bit buffer in bi_buf */
  24419. /* ===========================================================================
  24420. * Constants
  24421. */
  24422. var MAX_BL_BITS = 7;
  24423. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24424. var END_BLOCK = 256;
  24425. /* end of block literal code */
  24426. var REP_3_6 = 16;
  24427. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24428. var REPZ_3_10 = 17;
  24429. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24430. var REPZ_11_138 = 18;
  24431. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24432. var extra_lbits = /* extra bits for each length code */
  24433. [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];
  24434. var extra_dbits = /* extra bits for each distance code */
  24435. [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];
  24436. var extra_blbits = /* extra bits for each bit length code */
  24437. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24438. var bl_order =
  24439. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24440. /* The lengths of the bit length codes are sent in order of decreasing
  24441. * probability, to avoid transmitting the lengths for unused bit length codes.
  24442. */
  24443. /* ===========================================================================
  24444. * Local data. These are initialized only once.
  24445. */
  24446. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24447. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24448. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24449. var static_ltree = new Array((L_CODES+2) * 2);
  24450. zero(static_ltree);
  24451. /* The static literal tree. Since the bit lengths are imposed, there is no
  24452. * need for the L_CODES extra codes used during heap construction. However
  24453. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24454. * below).
  24455. */
  24456. var static_dtree = new Array(D_CODES * 2);
  24457. zero(static_dtree);
  24458. /* The static distance tree. (Actually a trivial tree since all codes use
  24459. * 5 bits.)
  24460. */
  24461. var _dist_code = new Array(DIST_CODE_LEN);
  24462. zero(_dist_code);
  24463. /* Distance codes. The first 256 values correspond to the distances
  24464. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24465. * the 15 bit distances.
  24466. */
  24467. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24468. zero(_length_code);
  24469. /* length code for each normalized match length (0 == MIN_MATCH) */
  24470. var base_length = new Array(LENGTH_CODES);
  24471. zero(base_length);
  24472. /* First normalized length for each code (0 = MIN_MATCH) */
  24473. var base_dist = new Array(D_CODES);
  24474. zero(base_dist);
  24475. /* First normalized distance for each code (0 = distance of 1) */
  24476. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24477. this.static_tree = static_tree; /* static tree or NULL */
  24478. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24479. this.extra_base = extra_base; /* base index for extra_bits */
  24480. this.elems = elems; /* max number of elements in the tree */
  24481. this.max_length = max_length; /* max bit length for the codes */
  24482. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24483. this.has_stree = static_tree && static_tree.length;
  24484. };
  24485. var static_l_desc;
  24486. var static_d_desc;
  24487. var static_bl_desc;
  24488. var TreeDesc = function(dyn_tree, stat_desc) {
  24489. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24490. this.max_code = 0; /* largest code with non zero frequency */
  24491. this.stat_desc = stat_desc; /* the corresponding static tree */
  24492. };
  24493. function d_code(dist) {
  24494. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24495. }
  24496. /* ===========================================================================
  24497. * Output a short LSB first on the stream.
  24498. * IN assertion: there is enough room in pendingBuf.
  24499. */
  24500. function put_short (s, w) {
  24501. // put_byte(s, (uch)((w) & 0xff));
  24502. // put_byte(s, (uch)((ush)(w) >> 8));
  24503. s.pending_buf[s.pending++] = (w) & 0xff;
  24504. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24505. }
  24506. /* ===========================================================================
  24507. * Send a value on a given number of bits.
  24508. * IN assertion: length <= 16 and value fits in length bits.
  24509. */
  24510. function send_bits(s, value, length) {
  24511. if (s.bi_valid > (Buf_size - length)) {
  24512. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24513. put_short(s, s.bi_buf);
  24514. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24515. s.bi_valid += length - Buf_size;
  24516. } else {
  24517. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24518. s.bi_valid += length;
  24519. }
  24520. }
  24521. function send_code(s, c, tree) {
  24522. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24523. }
  24524. /* ===========================================================================
  24525. * Reverse the first len bits of a code, using straightforward code (a faster
  24526. * method would use a table)
  24527. * IN assertion: 1 <= len <= 15
  24528. */
  24529. function bi_reverse(code, len) {
  24530. var res = 0;
  24531. do {
  24532. res |= code & 1;
  24533. code >>>= 1;
  24534. res <<= 1;
  24535. } while (--len > 0);
  24536. return res >>> 1;
  24537. }
  24538. /* ===========================================================================
  24539. * Flush the bit buffer, keeping at most 7 bits in it.
  24540. */
  24541. function bi_flush(s) {
  24542. if (s.bi_valid === 16) {
  24543. put_short(s, s.bi_buf);
  24544. s.bi_buf = 0;
  24545. s.bi_valid = 0;
  24546. } else if (s.bi_valid >= 8) {
  24547. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24548. s.bi_buf >>= 8;
  24549. s.bi_valid -= 8;
  24550. }
  24551. }
  24552. /* ===========================================================================
  24553. * Compute the optimal bit lengths for a tree and update the total bit length
  24554. * for the current block.
  24555. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24556. * above are the tree nodes sorted by increasing frequency.
  24557. * OUT assertions: the field len is set to the optimal bit length, the
  24558. * array bl_count contains the frequencies for each bit length.
  24559. * The length opt_len is updated; static_len is also updated if stree is
  24560. * not null.
  24561. */
  24562. function gen_bitlen(s, desc)
  24563. // deflate_state *s;
  24564. // tree_desc *desc; /* the tree descriptor */
  24565. {
  24566. var tree = desc.dyn_tree;
  24567. var max_code = desc.max_code;
  24568. var stree = desc.stat_desc.static_tree;
  24569. var has_stree = desc.stat_desc.has_stree;
  24570. var extra = desc.stat_desc.extra_bits;
  24571. var base = desc.stat_desc.extra_base;
  24572. var max_length = desc.stat_desc.max_length;
  24573. var h; /* heap index */
  24574. var n, m; /* iterate over the tree elements */
  24575. var bits; /* bit length */
  24576. var xbits; /* extra bits */
  24577. var f; /* frequency */
  24578. var overflow = 0; /* number of elements with bit length too large */
  24579. for (bits = 0; bits <= MAX_BITS; bits++) {
  24580. s.bl_count[bits] = 0;
  24581. }
  24582. /* In a first pass, compute the optimal bit lengths (which may
  24583. * overflow in the case of the bit length tree).
  24584. */
  24585. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24586. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24587. n = s.heap[h];
  24588. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24589. if (bits > max_length) {
  24590. bits = max_length;
  24591. overflow++;
  24592. }
  24593. tree[n*2 + 1]/*.Len*/ = bits;
  24594. /* We overwrite tree[n].Dad which is no longer needed */
  24595. if (n > max_code) { continue; } /* not a leaf node */
  24596. s.bl_count[bits]++;
  24597. xbits = 0;
  24598. if (n >= base) {
  24599. xbits = extra[n-base];
  24600. }
  24601. f = tree[n * 2]/*.Freq*/;
  24602. s.opt_len += f * (bits + xbits);
  24603. if (has_stree) {
  24604. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24605. }
  24606. }
  24607. if (overflow === 0) { return; }
  24608. // Trace((stderr,"\nbit length overflow\n"));
  24609. /* This happens for example on obj2 and pic of the Calgary corpus */
  24610. /* Find the first bit length which could increase: */
  24611. do {
  24612. bits = max_length-1;
  24613. while (s.bl_count[bits] === 0) { bits--; }
  24614. s.bl_count[bits]--; /* move one leaf down the tree */
  24615. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24616. s.bl_count[max_length]--;
  24617. /* The brother of the overflow item also moves one step up,
  24618. * but this does not affect bl_count[max_length]
  24619. */
  24620. overflow -= 2;
  24621. } while (overflow > 0);
  24622. /* Now recompute all bit lengths, scanning in increasing frequency.
  24623. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24624. * lengths instead of fixing only the wrong ones. This idea is taken
  24625. * from 'ar' written by Haruhiko Okumura.)
  24626. */
  24627. for (bits = max_length; bits !== 0; bits--) {
  24628. n = s.bl_count[bits];
  24629. while (n !== 0) {
  24630. m = s.heap[--h];
  24631. if (m > max_code) { continue; }
  24632. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24633. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24634. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24635. tree[m*2 + 1]/*.Len*/ = bits;
  24636. }
  24637. n--;
  24638. }
  24639. }
  24640. }
  24641. /* ===========================================================================
  24642. * Generate the codes for a given tree and bit counts (which need not be
  24643. * optimal).
  24644. * IN assertion: the array bl_count contains the bit length statistics for
  24645. * the given tree and the field len is set for all tree elements.
  24646. * OUT assertion: the field code is set for all tree elements of non
  24647. * zero code length.
  24648. */
  24649. function gen_codes(tree, max_code, bl_count)
  24650. // ct_data *tree; /* the tree to decorate */
  24651. // int max_code; /* largest code with non zero frequency */
  24652. // ushf *bl_count; /* number of codes at each bit length */
  24653. {
  24654. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24655. var code = 0; /* running code value */
  24656. var bits; /* bit index */
  24657. var n; /* code index */
  24658. /* The distribution counts are first used to generate the code values
  24659. * without bit reversal.
  24660. */
  24661. for (bits = 1; bits <= MAX_BITS; bits++) {
  24662. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24663. }
  24664. /* Check that the bit counts in bl_count are consistent. The last code
  24665. * must be all ones.
  24666. */
  24667. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24668. // "inconsistent bit counts");
  24669. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24670. for (n = 0; n <= max_code; n++) {
  24671. var len = tree[n*2 + 1]/*.Len*/;
  24672. if (len === 0) { continue; }
  24673. /* Now reverse the bits */
  24674. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24675. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24676. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24677. }
  24678. }
  24679. /* ===========================================================================
  24680. * Initialize the various 'constant' tables.
  24681. */
  24682. function tr_static_init() {
  24683. var n; /* iterates over tree elements */
  24684. var bits; /* bit counter */
  24685. var length; /* length value */
  24686. var code; /* code value */
  24687. var dist; /* distance index */
  24688. var bl_count = new Array(MAX_BITS+1);
  24689. /* number of codes at each bit length for an optimal tree */
  24690. // do check in _tr_init()
  24691. //if (static_init_done) return;
  24692. /* For some embedded targets, global variables are not initialized: */
  24693. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24694. static_l_desc.static_tree = static_ltree;
  24695. static_l_desc.extra_bits = extra_lbits;
  24696. static_d_desc.static_tree = static_dtree;
  24697. static_d_desc.extra_bits = extra_dbits;
  24698. static_bl_desc.extra_bits = extra_blbits;
  24699. #endif*/
  24700. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24701. length = 0;
  24702. for (code = 0; code < LENGTH_CODES-1; code++) {
  24703. base_length[code] = length;
  24704. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24705. _length_code[length++] = code;
  24706. }
  24707. }
  24708. //Assert (length == 256, "tr_static_init: length != 256");
  24709. /* Note that the length 255 (match length 258) can be represented
  24710. * in two different ways: code 284 + 5 bits or code 285, so we
  24711. * overwrite length_code[255] to use the best encoding:
  24712. */
  24713. _length_code[length-1] = code;
  24714. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24715. dist = 0;
  24716. for (code = 0 ; code < 16; code++) {
  24717. base_dist[code] = dist;
  24718. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24719. _dist_code[dist++] = code;
  24720. }
  24721. }
  24722. //Assert (dist == 256, "tr_static_init: dist != 256");
  24723. dist >>= 7; /* from now on, all distances are divided by 128 */
  24724. for (; code < D_CODES; code++) {
  24725. base_dist[code] = dist << 7;
  24726. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24727. _dist_code[256 + dist++] = code;
  24728. }
  24729. }
  24730. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24731. /* Construct the codes of the static literal tree */
  24732. for (bits = 0; bits <= MAX_BITS; bits++) {
  24733. bl_count[bits] = 0;
  24734. }
  24735. n = 0;
  24736. while (n <= 143) {
  24737. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24738. n++;
  24739. bl_count[8]++;
  24740. }
  24741. while (n <= 255) {
  24742. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24743. n++;
  24744. bl_count[9]++;
  24745. }
  24746. while (n <= 279) {
  24747. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24748. n++;
  24749. bl_count[7]++;
  24750. }
  24751. while (n <= 287) {
  24752. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24753. n++;
  24754. bl_count[8]++;
  24755. }
  24756. /* Codes 286 and 287 do not exist, but we must include them in the
  24757. * tree construction to get a canonical Huffman tree (longest code
  24758. * all ones)
  24759. */
  24760. gen_codes(static_ltree, L_CODES+1, bl_count);
  24761. /* The static distance tree is trivial: */
  24762. for (n = 0; n < D_CODES; n++) {
  24763. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24764. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24765. }
  24766. // Now data ready and we can init static trees
  24767. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24768. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24769. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24770. //static_init_done = true;
  24771. }
  24772. /* ===========================================================================
  24773. * Initialize a new block.
  24774. */
  24775. function init_block(s) {
  24776. var n; /* iterates over tree elements */
  24777. /* Initialize the trees. */
  24778. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24779. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24780. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24781. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24782. s.opt_len = s.static_len = 0;
  24783. s.last_lit = s.matches = 0;
  24784. }
  24785. /* ===========================================================================
  24786. * Flush the bit buffer and align the output on a byte boundary
  24787. */
  24788. function bi_windup(s)
  24789. {
  24790. if (s.bi_valid > 8) {
  24791. put_short(s, s.bi_buf);
  24792. } else if (s.bi_valid > 0) {
  24793. //put_byte(s, (Byte)s->bi_buf);
  24794. s.pending_buf[s.pending++] = s.bi_buf;
  24795. }
  24796. s.bi_buf = 0;
  24797. s.bi_valid = 0;
  24798. }
  24799. /* ===========================================================================
  24800. * Copy a stored block, storing first the length and its
  24801. * one's complement if requested.
  24802. */
  24803. function copy_block(s, buf, len, header)
  24804. //DeflateState *s;
  24805. //charf *buf; /* the input data */
  24806. //unsigned len; /* its length */
  24807. //int header; /* true if block header must be written */
  24808. {
  24809. bi_windup(s); /* align on byte boundary */
  24810. if (header) {
  24811. put_short(s, len);
  24812. put_short(s, ~len);
  24813. }
  24814. // while (len--) {
  24815. // put_byte(s, *buf++);
  24816. // }
  24817. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24818. s.pending += len;
  24819. }
  24820. /* ===========================================================================
  24821. * Compares to subtrees, using the tree depth as tie breaker when
  24822. * the subtrees have equal frequency. This minimizes the worst case length.
  24823. */
  24824. function smaller(tree, n, m, depth) {
  24825. var _n2 = n*2;
  24826. var _m2 = m*2;
  24827. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24828. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24829. }
  24830. /* ===========================================================================
  24831. * Restore the heap property by moving down the tree starting at node k,
  24832. * exchanging a node with the smallest of its two sons if necessary, stopping
  24833. * when the heap property is re-established (each father smaller than its
  24834. * two sons).
  24835. */
  24836. function pqdownheap(s, tree, k)
  24837. // deflate_state *s;
  24838. // ct_data *tree; /* the tree to restore */
  24839. // int k; /* node to move down */
  24840. {
  24841. var v = s.heap[k];
  24842. var j = k << 1; /* left son of k */
  24843. while (j <= s.heap_len) {
  24844. /* Set j to the smallest of the two sons: */
  24845. if (j < s.heap_len &&
  24846. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24847. j++;
  24848. }
  24849. /* Exit if v is smaller than both sons */
  24850. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24851. /* Exchange v with the smallest son */
  24852. s.heap[k] = s.heap[j];
  24853. k = j;
  24854. /* And continue down the tree, setting j to the left son of k */
  24855. j <<= 1;
  24856. }
  24857. s.heap[k] = v;
  24858. }
  24859. // inlined manually
  24860. // var SMALLEST = 1;
  24861. /* ===========================================================================
  24862. * Send the block data compressed using the given Huffman trees
  24863. */
  24864. function compress_block(s, ltree, dtree)
  24865. // deflate_state *s;
  24866. // const ct_data *ltree; /* literal tree */
  24867. // const ct_data *dtree; /* distance tree */
  24868. {
  24869. var dist; /* distance of matched string */
  24870. var lc; /* match length or unmatched char (if dist == 0) */
  24871. var lx = 0; /* running index in l_buf */
  24872. var code; /* the code to send */
  24873. var extra; /* number of extra bits to send */
  24874. if (s.last_lit !== 0) {
  24875. do {
  24876. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24877. lc = s.pending_buf[s.l_buf + lx];
  24878. lx++;
  24879. if (dist === 0) {
  24880. send_code(s, lc, ltree); /* send a literal byte */
  24881. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24882. } else {
  24883. /* Here, lc is the match length - MIN_MATCH */
  24884. code = _length_code[lc];
  24885. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24886. extra = extra_lbits[code];
  24887. if (extra !== 0) {
  24888. lc -= base_length[code];
  24889. send_bits(s, lc, extra); /* send the extra length bits */
  24890. }
  24891. dist--; /* dist is now the match distance - 1 */
  24892. code = d_code(dist);
  24893. //Assert (code < D_CODES, "bad d_code");
  24894. send_code(s, code, dtree); /* send the distance code */
  24895. extra = extra_dbits[code];
  24896. if (extra !== 0) {
  24897. dist -= base_dist[code];
  24898. send_bits(s, dist, extra); /* send the extra distance bits */
  24899. }
  24900. } /* literal or match pair ? */
  24901. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24902. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24903. // "pendingBuf overflow");
  24904. } while (lx < s.last_lit);
  24905. }
  24906. send_code(s, END_BLOCK, ltree);
  24907. }
  24908. /* ===========================================================================
  24909. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24910. * Update the total bit length for the current block.
  24911. * IN assertion: the field freq is set for all tree elements.
  24912. * OUT assertions: the fields len and code are set to the optimal bit length
  24913. * and corresponding code. The length opt_len is updated; static_len is
  24914. * also updated if stree is not null. The field max_code is set.
  24915. */
  24916. function build_tree(s, desc)
  24917. // deflate_state *s;
  24918. // tree_desc *desc; /* the tree descriptor */
  24919. {
  24920. var tree = desc.dyn_tree;
  24921. var stree = desc.stat_desc.static_tree;
  24922. var has_stree = desc.stat_desc.has_stree;
  24923. var elems = desc.stat_desc.elems;
  24924. var n, m; /* iterate over heap elements */
  24925. var max_code = -1; /* largest code with non zero frequency */
  24926. var node; /* new node being created */
  24927. /* Construct the initial heap, with least frequent element in
  24928. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24929. * heap[0] is not used.
  24930. */
  24931. s.heap_len = 0;
  24932. s.heap_max = HEAP_SIZE;
  24933. for (n = 0; n < elems; n++) {
  24934. if (tree[n * 2]/*.Freq*/ !== 0) {
  24935. s.heap[++s.heap_len] = max_code = n;
  24936. s.depth[n] = 0;
  24937. } else {
  24938. tree[n*2 + 1]/*.Len*/ = 0;
  24939. }
  24940. }
  24941. /* The pkzip format requires that at least one distance code exists,
  24942. * and that at least one bit should be sent even if there is only one
  24943. * possible code. So to avoid special checks later on we force at least
  24944. * two codes of non zero frequency.
  24945. */
  24946. while (s.heap_len < 2) {
  24947. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24948. tree[node * 2]/*.Freq*/ = 1;
  24949. s.depth[node] = 0;
  24950. s.opt_len--;
  24951. if (has_stree) {
  24952. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24953. }
  24954. /* node is 0 or 1 so it does not have extra bits */
  24955. }
  24956. desc.max_code = max_code;
  24957. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24958. * establish sub-heaps of increasing lengths:
  24959. */
  24960. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24961. /* Construct the Huffman tree by repeatedly combining the least two
  24962. * frequent nodes.
  24963. */
  24964. node = elems; /* next internal node of the tree */
  24965. do {
  24966. //pqremove(s, tree, n); /* n = node of least frequency */
  24967. /*** pqremove ***/
  24968. n = s.heap[1/*SMALLEST*/];
  24969. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24970. pqdownheap(s, tree, 1/*SMALLEST*/);
  24971. /***/
  24972. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24973. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24974. s.heap[--s.heap_max] = m;
  24975. /* Create a new node father of n and m */
  24976. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24977. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24978. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24979. /* and insert the new node in the heap */
  24980. s.heap[1/*SMALLEST*/] = node++;
  24981. pqdownheap(s, tree, 1/*SMALLEST*/);
  24982. } while (s.heap_len >= 2);
  24983. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24984. /* At this point, the fields freq and dad are set. We can now
  24985. * generate the bit lengths.
  24986. */
  24987. gen_bitlen(s, desc);
  24988. /* The field len is now set, we can generate the bit codes */
  24989. gen_codes(tree, max_code, s.bl_count);
  24990. }
  24991. /* ===========================================================================
  24992. * Scan a literal or distance tree to determine the frequencies of the codes
  24993. * in the bit length tree.
  24994. */
  24995. function scan_tree(s, tree, max_code)
  24996. // deflate_state *s;
  24997. // ct_data *tree; /* the tree to be scanned */
  24998. // int max_code; /* and its largest code of non zero frequency */
  24999. {
  25000. var n; /* iterates over all tree elements */
  25001. var prevlen = -1; /* last emitted length */
  25002. var curlen; /* length of current code */
  25003. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25004. var count = 0; /* repeat count of the current code */
  25005. var max_count = 7; /* max repeat count */
  25006. var min_count = 4; /* min repeat count */
  25007. if (nextlen === 0) {
  25008. max_count = 138;
  25009. min_count = 3;
  25010. }
  25011. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  25012. for (n = 0; n <= max_code; n++) {
  25013. curlen = nextlen;
  25014. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25015. if (++count < max_count && curlen === nextlen) {
  25016. continue;
  25017. } else if (count < min_count) {
  25018. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  25019. } else if (curlen !== 0) {
  25020. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  25021. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  25022. } else if (count <= 10) {
  25023. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  25024. } else {
  25025. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  25026. }
  25027. count = 0;
  25028. prevlen = curlen;
  25029. if (nextlen === 0) {
  25030. max_count = 138;
  25031. min_count = 3;
  25032. } else if (curlen === nextlen) {
  25033. max_count = 6;
  25034. min_count = 3;
  25035. } else {
  25036. max_count = 7;
  25037. min_count = 4;
  25038. }
  25039. }
  25040. }
  25041. /* ===========================================================================
  25042. * Send a literal or distance tree in compressed form, using the codes in
  25043. * bl_tree.
  25044. */
  25045. function send_tree(s, tree, max_code)
  25046. // deflate_state *s;
  25047. // ct_data *tree; /* the tree to be scanned */
  25048. // int max_code; /* and its largest code of non zero frequency */
  25049. {
  25050. var n; /* iterates over all tree elements */
  25051. var prevlen = -1; /* last emitted length */
  25052. var curlen; /* length of current code */
  25053. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25054. var count = 0; /* repeat count of the current code */
  25055. var max_count = 7; /* max repeat count */
  25056. var min_count = 4; /* min repeat count */
  25057. /* tree[max_code+1].Len = -1; */ /* guard already set */
  25058. if (nextlen === 0) {
  25059. max_count = 138;
  25060. min_count = 3;
  25061. }
  25062. for (n = 0; n <= max_code; n++) {
  25063. curlen = nextlen;
  25064. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25065. if (++count < max_count && curlen === nextlen) {
  25066. continue;
  25067. } else if (count < min_count) {
  25068. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  25069. } else if (curlen !== 0) {
  25070. if (curlen !== prevlen) {
  25071. send_code(s, curlen, s.bl_tree);
  25072. count--;
  25073. }
  25074. //Assert(count >= 3 && count <= 6, " 3_6?");
  25075. send_code(s, REP_3_6, s.bl_tree);
  25076. send_bits(s, count-3, 2);
  25077. } else if (count <= 10) {
  25078. send_code(s, REPZ_3_10, s.bl_tree);
  25079. send_bits(s, count-3, 3);
  25080. } else {
  25081. send_code(s, REPZ_11_138, s.bl_tree);
  25082. send_bits(s, count-11, 7);
  25083. }
  25084. count = 0;
  25085. prevlen = curlen;
  25086. if (nextlen === 0) {
  25087. max_count = 138;
  25088. min_count = 3;
  25089. } else if (curlen === nextlen) {
  25090. max_count = 6;
  25091. min_count = 3;
  25092. } else {
  25093. max_count = 7;
  25094. min_count = 4;
  25095. }
  25096. }
  25097. }
  25098. /* ===========================================================================
  25099. * Construct the Huffman tree for the bit lengths and return the index in
  25100. * bl_order of the last bit length code to send.
  25101. */
  25102. function build_bl_tree(s) {
  25103. var max_blindex; /* index of last bit length code of non zero freq */
  25104. /* Determine the bit length frequencies for literal and distance trees */
  25105. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  25106. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  25107. /* Build the bit length tree: */
  25108. build_tree(s, s.bl_desc);
  25109. /* opt_len now includes the length of the tree representations, except
  25110. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  25111. */
  25112. /* Determine the number of bit length codes to send. The pkzip format
  25113. * requires that at least 4 bit length codes be sent. (appnote.txt says
  25114. * 3 but the actual value used is 4.)
  25115. */
  25116. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  25117. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  25118. break;
  25119. }
  25120. }
  25121. /* Update opt_len to include the bit length tree and counts */
  25122. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  25123. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  25124. // s->opt_len, s->static_len));
  25125. return max_blindex;
  25126. }
  25127. /* ===========================================================================
  25128. * Send the header for a block using dynamic Huffman trees: the counts, the
  25129. * lengths of the bit length codes, the literal tree and the distance tree.
  25130. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  25131. */
  25132. function send_all_trees(s, lcodes, dcodes, blcodes)
  25133. // deflate_state *s;
  25134. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  25135. {
  25136. var rank; /* index in bl_order */
  25137. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  25138. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  25139. // "too many codes");
  25140. //Tracev((stderr, "\nbl counts: "));
  25141. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  25142. send_bits(s, dcodes-1, 5);
  25143. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  25144. for (rank = 0; rank < blcodes; rank++) {
  25145. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  25146. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  25147. }
  25148. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  25149. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  25150. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  25151. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  25152. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  25153. }
  25154. /* ===========================================================================
  25155. * Check if the data type is TEXT or BINARY, using the following algorithm:
  25156. * - TEXT if the two conditions below are satisfied:
  25157. * a) There are no non-portable control characters belonging to the
  25158. * "black list" (0..6, 14..25, 28..31).
  25159. * b) There is at least one printable character belonging to the
  25160. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  25161. * - BINARY otherwise.
  25162. * - The following partially-portable control characters form a
  25163. * "gray list" that is ignored in this detection algorithm:
  25164. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  25165. * IN assertion: the fields Freq of dyn_ltree are set.
  25166. */
  25167. function detect_data_type(s) {
  25168. /* black_mask is the bit mask of black-listed bytes
  25169. * set bits 0..6, 14..25, and 28..31
  25170. * 0xf3ffc07f = binary 11110011111111111100000001111111
  25171. */
  25172. var black_mask = 0xf3ffc07f;
  25173. var n;
  25174. /* Check for non-textual ("black-listed") bytes. */
  25175. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  25176. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  25177. return Z_BINARY;
  25178. }
  25179. }
  25180. /* Check for textual ("white-listed") bytes. */
  25181. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  25182. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  25183. return Z_TEXT;
  25184. }
  25185. for (n = 32; n < LITERALS; n++) {
  25186. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  25187. return Z_TEXT;
  25188. }
  25189. }
  25190. /* There are no "black-listed" or "white-listed" bytes:
  25191. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  25192. */
  25193. return Z_BINARY;
  25194. }
  25195. var static_init_done = false;
  25196. /* ===========================================================================
  25197. * Initialize the tree data structures for a new zlib stream.
  25198. */
  25199. function _tr_init(s)
  25200. {
  25201. if (!static_init_done) {
  25202. tr_static_init();
  25203. static_init_done = true;
  25204. }
  25205. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  25206. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  25207. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  25208. s.bi_buf = 0;
  25209. s.bi_valid = 0;
  25210. /* Initialize the first block of the first file: */
  25211. init_block(s);
  25212. }
  25213. /* ===========================================================================
  25214. * Send a stored block
  25215. */
  25216. function _tr_stored_block(s, buf, stored_len, last)
  25217. //DeflateState *s;
  25218. //charf *buf; /* input block */
  25219. //ulg stored_len; /* length of input block */
  25220. //int last; /* one if this is the last block for a file */
  25221. {
  25222. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  25223. copy_block(s, buf, stored_len, true); /* with header */
  25224. }
  25225. /* ===========================================================================
  25226. * Send one empty static block to give enough lookahead for inflate.
  25227. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25228. */
  25229. function _tr_align(s) {
  25230. send_bits(s, STATIC_TREES<<1, 3);
  25231. send_code(s, END_BLOCK, static_ltree);
  25232. bi_flush(s);
  25233. }
  25234. /* ===========================================================================
  25235. * Determine the best encoding for the current block: dynamic trees, static
  25236. * trees or store, and output the encoded block to the zip file.
  25237. */
  25238. function _tr_flush_block(s, buf, stored_len, last)
  25239. //DeflateState *s;
  25240. //charf *buf; /* input block, or NULL if too old */
  25241. //ulg stored_len; /* length of input block */
  25242. //int last; /* one if this is the last block for a file */
  25243. {
  25244. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25245. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25246. /* Build the Huffman trees unless a stored block is forced */
  25247. if (s.level > 0) {
  25248. /* Check if the file is binary or text */
  25249. if (s.strm.data_type === Z_UNKNOWN) {
  25250. s.strm.data_type = detect_data_type(s);
  25251. }
  25252. /* Construct the literal and distance trees */
  25253. build_tree(s, s.l_desc);
  25254. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25255. // s->static_len));
  25256. build_tree(s, s.d_desc);
  25257. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25258. // s->static_len));
  25259. /* At this point, opt_len and static_len are the total bit lengths of
  25260. * the compressed block data, excluding the tree representations.
  25261. */
  25262. /* Build the bit length tree for the above two trees, and get the index
  25263. * in bl_order of the last bit length code to send.
  25264. */
  25265. max_blindex = build_bl_tree(s);
  25266. /* Determine the best encoding. Compute the block lengths in bytes. */
  25267. opt_lenb = (s.opt_len+3+7) >>> 3;
  25268. static_lenb = (s.static_len+3+7) >>> 3;
  25269. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25270. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25271. // s->last_lit));
  25272. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25273. } else {
  25274. // Assert(buf != (char*)0, "lost buf");
  25275. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25276. }
  25277. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25278. /* 4: two words for the lengths */
  25279. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25280. * Otherwise we can't have processed more than WSIZE input bytes since
  25281. * the last block flush, because compression would have been
  25282. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25283. * transform a block into a stored block.
  25284. */
  25285. _tr_stored_block(s, buf, stored_len, last);
  25286. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25287. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25288. compress_block(s, static_ltree, static_dtree);
  25289. } else {
  25290. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25291. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25292. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25293. }
  25294. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25295. /* The above check is made mod 2^32, for files larger than 512 MB
  25296. * and uLong implemented on 32 bits.
  25297. */
  25298. init_block(s);
  25299. if (last) {
  25300. bi_windup(s);
  25301. }
  25302. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25303. // s->compressed_len-7*last));
  25304. }
  25305. /* ===========================================================================
  25306. * Save the match info and tally the frequency counts. Return true if
  25307. * the current block must be flushed.
  25308. */
  25309. function _tr_tally(s, dist, lc)
  25310. // deflate_state *s;
  25311. // unsigned dist; /* distance of matched string */
  25312. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25313. {
  25314. //var out_length, in_length, dcode;
  25315. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25316. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25317. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25318. s.last_lit++;
  25319. if (dist === 0) {
  25320. /* lc is the unmatched char */
  25321. s.dyn_ltree[lc*2]/*.Freq*/++;
  25322. } else {
  25323. s.matches++;
  25324. /* Here, lc is the match length - MIN_MATCH */
  25325. dist--; /* dist = match distance - 1 */
  25326. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25327. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25328. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25329. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25330. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25331. }
  25332. // (!) This block is disabled in zlib defailts,
  25333. // don't enable it for binary compatibility
  25334. //#ifdef TRUNCATE_BLOCK
  25335. // /* Try to guess if it is profitable to stop the current block here */
  25336. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25337. // /* Compute an upper bound for the compressed length */
  25338. // out_length = s.last_lit*8;
  25339. // in_length = s.strstart - s.block_start;
  25340. //
  25341. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25342. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25343. // }
  25344. // out_length >>>= 3;
  25345. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25346. // // s->last_lit, in_length, out_length,
  25347. // // 100L - out_length*100L/in_length));
  25348. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25349. // return true;
  25350. // }
  25351. // }
  25352. //#endif
  25353. return (s.last_lit === s.lit_bufsize-1);
  25354. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25355. * on 16 bit machines and because stored blocks are restricted to
  25356. * 64K-1 bytes.
  25357. */
  25358. }
  25359. exports._tr_init = _tr_init;
  25360. exports._tr_stored_block = _tr_stored_block;
  25361. exports._tr_flush_block = _tr_flush_block;
  25362. exports._tr_tally = _tr_tally;
  25363. exports._tr_align = _tr_align;
  25364. },{"../utils/common":75}],87:[function(require,module,exports){
  25365. 'use strict';
  25366. function ZStream() {
  25367. /* next input byte */
  25368. this.input = null; // JS specific, because we have no pointers
  25369. this.next_in = 0;
  25370. /* number of bytes available at input */
  25371. this.avail_in = 0;
  25372. /* total number of input bytes read so far */
  25373. this.total_in = 0;
  25374. /* next output byte should be put there */
  25375. this.output = null; // JS specific, because we have no pointers
  25376. this.next_out = 0;
  25377. /* remaining free space at output */
  25378. this.avail_out = 0;
  25379. /* total number of bytes output so far */
  25380. this.total_out = 0;
  25381. /* last error message, NULL if no error */
  25382. this.msg = ''/*Z_NULL*/;
  25383. /* not visible by applications */
  25384. this.state = null;
  25385. /* best guess about the data type: binary or text */
  25386. this.data_type = 2/*Z_UNKNOWN*/;
  25387. /* adler32 value of the uncompressed data */
  25388. this.adler = 0;
  25389. }
  25390. module.exports = ZStream;
  25391. },{}],88:[function(require,module,exports){
  25392. module.exports = require('./lib/retry');
  25393. },{"./lib/retry":89}],89:[function(require,module,exports){
  25394. var RetryOperation = require('./retry_operation');
  25395. exports.operation = function(options) {
  25396. var timeouts = exports.timeouts(options);
  25397. return new RetryOperation(timeouts);
  25398. };
  25399. exports.timeouts = function(options) {
  25400. if (options instanceof Array) {
  25401. return [].concat(options);
  25402. }
  25403. var opts = {
  25404. retries: 10,
  25405. factor: 2,
  25406. minTimeout: 1 * 1000,
  25407. maxTimeout: Infinity,
  25408. randomize: false
  25409. };
  25410. for (var key in options) {
  25411. opts[key] = options[key];
  25412. }
  25413. if (opts.minTimeout > opts.maxTimeout) {
  25414. throw new Error('minTimeout is greater than maxTimeout');
  25415. }
  25416. var timeouts = [];
  25417. for (var i = 0; i < opts.retries; i++) {
  25418. timeouts.push(this._createTimeout(i, opts));
  25419. }
  25420. // sort the array numerically ascending
  25421. timeouts.sort(function(a,b) {
  25422. return a - b;
  25423. });
  25424. return timeouts;
  25425. };
  25426. exports._createTimeout = function(attempt, opts) {
  25427. var random = (opts.randomize)
  25428. ? (Math.random() + 1)
  25429. : 1;
  25430. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25431. timeout = Math.min(timeout, opts.maxTimeout);
  25432. return timeout;
  25433. };
  25434. },{"./retry_operation":90}],90:[function(require,module,exports){
  25435. function RetryOperation(timeouts) {
  25436. this._timeouts = timeouts;
  25437. this._fn = null;
  25438. this._errors = [];
  25439. this._attempts = 1;
  25440. this._operationTimeout = null;
  25441. this._operationTimeoutCb = null;
  25442. this._timeout = null;
  25443. }
  25444. module.exports = RetryOperation;
  25445. RetryOperation.prototype.retry = function(err) {
  25446. if (this._timeout) {
  25447. clearTimeout(this._timeout);
  25448. }
  25449. if (!err) {
  25450. return false;
  25451. }
  25452. this._errors.push(err);
  25453. var timeout = this._timeouts.shift();
  25454. if (timeout === undefined) {
  25455. return false;
  25456. }
  25457. this._attempts++;
  25458. var self = this;
  25459. setTimeout(function() {
  25460. self._fn(self._attempts);
  25461. if (self._operationTimeoutCb) {
  25462. self._timeout = setTimeout(function() {
  25463. self._operationTimeoutCb(self._attempts);
  25464. }, self._operationTimeout);
  25465. }
  25466. }, timeout);
  25467. return true;
  25468. };
  25469. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25470. this._fn = fn;
  25471. if (timeoutOps) {
  25472. if (timeoutOps.timeout) {
  25473. this._operationTimeout = timeoutOps.timeout;
  25474. }
  25475. if (timeoutOps.cb) {
  25476. this._operationTimeoutCb = timeoutOps.cb;
  25477. }
  25478. }
  25479. this._fn(this._attempts);
  25480. var self = this;
  25481. if (this._operationTimeoutCb) {
  25482. this._timeout = setTimeout(function() {
  25483. self._operationTimeoutCb();
  25484. }, self._operationTimeout);
  25485. }
  25486. };
  25487. RetryOperation.prototype.try = function(fn) {
  25488. console.log('Using RetryOperation.try() is deprecated');
  25489. this.attempt(fn);
  25490. };
  25491. RetryOperation.prototype.start = function(fn) {
  25492. console.log('Using RetryOperation.start() is deprecated');
  25493. this.attempt(fn);
  25494. };
  25495. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25496. RetryOperation.prototype.errors = function() {
  25497. return this._errors;
  25498. };
  25499. RetryOperation.prototype.attempts = function() {
  25500. return this._attempts;
  25501. };
  25502. RetryOperation.prototype.mainError = function() {
  25503. if (this._errors.length === 0) {
  25504. return null;
  25505. }
  25506. var counts = {};
  25507. var mainError = null;
  25508. var mainErrorCount = 0;
  25509. for (var i = 0; i < this._errors.length; i++) {
  25510. var error = this._errors[i];
  25511. var message = error.message;
  25512. var count = (counts[message] || 0) + 1;
  25513. counts[message] = count;
  25514. if (count >= mainErrorCount) {
  25515. mainError = error;
  25516. mainErrorCount = count;
  25517. }
  25518. }
  25519. return mainError;
  25520. };
  25521. },{}],91:[function(require,module,exports){
  25522. module.exports = function arrayEquals(array) {
  25523. // if the other array is a falsy value, return
  25524. if (!array)
  25525. return false;
  25526. // compare lengths - can save a lot of time
  25527. if (this.length != array.length)
  25528. return false;
  25529. for (var i = 0, l = this.length; i < l; i++) {
  25530. // Check if we have nested arrays
  25531. if (this[i] instanceof Array && array[i] instanceof Array) {
  25532. // recurse into the nested arrays
  25533. if (!arrayEquals.apply(this[i], [array[i]]))
  25534. return false;
  25535. } else if (this[i] != array[i]) {
  25536. // Warning - two different object instances will never be equal:
  25537. // {x:20} != {x:20}
  25538. return false;
  25539. }
  25540. }
  25541. return true;
  25542. }
  25543. },{}],92:[function(require,module,exports){
  25544. exports.Interop = require('./interop');
  25545. },{"./interop":93}],93:[function(require,module,exports){
  25546. "use strict";
  25547. var transform = require('./transform');
  25548. var arrayEquals = require('./array-equals');
  25549. function Interop() {
  25550. /**
  25551. * This map holds the most recent Unified Plan offer/answer SDP that was
  25552. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25553. * the SDP string as values.
  25554. *
  25555. * @type {{}}
  25556. */
  25557. this.cache = {};
  25558. }
  25559. module.exports = Interop;
  25560. /**
  25561. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25562. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25563. * application.
  25564. *
  25565. * @param desc
  25566. * @returns {*}
  25567. */
  25568. Interop.prototype.toPlanB = function(desc) {
  25569. //#region Preliminary input validation.
  25570. if (typeof desc !== 'object' || desc === null ||
  25571. typeof desc.sdp !== 'string') {
  25572. console.warn('An empty description was passed as an argument.');
  25573. return desc;
  25574. }
  25575. // Objectify the SDP for easier manipulation.
  25576. var session = transform.parse(desc.sdp);
  25577. // If the SDP contains no media, there's nothing to transform.
  25578. if (typeof session.media === 'undefined' ||
  25579. !Array.isArray(session.media) || session.media.length === 0) {
  25580. console.warn('The description has no media.');
  25581. return desc;
  25582. }
  25583. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25584. // SDP has a video, an audio and a data "channel" at most.
  25585. if (session.media.length <= 3 && session.media.every(function(m) {
  25586. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25587. })) {
  25588. console.warn('This description does not look like Unified Plan.');
  25589. return desc;
  25590. }
  25591. //#endregion
  25592. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25593. // -> Unified Plan transformation.
  25594. this.cache[desc.type] = desc.sdp;
  25595. //#region Convert from Unified Plan to Plan B.
  25596. // We rebuild the session.media array.
  25597. var media = session.media;
  25598. session.media = [];
  25599. // Associative array that maps channel types to channel objects for fast
  25600. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25601. // obj.
  25602. var type2bl = {};
  25603. // Used to build the group:BUNDLE value after the channels construction
  25604. // loop.
  25605. var types = [];
  25606. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25607. media.forEach(function(unifiedLine) {
  25608. // rtcp-mux is required in the Plan B SDP.
  25609. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25610. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25611. unifiedLine.direction !== 'inactive') {
  25612. throw new Error('Cannot convert to Plan B because m-lines ' +
  25613. 'without the rtcp-mux attribute were found.');
  25614. }
  25615. if (unifiedLine.type === 'application') {
  25616. session.media.push(unifiedLine);
  25617. types.push(unifiedLine.mid);
  25618. return;
  25619. }
  25620. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25621. // as the channel basis.
  25622. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25623. type2bl[unifiedLine.type] = unifiedLine;
  25624. }
  25625. // Add sources to the channel and handle a=msid.
  25626. if (typeof unifiedLine.sources === 'object') {
  25627. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25628. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25629. type2bl[unifiedLine.type].sources = {};
  25630. // Assign the sources to the channel.
  25631. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25632. if (typeof unifiedLine.msid !== 'undefined') {
  25633. // In Plan B the msid is an SSRC attribute. Also, we don't
  25634. // care about the obsolete label and mslabel attributes.
  25635. //
  25636. // Note that it is not guaranteed that the unifiedLine will have
  25637. // an msid. recvonly channels in particular don't have one.
  25638. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25639. }
  25640. // NOTE ssrcs in ssrc groups will share msids, as
  25641. // draft-uberti-rtcweb-plan-00 mandates.
  25642. });
  25643. }
  25644. // Add ssrc groups to the channel.
  25645. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25646. Array.isArray(unifiedLine.ssrcGroups)) {
  25647. // Create the ssrcGroups array, if it's not defined.
  25648. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25649. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25650. type2bl[unifiedLine.type].ssrcGroups = [];
  25651. }
  25652. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25653. }
  25654. if (type2bl[unifiedLine.type] === unifiedLine) {
  25655. // Copy ICE related stuff from the principal media line.
  25656. unifiedLine.candidates = media[0].candidates;
  25657. unifiedLine.iceUfrag = media[0].iceUfrag;
  25658. unifiedLine.icePwd = media[0].icePwd;
  25659. unifiedLine.fingerprint = media[0].fingerprint;
  25660. // Plan B mids are in ['audio', 'video', 'data']
  25661. unifiedLine.mid = unifiedLine.type;
  25662. // Plan B doesn't support/need the bundle-only attribute.
  25663. delete unifiedLine.bundleOnly;
  25664. // In Plan B the msid is an SSRC attribute.
  25665. delete unifiedLine.msid;
  25666. // Used to build the group:BUNDLE value after this loop.
  25667. types.push(unifiedLine.type);
  25668. // Add the channel to the new media array.
  25669. session.media.push(unifiedLine);
  25670. }
  25671. });
  25672. // We regenerate the BUNDLE group with the new mids.
  25673. session.groups.some(function(group) {
  25674. if (group.type === 'BUNDLE') {
  25675. group.mids = types.join(' ');
  25676. return true;
  25677. }
  25678. });
  25679. // msid semantic
  25680. session.msidSemantic = {
  25681. semantic: 'WMS',
  25682. token: '*'
  25683. };
  25684. var resStr = transform.write(session);
  25685. return new RTCSessionDescription({
  25686. type: desc.type,
  25687. sdp: resStr
  25688. });
  25689. //#endregion
  25690. };
  25691. /**
  25692. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25693. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25694. * to FF.
  25695. *
  25696. * @param desc
  25697. * @returns {*}
  25698. */
  25699. Interop.prototype.toUnifiedPlan = function(desc) {
  25700. //#region Preliminary input validation.
  25701. if (typeof desc !== 'object' || desc === null ||
  25702. typeof desc.sdp !== 'string') {
  25703. console.warn('An empty description was passed as an argument.');
  25704. return desc;
  25705. }
  25706. var session = transform.parse(desc.sdp);
  25707. // If the SDP contains no media, there's nothing to transform.
  25708. if (typeof session.media === 'undefined' ||
  25709. !Array.isArray(session.media) || session.media.length === 0) {
  25710. console.warn('The description has no media.');
  25711. return desc;
  25712. }
  25713. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25714. // a video, an audio and a data "channel" at most.
  25715. if (session.media.length > 3 || !session.media.every(function(m) {
  25716. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25717. })) {
  25718. console.warn('This description does not look like Plan B.');
  25719. return desc;
  25720. }
  25721. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25722. var mids = [];
  25723. session.media.forEach(function(m) {
  25724. mids.push(m.mid);
  25725. });
  25726. var hasBundle = false;
  25727. if (typeof session.groups !== 'undefined' &&
  25728. Array.isArray(session.groups)) {
  25729. hasBundle = session.groups.every(function(g) {
  25730. return g.type !== 'BUNDLE' ||
  25731. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25732. });
  25733. }
  25734. if (!hasBundle) {
  25735. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25736. " are not bundled were found.");
  25737. }
  25738. //#endregion
  25739. //#region Convert from Plan B to Unified Plan.
  25740. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25741. // rebuild an equivalent Unified Plan offer/answer.
  25742. //
  25743. // For example, if this is a local answer (in Unified Plan style) that we
  25744. // convert to Plan B prior to handing it over to the application (the
  25745. // PeerConnection wrapper called us, for instance, after a successful
  25746. // createAnswer), we want to remember the m-line at which we've seen the
  25747. // (local) SSRC. That's because when the application wants to do call the
  25748. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25749. // Unified Plan), we need to know to which m-line to assign the (local)
  25750. // SSRC. We also need to know all the other m-lines that the original
  25751. // answer had and include them in the transformed answer as well.
  25752. //
  25753. // Another example is if this is a remote offer that we convert to Plan B
  25754. // prior to giving it to the application, we want to remember the mid at
  25755. // which we've seen the (remote) SSRC.
  25756. //
  25757. // In the iteration that follows, we use the cached Unified Plan (if it
  25758. // exists) to assign mids to ssrcs.
  25759. var cached;
  25760. if (typeof this.cache[desc.type] !== 'undefined') {
  25761. cached = transform.parse(this.cache[desc.type]);
  25762. }
  25763. // A helper map that sends mids to m-line objects. We use it later to
  25764. // rebuild the Unified Plan style session.media array.
  25765. var mid2ul = {};
  25766. session.media.forEach(function(bLine) {
  25767. if ((typeof bLine.rtcpMux !== 'string' ||
  25768. bLine.rtcpMux !== 'rtcp-mux') &&
  25769. bLine.direction !== 'inactive') {
  25770. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25771. "without the rtcp-mux attribute were found.");
  25772. }
  25773. if (bLine.type === 'application') {
  25774. mid2ul[bLine.mid] = bLine;
  25775. return;
  25776. }
  25777. // With rtcp-mux and bundle all the channels should have the same ICE
  25778. // stuff.
  25779. var sources = bLine.sources;
  25780. var ssrcGroups = bLine.ssrcGroups;
  25781. var candidates = bLine.candidates;
  25782. var iceUfrag = bLine.iceUfrag;
  25783. var icePwd = bLine.icePwd;
  25784. var fingerprint = bLine.fingerprint;
  25785. var port = bLine.port;
  25786. // We'll use the "bLine" object as a prototype for each new "mLine"
  25787. // that we create, but first we need to clean it up a bit.
  25788. delete bLine.sources;
  25789. delete bLine.ssrcGroups;
  25790. delete bLine.candidates;
  25791. delete bLine.iceUfrag;
  25792. delete bLine.icePwd;
  25793. delete bLine.fingerprint;
  25794. delete bLine.port;
  25795. delete bLine.mid;
  25796. // inverted ssrc group map
  25797. var ssrc2group = {};
  25798. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25799. ssrcGroups.forEach(function (ssrcGroup) {
  25800. // TODO(gp) find out how to receive simulcast with FF. For the
  25801. // time being, hide it.
  25802. if (ssrcGroup.semantics === 'SIM') {
  25803. return;
  25804. }
  25805. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25806. Array.isArray(ssrcGroup.ssrcs)) {
  25807. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25808. if (typeof ssrc2group[ssrc] === 'undefined') {
  25809. ssrc2group[ssrc] = [];
  25810. }
  25811. ssrc2group[ssrc].push(ssrcGroup);
  25812. });
  25813. }
  25814. });
  25815. }
  25816. // ssrc to m-line index.
  25817. var ssrc2ml = {};
  25818. if (typeof sources === 'object') {
  25819. // Explode the Plan B channel sources with one m-line per source.
  25820. Object.keys(sources).forEach(function(ssrc) {
  25821. // The (unified) m-line for this SSRC. We either create it from
  25822. // scratch or, if it's a grouped SSRC, we re-use a related
  25823. // mline. In other words, if the source is grouped with another
  25824. // source, put the two together in the same m-line.
  25825. var unifiedLine;
  25826. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25827. Array.isArray(ssrc2group[ssrc])) {
  25828. ssrc2group[ssrc].some(function (ssrcGroup) {
  25829. // ssrcGroup.ssrcs *is* an Array, no need to check
  25830. // again here.
  25831. return ssrcGroup.ssrcs.some(function (related) {
  25832. if (typeof ssrc2ml[related] === 'object') {
  25833. unifiedLine = ssrc2ml[related];
  25834. return true;
  25835. }
  25836. });
  25837. });
  25838. }
  25839. if (typeof unifiedLine === 'object') {
  25840. // the m-line already exists. Just add the source.
  25841. unifiedLine.sources[ssrc] = sources[ssrc];
  25842. delete sources[ssrc].msid;
  25843. } else {
  25844. // Use the "bLine" as a prototype for the "unifiedLine".
  25845. unifiedLine = Object.create(bLine);
  25846. ssrc2ml[ssrc] = unifiedLine;
  25847. if (typeof sources[ssrc].msid !== 'undefined') {
  25848. // Assign the msid of the source to the m-line. Note
  25849. // that it is not guaranteed that the source will have
  25850. // msid. In particular "recvonly" sources don't have an
  25851. // msid. Note that "recvonly" is a term only defined
  25852. // for m-lines.
  25853. unifiedLine.msid = sources[ssrc].msid;
  25854. delete sources[ssrc].msid;
  25855. }
  25856. // We assign one SSRC per media line.
  25857. unifiedLine.sources = {};
  25858. unifiedLine.sources[ssrc] = sources[ssrc];
  25859. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25860. // Use the cached Unified Plan SDP (if it exists) to assign
  25861. // SSRCs to mids.
  25862. if (typeof cached !== 'undefined' &&
  25863. typeof cached.media !== 'undefined' &&
  25864. Array.isArray(cached.media)) {
  25865. cached.media.forEach(function (m) {
  25866. if (typeof m.sources === 'object') {
  25867. Object.keys(m.sources).forEach(function (s) {
  25868. if (s === ssrc) {
  25869. unifiedLine.mid = m.mid;
  25870. }
  25871. });
  25872. }
  25873. });
  25874. }
  25875. if (typeof unifiedLine.mid === 'undefined') {
  25876. // If this is an SSRC that we see for the first time
  25877. // assign it a new mid. This is typically the case when
  25878. // this method is called to transform a remote
  25879. // description for the first time or when there is a
  25880. // new SSRC in the remote description because a new
  25881. // peer has joined the conference. Local SSRCs should
  25882. // have already been added to the map in the toPlanB
  25883. // method.
  25884. //
  25885. // Because FF generates answers in Unified Plan style,
  25886. // we MUST already have a cached answer with all the
  25887. // local SSRCs mapped to some m-line/mid.
  25888. if (desc.type === 'answer') {
  25889. throw new Error("An unmapped SSRC was found.");
  25890. }
  25891. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25892. }
  25893. // Include the candidates in the 1st media line.
  25894. unifiedLine.candidates = candidates;
  25895. unifiedLine.iceUfrag = iceUfrag;
  25896. unifiedLine.icePwd = icePwd;
  25897. unifiedLine.fingerprint = fingerprint;
  25898. unifiedLine.port = port;
  25899. mid2ul[unifiedLine.mid] = unifiedLine;
  25900. }
  25901. });
  25902. }
  25903. });
  25904. // Rebuild the media array in the right order and add the missing mLines
  25905. // (missing from the Plan B SDP).
  25906. session.media = [];
  25907. mids = []; // reuse
  25908. if (desc.type === 'answer') {
  25909. // The media lines in the answer must match the media lines in the
  25910. // offer. The order is important too. Here we assume that Firefox is the
  25911. // answerer, so we merely have to use the reconstructed (unified) answer
  25912. // to update the cached (unified) answer accordingly.
  25913. //
  25914. // In the general case, one would have to use the cached (unified) offer
  25915. // to find the m-lines that are missing from the reconstructed answer,
  25916. // potentially grabbing them from the cached (unified) answer. One has
  25917. // to be carefull with this approach because inactive m-lines do not
  25918. // always have an mid, making it tricky (impossible?) to find where
  25919. // exactly and which m-lines are missing from the reconstructed answer.
  25920. for (var i = 0; i < cached.media.length; i++) {
  25921. var unifiedLine = cached.media[i];
  25922. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25923. // The mid isn't in the reconstructed (unified) answer.
  25924. // This is either a (unified) m-line containing a remote
  25925. // track only, or a (unified) m-line containing a remote
  25926. // track and a local track that has been removed.
  25927. // In either case, it MUST exist in the cached
  25928. // (unified) answer.
  25929. //
  25930. // In case this is a removed local track, clean-up
  25931. // the (unified) m-line and make sure it's 'recvonly' or
  25932. // 'inactive'.
  25933. delete unifiedLine.msid;
  25934. delete unifiedLine.sources;
  25935. delete unifiedLine.ssrcGroups;
  25936. if (!unifiedLine.direction
  25937. || unifiedLine.direction === 'sendrecv')
  25938. unifiedLine.direction = 'recvonly';
  25939. if (!unifiedLine.direction
  25940. || unifiedLine.direction === 'sendonly')
  25941. unifiedLine.direction = 'inactive';
  25942. } else {
  25943. // This is an (unified) m-line/channel that contains a local
  25944. // track (sendrecv or sendonly channel) or it's a unified
  25945. // recvonly m-line/channel. In either case, since we're
  25946. // going from PlanB -> Unified Plan this m-line MUST
  25947. // exist in the cached answer.
  25948. }
  25949. session.media.push(unifiedLine);
  25950. if (typeof unifiedLine.mid === 'string') {
  25951. // inactive lines don't/may not have an mid.
  25952. mids.push(unifiedLine.mid);
  25953. }
  25954. }
  25955. } else {
  25956. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25957. // under any circumstances. If we are no longer interested in sending a
  25958. // track, we just remove the msid and ssrc attributes and set it to
  25959. // either a=recvonly (as the reofferer, we must use recvonly if the
  25960. // other side was previously sending on the m-section, but we can also
  25961. // leave the possibility open if it wasn't previously in use), or
  25962. // a=inacive.
  25963. if (typeof cached !== 'undefined' &&
  25964. typeof cached.media !== 'undefined' &&
  25965. Array.isArray(cached.media)) {
  25966. cached.media.forEach(function(unifiedLine) {
  25967. mids.push(unifiedLine.mid);
  25968. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25969. session.media.push(mid2ul[unifiedLine.mid]);
  25970. } else {
  25971. delete unifiedLine.msid;
  25972. delete unifiedLine.sources;
  25973. delete unifiedLine.ssrcGroups;
  25974. if (!unifiedLine.direction
  25975. || unifiedLine.direction === 'sendrecv')
  25976. unifiedLine.direction = 'recvonly';
  25977. if (!unifiedLine.direction
  25978. || unifiedLine.direction === 'sendonly')
  25979. unifiedLine.direction = 'inactive';
  25980. session.media.push(unifiedLine);
  25981. }
  25982. });
  25983. }
  25984. // Add all the remaining (new) m-lines of the transformed SDP.
  25985. Object.keys(mid2ul).forEach(function(mid) {
  25986. if (mids.indexOf(mid) === -1) {
  25987. mids.push(mid);
  25988. if (typeof mid2ul[mid].direction === 'recvonly') {
  25989. // This is a remote recvonly channel. Add its SSRC to the
  25990. // appropriate sendrecv or sendonly channel.
  25991. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25992. session.media.some(function (unifiedLine) {
  25993. if ((unifiedLine.direction === 'sendrecv' ||
  25994. unifiedLine.direction === 'sendonly') &&
  25995. unifiedLine.type === mid2ul[mid].type) {
  25996. // mid2ul[mid] shouldn't have any ssrc-groups
  25997. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25998. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25999. });
  26000. return true;
  26001. }
  26002. });
  26003. } else {
  26004. session.media.push(mid2ul[mid]);
  26005. }
  26006. }
  26007. });
  26008. }
  26009. // We regenerate the BUNDLE group (since we regenerated the mids)
  26010. session.groups.some(function(group) {
  26011. if (group.type === 'BUNDLE') {
  26012. group.mids = mids.join(' ');
  26013. return true;
  26014. }
  26015. });
  26016. // msid semantic
  26017. session.msidSemantic = {
  26018. semantic: 'WMS',
  26019. token: '*'
  26020. };
  26021. var resStr = transform.write(session);
  26022. // Cache the transformed SDP (Unified Plan) for later re-use in this
  26023. // function.
  26024. this.cache[desc.type] = resStr;
  26025. return new RTCSessionDescription({
  26026. type: desc.type,
  26027. sdp: resStr
  26028. });
  26029. //#endregion
  26030. };
  26031. },{"./array-equals":91,"./transform":94}],94:[function(require,module,exports){
  26032. var transform = require('sdp-transform');
  26033. exports.write = function(session, opts) {
  26034. if (typeof session !== 'undefined' &&
  26035. typeof session.media !== 'undefined' &&
  26036. Array.isArray(session.media)) {
  26037. session.media.forEach(function (mLine) {
  26038. // expand sources to ssrcs
  26039. if (typeof mLine.sources !== 'undefined' &&
  26040. Object.keys(mLine.sources).length !== 0) {
  26041. mLine.ssrcs = [];
  26042. Object.keys(mLine.sources).forEach(function (ssrc) {
  26043. var source = mLine.sources[ssrc];
  26044. Object.keys(source).forEach(function (attribute) {
  26045. mLine.ssrcs.push({
  26046. id: ssrc,
  26047. attribute: attribute,
  26048. value: source[attribute]
  26049. });
  26050. });
  26051. });
  26052. delete mLine.sources;
  26053. }
  26054. // join ssrcs in ssrc groups
  26055. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26056. Array.isArray(mLine.ssrcGroups)) {
  26057. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26058. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26059. Array.isArray(ssrcGroup.ssrcs)) {
  26060. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  26061. }
  26062. });
  26063. }
  26064. });
  26065. }
  26066. // join group mids
  26067. if (typeof session !== 'undefined' &&
  26068. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26069. session.groups.forEach(function (g) {
  26070. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  26071. g.mids = g.mids.join(' ');
  26072. }
  26073. });
  26074. }
  26075. return transform.write(session, opts);
  26076. };
  26077. exports.parse = function(sdp) {
  26078. var session = transform.parse(sdp);
  26079. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  26080. Array.isArray(session.media)) {
  26081. session.media.forEach(function (mLine) {
  26082. // group sources attributes by ssrc
  26083. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26084. mLine.sources = {};
  26085. mLine.ssrcs.forEach(function (ssrc) {
  26086. if (!mLine.sources[ssrc.id])
  26087. mLine.sources[ssrc.id] = {};
  26088. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26089. });
  26090. delete mLine.ssrcs;
  26091. }
  26092. // split ssrcs in ssrc groups
  26093. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26094. Array.isArray(mLine.ssrcGroups)) {
  26095. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26096. if (typeof ssrcGroup.ssrcs === 'string') {
  26097. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  26098. }
  26099. });
  26100. }
  26101. });
  26102. }
  26103. // split group mids
  26104. if (typeof session !== 'undefined' &&
  26105. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26106. session.groups.forEach(function (g) {
  26107. if (typeof g.mids === 'string') {
  26108. g.mids = g.mids.split(' ');
  26109. }
  26110. });
  26111. }
  26112. return session;
  26113. };
  26114. },{"sdp-transform":98}],95:[function(require,module,exports){
  26115. var transform = require('sdp-transform');
  26116. var transformUtils = require('./transform-utils');
  26117. var parseSsrcs = transformUtils.parseSsrcs;
  26118. var writeSsrcs = transformUtils.writeSsrcs;
  26119. //region Constants
  26120. var DEFAULT_NUM_OF_LAYERS = 3;
  26121. //endregion
  26122. //region Ctor
  26123. function Simulcast(options) {
  26124. this.options = options ? options : {};
  26125. if (!this.options.numOfLayers) {
  26126. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26127. }
  26128. this.layers = [];
  26129. }
  26130. //endregion
  26131. //region Stateless private utility functions
  26132. /**
  26133. * Returns a random integer between min (included) and max (excluded)
  26134. * Using Math.round() gives a non-uniform distribution!
  26135. * @returns {number}
  26136. */
  26137. function generateSSRC() {
  26138. var min = 0, max = 0xffffffff;
  26139. return Math.floor(Math.random() * (max - min)) + min;
  26140. };
  26141. function processVideo(session, action) {
  26142. if (session == null || !Array.isArray(session.media)) {
  26143. return;
  26144. }
  26145. session.media.forEach(function (mLine) {
  26146. if (mLine.type === 'video') {
  26147. action(mLine);
  26148. }
  26149. });
  26150. }
  26151. function validateDescription(desc)
  26152. {
  26153. return desc && desc != null
  26154. && desc.type && desc.type != ''
  26155. && desc.sdp && desc.sdp != '';
  26156. }
  26157. function explodeRemoteSimulcast(mLine) {
  26158. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26159. return;
  26160. }
  26161. var sources = parseSsrcs(mLine);
  26162. var order = [];
  26163. // Find the SIM group and explode its sources.
  26164. var j = mLine.ssrcGroups.length;
  26165. while (j--) {
  26166. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26167. continue;
  26168. }
  26169. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26170. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26171. var ssrc = simulcastSsrcs[i];
  26172. order.push(ssrc);
  26173. var parts = sources[ssrc].msid.split(' ');
  26174. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26175. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26176. // Remove all the groups that this SSRC participates in.
  26177. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26178. if (relatedGroup.semantics === 'SIM') {
  26179. return;
  26180. }
  26181. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26182. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26183. return;
  26184. }
  26185. // Nuke all the related SSRCs.
  26186. relatedSsrcs.forEach(function (relatedSSRC) {
  26187. sources[relatedSSRC].msid = sources[ssrc].msid;
  26188. sources[relatedSSRC].cname = sources[ssrc].cname;
  26189. if (relatedSSRC !== ssrc) {
  26190. order.push(relatedSSRC);
  26191. }
  26192. });
  26193. // Schedule the related group for nuking.
  26194. })
  26195. }
  26196. mLine.ssrcs = writeSsrcs(sources, order);
  26197. mLine.ssrcGroups.splice(j, 1);
  26198. };
  26199. }
  26200. function squeezeRemoteSimulcast(mLine) {
  26201. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26202. return;
  26203. }
  26204. var sources = parseSsrcs(mLine);
  26205. // Find the SIM group and nuke it.
  26206. mLine.ssrcGroups.some(function (simulcastGroup) {
  26207. if (simulcastGroup.semantics !== 'SIM') {
  26208. return false;
  26209. }
  26210. // Schedule the SIM group for nuking.
  26211. simulcastGroup.nuke = true;
  26212. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26213. // Nuke all the higher layer SSRCs.
  26214. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26215. var ssrc = simulcastSsrcs[i];
  26216. delete sources[ssrc];
  26217. // Remove all the groups that this SSRC participates in.
  26218. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26219. if (relatedGroup.semantics === 'SIM') {
  26220. return;
  26221. }
  26222. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26223. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26224. return;
  26225. }
  26226. // Nuke all the related SSRCs.
  26227. relatedSsrcs.forEach(function (relatedSSRC) {
  26228. delete sources[relatedSSRC];
  26229. });
  26230. // Schedule the related group for nuking.
  26231. relatedGroup.nuke = true;
  26232. })
  26233. }
  26234. return true;
  26235. });
  26236. mLine.ssrcs = writeSsrcs(sources);
  26237. // Nuke all the scheduled groups.
  26238. var i = mLine.ssrcGroups.length;
  26239. while (i--) {
  26240. if (mLine.ssrcGroups[i].nuke) {
  26241. mLine.ssrcGroups.splice(i, 1);
  26242. }
  26243. }
  26244. }
  26245. function removeGoogConference(mLine) {
  26246. if (!mLine || !Array.isArray(mLine.invalid)) {
  26247. return;
  26248. }
  26249. var i = mLine.invalid.length;
  26250. while (i--) {
  26251. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26252. mLine.invalid.splice(i, 1);
  26253. }
  26254. }
  26255. }
  26256. function assertGoogConference(mLine) {
  26257. if (!mLine) {
  26258. return;
  26259. }
  26260. if (!Array.isArray(mLine.invalid)) {
  26261. mLine.invalid = [];
  26262. }
  26263. if (!mLine.invalid.some(
  26264. function (i) { return i.value === 'x-google-flag:conference' })) {
  26265. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26266. }
  26267. }
  26268. //endregion
  26269. //region "Private" functions
  26270. /**
  26271. *
  26272. * @param mLine
  26273. * @private
  26274. */
  26275. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26276. if (!mLine || mLine.type !== 'video') {
  26277. return;
  26278. }
  26279. var sources = parseSsrcs(mLine);
  26280. if (Object.keys(sources).length === 0) {
  26281. // no sources, disable simulcast.
  26282. if (this.layers.length !== 0) {
  26283. this.layers = [];
  26284. }
  26285. return;
  26286. }
  26287. // find the base layer (we'll reuse its msid and cname).
  26288. var baseLayerSSRC = Object.keys(sources)[0];
  26289. var baseLayer = sources[baseLayerSSRC];
  26290. // todo(gp) handle screen sharing.
  26291. // check if base CNAME has changed and reinitialise layers.
  26292. if (this.layers.length > 0
  26293. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26294. this.layers = [];
  26295. }
  26296. // (re)initialise layers
  26297. if (this.layers.length < 1) {
  26298. // first push the base layer.
  26299. this.layers.push({
  26300. ssrc: baseLayerSSRC,
  26301. msid: baseLayer.msid,
  26302. cname: baseLayer.cname
  26303. });
  26304. var rtx = false; // RFC 4588
  26305. if (Array.isArray(mLine.rtp)) {
  26306. rtx = mLine.rtp.some(
  26307. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26308. }
  26309. if (rtx) {
  26310. this.layers[0].rtx = generateSSRC();
  26311. }
  26312. // now push additional layers.
  26313. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26314. var layer = { ssrc: generateSSRC() };
  26315. if (rtx) {
  26316. layer.rtx = generateSSRC();
  26317. }
  26318. this.layers.push(layer);
  26319. }
  26320. }
  26321. };
  26322. /**
  26323. *
  26324. * @param mLine
  26325. * @private
  26326. */
  26327. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26328. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26329. var sources = {};
  26330. var msid = this.layers[0].msid;
  26331. var cname = this.layers[0].cname;
  26332. var simulcastSsrcs = [];
  26333. var ssrcGroups = [];
  26334. for (var i = 0; i < this.layers.length; i++) {
  26335. var layer = this.layers[i];
  26336. sources[layer.ssrc] = { msid: msid, cname: cname };
  26337. simulcastSsrcs.push(layer.ssrc);
  26338. if (layer.rtx) {
  26339. sources[layer.rtx] = {
  26340. msid: msid,
  26341. cname: cname
  26342. }
  26343. ssrcGroups.push({
  26344. semantics: 'FID',
  26345. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26346. });
  26347. }
  26348. }
  26349. ssrcGroups.push({
  26350. semantics: 'SIM',
  26351. ssrcs: simulcastSsrcs.join(' ')
  26352. });
  26353. mLine.ssrcGroups = ssrcGroups;
  26354. mLine.ssrcs = writeSsrcs(sources);
  26355. }
  26356. }
  26357. //endregion
  26358. //region "Public" functions
  26359. Simulcast.prototype.isSupported = function () {
  26360. return window.chrome;
  26361. // TODO this needs improvements. For example I doubt that Chrome in Android
  26362. // has simulcast support. Also, only recent versions of Chromium have native
  26363. // simulcast support.
  26364. }
  26365. /**
  26366. *
  26367. * @param desc
  26368. * @returns {RTCSessionDescription}
  26369. */
  26370. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26371. if (!validateDescription(desc)) {
  26372. return desc;
  26373. }
  26374. var session = transform.parse(desc.sdp);
  26375. var self = this;
  26376. processVideo(session, function (mLine) {
  26377. // Handle simulcast reception.
  26378. if (self.options.explodeRemoteSimulcast) {
  26379. explodeRemoteSimulcast(mLine);
  26380. } else {
  26381. squeezeRemoteSimulcast(mLine);
  26382. }
  26383. // If native simulcast is enabled, we must append the x-goog-conference
  26384. // attribute to the SDP.
  26385. if (self.layers.length < 1) {
  26386. removeGoogConference(mLine);
  26387. } else {
  26388. assertGoogConference(mLine);
  26389. }
  26390. });
  26391. return new RTCSessionDescription({
  26392. type: desc.type,
  26393. sdp: transform.write(session)
  26394. });
  26395. };
  26396. /**
  26397. *
  26398. * @param desc
  26399. * @returns {RTCSessionDescription}
  26400. */
  26401. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26402. if (!validateDescription(desc) || !this.isSupported()) {
  26403. return desc;
  26404. }
  26405. var session = transform.parse(desc.sdp);
  26406. var self = this;
  26407. processVideo(session, function (mLine) {
  26408. // Initialize native simulcast layers, if not already done.
  26409. self._maybeInitializeLayers(mLine);
  26410. // Update the SDP with the simulcast layers.
  26411. self._restoreSimulcastView(mLine);
  26412. });
  26413. return new RTCSessionDescription({
  26414. type: desc.type,
  26415. sdp: transform.write(session)
  26416. });
  26417. };
  26418. //endregion
  26419. module.exports = Simulcast;
  26420. },{"./transform-utils":96,"sdp-transform":98}],96:[function(require,module,exports){
  26421. exports.writeSsrcs = function(sources, order) {
  26422. var ssrcs = [];
  26423. // expand sources to ssrcs
  26424. if (typeof sources !== 'undefined' &&
  26425. Object.keys(sources).length !== 0) {
  26426. if (Array.isArray(order)) {
  26427. for (var i = 0; i < order.length; i++) {
  26428. var ssrc = order[i];
  26429. var source = sources[ssrc];
  26430. Object.keys(source).forEach(function (attribute) {
  26431. ssrcs.push({
  26432. id: ssrc,
  26433. attribute: attribute,
  26434. value: source[attribute]
  26435. });
  26436. });
  26437. }
  26438. } else {
  26439. Object.keys(sources).forEach(function (ssrc) {
  26440. var source = sources[ssrc];
  26441. Object.keys(source).forEach(function (attribute) {
  26442. ssrcs.push({
  26443. id: ssrc,
  26444. attribute: attribute,
  26445. value: source[attribute]
  26446. });
  26447. });
  26448. });
  26449. }
  26450. }
  26451. return ssrcs;
  26452. };
  26453. exports.parseSsrcs = function (mLine) {
  26454. var sources = {};
  26455. // group sources attributes by ssrc.
  26456. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26457. mLine.ssrcs.forEach(function (ssrc) {
  26458. if (!sources[ssrc.id])
  26459. sources[ssrc.id] = {};
  26460. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26461. });
  26462. }
  26463. return sources;
  26464. };
  26465. },{}],97:[function(require,module,exports){
  26466. var grammar = module.exports = {
  26467. v: [{
  26468. name: 'version',
  26469. reg: /^(\d*)$/
  26470. }],
  26471. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26472. // NB: sessionId will be a String in most cases because it is huge
  26473. name: 'origin',
  26474. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26475. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26476. format: "%s %s %d %s IP%d %s"
  26477. }],
  26478. // default parsing of these only (though some of these feel outdated)
  26479. s: [{ name: 'name' }],
  26480. i: [{ name: 'description' }],
  26481. u: [{ name: 'uri' }],
  26482. e: [{ name: 'email' }],
  26483. p: [{ name: 'phone' }],
  26484. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26485. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26486. //k: [{}], // outdated thing ignored
  26487. t: [{ //t=0 0
  26488. name: 'timing',
  26489. reg: /^(\d*) (\d*)/,
  26490. names: ['start', 'stop'],
  26491. format: "%d %d"
  26492. }],
  26493. c: [{ //c=IN IP4 10.47.197.26
  26494. name: 'connection',
  26495. reg: /^IN IP(\d) (\S*)/,
  26496. names: ['version', 'ip'],
  26497. format: "IN IP%d %s"
  26498. }],
  26499. b: [{ //b=AS:4000
  26500. push: 'bandwidth',
  26501. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26502. names: ['type', 'limit'],
  26503. format: "%s:%s"
  26504. }],
  26505. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26506. // NB: special - pushes to session
  26507. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26508. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26509. names: ['type', 'port', 'protocol', 'payloads'],
  26510. format: "%s %d %s %s"
  26511. }],
  26512. a: [
  26513. { //a=rtpmap:110 opus/48000/2
  26514. push: 'rtp',
  26515. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26516. names: ['payload', 'codec', 'rate', 'encoding'],
  26517. format: function (o) {
  26518. return (o.encoding) ?
  26519. "rtpmap:%d %s/%s/%s":
  26520. "rtpmap:%d %s/%s";
  26521. }
  26522. },
  26523. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26524. push: 'fmtp',
  26525. reg: /^fmtp:(\d*) (\S*)/,
  26526. names: ['payload', 'config'],
  26527. format: "fmtp:%d %s"
  26528. },
  26529. { //a=control:streamid=0
  26530. name: 'control',
  26531. reg: /^control:(.*)/,
  26532. format: "control:%s"
  26533. },
  26534. { //a=rtcp:65179 IN IP4 193.84.77.194
  26535. name: 'rtcp',
  26536. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26537. names: ['port', 'netType', 'ipVer', 'address'],
  26538. format: function (o) {
  26539. return (o.address != null) ?
  26540. "rtcp:%d %s IP%d %s":
  26541. "rtcp:%d";
  26542. }
  26543. },
  26544. { //a=rtcp-fb:98 trr-int 100
  26545. push: 'rtcpFbTrrInt',
  26546. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26547. names: ['payload', 'value'],
  26548. format: "rtcp-fb:%d trr-int %d"
  26549. },
  26550. { //a=rtcp-fb:98 nack rpsi
  26551. push: 'rtcpFb',
  26552. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26553. names: ['payload', 'type', 'subtype'],
  26554. format: function (o) {
  26555. return (o.subtype != null) ?
  26556. "rtcp-fb:%s %s %s":
  26557. "rtcp-fb:%s %s";
  26558. }
  26559. },
  26560. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26561. //a=extmap:1/recvonly URI-gps-string
  26562. push: 'ext',
  26563. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26564. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26565. format: function (o) {
  26566. return (o.config != null) ?
  26567. "extmap:%s %s %s":
  26568. "extmap:%s %s";
  26569. }
  26570. },
  26571. {
  26572. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26573. push: 'crypto',
  26574. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26575. names: ['id', 'suite', 'config', 'sessionConfig'],
  26576. format: function (o) {
  26577. return (o.sessionConfig != null) ?
  26578. "crypto:%d %s %s %s":
  26579. "crypto:%d %s %s";
  26580. }
  26581. },
  26582. { //a=setup:actpass
  26583. name: 'setup',
  26584. reg: /^setup:(\w*)/,
  26585. format: "setup:%s"
  26586. },
  26587. { //a=mid:1
  26588. name: 'mid',
  26589. reg: /^mid:([^\s]*)/,
  26590. format: "mid:%s"
  26591. },
  26592. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26593. name: 'msid',
  26594. reg: /^msid:(.*)/,
  26595. format: "msid:%s"
  26596. },
  26597. { //a=ptime:20
  26598. name: 'ptime',
  26599. reg: /^ptime:(\d*)/,
  26600. format: "ptime:%d"
  26601. },
  26602. { //a=maxptime:60
  26603. name: 'maxptime',
  26604. reg: /^maxptime:(\d*)/,
  26605. format: "maxptime:%d"
  26606. },
  26607. { //a=sendrecv
  26608. name: 'direction',
  26609. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26610. },
  26611. { //a=ice-lite
  26612. name: 'icelite',
  26613. reg: /^(ice-lite)/
  26614. },
  26615. { //a=ice-ufrag:F7gI
  26616. name: 'iceUfrag',
  26617. reg: /^ice-ufrag:(\S*)/,
  26618. format: "ice-ufrag:%s"
  26619. },
  26620. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26621. name: 'icePwd',
  26622. reg: /^ice-pwd:(\S*)/,
  26623. format: "ice-pwd:%s"
  26624. },
  26625. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26626. name: 'fingerprint',
  26627. reg: /^fingerprint:(\S*) (\S*)/,
  26628. names: ['type', 'hash'],
  26629. format: "fingerprint:%s %s"
  26630. },
  26631. {
  26632. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26633. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26634. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26635. push:'candidates',
  26636. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26637. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26638. format: function (o) {
  26639. var str = "candidate:%s %d %s %d %s %d typ %s";
  26640. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26641. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26642. if (o.generation != null) {
  26643. str += " generation %d";
  26644. }
  26645. return str;
  26646. }
  26647. },
  26648. { //a=end-of-candidates (keep after the candidates line for readability)
  26649. name: 'endOfCandidates',
  26650. reg: /^(end-of-candidates)/
  26651. },
  26652. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26653. name: 'remoteCandidates',
  26654. reg: /^remote-candidates:(.*)/,
  26655. format: "remote-candidates:%s"
  26656. },
  26657. { //a=ice-options:google-ice
  26658. name: 'iceOptions',
  26659. reg: /^ice-options:(\S*)/,
  26660. format: "ice-options:%s"
  26661. },
  26662. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26663. push: "ssrcs",
  26664. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26665. names: ['id', 'attribute', 'value'],
  26666. format: "ssrc:%d %s:%s"
  26667. },
  26668. { //a=ssrc-group:FEC 1 2
  26669. push: "ssrcGroups",
  26670. reg: /^ssrc-group:(\w*) (.*)/,
  26671. names: ['semantics', 'ssrcs'],
  26672. format: "ssrc-group:%s %s"
  26673. },
  26674. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26675. name: "msidSemantic",
  26676. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26677. names: ['semantic', 'token'],
  26678. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26679. },
  26680. { //a=group:BUNDLE audio video
  26681. push: 'groups',
  26682. reg: /^group:(\w*) (.*)/,
  26683. names: ['type', 'mids'],
  26684. format: "group:%s %s"
  26685. },
  26686. { //a=rtcp-mux
  26687. name: 'rtcpMux',
  26688. reg: /^(rtcp-mux)/
  26689. },
  26690. { //a=rtcp-rsize
  26691. name: 'rtcpRsize',
  26692. reg: /^(rtcp-rsize)/
  26693. },
  26694. { // any a= that we don't understand is kepts verbatim on media.invalid
  26695. push: 'invalid',
  26696. names: ["value"]
  26697. }
  26698. ]
  26699. };
  26700. // set sensible defaults to avoid polluting the grammar with boring details
  26701. Object.keys(grammar).forEach(function (key) {
  26702. var objs = grammar[key];
  26703. objs.forEach(function (obj) {
  26704. if (!obj.reg) {
  26705. obj.reg = /(.*)/;
  26706. }
  26707. if (!obj.format) {
  26708. obj.format = "%s";
  26709. }
  26710. });
  26711. });
  26712. },{}],98:[function(require,module,exports){
  26713. var parser = require('./parser');
  26714. var writer = require('./writer');
  26715. exports.write = writer;
  26716. exports.parse = parser.parse;
  26717. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26718. exports.parsePayloads = parser.parsePayloads;
  26719. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26720. },{"./parser":99,"./writer":100}],99:[function(require,module,exports){
  26721. var toIntIfInt = function (v) {
  26722. return String(Number(v)) === v ? Number(v) : v;
  26723. };
  26724. var attachProperties = function (match, location, names, rawName) {
  26725. if (rawName && !names) {
  26726. location[rawName] = toIntIfInt(match[1]);
  26727. }
  26728. else {
  26729. for (var i = 0; i < names.length; i += 1) {
  26730. if (match[i+1] != null) {
  26731. location[names[i]] = toIntIfInt(match[i+1]);
  26732. }
  26733. }
  26734. }
  26735. };
  26736. var parseReg = function (obj, location, content) {
  26737. var needsBlank = obj.name && obj.names;
  26738. if (obj.push && !location[obj.push]) {
  26739. location[obj.push] = [];
  26740. }
  26741. else if (needsBlank && !location[obj.name]) {
  26742. location[obj.name] = {};
  26743. }
  26744. var keyLocation = obj.push ?
  26745. {} : // blank object that will be pushed
  26746. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26747. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26748. if (obj.push) {
  26749. location[obj.push].push(keyLocation);
  26750. }
  26751. };
  26752. var grammar = require('./grammar');
  26753. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26754. exports.parse = function (sdp) {
  26755. var session = {}
  26756. , media = []
  26757. , location = session; // points at where properties go under (one of the above)
  26758. // parse lines we understand
  26759. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26760. var type = l[0];
  26761. var content = l.slice(2);
  26762. if (type === 'm') {
  26763. media.push({rtp: [], fmtp: []});
  26764. location = media[media.length-1]; // point at latest media line
  26765. }
  26766. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26767. var obj = grammar[type][j];
  26768. if (obj.reg.test(content)) {
  26769. return parseReg(obj, location, content);
  26770. }
  26771. }
  26772. });
  26773. session.media = media; // link it up
  26774. return session;
  26775. };
  26776. var fmtpReducer = function (acc, expr) {
  26777. var s = expr.split('=');
  26778. if (s.length === 2) {
  26779. acc[s[0]] = toIntIfInt(s[1]);
  26780. }
  26781. return acc;
  26782. };
  26783. exports.parseFmtpConfig = function (str) {
  26784. return str.split(';').reduce(fmtpReducer, {});
  26785. };
  26786. exports.parsePayloads = function (str) {
  26787. return str.split(' ').map(Number);
  26788. };
  26789. exports.parseRemoteCandidates = function (str) {
  26790. var candidates = [];
  26791. var parts = str.split(' ').map(toIntIfInt);
  26792. for (var i = 0; i < parts.length; i += 3) {
  26793. candidates.push({
  26794. component: parts[i],
  26795. ip: parts[i + 1],
  26796. port: parts[i + 2]
  26797. });
  26798. }
  26799. return candidates;
  26800. };
  26801. },{"./grammar":97}],100:[function(require,module,exports){
  26802. var grammar = require('./grammar');
  26803. // customized util.format - discards excess arguments and can void middle ones
  26804. var formatRegExp = /%[sdv%]/g;
  26805. var format = function (formatStr) {
  26806. var i = 1;
  26807. var args = arguments;
  26808. var len = args.length;
  26809. return formatStr.replace(formatRegExp, function (x) {
  26810. if (i >= len) {
  26811. return x; // missing argument
  26812. }
  26813. var arg = args[i];
  26814. i += 1;
  26815. switch (x) {
  26816. case '%%':
  26817. return '%';
  26818. case '%s':
  26819. return String(arg);
  26820. case '%d':
  26821. return Number(arg);
  26822. case '%v':
  26823. return '';
  26824. }
  26825. });
  26826. // NB: we discard excess arguments - they are typically undefined from makeLine
  26827. };
  26828. var makeLine = function (type, obj, location) {
  26829. var str = obj.format instanceof Function ?
  26830. (obj.format(obj.push ? location : location[obj.name])) :
  26831. obj.format;
  26832. var args = [type + '=' + str];
  26833. if (obj.names) {
  26834. for (var i = 0; i < obj.names.length; i += 1) {
  26835. var n = obj.names[i];
  26836. if (obj.name) {
  26837. args.push(location[obj.name][n]);
  26838. }
  26839. else { // for mLine and push attributes
  26840. args.push(location[obj.names[i]]);
  26841. }
  26842. }
  26843. }
  26844. else {
  26845. args.push(location[obj.name]);
  26846. }
  26847. return format.apply(null, args);
  26848. };
  26849. // RFC specified order
  26850. // TODO: extend this with all the rest
  26851. var defaultOuterOrder = [
  26852. 'v', 'o', 's', 'i',
  26853. 'u', 'e', 'p', 'c',
  26854. 'b', 't', 'r', 'z', 'a'
  26855. ];
  26856. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26857. module.exports = function (session, opts) {
  26858. opts = opts || {};
  26859. // ensure certain properties exist
  26860. if (session.version == null) {
  26861. session.version = 0; // "v=0" must be there (only defined version atm)
  26862. }
  26863. if (session.name == null) {
  26864. session.name = " "; // "s= " must be there if no meaningful name set
  26865. }
  26866. session.media.forEach(function (mLine) {
  26867. if (mLine.payloads == null) {
  26868. mLine.payloads = "";
  26869. }
  26870. });
  26871. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26872. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26873. var sdp = [];
  26874. // loop through outerOrder for matching properties on session
  26875. outerOrder.forEach(function (type) {
  26876. grammar[type].forEach(function (obj) {
  26877. if (obj.name in session && session[obj.name] != null) {
  26878. sdp.push(makeLine(type, obj, session));
  26879. }
  26880. else if (obj.push in session && session[obj.push] != null) {
  26881. session[obj.push].forEach(function (el) {
  26882. sdp.push(makeLine(type, obj, el));
  26883. });
  26884. }
  26885. });
  26886. });
  26887. // then for each media line, follow the innerOrder
  26888. session.media.forEach(function (mLine) {
  26889. sdp.push(makeLine('m', grammar.m[0], mLine));
  26890. innerOrder.forEach(function (type) {
  26891. grammar[type].forEach(function (obj) {
  26892. if (obj.name in mLine && mLine[obj.name] != null) {
  26893. sdp.push(makeLine(type, obj, mLine));
  26894. }
  26895. else if (obj.push in mLine && mLine[obj.push] != null) {
  26896. mLine[obj.push].forEach(function (el) {
  26897. sdp.push(makeLine(type, obj, el));
  26898. });
  26899. }
  26900. });
  26901. });
  26902. });
  26903. return sdp.join('\r\n') + '\r\n';
  26904. };
  26905. },{"./grammar":97}],101:[function(require,module,exports){
  26906. module.exports = require('./lib/');
  26907. },{"./lib/":102}],102:[function(require,module,exports){
  26908. /**
  26909. * Module dependencies.
  26910. */
  26911. var url = require('./url');
  26912. var parser = require('socket.io-parser');
  26913. var Manager = require('./manager');
  26914. var debug = require('debug')('socket.io-client');
  26915. /**
  26916. * Module exports.
  26917. */
  26918. module.exports = exports = lookup;
  26919. /**
  26920. * Managers cache.
  26921. */
  26922. var cache = exports.managers = {};
  26923. /**
  26924. * Looks up an existing `Manager` for multiplexing.
  26925. * If the user summons:
  26926. *
  26927. * `io('http://localhost/a');`
  26928. * `io('http://localhost/b');`
  26929. *
  26930. * We reuse the existing instance based on same scheme/port/host,
  26931. * and we initialize sockets for each namespace.
  26932. *
  26933. * @api public
  26934. */
  26935. function lookup(uri, opts) {
  26936. if (typeof uri == 'object') {
  26937. opts = uri;
  26938. uri = undefined;
  26939. }
  26940. opts = opts || {};
  26941. var parsed = url(uri);
  26942. var source = parsed.source;
  26943. var id = parsed.id;
  26944. var io;
  26945. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  26946. debug('ignoring socket cache for %s', source);
  26947. io = Manager(source, opts);
  26948. } else {
  26949. if (!cache[id]) {
  26950. debug('new io instance for %s', source);
  26951. cache[id] = Manager(source, opts);
  26952. }
  26953. io = cache[id];
  26954. }
  26955. return io.socket(parsed.path);
  26956. }
  26957. /**
  26958. * Protocol version.
  26959. *
  26960. * @api public
  26961. */
  26962. exports.protocol = parser.protocol;
  26963. /**
  26964. * `connect`.
  26965. *
  26966. * @param {String} uri
  26967. * @api public
  26968. */
  26969. exports.connect = lookup;
  26970. /**
  26971. * Expose constructors for standalone build.
  26972. *
  26973. * @api public
  26974. */
  26975. exports.Manager = require('./manager');
  26976. exports.Socket = require('./socket');
  26977. },{"./manager":103,"./socket":105,"./url":106,"debug":110,"socket.io-parser":146}],103:[function(require,module,exports){
  26978. /**
  26979. * Module dependencies.
  26980. */
  26981. var url = require('./url');
  26982. var eio = require('engine.io-client');
  26983. var Socket = require('./socket');
  26984. var Emitter = require('component-emitter');
  26985. var parser = require('socket.io-parser');
  26986. var on = require('./on');
  26987. var bind = require('component-bind');
  26988. var object = require('object-component');
  26989. var debug = require('debug')('socket.io-client:manager');
  26990. var indexOf = require('indexof');
  26991. var Backoff = require('backo2');
  26992. /**
  26993. * Module exports
  26994. */
  26995. module.exports = Manager;
  26996. /**
  26997. * `Manager` constructor.
  26998. *
  26999. * @param {String} engine instance or engine uri/opts
  27000. * @param {Object} options
  27001. * @api public
  27002. */
  27003. function Manager(uri, opts){
  27004. if (!(this instanceof Manager)) return new Manager(uri, opts);
  27005. if (uri && ('object' == typeof uri)) {
  27006. opts = uri;
  27007. uri = undefined;
  27008. }
  27009. opts = opts || {};
  27010. opts.path = opts.path || '/socket.io';
  27011. this.nsps = {};
  27012. this.subs = [];
  27013. this.opts = opts;
  27014. this.reconnection(opts.reconnection !== false);
  27015. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  27016. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  27017. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  27018. this.randomizationFactor(opts.randomizationFactor || 0.5);
  27019. this.backoff = new Backoff({
  27020. min: this.reconnectionDelay(),
  27021. max: this.reconnectionDelayMax(),
  27022. jitter: this.randomizationFactor()
  27023. });
  27024. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  27025. this.readyState = 'closed';
  27026. this.uri = uri;
  27027. this.connected = [];
  27028. this.encoding = false;
  27029. this.packetBuffer = [];
  27030. this.encoder = new parser.Encoder();
  27031. this.decoder = new parser.Decoder();
  27032. this.autoConnect = opts.autoConnect !== false;
  27033. if (this.autoConnect) this.open();
  27034. }
  27035. /**
  27036. * Propagate given event to sockets and emit on `this`
  27037. *
  27038. * @api private
  27039. */
  27040. Manager.prototype.emitAll = function() {
  27041. this.emit.apply(this, arguments);
  27042. for (var nsp in this.nsps) {
  27043. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  27044. }
  27045. };
  27046. /**
  27047. * Update `socket.id` of all sockets
  27048. *
  27049. * @api private
  27050. */
  27051. Manager.prototype.updateSocketIds = function(){
  27052. for (var nsp in this.nsps) {
  27053. this.nsps[nsp].id = this.engine.id;
  27054. }
  27055. };
  27056. /**
  27057. * Mix in `Emitter`.
  27058. */
  27059. Emitter(Manager.prototype);
  27060. /**
  27061. * Sets the `reconnection` config.
  27062. *
  27063. * @param {Boolean} true/false if it should automatically reconnect
  27064. * @return {Manager} self or value
  27065. * @api public
  27066. */
  27067. Manager.prototype.reconnection = function(v){
  27068. if (!arguments.length) return this._reconnection;
  27069. this._reconnection = !!v;
  27070. return this;
  27071. };
  27072. /**
  27073. * Sets the reconnection attempts config.
  27074. *
  27075. * @param {Number} max reconnection attempts before giving up
  27076. * @return {Manager} self or value
  27077. * @api public
  27078. */
  27079. Manager.prototype.reconnectionAttempts = function(v){
  27080. if (!arguments.length) return this._reconnectionAttempts;
  27081. this._reconnectionAttempts = v;
  27082. return this;
  27083. };
  27084. /**
  27085. * Sets the delay between reconnections.
  27086. *
  27087. * @param {Number} delay
  27088. * @return {Manager} self or value
  27089. * @api public
  27090. */
  27091. Manager.prototype.reconnectionDelay = function(v){
  27092. if (!arguments.length) return this._reconnectionDelay;
  27093. this._reconnectionDelay = v;
  27094. this.backoff && this.backoff.setMin(v);
  27095. return this;
  27096. };
  27097. Manager.prototype.randomizationFactor = function(v){
  27098. if (!arguments.length) return this._randomizationFactor;
  27099. this._randomizationFactor = v;
  27100. this.backoff && this.backoff.setJitter(v);
  27101. return this;
  27102. };
  27103. /**
  27104. * Sets the maximum delay between reconnections.
  27105. *
  27106. * @param {Number} delay
  27107. * @return {Manager} self or value
  27108. * @api public
  27109. */
  27110. Manager.prototype.reconnectionDelayMax = function(v){
  27111. if (!arguments.length) return this._reconnectionDelayMax;
  27112. this._reconnectionDelayMax = v;
  27113. this.backoff && this.backoff.setMax(v);
  27114. return this;
  27115. };
  27116. /**
  27117. * Sets the connection timeout. `false` to disable
  27118. *
  27119. * @return {Manager} self or value
  27120. * @api public
  27121. */
  27122. Manager.prototype.timeout = function(v){
  27123. if (!arguments.length) return this._timeout;
  27124. this._timeout = v;
  27125. return this;
  27126. };
  27127. /**
  27128. * Starts trying to reconnect if reconnection is enabled and we have not
  27129. * started reconnecting yet
  27130. *
  27131. * @api private
  27132. */
  27133. Manager.prototype.maybeReconnectOnOpen = function() {
  27134. // Only try to reconnect if it's the first time we're connecting
  27135. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  27136. // keeps reconnection from firing twice for the same reconnection loop
  27137. this.reconnect();
  27138. }
  27139. };
  27140. /**
  27141. * Sets the current transport `socket`.
  27142. *
  27143. * @param {Function} optional, callback
  27144. * @return {Manager} self
  27145. * @api public
  27146. */
  27147. Manager.prototype.open =
  27148. Manager.prototype.connect = function(fn){
  27149. debug('readyState %s', this.readyState);
  27150. if (~this.readyState.indexOf('open')) return this;
  27151. debug('opening %s', this.uri);
  27152. this.engine = eio(this.uri, this.opts);
  27153. var socket = this.engine;
  27154. var self = this;
  27155. this.readyState = 'opening';
  27156. this.skipReconnect = false;
  27157. // emit `open`
  27158. var openSub = on(socket, 'open', function() {
  27159. self.onopen();
  27160. fn && fn();
  27161. });
  27162. // emit `connect_error`
  27163. var errorSub = on(socket, 'error', function(data){
  27164. debug('connect_error');
  27165. self.cleanup();
  27166. self.readyState = 'closed';
  27167. self.emitAll('connect_error', data);
  27168. if (fn) {
  27169. var err = new Error('Connection error');
  27170. err.data = data;
  27171. fn(err);
  27172. } else {
  27173. // Only do this if there is no fn to handle the error
  27174. self.maybeReconnectOnOpen();
  27175. }
  27176. });
  27177. // emit `connect_timeout`
  27178. if (false !== this._timeout) {
  27179. var timeout = this._timeout;
  27180. debug('connect attempt will timeout after %d', timeout);
  27181. // set timer
  27182. var timer = setTimeout(function(){
  27183. debug('connect attempt timed out after %d', timeout);
  27184. openSub.destroy();
  27185. socket.close();
  27186. socket.emit('error', 'timeout');
  27187. self.emitAll('connect_timeout', timeout);
  27188. }, timeout);
  27189. this.subs.push({
  27190. destroy: function(){
  27191. clearTimeout(timer);
  27192. }
  27193. });
  27194. }
  27195. this.subs.push(openSub);
  27196. this.subs.push(errorSub);
  27197. return this;
  27198. };
  27199. /**
  27200. * Called upon transport open.
  27201. *
  27202. * @api private
  27203. */
  27204. Manager.prototype.onopen = function(){
  27205. debug('open');
  27206. // clear old subs
  27207. this.cleanup();
  27208. // mark as open
  27209. this.readyState = 'open';
  27210. this.emit('open');
  27211. // add new subs
  27212. var socket = this.engine;
  27213. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  27214. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  27215. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  27216. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  27217. };
  27218. /**
  27219. * Called with data.
  27220. *
  27221. * @api private
  27222. */
  27223. Manager.prototype.ondata = function(data){
  27224. this.decoder.add(data);
  27225. };
  27226. /**
  27227. * Called when parser fully decodes a packet.
  27228. *
  27229. * @api private
  27230. */
  27231. Manager.prototype.ondecoded = function(packet) {
  27232. this.emit('packet', packet);
  27233. };
  27234. /**
  27235. * Called upon socket error.
  27236. *
  27237. * @api private
  27238. */
  27239. Manager.prototype.onerror = function(err){
  27240. debug('error', err);
  27241. this.emitAll('error', err);
  27242. };
  27243. /**
  27244. * Creates a new socket for the given `nsp`.
  27245. *
  27246. * @return {Socket}
  27247. * @api public
  27248. */
  27249. Manager.prototype.socket = function(nsp){
  27250. var socket = this.nsps[nsp];
  27251. if (!socket) {
  27252. socket = new Socket(this, nsp);
  27253. this.nsps[nsp] = socket;
  27254. var self = this;
  27255. socket.on('connect', function(){
  27256. socket.id = self.engine.id;
  27257. if (!~indexOf(self.connected, socket)) {
  27258. self.connected.push(socket);
  27259. }
  27260. });
  27261. }
  27262. return socket;
  27263. };
  27264. /**
  27265. * Called upon a socket close.
  27266. *
  27267. * @param {Socket} socket
  27268. */
  27269. Manager.prototype.destroy = function(socket){
  27270. var index = indexOf(this.connected, socket);
  27271. if (~index) this.connected.splice(index, 1);
  27272. if (this.connected.length) return;
  27273. this.close();
  27274. };
  27275. /**
  27276. * Writes a packet.
  27277. *
  27278. * @param {Object} packet
  27279. * @api private
  27280. */
  27281. Manager.prototype.packet = function(packet){
  27282. debug('writing packet %j', packet);
  27283. var self = this;
  27284. if (!self.encoding) {
  27285. // encode, then write to engine with result
  27286. self.encoding = true;
  27287. this.encoder.encode(packet, function(encodedPackets) {
  27288. for (var i = 0; i < encodedPackets.length; i++) {
  27289. self.engine.write(encodedPackets[i]);
  27290. }
  27291. self.encoding = false;
  27292. self.processPacketQueue();
  27293. });
  27294. } else { // add packet to the queue
  27295. self.packetBuffer.push(packet);
  27296. }
  27297. };
  27298. /**
  27299. * If packet buffer is non-empty, begins encoding the
  27300. * next packet in line.
  27301. *
  27302. * @api private
  27303. */
  27304. Manager.prototype.processPacketQueue = function() {
  27305. if (this.packetBuffer.length > 0 && !this.encoding) {
  27306. var pack = this.packetBuffer.shift();
  27307. this.packet(pack);
  27308. }
  27309. };
  27310. /**
  27311. * Clean up transport subscriptions and packet buffer.
  27312. *
  27313. * @api private
  27314. */
  27315. Manager.prototype.cleanup = function(){
  27316. var sub;
  27317. while (sub = this.subs.shift()) sub.destroy();
  27318. this.packetBuffer = [];
  27319. this.encoding = false;
  27320. this.decoder.destroy();
  27321. };
  27322. /**
  27323. * Close the current socket.
  27324. *
  27325. * @api private
  27326. */
  27327. Manager.prototype.close =
  27328. Manager.prototype.disconnect = function(){
  27329. this.skipReconnect = true;
  27330. this.backoff.reset();
  27331. this.readyState = 'closed';
  27332. this.engine && this.engine.close();
  27333. };
  27334. /**
  27335. * Called upon engine close.
  27336. *
  27337. * @api private
  27338. */
  27339. Manager.prototype.onclose = function(reason){
  27340. debug('close');
  27341. this.cleanup();
  27342. this.backoff.reset();
  27343. this.readyState = 'closed';
  27344. this.emit('close', reason);
  27345. if (this._reconnection && !this.skipReconnect) {
  27346. this.reconnect();
  27347. }
  27348. };
  27349. /**
  27350. * Attempt a reconnection.
  27351. *
  27352. * @api private
  27353. */
  27354. Manager.prototype.reconnect = function(){
  27355. if (this.reconnecting || this.skipReconnect) return this;
  27356. var self = this;
  27357. if (this.backoff.attempts >= this._reconnectionAttempts) {
  27358. debug('reconnect failed');
  27359. this.backoff.reset();
  27360. this.emitAll('reconnect_failed');
  27361. this.reconnecting = false;
  27362. } else {
  27363. var delay = this.backoff.duration();
  27364. debug('will wait %dms before reconnect attempt', delay);
  27365. this.reconnecting = true;
  27366. var timer = setTimeout(function(){
  27367. if (self.skipReconnect) return;
  27368. debug('attempting reconnect');
  27369. self.emitAll('reconnect_attempt', self.backoff.attempts);
  27370. self.emitAll('reconnecting', self.backoff.attempts);
  27371. // check again for the case socket closed in above events
  27372. if (self.skipReconnect) return;
  27373. self.open(function(err){
  27374. if (err) {
  27375. debug('reconnect attempt error');
  27376. self.reconnecting = false;
  27377. self.reconnect();
  27378. self.emitAll('reconnect_error', err.data);
  27379. } else {
  27380. debug('reconnect success');
  27381. self.onreconnect();
  27382. }
  27383. });
  27384. }, delay);
  27385. this.subs.push({
  27386. destroy: function(){
  27387. clearTimeout(timer);
  27388. }
  27389. });
  27390. }
  27391. };
  27392. /**
  27393. * Called upon successful reconnect.
  27394. *
  27395. * @api private
  27396. */
  27397. Manager.prototype.onreconnect = function(){
  27398. var attempt = this.backoff.attempts;
  27399. this.reconnecting = false;
  27400. this.backoff.reset();
  27401. this.updateSocketIds();
  27402. this.emitAll('reconnect', attempt);
  27403. };
  27404. },{"./on":104,"./socket":105,"./url":106,"backo2":107,"component-bind":108,"component-emitter":109,"debug":110,"engine.io-client":111,"indexof":142,"object-component":143,"socket.io-parser":146}],104:[function(require,module,exports){
  27405. /**
  27406. * Module exports.
  27407. */
  27408. module.exports = on;
  27409. /**
  27410. * Helper for subscriptions.
  27411. *
  27412. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  27413. * @param {String} event name
  27414. * @param {Function} callback
  27415. * @api public
  27416. */
  27417. function on(obj, ev, fn) {
  27418. obj.on(ev, fn);
  27419. return {
  27420. destroy: function(){
  27421. obj.removeListener(ev, fn);
  27422. }
  27423. };
  27424. }
  27425. },{}],105:[function(require,module,exports){
  27426. /**
  27427. * Module dependencies.
  27428. */
  27429. var parser = require('socket.io-parser');
  27430. var Emitter = require('component-emitter');
  27431. var toArray = require('to-array');
  27432. var on = require('./on');
  27433. var bind = require('component-bind');
  27434. var debug = require('debug')('socket.io-client:socket');
  27435. var hasBin = require('has-binary');
  27436. /**
  27437. * Module exports.
  27438. */
  27439. module.exports = exports = Socket;
  27440. /**
  27441. * Internal events (blacklisted).
  27442. * These events can't be emitted by the user.
  27443. *
  27444. * @api private
  27445. */
  27446. var events = {
  27447. connect: 1,
  27448. connect_error: 1,
  27449. connect_timeout: 1,
  27450. disconnect: 1,
  27451. error: 1,
  27452. reconnect: 1,
  27453. reconnect_attempt: 1,
  27454. reconnect_failed: 1,
  27455. reconnect_error: 1,
  27456. reconnecting: 1
  27457. };
  27458. /**
  27459. * Shortcut to `Emitter#emit`.
  27460. */
  27461. var emit = Emitter.prototype.emit;
  27462. /**
  27463. * `Socket` constructor.
  27464. *
  27465. * @api public
  27466. */
  27467. function Socket(io, nsp){
  27468. this.io = io;
  27469. this.nsp = nsp;
  27470. this.json = this; // compat
  27471. this.ids = 0;
  27472. this.acks = {};
  27473. if (this.io.autoConnect) this.open();
  27474. this.receiveBuffer = [];
  27475. this.sendBuffer = [];
  27476. this.connected = false;
  27477. this.disconnected = true;
  27478. }
  27479. /**
  27480. * Mix in `Emitter`.
  27481. */
  27482. Emitter(Socket.prototype);
  27483. /**
  27484. * Subscribe to open, close and packet events
  27485. *
  27486. * @api private
  27487. */
  27488. Socket.prototype.subEvents = function() {
  27489. if (this.subs) return;
  27490. var io = this.io;
  27491. this.subs = [
  27492. on(io, 'open', bind(this, 'onopen')),
  27493. on(io, 'packet', bind(this, 'onpacket')),
  27494. on(io, 'close', bind(this, 'onclose'))
  27495. ];
  27496. };
  27497. /**
  27498. * "Opens" the socket.
  27499. *
  27500. * @api public
  27501. */
  27502. Socket.prototype.open =
  27503. Socket.prototype.connect = function(){
  27504. if (this.connected) return this;
  27505. this.subEvents();
  27506. this.io.open(); // ensure open
  27507. if ('open' == this.io.readyState) this.onopen();
  27508. return this;
  27509. };
  27510. /**
  27511. * Sends a `message` event.
  27512. *
  27513. * @return {Socket} self
  27514. * @api public
  27515. */
  27516. Socket.prototype.send = function(){
  27517. var args = toArray(arguments);
  27518. args.unshift('message');
  27519. this.emit.apply(this, args);
  27520. return this;
  27521. };
  27522. /**
  27523. * Override `emit`.
  27524. * If the event is in `events`, it's emitted normally.
  27525. *
  27526. * @param {String} event name
  27527. * @return {Socket} self
  27528. * @api public
  27529. */
  27530. Socket.prototype.emit = function(ev){
  27531. if (events.hasOwnProperty(ev)) {
  27532. emit.apply(this, arguments);
  27533. return this;
  27534. }
  27535. var args = toArray(arguments);
  27536. var parserType = parser.EVENT; // default
  27537. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  27538. var packet = { type: parserType, data: args };
  27539. // event ack callback
  27540. if ('function' == typeof args[args.length - 1]) {
  27541. debug('emitting packet with ack id %d', this.ids);
  27542. this.acks[this.ids] = args.pop();
  27543. packet.id = this.ids++;
  27544. }
  27545. if (this.connected) {
  27546. this.packet(packet);
  27547. } else {
  27548. this.sendBuffer.push(packet);
  27549. }
  27550. return this;
  27551. };
  27552. /**
  27553. * Sends a packet.
  27554. *
  27555. * @param {Object} packet
  27556. * @api private
  27557. */
  27558. Socket.prototype.packet = function(packet){
  27559. packet.nsp = this.nsp;
  27560. this.io.packet(packet);
  27561. };
  27562. /**
  27563. * Called upon engine `open`.
  27564. *
  27565. * @api private
  27566. */
  27567. Socket.prototype.onopen = function(){
  27568. debug('transport is open - connecting');
  27569. // write connect packet if necessary
  27570. if ('/' != this.nsp) {
  27571. this.packet({ type: parser.CONNECT });
  27572. }
  27573. };
  27574. /**
  27575. * Called upon engine `close`.
  27576. *
  27577. * @param {String} reason
  27578. * @api private
  27579. */
  27580. Socket.prototype.onclose = function(reason){
  27581. debug('close (%s)', reason);
  27582. this.connected = false;
  27583. this.disconnected = true;
  27584. delete this.id;
  27585. this.emit('disconnect', reason);
  27586. };
  27587. /**
  27588. * Called with socket packet.
  27589. *
  27590. * @param {Object} packet
  27591. * @api private
  27592. */
  27593. Socket.prototype.onpacket = function(packet){
  27594. if (packet.nsp != this.nsp) return;
  27595. switch (packet.type) {
  27596. case parser.CONNECT:
  27597. this.onconnect();
  27598. break;
  27599. case parser.EVENT:
  27600. this.onevent(packet);
  27601. break;
  27602. case parser.BINARY_EVENT:
  27603. this.onevent(packet);
  27604. break;
  27605. case parser.ACK:
  27606. this.onack(packet);
  27607. break;
  27608. case parser.BINARY_ACK:
  27609. this.onack(packet);
  27610. break;
  27611. case parser.DISCONNECT:
  27612. this.ondisconnect();
  27613. break;
  27614. case parser.ERROR:
  27615. this.emit('error', packet.data);
  27616. break;
  27617. }
  27618. };
  27619. /**
  27620. * Called upon a server event.
  27621. *
  27622. * @param {Object} packet
  27623. * @api private
  27624. */
  27625. Socket.prototype.onevent = function(packet){
  27626. var args = packet.data || [];
  27627. debug('emitting event %j', args);
  27628. if (null != packet.id) {
  27629. debug('attaching ack callback to event');
  27630. args.push(this.ack(packet.id));
  27631. }
  27632. if (this.connected) {
  27633. emit.apply(this, args);
  27634. } else {
  27635. this.receiveBuffer.push(args);
  27636. }
  27637. };
  27638. /**
  27639. * Produces an ack callback to emit with an event.
  27640. *
  27641. * @api private
  27642. */
  27643. Socket.prototype.ack = function(id){
  27644. var self = this;
  27645. var sent = false;
  27646. return function(){
  27647. // prevent double callbacks
  27648. if (sent) return;
  27649. sent = true;
  27650. var args = toArray(arguments);
  27651. debug('sending ack %j', args);
  27652. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  27653. self.packet({
  27654. type: type,
  27655. id: id,
  27656. data: args
  27657. });
  27658. };
  27659. };
  27660. /**
  27661. * Called upon a server acknowlegement.
  27662. *
  27663. * @param {Object} packet
  27664. * @api private
  27665. */
  27666. Socket.prototype.onack = function(packet){
  27667. debug('calling ack %s with %j', packet.id, packet.data);
  27668. var fn = this.acks[packet.id];
  27669. fn.apply(this, packet.data);
  27670. delete this.acks[packet.id];
  27671. };
  27672. /**
  27673. * Called upon server connect.
  27674. *
  27675. * @api private
  27676. */
  27677. Socket.prototype.onconnect = function(){
  27678. this.connected = true;
  27679. this.disconnected = false;
  27680. this.emit('connect');
  27681. this.emitBuffered();
  27682. };
  27683. /**
  27684. * Emit buffered events (received and emitted).
  27685. *
  27686. * @api private
  27687. */
  27688. Socket.prototype.emitBuffered = function(){
  27689. var i;
  27690. for (i = 0; i < this.receiveBuffer.length; i++) {
  27691. emit.apply(this, this.receiveBuffer[i]);
  27692. }
  27693. this.receiveBuffer = [];
  27694. for (i = 0; i < this.sendBuffer.length; i++) {
  27695. this.packet(this.sendBuffer[i]);
  27696. }
  27697. this.sendBuffer = [];
  27698. };
  27699. /**
  27700. * Called upon server disconnect.
  27701. *
  27702. * @api private
  27703. */
  27704. Socket.prototype.ondisconnect = function(){
  27705. debug('server disconnect (%s)', this.nsp);
  27706. this.destroy();
  27707. this.onclose('io server disconnect');
  27708. };
  27709. /**
  27710. * Called upon forced client/server side disconnections,
  27711. * this method ensures the manager stops tracking us and
  27712. * that reconnections don't get triggered for this.
  27713. *
  27714. * @api private.
  27715. */
  27716. Socket.prototype.destroy = function(){
  27717. if (this.subs) {
  27718. // clean subscriptions to avoid reconnections
  27719. for (var i = 0; i < this.subs.length; i++) {
  27720. this.subs[i].destroy();
  27721. }
  27722. this.subs = null;
  27723. }
  27724. this.io.destroy(this);
  27725. };
  27726. /**
  27727. * Disconnects the socket manually.
  27728. *
  27729. * @return {Socket} self
  27730. * @api public
  27731. */
  27732. Socket.prototype.close =
  27733. Socket.prototype.disconnect = function(){
  27734. if (this.connected) {
  27735. debug('performing disconnect (%s)', this.nsp);
  27736. this.packet({ type: parser.DISCONNECT });
  27737. }
  27738. // remove socket from pool
  27739. this.destroy();
  27740. if (this.connected) {
  27741. // fire events
  27742. this.onclose('io client disconnect');
  27743. }
  27744. return this;
  27745. };
  27746. },{"./on":104,"component-bind":108,"component-emitter":109,"debug":110,"has-binary":140,"socket.io-parser":146,"to-array":150}],106:[function(require,module,exports){
  27747. (function (global){
  27748. /**
  27749. * Module dependencies.
  27750. */
  27751. var parseuri = require('parseuri');
  27752. var debug = require('debug')('socket.io-client:url');
  27753. /**
  27754. * Module exports.
  27755. */
  27756. module.exports = url;
  27757. /**
  27758. * URL parser.
  27759. *
  27760. * @param {String} url
  27761. * @param {Object} An object meant to mimic window.location.
  27762. * Defaults to window.location.
  27763. * @api public
  27764. */
  27765. function url(uri, loc){
  27766. var obj = uri;
  27767. // default to window.location
  27768. var loc = loc || global.location;
  27769. if (null == uri) uri = loc.protocol + '//' + loc.host;
  27770. // relative path support
  27771. if ('string' == typeof uri) {
  27772. if ('/' == uri.charAt(0)) {
  27773. if ('/' == uri.charAt(1)) {
  27774. uri = loc.protocol + uri;
  27775. } else {
  27776. uri = loc.hostname + uri;
  27777. }
  27778. }
  27779. if (!/^(https?|wss?):\/\//.test(uri)) {
  27780. debug('protocol-less url %s', uri);
  27781. if ('undefined' != typeof loc) {
  27782. uri = loc.protocol + '//' + uri;
  27783. } else {
  27784. uri = 'https://' + uri;
  27785. }
  27786. }
  27787. // parse
  27788. debug('parse %s', uri);
  27789. obj = parseuri(uri);
  27790. }
  27791. // make sure we treat `localhost:80` and `localhost` equally
  27792. if (!obj.port) {
  27793. if (/^(http|ws)$/.test(obj.protocol)) {
  27794. obj.port = '80';
  27795. }
  27796. else if (/^(http|ws)s$/.test(obj.protocol)) {
  27797. obj.port = '443';
  27798. }
  27799. }
  27800. obj.path = obj.path || '/';
  27801. // define unique id
  27802. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  27803. // define href
  27804. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  27805. return obj;
  27806. }
  27807. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  27808. },{"debug":110,"parseuri":144}],107:[function(require,module,exports){
  27809. /**
  27810. * Expose `Backoff`.
  27811. */
  27812. module.exports = Backoff;
  27813. /**
  27814. * Initialize backoff timer with `opts`.
  27815. *
  27816. * - `min` initial timeout in milliseconds [100]
  27817. * - `max` max timeout [10000]
  27818. * - `jitter` [0]
  27819. * - `factor` [2]
  27820. *
  27821. * @param {Object} opts
  27822. * @api public
  27823. */
  27824. function Backoff(opts) {
  27825. opts = opts || {};
  27826. this.ms = opts.min || 100;
  27827. this.max = opts.max || 10000;
  27828. this.factor = opts.factor || 2;
  27829. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  27830. this.attempts = 0;
  27831. }
  27832. /**
  27833. * Return the backoff duration.
  27834. *
  27835. * @return {Number}
  27836. * @api public
  27837. */
  27838. Backoff.prototype.duration = function(){
  27839. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  27840. if (this.jitter) {
  27841. var rand = Math.random();
  27842. var deviation = Math.floor(rand * this.jitter * ms);
  27843. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  27844. }
  27845. return Math.min(ms, this.max) | 0;
  27846. };
  27847. /**
  27848. * Reset the number of attempts.
  27849. *
  27850. * @api public
  27851. */
  27852. Backoff.prototype.reset = function(){
  27853. this.attempts = 0;
  27854. };
  27855. /**
  27856. * Set the minimum duration
  27857. *
  27858. * @api public
  27859. */
  27860. Backoff.prototype.setMin = function(min){
  27861. this.ms = min;
  27862. };
  27863. /**
  27864. * Set the maximum duration
  27865. *
  27866. * @api public
  27867. */
  27868. Backoff.prototype.setMax = function(max){
  27869. this.max = max;
  27870. };
  27871. /**
  27872. * Set the jitter
  27873. *
  27874. * @api public
  27875. */
  27876. Backoff.prototype.setJitter = function(jitter){
  27877. this.jitter = jitter;
  27878. };
  27879. },{}],108:[function(require,module,exports){
  27880. /**
  27881. * Slice reference.
  27882. */
  27883. var slice = [].slice;
  27884. /**
  27885. * Bind `obj` to `fn`.
  27886. *
  27887. * @param {Object} obj
  27888. * @param {Function|String} fn or string
  27889. * @return {Function}
  27890. * @api public
  27891. */
  27892. module.exports = function(obj, fn){
  27893. if ('string' == typeof fn) fn = obj[fn];
  27894. if ('function' != typeof fn) throw new Error('bind() requires a function');
  27895. var args = slice.call(arguments, 2);
  27896. return function(){
  27897. return fn.apply(obj, args.concat(slice.call(arguments)));
  27898. }
  27899. };
  27900. },{}],109:[function(require,module,exports){
  27901. /**
  27902. * Expose `Emitter`.
  27903. */
  27904. module.exports = Emitter;
  27905. /**
  27906. * Initialize a new `Emitter`.
  27907. *
  27908. * @api public
  27909. */
  27910. function Emitter(obj) {
  27911. if (obj) return mixin(obj);
  27912. };
  27913. /**
  27914. * Mixin the emitter properties.
  27915. *
  27916. * @param {Object} obj
  27917. * @return {Object}
  27918. * @api private
  27919. */
  27920. function mixin(obj) {
  27921. for (var key in Emitter.prototype) {
  27922. obj[key] = Emitter.prototype[key];
  27923. }
  27924. return obj;
  27925. }
  27926. /**
  27927. * Listen on the given `event` with `fn`.
  27928. *
  27929. * @param {String} event
  27930. * @param {Function} fn
  27931. * @return {Emitter}
  27932. * @api public
  27933. */
  27934. Emitter.prototype.on =
  27935. Emitter.prototype.addEventListener = function(event, fn){
  27936. this._callbacks = this._callbacks || {};
  27937. (this._callbacks[event] = this._callbacks[event] || [])
  27938. .push(fn);
  27939. return this;
  27940. };
  27941. /**
  27942. * Adds an `event` listener that will be invoked a single
  27943. * time then automatically removed.
  27944. *
  27945. * @param {String} event
  27946. * @param {Function} fn
  27947. * @return {Emitter}
  27948. * @api public
  27949. */
  27950. Emitter.prototype.once = function(event, fn){
  27951. var self = this;
  27952. this._callbacks = this._callbacks || {};
  27953. function on() {
  27954. self.off(event, on);
  27955. fn.apply(this, arguments);
  27956. }
  27957. on.fn = fn;
  27958. this.on(event, on);
  27959. return this;
  27960. };
  27961. /**
  27962. * Remove the given callback for `event` or all
  27963. * registered callbacks.
  27964. *
  27965. * @param {String} event
  27966. * @param {Function} fn
  27967. * @return {Emitter}
  27968. * @api public
  27969. */
  27970. Emitter.prototype.off =
  27971. Emitter.prototype.removeListener =
  27972. Emitter.prototype.removeAllListeners =
  27973. Emitter.prototype.removeEventListener = function(event, fn){
  27974. this._callbacks = this._callbacks || {};
  27975. // all
  27976. if (0 == arguments.length) {
  27977. this._callbacks = {};
  27978. return this;
  27979. }
  27980. // specific event
  27981. var callbacks = this._callbacks[event];
  27982. if (!callbacks) return this;
  27983. // remove all handlers
  27984. if (1 == arguments.length) {
  27985. delete this._callbacks[event];
  27986. return this;
  27987. }
  27988. // remove specific handler
  27989. var cb;
  27990. for (var i = 0; i < callbacks.length; i++) {
  27991. cb = callbacks[i];
  27992. if (cb === fn || cb.fn === fn) {
  27993. callbacks.splice(i, 1);
  27994. break;
  27995. }
  27996. }
  27997. return this;
  27998. };
  27999. /**
  28000. * Emit `event` with the given args.
  28001. *
  28002. * @param {String} event
  28003. * @param {Mixed} ...
  28004. * @return {Emitter}
  28005. */
  28006. Emitter.prototype.emit = function(event){
  28007. this._callbacks = this._callbacks || {};
  28008. var args = [].slice.call(arguments, 1)
  28009. , callbacks = this._callbacks[event];
  28010. if (callbacks) {
  28011. callbacks = callbacks.slice(0);
  28012. for (var i = 0, len = callbacks.length; i < len; ++i) {
  28013. callbacks[i].apply(this, args);
  28014. }
  28015. }
  28016. return this;
  28017. };
  28018. /**
  28019. * Return array of callbacks for `event`.
  28020. *
  28021. * @param {String} event
  28022. * @return {Array}
  28023. * @api public
  28024. */
  28025. Emitter.prototype.listeners = function(event){
  28026. this._callbacks = this._callbacks || {};
  28027. return this._callbacks[event] || [];
  28028. };
  28029. /**
  28030. * Check if this emitter has `event` handlers.
  28031. *
  28032. * @param {String} event
  28033. * @return {Boolean}
  28034. * @api public
  28035. */
  28036. Emitter.prototype.hasListeners = function(event){
  28037. return !! this.listeners(event).length;
  28038. };
  28039. },{}],110:[function(require,module,exports){
  28040. /**
  28041. * Expose `debug()` as the module.
  28042. */
  28043. module.exports = debug;
  28044. /**
  28045. * Create a debugger with the given `name`.
  28046. *
  28047. * @param {String} name
  28048. * @return {Type}
  28049. * @api public
  28050. */
  28051. function debug(name) {
  28052. if (!debug.enabled(name)) return function(){};
  28053. return function(fmt){
  28054. fmt = coerce(fmt);
  28055. var curr = new Date;
  28056. var ms = curr - (debug[name] || curr);
  28057. debug[name] = curr;
  28058. fmt = name
  28059. + ' '
  28060. + fmt
  28061. + ' +' + debug.humanize(ms);
  28062. // This hackery is required for IE8
  28063. // where `console.log` doesn't have 'apply'
  28064. window.console
  28065. && console.log
  28066. && Function.prototype.apply.call(console.log, console, arguments);
  28067. }
  28068. }
  28069. /**
  28070. * The currently active debug mode names.
  28071. */
  28072. debug.names = [];
  28073. debug.skips = [];
  28074. /**
  28075. * Enables a debug mode by name. This can include modes
  28076. * separated by a colon and wildcards.
  28077. *
  28078. * @param {String} name
  28079. * @api public
  28080. */
  28081. debug.enable = function(name) {
  28082. try {
  28083. localStorage.debug = name;
  28084. } catch(e){}
  28085. var split = (name || '').split(/[\s,]+/)
  28086. , len = split.length;
  28087. for (var i = 0; i < len; i++) {
  28088. name = split[i].replace('*', '.*?');
  28089. if (name[0] === '-') {
  28090. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  28091. }
  28092. else {
  28093. debug.names.push(new RegExp('^' + name + '$'));
  28094. }
  28095. }
  28096. };
  28097. /**
  28098. * Disable debug output.
  28099. *
  28100. * @api public
  28101. */
  28102. debug.disable = function(){
  28103. debug.enable('');
  28104. };
  28105. /**
  28106. * Humanize the given `ms`.
  28107. *
  28108. * @param {Number} m
  28109. * @return {String}
  28110. * @api private
  28111. */
  28112. debug.humanize = function(ms) {
  28113. var sec = 1000
  28114. , min = 60 * 1000
  28115. , hour = 60 * min;
  28116. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  28117. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  28118. if (ms >= sec) return (ms / sec | 0) + 's';
  28119. return ms + 'ms';
  28120. };
  28121. /**
  28122. * Returns true if the given mode name is enabled, false otherwise.
  28123. *
  28124. * @param {String} name
  28125. * @return {Boolean}
  28126. * @api public
  28127. */
  28128. debug.enabled = function(name) {
  28129. for (var i = 0, len = debug.skips.length; i < len; i++) {
  28130. if (debug.skips[i].test(name)) {
  28131. return false;
  28132. }
  28133. }
  28134. for (var i = 0, len = debug.names.length; i < len; i++) {
  28135. if (debug.names[i].test(name)) {
  28136. return true;
  28137. }
  28138. }
  28139. return false;
  28140. };
  28141. /**
  28142. * Coerce `val`.
  28143. */
  28144. function coerce(val) {
  28145. if (val instanceof Error) return val.stack || val.message;
  28146. return val;
  28147. }
  28148. // persist
  28149. try {
  28150. if (window.localStorage) debug.enable(localStorage.debug);
  28151. } catch(e){}
  28152. },{}],111:[function(require,module,exports){
  28153. module.exports = require('./lib/');
  28154. },{"./lib/":112}],112:[function(require,module,exports){
  28155. module.exports = require('./socket');
  28156. /**
  28157. * Exports parser
  28158. *
  28159. * @api public
  28160. *
  28161. */
  28162. module.exports.parser = require('engine.io-parser');
  28163. },{"./socket":113,"engine.io-parser":125}],113:[function(require,module,exports){
  28164. (function (global){
  28165. /**
  28166. * Module dependencies.
  28167. */
  28168. var transports = require('./transports');
  28169. var Emitter = require('component-emitter');
  28170. var debug = require('debug')('engine.io-client:socket');
  28171. var index = require('indexof');
  28172. var parser = require('engine.io-parser');
  28173. var parseuri = require('parseuri');
  28174. var parsejson = require('parsejson');
  28175. var parseqs = require('parseqs');
  28176. /**
  28177. * Module exports.
  28178. */
  28179. module.exports = Socket;
  28180. /**
  28181. * Noop function.
  28182. *
  28183. * @api private
  28184. */
  28185. function noop(){}
  28186. /**
  28187. * Socket constructor.
  28188. *
  28189. * @param {String|Object} uri or options
  28190. * @param {Object} options
  28191. * @api public
  28192. */
  28193. function Socket(uri, opts){
  28194. if (!(this instanceof Socket)) return new Socket(uri, opts);
  28195. opts = opts || {};
  28196. if (uri && 'object' == typeof uri) {
  28197. opts = uri;
  28198. uri = null;
  28199. }
  28200. if (uri) {
  28201. uri = parseuri(uri);
  28202. opts.host = uri.host;
  28203. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  28204. opts.port = uri.port;
  28205. if (uri.query) opts.query = uri.query;
  28206. }
  28207. this.secure = null != opts.secure ? opts.secure :
  28208. (global.location && 'https:' == location.protocol);
  28209. if (opts.host) {
  28210. var pieces = opts.host.split(':');
  28211. opts.hostname = pieces.shift();
  28212. if (pieces.length) {
  28213. opts.port = pieces.pop();
  28214. } else if (!opts.port) {
  28215. // if no port is specified manually, use the protocol default
  28216. opts.port = this.secure ? '443' : '80';
  28217. }
  28218. }
  28219. this.agent = opts.agent || false;
  28220. this.hostname = opts.hostname ||
  28221. (global.location ? location.hostname : 'localhost');
  28222. this.port = opts.port || (global.location && location.port ?
  28223. location.port :
  28224. (this.secure ? 443 : 80));
  28225. this.query = opts.query || {};
  28226. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  28227. this.upgrade = false !== opts.upgrade;
  28228. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  28229. this.forceJSONP = !!opts.forceJSONP;
  28230. this.jsonp = false !== opts.jsonp;
  28231. this.forceBase64 = !!opts.forceBase64;
  28232. this.enablesXDR = !!opts.enablesXDR;
  28233. this.timestampParam = opts.timestampParam || 't';
  28234. this.timestampRequests = opts.timestampRequests;
  28235. this.transports = opts.transports || ['polling', 'websocket'];
  28236. this.readyState = '';
  28237. this.writeBuffer = [];
  28238. this.callbackBuffer = [];
  28239. this.policyPort = opts.policyPort || 843;
  28240. this.rememberUpgrade = opts.rememberUpgrade || false;
  28241. this.binaryType = null;
  28242. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  28243. // SSL options for Node.js client
  28244. this.pfx = opts.pfx || null;
  28245. this.key = opts.key || null;
  28246. this.passphrase = opts.passphrase || null;
  28247. this.cert = opts.cert || null;
  28248. this.ca = opts.ca || null;
  28249. this.ciphers = opts.ciphers || null;
  28250. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  28251. this.open();
  28252. }
  28253. Socket.priorWebsocketSuccess = false;
  28254. /**
  28255. * Mix in `Emitter`.
  28256. */
  28257. Emitter(Socket.prototype);
  28258. /**
  28259. * Protocol version.
  28260. *
  28261. * @api public
  28262. */
  28263. Socket.protocol = parser.protocol; // this is an int
  28264. /**
  28265. * Expose deps for legacy compatibility
  28266. * and standalone browser access.
  28267. */
  28268. Socket.Socket = Socket;
  28269. Socket.Transport = require('./transport');
  28270. Socket.transports = require('./transports');
  28271. Socket.parser = require('engine.io-parser');
  28272. /**
  28273. * Creates transport of the given type.
  28274. *
  28275. * @param {String} transport name
  28276. * @return {Transport}
  28277. * @api private
  28278. */
  28279. Socket.prototype.createTransport = function (name) {
  28280. debug('creating transport "%s"', name);
  28281. var query = clone(this.query);
  28282. // append engine.io protocol identifier
  28283. query.EIO = parser.protocol;
  28284. // transport name
  28285. query.transport = name;
  28286. // session id if we already have one
  28287. if (this.id) query.sid = this.id;
  28288. var transport = new transports[name]({
  28289. agent: this.agent,
  28290. hostname: this.hostname,
  28291. port: this.port,
  28292. secure: this.secure,
  28293. path: this.path,
  28294. query: query,
  28295. forceJSONP: this.forceJSONP,
  28296. jsonp: this.jsonp,
  28297. forceBase64: this.forceBase64,
  28298. enablesXDR: this.enablesXDR,
  28299. timestampRequests: this.timestampRequests,
  28300. timestampParam: this.timestampParam,
  28301. policyPort: this.policyPort,
  28302. socket: this,
  28303. pfx: this.pfx,
  28304. key: this.key,
  28305. passphrase: this.passphrase,
  28306. cert: this.cert,
  28307. ca: this.ca,
  28308. ciphers: this.ciphers,
  28309. rejectUnauthorized: this.rejectUnauthorized
  28310. });
  28311. return transport;
  28312. };
  28313. function clone (obj) {
  28314. var o = {};
  28315. for (var i in obj) {
  28316. if (obj.hasOwnProperty(i)) {
  28317. o[i] = obj[i];
  28318. }
  28319. }
  28320. return o;
  28321. }
  28322. /**
  28323. * Initializes transport to use and starts probe.
  28324. *
  28325. * @api private
  28326. */
  28327. Socket.prototype.open = function () {
  28328. var transport;
  28329. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  28330. transport = 'websocket';
  28331. } else if (0 == this.transports.length) {
  28332. // Emit error on next tick so it can be listened to
  28333. var self = this;
  28334. setTimeout(function() {
  28335. self.emit('error', 'No transports available');
  28336. }, 0);
  28337. return;
  28338. } else {
  28339. transport = this.transports[0];
  28340. }
  28341. this.readyState = 'opening';
  28342. // Retry with the next transport if the transport is disabled (jsonp: false)
  28343. var transport;
  28344. try {
  28345. transport = this.createTransport(transport);
  28346. } catch (e) {
  28347. this.transports.shift();
  28348. this.open();
  28349. return;
  28350. }
  28351. transport.open();
  28352. this.setTransport(transport);
  28353. };
  28354. /**
  28355. * Sets the current transport. Disables the existing one (if any).
  28356. *
  28357. * @api private
  28358. */
  28359. Socket.prototype.setTransport = function(transport){
  28360. debug('setting transport %s', transport.name);
  28361. var self = this;
  28362. if (this.transport) {
  28363. debug('clearing existing transport %s', this.transport.name);
  28364. this.transport.removeAllListeners();
  28365. }
  28366. // set up transport
  28367. this.transport = transport;
  28368. // set up transport listeners
  28369. transport
  28370. .on('drain', function(){
  28371. self.onDrain();
  28372. })
  28373. .on('packet', function(packet){
  28374. self.onPacket(packet);
  28375. })
  28376. .on('error', function(e){
  28377. self.onError(e);
  28378. })
  28379. .on('close', function(){
  28380. self.onClose('transport close');
  28381. });
  28382. };
  28383. /**
  28384. * Probes a transport.
  28385. *
  28386. * @param {String} transport name
  28387. * @api private
  28388. */
  28389. Socket.prototype.probe = function (name) {
  28390. debug('probing transport "%s"', name);
  28391. var transport = this.createTransport(name, { probe: 1 })
  28392. , failed = false
  28393. , self = this;
  28394. Socket.priorWebsocketSuccess = false;
  28395. function onTransportOpen(){
  28396. if (self.onlyBinaryUpgrades) {
  28397. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  28398. failed = failed || upgradeLosesBinary;
  28399. }
  28400. if (failed) return;
  28401. debug('probe transport "%s" opened', name);
  28402. transport.send([{ type: 'ping', data: 'probe' }]);
  28403. transport.once('packet', function (msg) {
  28404. if (failed) return;
  28405. if ('pong' == msg.type && 'probe' == msg.data) {
  28406. debug('probe transport "%s" pong', name);
  28407. self.upgrading = true;
  28408. self.emit('upgrading', transport);
  28409. if (!transport) return;
  28410. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  28411. debug('pausing current transport "%s"', self.transport.name);
  28412. self.transport.pause(function () {
  28413. if (failed) return;
  28414. if ('closed' == self.readyState) return;
  28415. debug('changing transport and sending upgrade packet');
  28416. cleanup();
  28417. self.setTransport(transport);
  28418. transport.send([{ type: 'upgrade' }]);
  28419. self.emit('upgrade', transport);
  28420. transport = null;
  28421. self.upgrading = false;
  28422. self.flush();
  28423. });
  28424. } else {
  28425. debug('probe transport "%s" failed', name);
  28426. var err = new Error('probe error');
  28427. err.transport = transport.name;
  28428. self.emit('upgradeError', err);
  28429. }
  28430. });
  28431. }
  28432. function freezeTransport() {
  28433. if (failed) return;
  28434. // Any callback called by transport should be ignored since now
  28435. failed = true;
  28436. cleanup();
  28437. transport.close();
  28438. transport = null;
  28439. }
  28440. //Handle any error that happens while probing
  28441. function onerror(err) {
  28442. var error = new Error('probe error: ' + err);
  28443. error.transport = transport.name;
  28444. freezeTransport();
  28445. debug('probe transport "%s" failed because of error: %s', name, err);
  28446. self.emit('upgradeError', error);
  28447. }
  28448. function onTransportClose(){
  28449. onerror("transport closed");
  28450. }
  28451. //When the socket is closed while we're probing
  28452. function onclose(){
  28453. onerror("socket closed");
  28454. }
  28455. //When the socket is upgraded while we're probing
  28456. function onupgrade(to){
  28457. if (transport && to.name != transport.name) {
  28458. debug('"%s" works - aborting "%s"', to.name, transport.name);
  28459. freezeTransport();
  28460. }
  28461. }
  28462. //Remove all listeners on the transport and on self
  28463. function cleanup(){
  28464. transport.removeListener('open', onTransportOpen);
  28465. transport.removeListener('error', onerror);
  28466. transport.removeListener('close', onTransportClose);
  28467. self.removeListener('close', onclose);
  28468. self.removeListener('upgrading', onupgrade);
  28469. }
  28470. transport.once('open', onTransportOpen);
  28471. transport.once('error', onerror);
  28472. transport.once('close', onTransportClose);
  28473. this.once('close', onclose);
  28474. this.once('upgrading', onupgrade);
  28475. transport.open();
  28476. };
  28477. /**
  28478. * Called when connection is deemed open.
  28479. *
  28480. * @api public
  28481. */
  28482. Socket.prototype.onOpen = function () {
  28483. debug('socket open');
  28484. this.readyState = 'open';
  28485. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  28486. this.emit('open');
  28487. this.flush();
  28488. // we check for `readyState` in case an `open`
  28489. // listener already closed the socket
  28490. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  28491. debug('starting upgrade probes');
  28492. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  28493. this.probe(this.upgrades[i]);
  28494. }
  28495. }
  28496. };
  28497. /**
  28498. * Handles a packet.
  28499. *
  28500. * @api private
  28501. */
  28502. Socket.prototype.onPacket = function (packet) {
  28503. if ('opening' == this.readyState || 'open' == this.readyState) {
  28504. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  28505. this.emit('packet', packet);
  28506. // Socket is live - any packet counts
  28507. this.emit('heartbeat');
  28508. switch (packet.type) {
  28509. case 'open':
  28510. this.onHandshake(parsejson(packet.data));
  28511. break;
  28512. case 'pong':
  28513. this.setPing();
  28514. break;
  28515. case 'error':
  28516. var err = new Error('server error');
  28517. err.code = packet.data;
  28518. this.emit('error', err);
  28519. break;
  28520. case 'message':
  28521. this.emit('data', packet.data);
  28522. this.emit('message', packet.data);
  28523. break;
  28524. }
  28525. } else {
  28526. debug('packet received with socket readyState "%s"', this.readyState);
  28527. }
  28528. };
  28529. /**
  28530. * Called upon handshake completion.
  28531. *
  28532. * @param {Object} handshake obj
  28533. * @api private
  28534. */
  28535. Socket.prototype.onHandshake = function (data) {
  28536. this.emit('handshake', data);
  28537. this.id = data.sid;
  28538. this.transport.query.sid = data.sid;
  28539. this.upgrades = this.filterUpgrades(data.upgrades);
  28540. this.pingInterval = data.pingInterval;
  28541. this.pingTimeout = data.pingTimeout;
  28542. this.onOpen();
  28543. // In case open handler closes socket
  28544. if ('closed' == this.readyState) return;
  28545. this.setPing();
  28546. // Prolong liveness of socket on heartbeat
  28547. this.removeListener('heartbeat', this.onHeartbeat);
  28548. this.on('heartbeat', this.onHeartbeat);
  28549. };
  28550. /**
  28551. * Resets ping timeout.
  28552. *
  28553. * @api private
  28554. */
  28555. Socket.prototype.onHeartbeat = function (timeout) {
  28556. clearTimeout(this.pingTimeoutTimer);
  28557. var self = this;
  28558. self.pingTimeoutTimer = setTimeout(function () {
  28559. if ('closed' == self.readyState) return;
  28560. self.onClose('ping timeout');
  28561. }, timeout || (self.pingInterval + self.pingTimeout));
  28562. };
  28563. /**
  28564. * Pings server every `this.pingInterval` and expects response
  28565. * within `this.pingTimeout` or closes connection.
  28566. *
  28567. * @api private
  28568. */
  28569. Socket.prototype.setPing = function () {
  28570. var self = this;
  28571. clearTimeout(self.pingIntervalTimer);
  28572. self.pingIntervalTimer = setTimeout(function () {
  28573. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  28574. self.ping();
  28575. self.onHeartbeat(self.pingTimeout);
  28576. }, self.pingInterval);
  28577. };
  28578. /**
  28579. * Sends a ping packet.
  28580. *
  28581. * @api public
  28582. */
  28583. Socket.prototype.ping = function () {
  28584. this.sendPacket('ping');
  28585. };
  28586. /**
  28587. * Called on `drain` event
  28588. *
  28589. * @api private
  28590. */
  28591. Socket.prototype.onDrain = function() {
  28592. for (var i = 0; i < this.prevBufferLen; i++) {
  28593. if (this.callbackBuffer[i]) {
  28594. this.callbackBuffer[i]();
  28595. }
  28596. }
  28597. this.writeBuffer.splice(0, this.prevBufferLen);
  28598. this.callbackBuffer.splice(0, this.prevBufferLen);
  28599. // setting prevBufferLen = 0 is very important
  28600. // for example, when upgrading, upgrade packet is sent over,
  28601. // and a nonzero prevBufferLen could cause problems on `drain`
  28602. this.prevBufferLen = 0;
  28603. if (this.writeBuffer.length == 0) {
  28604. this.emit('drain');
  28605. } else {
  28606. this.flush();
  28607. }
  28608. };
  28609. /**
  28610. * Flush write buffers.
  28611. *
  28612. * @api private
  28613. */
  28614. Socket.prototype.flush = function () {
  28615. if ('closed' != this.readyState && this.transport.writable &&
  28616. !this.upgrading && this.writeBuffer.length) {
  28617. debug('flushing %d packets in socket', this.writeBuffer.length);
  28618. this.transport.send(this.writeBuffer);
  28619. // keep track of current length of writeBuffer
  28620. // splice writeBuffer and callbackBuffer on `drain`
  28621. this.prevBufferLen = this.writeBuffer.length;
  28622. this.emit('flush');
  28623. }
  28624. };
  28625. /**
  28626. * Sends a message.
  28627. *
  28628. * @param {String} message.
  28629. * @param {Function} callback function.
  28630. * @return {Socket} for chaining.
  28631. * @api public
  28632. */
  28633. Socket.prototype.write =
  28634. Socket.prototype.send = function (msg, fn) {
  28635. this.sendPacket('message', msg, fn);
  28636. return this;
  28637. };
  28638. /**
  28639. * Sends a packet.
  28640. *
  28641. * @param {String} packet type.
  28642. * @param {String} data.
  28643. * @param {Function} callback function.
  28644. * @api private
  28645. */
  28646. Socket.prototype.sendPacket = function (type, data, fn) {
  28647. if ('closing' == this.readyState || 'closed' == this.readyState) {
  28648. return;
  28649. }
  28650. var packet = { type: type, data: data };
  28651. this.emit('packetCreate', packet);
  28652. this.writeBuffer.push(packet);
  28653. this.callbackBuffer.push(fn);
  28654. this.flush();
  28655. };
  28656. /**
  28657. * Closes the connection.
  28658. *
  28659. * @api private
  28660. */
  28661. Socket.prototype.close = function () {
  28662. if ('opening' == this.readyState || 'open' == this.readyState) {
  28663. this.readyState = 'closing';
  28664. var self = this;
  28665. function close() {
  28666. self.onClose('forced close');
  28667. debug('socket closing - telling transport to close');
  28668. self.transport.close();
  28669. }
  28670. function cleanupAndClose() {
  28671. self.removeListener('upgrade', cleanupAndClose);
  28672. self.removeListener('upgradeError', cleanupAndClose);
  28673. close();
  28674. }
  28675. function waitForUpgrade() {
  28676. // wait for upgrade to finish since we can't send packets while pausing a transport
  28677. self.once('upgrade', cleanupAndClose);
  28678. self.once('upgradeError', cleanupAndClose);
  28679. }
  28680. if (this.writeBuffer.length) {
  28681. this.once('drain', function() {
  28682. if (this.upgrading) {
  28683. waitForUpgrade();
  28684. } else {
  28685. close();
  28686. }
  28687. });
  28688. } else if (this.upgrading) {
  28689. waitForUpgrade();
  28690. } else {
  28691. close();
  28692. }
  28693. }
  28694. return this;
  28695. };
  28696. /**
  28697. * Called upon transport error
  28698. *
  28699. * @api private
  28700. */
  28701. Socket.prototype.onError = function (err) {
  28702. debug('socket error %j', err);
  28703. Socket.priorWebsocketSuccess = false;
  28704. this.emit('error', err);
  28705. this.onClose('transport error', err);
  28706. };
  28707. /**
  28708. * Called upon transport close.
  28709. *
  28710. * @api private
  28711. */
  28712. Socket.prototype.onClose = function (reason, desc) {
  28713. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  28714. debug('socket close with reason: "%s"', reason);
  28715. var self = this;
  28716. // clear timers
  28717. clearTimeout(this.pingIntervalTimer);
  28718. clearTimeout(this.pingTimeoutTimer);
  28719. // clean buffers in next tick, so developers can still
  28720. // grab the buffers on `close` event
  28721. setTimeout(function() {
  28722. self.writeBuffer = [];
  28723. self.callbackBuffer = [];
  28724. self.prevBufferLen = 0;
  28725. }, 0);
  28726. // stop event from firing again for transport
  28727. this.transport.removeAllListeners('close');
  28728. // ensure transport won't stay open
  28729. this.transport.close();
  28730. // ignore further transport communication
  28731. this.transport.removeAllListeners();
  28732. // set ready state
  28733. this.readyState = 'closed';
  28734. // clear session id
  28735. this.id = null;
  28736. // emit close event
  28737. this.emit('close', reason, desc);
  28738. }
  28739. };
  28740. /**
  28741. * Filters upgrades, returning only those matching client transports.
  28742. *
  28743. * @param {Array} server upgrades
  28744. * @api private
  28745. *
  28746. */
  28747. Socket.prototype.filterUpgrades = function (upgrades) {
  28748. var filteredUpgrades = [];
  28749. for (var i = 0, j = upgrades.length; i<j; i++) {
  28750. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  28751. }
  28752. return filteredUpgrades;
  28753. };
  28754. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  28755. },{"./transport":114,"./transports":115,"component-emitter":109,"debug":122,"engine.io-parser":125,"indexof":142,"parsejson":136,"parseqs":137,"parseuri":138}],114:[function(require,module,exports){
  28756. /**
  28757. * Module dependencies.
  28758. */
  28759. var parser = require('engine.io-parser');
  28760. var Emitter = require('component-emitter');
  28761. /**
  28762. * Module exports.
  28763. */
  28764. module.exports = Transport;
  28765. /**
  28766. * Transport abstract constructor.
  28767. *
  28768. * @param {Object} options.
  28769. * @api private
  28770. */
  28771. function Transport (opts) {
  28772. this.path = opts.path;
  28773. this.hostname = opts.hostname;
  28774. this.port = opts.port;
  28775. this.secure = opts.secure;
  28776. this.query = opts.query;
  28777. this.timestampParam = opts.timestampParam;
  28778. this.timestampRequests = opts.timestampRequests;
  28779. this.readyState = '';
  28780. this.agent = opts.agent || false;
  28781. this.socket = opts.socket;
  28782. this.enablesXDR = opts.enablesXDR;
  28783. // SSL options for Node.js client
  28784. this.pfx = opts.pfx;
  28785. this.key = opts.key;
  28786. this.passphrase = opts.passphrase;
  28787. this.cert = opts.cert;
  28788. this.ca = opts.ca;
  28789. this.ciphers = opts.ciphers;
  28790. this.rejectUnauthorized = opts.rejectUnauthorized;
  28791. }
  28792. /**
  28793. * Mix in `Emitter`.
  28794. */
  28795. Emitter(Transport.prototype);
  28796. /**
  28797. * A counter used to prevent collisions in the timestamps used
  28798. * for cache busting.
  28799. */
  28800. Transport.timestamps = 0;
  28801. /**
  28802. * Emits an error.
  28803. *
  28804. * @param {String} str
  28805. * @return {Transport} for chaining
  28806. * @api public
  28807. */
  28808. Transport.prototype.onError = function (msg, desc) {
  28809. var err = new Error(msg);
  28810. err.type = 'TransportError';
  28811. err.description = desc;
  28812. this.emit('error', err);
  28813. return this;
  28814. };
  28815. /**
  28816. * Opens the transport.
  28817. *
  28818. * @api public
  28819. */
  28820. Transport.prototype.open = function () {
  28821. if ('closed' == this.readyState || '' == this.readyState) {
  28822. this.readyState = 'opening';
  28823. this.doOpen();
  28824. }
  28825. return this;
  28826. };
  28827. /**
  28828. * Closes the transport.
  28829. *
  28830. * @api private
  28831. */
  28832. Transport.prototype.close = function () {
  28833. if ('opening' == this.readyState || 'open' == this.readyState) {
  28834. this.doClose();
  28835. this.onClose();
  28836. }
  28837. return this;
  28838. };
  28839. /**
  28840. * Sends multiple packets.
  28841. *
  28842. * @param {Array} packets
  28843. * @api private
  28844. */
  28845. Transport.prototype.send = function(packets){
  28846. if ('open' == this.readyState) {
  28847. this.write(packets);
  28848. } else {
  28849. throw new Error('Transport not open');
  28850. }
  28851. };
  28852. /**
  28853. * Called upon open
  28854. *
  28855. * @api private
  28856. */
  28857. Transport.prototype.onOpen = function () {
  28858. this.readyState = 'open';
  28859. this.writable = true;
  28860. this.emit('open');
  28861. };
  28862. /**
  28863. * Called with data.
  28864. *
  28865. * @param {String} data
  28866. * @api private
  28867. */
  28868. Transport.prototype.onData = function(data){
  28869. var packet = parser.decodePacket(data, this.socket.binaryType);
  28870. this.onPacket(packet);
  28871. };
  28872. /**
  28873. * Called with a decoded packet.
  28874. */
  28875. Transport.prototype.onPacket = function (packet) {
  28876. this.emit('packet', packet);
  28877. };
  28878. /**
  28879. * Called upon close.
  28880. *
  28881. * @api private
  28882. */
  28883. Transport.prototype.onClose = function () {
  28884. this.readyState = 'closed';
  28885. this.emit('close');
  28886. };
  28887. },{"component-emitter":109,"engine.io-parser":125}],115:[function(require,module,exports){
  28888. (function (global){
  28889. /**
  28890. * Module dependencies
  28891. */
  28892. var XMLHttpRequest = require('xmlhttprequest');
  28893. var XHR = require('./polling-xhr');
  28894. var JSONP = require('./polling-jsonp');
  28895. var websocket = require('./websocket');
  28896. /**
  28897. * Export transports.
  28898. */
  28899. exports.polling = polling;
  28900. exports.websocket = websocket;
  28901. /**
  28902. * Polling transport polymorphic constructor.
  28903. * Decides on xhr vs jsonp based on feature detection.
  28904. *
  28905. * @api private
  28906. */
  28907. function polling(opts){
  28908. var xhr;
  28909. var xd = false;
  28910. var xs = false;
  28911. var jsonp = false !== opts.jsonp;
  28912. if (global.location) {
  28913. var isSSL = 'https:' == location.protocol;
  28914. var port = location.port;
  28915. // some user agents have empty `location.port`
  28916. if (!port) {
  28917. port = isSSL ? 443 : 80;
  28918. }
  28919. xd = opts.hostname != location.hostname || port != opts.port;
  28920. xs = opts.secure != isSSL;
  28921. }
  28922. opts.xdomain = xd;
  28923. opts.xscheme = xs;
  28924. xhr = new XMLHttpRequest(opts);
  28925. if ('open' in xhr && !opts.forceJSONP) {
  28926. return new XHR(opts);
  28927. } else {
  28928. if (!jsonp) throw new Error('JSONP disabled');
  28929. return new JSONP(opts);
  28930. }
  28931. }
  28932. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  28933. },{"./polling-jsonp":116,"./polling-xhr":117,"./websocket":119,"xmlhttprequest":120}],116:[function(require,module,exports){
  28934. (function (global){
  28935. /**
  28936. * Module requirements.
  28937. */
  28938. var Polling = require('./polling');
  28939. var inherit = require('component-inherit');
  28940. /**
  28941. * Module exports.
  28942. */
  28943. module.exports = JSONPPolling;
  28944. /**
  28945. * Cached regular expressions.
  28946. */
  28947. var rNewline = /\n/g;
  28948. var rEscapedNewline = /\\n/g;
  28949. /**
  28950. * Global JSONP callbacks.
  28951. */
  28952. var callbacks;
  28953. /**
  28954. * Callbacks count.
  28955. */
  28956. var index = 0;
  28957. /**
  28958. * Noop.
  28959. */
  28960. function empty () { }
  28961. /**
  28962. * JSONP Polling constructor.
  28963. *
  28964. * @param {Object} opts.
  28965. * @api public
  28966. */
  28967. function JSONPPolling (opts) {
  28968. Polling.call(this, opts);
  28969. this.query = this.query || {};
  28970. // define global callbacks array if not present
  28971. // we do this here (lazily) to avoid unneeded global pollution
  28972. if (!callbacks) {
  28973. // we need to consider multiple engines in the same page
  28974. if (!global.___eio) global.___eio = [];
  28975. callbacks = global.___eio;
  28976. }
  28977. // callback identifier
  28978. this.index = callbacks.length;
  28979. // add callback to jsonp global
  28980. var self = this;
  28981. callbacks.push(function (msg) {
  28982. self.onData(msg);
  28983. });
  28984. // append to query string
  28985. this.query.j = this.index;
  28986. // prevent spurious errors from being emitted when the window is unloaded
  28987. if (global.document && global.addEventListener) {
  28988. global.addEventListener('beforeunload', function () {
  28989. if (self.script) self.script.onerror = empty;
  28990. }, false);
  28991. }
  28992. }
  28993. /**
  28994. * Inherits from Polling.
  28995. */
  28996. inherit(JSONPPolling, Polling);
  28997. /*
  28998. * JSONP only supports binary as base64 encoded strings
  28999. */
  29000. JSONPPolling.prototype.supportsBinary = false;
  29001. /**
  29002. * Closes the socket.
  29003. *
  29004. * @api private
  29005. */
  29006. JSONPPolling.prototype.doClose = function () {
  29007. if (this.script) {
  29008. this.script.parentNode.removeChild(this.script);
  29009. this.script = null;
  29010. }
  29011. if (this.form) {
  29012. this.form.parentNode.removeChild(this.form);
  29013. this.form = null;
  29014. this.iframe = null;
  29015. }
  29016. Polling.prototype.doClose.call(this);
  29017. };
  29018. /**
  29019. * Starts a poll cycle.
  29020. *
  29021. * @api private
  29022. */
  29023. JSONPPolling.prototype.doPoll = function () {
  29024. var self = this;
  29025. var script = document.createElement('script');
  29026. if (this.script) {
  29027. this.script.parentNode.removeChild(this.script);
  29028. this.script = null;
  29029. }
  29030. script.async = true;
  29031. script.src = this.uri();
  29032. script.onerror = function(e){
  29033. self.onError('jsonp poll error',e);
  29034. };
  29035. var insertAt = document.getElementsByTagName('script')[0];
  29036. insertAt.parentNode.insertBefore(script, insertAt);
  29037. this.script = script;
  29038. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  29039. if (isUAgecko) {
  29040. setTimeout(function () {
  29041. var iframe = document.createElement('iframe');
  29042. document.body.appendChild(iframe);
  29043. document.body.removeChild(iframe);
  29044. }, 100);
  29045. }
  29046. };
  29047. /**
  29048. * Writes with a hidden iframe.
  29049. *
  29050. * @param {String} data to send
  29051. * @param {Function} called upon flush.
  29052. * @api private
  29053. */
  29054. JSONPPolling.prototype.doWrite = function (data, fn) {
  29055. var self = this;
  29056. if (!this.form) {
  29057. var form = document.createElement('form');
  29058. var area = document.createElement('textarea');
  29059. var id = this.iframeId = 'eio_iframe_' + this.index;
  29060. var iframe;
  29061. form.className = 'socketio';
  29062. form.style.position = 'absolute';
  29063. form.style.top = '-1000px';
  29064. form.style.left = '-1000px';
  29065. form.target = id;
  29066. form.method = 'POST';
  29067. form.setAttribute('accept-charset', 'utf-8');
  29068. area.name = 'd';
  29069. form.appendChild(area);
  29070. document.body.appendChild(form);
  29071. this.form = form;
  29072. this.area = area;
  29073. }
  29074. this.form.action = this.uri();
  29075. function complete () {
  29076. initIframe();
  29077. fn();
  29078. }
  29079. function initIframe () {
  29080. if (self.iframe) {
  29081. try {
  29082. self.form.removeChild(self.iframe);
  29083. } catch (e) {
  29084. self.onError('jsonp polling iframe removal error', e);
  29085. }
  29086. }
  29087. try {
  29088. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  29089. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  29090. iframe = document.createElement(html);
  29091. } catch (e) {
  29092. iframe = document.createElement('iframe');
  29093. iframe.name = self.iframeId;
  29094. iframe.src = 'javascript:0';
  29095. }
  29096. iframe.id = self.iframeId;
  29097. self.form.appendChild(iframe);
  29098. self.iframe = iframe;
  29099. }
  29100. initIframe();
  29101. // escape \n to prevent it from being converted into \r\n by some UAs
  29102. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  29103. data = data.replace(rEscapedNewline, '\\\n');
  29104. this.area.value = data.replace(rNewline, '\\n');
  29105. try {
  29106. this.form.submit();
  29107. } catch(e) {}
  29108. if (this.iframe.attachEvent) {
  29109. this.iframe.onreadystatechange = function(){
  29110. if (self.iframe.readyState == 'complete') {
  29111. complete();
  29112. }
  29113. };
  29114. } else {
  29115. this.iframe.onload = complete;
  29116. }
  29117. };
  29118. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29119. },{"./polling":118,"component-inherit":121}],117:[function(require,module,exports){
  29120. (function (global){
  29121. /**
  29122. * Module requirements.
  29123. */
  29124. var XMLHttpRequest = require('xmlhttprequest');
  29125. var Polling = require('./polling');
  29126. var Emitter = require('component-emitter');
  29127. var inherit = require('component-inherit');
  29128. var debug = require('debug')('engine.io-client:polling-xhr');
  29129. /**
  29130. * Module exports.
  29131. */
  29132. module.exports = XHR;
  29133. module.exports.Request = Request;
  29134. /**
  29135. * Empty function
  29136. */
  29137. function empty(){}
  29138. /**
  29139. * XHR Polling constructor.
  29140. *
  29141. * @param {Object} opts
  29142. * @api public
  29143. */
  29144. function XHR(opts){
  29145. Polling.call(this, opts);
  29146. if (global.location) {
  29147. var isSSL = 'https:' == location.protocol;
  29148. var port = location.port;
  29149. // some user agents have empty `location.port`
  29150. if (!port) {
  29151. port = isSSL ? 443 : 80;
  29152. }
  29153. this.xd = opts.hostname != global.location.hostname ||
  29154. port != opts.port;
  29155. this.xs = opts.secure != isSSL;
  29156. }
  29157. }
  29158. /**
  29159. * Inherits from Polling.
  29160. */
  29161. inherit(XHR, Polling);
  29162. /**
  29163. * XHR supports binary
  29164. */
  29165. XHR.prototype.supportsBinary = true;
  29166. /**
  29167. * Creates a request.
  29168. *
  29169. * @param {String} method
  29170. * @api private
  29171. */
  29172. XHR.prototype.request = function(opts){
  29173. opts = opts || {};
  29174. opts.uri = this.uri();
  29175. opts.xd = this.xd;
  29176. opts.xs = this.xs;
  29177. opts.agent = this.agent || false;
  29178. opts.supportsBinary = this.supportsBinary;
  29179. opts.enablesXDR = this.enablesXDR;
  29180. // SSL options for Node.js client
  29181. opts.pfx = this.pfx;
  29182. opts.key = this.key;
  29183. opts.passphrase = this.passphrase;
  29184. opts.cert = this.cert;
  29185. opts.ca = this.ca;
  29186. opts.ciphers = this.ciphers;
  29187. opts.rejectUnauthorized = this.rejectUnauthorized;
  29188. return new Request(opts);
  29189. };
  29190. /**
  29191. * Sends data.
  29192. *
  29193. * @param {String} data to send.
  29194. * @param {Function} called upon flush.
  29195. * @api private
  29196. */
  29197. XHR.prototype.doWrite = function(data, fn){
  29198. var isBinary = typeof data !== 'string' && data !== undefined;
  29199. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  29200. var self = this;
  29201. req.on('success', fn);
  29202. req.on('error', function(err){
  29203. self.onError('xhr post error', err);
  29204. });
  29205. this.sendXhr = req;
  29206. };
  29207. /**
  29208. * Starts a poll cycle.
  29209. *
  29210. * @api private
  29211. */
  29212. XHR.prototype.doPoll = function(){
  29213. debug('xhr poll');
  29214. var req = this.request();
  29215. var self = this;
  29216. req.on('data', function(data){
  29217. self.onData(data);
  29218. });
  29219. req.on('error', function(err){
  29220. self.onError('xhr poll error', err);
  29221. });
  29222. this.pollXhr = req;
  29223. };
  29224. /**
  29225. * Request constructor
  29226. *
  29227. * @param {Object} options
  29228. * @api public
  29229. */
  29230. function Request(opts){
  29231. this.method = opts.method || 'GET';
  29232. this.uri = opts.uri;
  29233. this.xd = !!opts.xd;
  29234. this.xs = !!opts.xs;
  29235. this.async = false !== opts.async;
  29236. this.data = undefined != opts.data ? opts.data : null;
  29237. this.agent = opts.agent;
  29238. this.isBinary = opts.isBinary;
  29239. this.supportsBinary = opts.supportsBinary;
  29240. this.enablesXDR = opts.enablesXDR;
  29241. // SSL options for Node.js client
  29242. this.pfx = opts.pfx;
  29243. this.key = opts.key;
  29244. this.passphrase = opts.passphrase;
  29245. this.cert = opts.cert;
  29246. this.ca = opts.ca;
  29247. this.ciphers = opts.ciphers;
  29248. this.rejectUnauthorized = opts.rejectUnauthorized;
  29249. this.create();
  29250. }
  29251. /**
  29252. * Mix in `Emitter`.
  29253. */
  29254. Emitter(Request.prototype);
  29255. /**
  29256. * Creates the XHR object and sends the request.
  29257. *
  29258. * @api private
  29259. */
  29260. Request.prototype.create = function(){
  29261. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  29262. // SSL options for Node.js client
  29263. opts.pfx = this.pfx;
  29264. opts.key = this.key;
  29265. opts.passphrase = this.passphrase;
  29266. opts.cert = this.cert;
  29267. opts.ca = this.ca;
  29268. opts.ciphers = this.ciphers;
  29269. opts.rejectUnauthorized = this.rejectUnauthorized;
  29270. var xhr = this.xhr = new XMLHttpRequest(opts);
  29271. var self = this;
  29272. try {
  29273. debug('xhr open %s: %s', this.method, this.uri);
  29274. xhr.open(this.method, this.uri, this.async);
  29275. if (this.supportsBinary) {
  29276. // This has to be done after open because Firefox is stupid
  29277. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  29278. xhr.responseType = 'arraybuffer';
  29279. }
  29280. if ('POST' == this.method) {
  29281. try {
  29282. if (this.isBinary) {
  29283. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  29284. } else {
  29285. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  29286. }
  29287. } catch (e) {}
  29288. }
  29289. // ie6 check
  29290. if ('withCredentials' in xhr) {
  29291. xhr.withCredentials = true;
  29292. }
  29293. if (this.hasXDR()) {
  29294. xhr.onload = function(){
  29295. self.onLoad();
  29296. };
  29297. xhr.onerror = function(){
  29298. self.onError(xhr.responseText);
  29299. };
  29300. } else {
  29301. xhr.onreadystatechange = function(){
  29302. if (4 != xhr.readyState) return;
  29303. if (200 == xhr.status || 1223 == xhr.status) {
  29304. self.onLoad();
  29305. } else {
  29306. // make sure the `error` event handler that's user-set
  29307. // does not throw in the same tick and gets caught here
  29308. setTimeout(function(){
  29309. self.onError(xhr.status);
  29310. }, 0);
  29311. }
  29312. };
  29313. }
  29314. debug('xhr data %s', this.data);
  29315. xhr.send(this.data);
  29316. } catch (e) {
  29317. // Need to defer since .create() is called directly fhrom the constructor
  29318. // and thus the 'error' event can only be only bound *after* this exception
  29319. // occurs. Therefore, also, we cannot throw here at all.
  29320. setTimeout(function() {
  29321. self.onError(e);
  29322. }, 0);
  29323. return;
  29324. }
  29325. if (global.document) {
  29326. this.index = Request.requestsCount++;
  29327. Request.requests[this.index] = this;
  29328. }
  29329. };
  29330. /**
  29331. * Called upon successful response.
  29332. *
  29333. * @api private
  29334. */
  29335. Request.prototype.onSuccess = function(){
  29336. this.emit('success');
  29337. this.cleanup();
  29338. };
  29339. /**
  29340. * Called if we have data.
  29341. *
  29342. * @api private
  29343. */
  29344. Request.prototype.onData = function(data){
  29345. this.emit('data', data);
  29346. this.onSuccess();
  29347. };
  29348. /**
  29349. * Called upon error.
  29350. *
  29351. * @api private
  29352. */
  29353. Request.prototype.onError = function(err){
  29354. this.emit('error', err);
  29355. this.cleanup(true);
  29356. };
  29357. /**
  29358. * Cleans up house.
  29359. *
  29360. * @api private
  29361. */
  29362. Request.prototype.cleanup = function(fromError){
  29363. if ('undefined' == typeof this.xhr || null === this.xhr) {
  29364. return;
  29365. }
  29366. // xmlhttprequest
  29367. if (this.hasXDR()) {
  29368. this.xhr.onload = this.xhr.onerror = empty;
  29369. } else {
  29370. this.xhr.onreadystatechange = empty;
  29371. }
  29372. if (fromError) {
  29373. try {
  29374. this.xhr.abort();
  29375. } catch(e) {}
  29376. }
  29377. if (global.document) {
  29378. delete Request.requests[this.index];
  29379. }
  29380. this.xhr = null;
  29381. };
  29382. /**
  29383. * Called upon load.
  29384. *
  29385. * @api private
  29386. */
  29387. Request.prototype.onLoad = function(){
  29388. var data;
  29389. try {
  29390. var contentType;
  29391. try {
  29392. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  29393. } catch (e) {}
  29394. if (contentType === 'application/octet-stream') {
  29395. data = this.xhr.response;
  29396. } else {
  29397. if (!this.supportsBinary) {
  29398. data = this.xhr.responseText;
  29399. } else {
  29400. data = 'ok';
  29401. }
  29402. }
  29403. } catch (e) {
  29404. this.onError(e);
  29405. }
  29406. if (null != data) {
  29407. this.onData(data);
  29408. }
  29409. };
  29410. /**
  29411. * Check if it has XDomainRequest.
  29412. *
  29413. * @api private
  29414. */
  29415. Request.prototype.hasXDR = function(){
  29416. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  29417. };
  29418. /**
  29419. * Aborts the request.
  29420. *
  29421. * @api public
  29422. */
  29423. Request.prototype.abort = function(){
  29424. this.cleanup();
  29425. };
  29426. /**
  29427. * Aborts pending requests when unloading the window. This is needed to prevent
  29428. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  29429. * emitted.
  29430. */
  29431. if (global.document) {
  29432. Request.requestsCount = 0;
  29433. Request.requests = {};
  29434. if (global.attachEvent) {
  29435. global.attachEvent('onunload', unloadHandler);
  29436. } else if (global.addEventListener) {
  29437. global.addEventListener('beforeunload', unloadHandler, false);
  29438. }
  29439. }
  29440. function unloadHandler() {
  29441. for (var i in Request.requests) {
  29442. if (Request.requests.hasOwnProperty(i)) {
  29443. Request.requests[i].abort();
  29444. }
  29445. }
  29446. }
  29447. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29448. },{"./polling":118,"component-emitter":109,"component-inherit":121,"debug":122,"xmlhttprequest":120}],118:[function(require,module,exports){
  29449. /**
  29450. * Module dependencies.
  29451. */
  29452. var Transport = require('../transport');
  29453. var parseqs = require('parseqs');
  29454. var parser = require('engine.io-parser');
  29455. var inherit = require('component-inherit');
  29456. var debug = require('debug')('engine.io-client:polling');
  29457. /**
  29458. * Module exports.
  29459. */
  29460. module.exports = Polling;
  29461. /**
  29462. * Is XHR2 supported?
  29463. */
  29464. var hasXHR2 = (function() {
  29465. var XMLHttpRequest = require('xmlhttprequest');
  29466. var xhr = new XMLHttpRequest({ xdomain: false });
  29467. return null != xhr.responseType;
  29468. })();
  29469. /**
  29470. * Polling interface.
  29471. *
  29472. * @param {Object} opts
  29473. * @api private
  29474. */
  29475. function Polling(opts){
  29476. var forceBase64 = (opts && opts.forceBase64);
  29477. if (!hasXHR2 || forceBase64) {
  29478. this.supportsBinary = false;
  29479. }
  29480. Transport.call(this, opts);
  29481. }
  29482. /**
  29483. * Inherits from Transport.
  29484. */
  29485. inherit(Polling, Transport);
  29486. /**
  29487. * Transport name.
  29488. */
  29489. Polling.prototype.name = 'polling';
  29490. /**
  29491. * Opens the socket (triggers polling). We write a PING message to determine
  29492. * when the transport is open.
  29493. *
  29494. * @api private
  29495. */
  29496. Polling.prototype.doOpen = function(){
  29497. this.poll();
  29498. };
  29499. /**
  29500. * Pauses polling.
  29501. *
  29502. * @param {Function} callback upon buffers are flushed and transport is paused
  29503. * @api private
  29504. */
  29505. Polling.prototype.pause = function(onPause){
  29506. var pending = 0;
  29507. var self = this;
  29508. this.readyState = 'pausing';
  29509. function pause(){
  29510. debug('paused');
  29511. self.readyState = 'paused';
  29512. onPause();
  29513. }
  29514. if (this.polling || !this.writable) {
  29515. var total = 0;
  29516. if (this.polling) {
  29517. debug('we are currently polling - waiting to pause');
  29518. total++;
  29519. this.once('pollComplete', function(){
  29520. debug('pre-pause polling complete');
  29521. --total || pause();
  29522. });
  29523. }
  29524. if (!this.writable) {
  29525. debug('we are currently writing - waiting to pause');
  29526. total++;
  29527. this.once('drain', function(){
  29528. debug('pre-pause writing complete');
  29529. --total || pause();
  29530. });
  29531. }
  29532. } else {
  29533. pause();
  29534. }
  29535. };
  29536. /**
  29537. * Starts polling cycle.
  29538. *
  29539. * @api public
  29540. */
  29541. Polling.prototype.poll = function(){
  29542. debug('polling');
  29543. this.polling = true;
  29544. this.doPoll();
  29545. this.emit('poll');
  29546. };
  29547. /**
  29548. * Overloads onData to detect payloads.
  29549. *
  29550. * @api private
  29551. */
  29552. Polling.prototype.onData = function(data){
  29553. var self = this;
  29554. debug('polling got data %s', data);
  29555. var callback = function(packet, index, total) {
  29556. // if its the first message we consider the transport open
  29557. if ('opening' == self.readyState) {
  29558. self.onOpen();
  29559. }
  29560. // if its a close packet, we close the ongoing requests
  29561. if ('close' == packet.type) {
  29562. self.onClose();
  29563. return false;
  29564. }
  29565. // otherwise bypass onData and handle the message
  29566. self.onPacket(packet);
  29567. };
  29568. // decode payload
  29569. parser.decodePayload(data, this.socket.binaryType, callback);
  29570. // if an event did not trigger closing
  29571. if ('closed' != this.readyState) {
  29572. // if we got data we're not polling
  29573. this.polling = false;
  29574. this.emit('pollComplete');
  29575. if ('open' == this.readyState) {
  29576. this.poll();
  29577. } else {
  29578. debug('ignoring poll - transport state "%s"', this.readyState);
  29579. }
  29580. }
  29581. };
  29582. /**
  29583. * For polling, send a close packet.
  29584. *
  29585. * @api private
  29586. */
  29587. Polling.prototype.doClose = function(){
  29588. var self = this;
  29589. function close(){
  29590. debug('writing close packet');
  29591. self.write([{ type: 'close' }]);
  29592. }
  29593. if ('open' == this.readyState) {
  29594. debug('transport open - closing');
  29595. close();
  29596. } else {
  29597. // in case we're trying to close while
  29598. // handshaking is in progress (GH-164)
  29599. debug('transport not open - deferring close');
  29600. this.once('open', close);
  29601. }
  29602. };
  29603. /**
  29604. * Writes a packets payload.
  29605. *
  29606. * @param {Array} data packets
  29607. * @param {Function} drain callback
  29608. * @api private
  29609. */
  29610. Polling.prototype.write = function(packets){
  29611. var self = this;
  29612. this.writable = false;
  29613. var callbackfn = function() {
  29614. self.writable = true;
  29615. self.emit('drain');
  29616. };
  29617. var self = this;
  29618. parser.encodePayload(packets, this.supportsBinary, function(data) {
  29619. self.doWrite(data, callbackfn);
  29620. });
  29621. };
  29622. /**
  29623. * Generates uri for connection.
  29624. *
  29625. * @api private
  29626. */
  29627. Polling.prototype.uri = function(){
  29628. var query = this.query || {};
  29629. var schema = this.secure ? 'https' : 'http';
  29630. var port = '';
  29631. // cache busting is forced
  29632. if (false !== this.timestampRequests) {
  29633. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  29634. }
  29635. if (!this.supportsBinary && !query.sid) {
  29636. query.b64 = 1;
  29637. }
  29638. query = parseqs.encode(query);
  29639. // avoid port if default for schema
  29640. if (this.port && (('https' == schema && this.port != 443) ||
  29641. ('http' == schema && this.port != 80))) {
  29642. port = ':' + this.port;
  29643. }
  29644. // prepend ? to query
  29645. if (query.length) {
  29646. query = '?' + query;
  29647. }
  29648. return schema + '://' + this.hostname + port + this.path + query;
  29649. };
  29650. },{"../transport":114,"component-inherit":121,"debug":122,"engine.io-parser":125,"parseqs":137,"xmlhttprequest":120}],119:[function(require,module,exports){
  29651. /**
  29652. * Module dependencies.
  29653. */
  29654. var Transport = require('../transport');
  29655. var parser = require('engine.io-parser');
  29656. var parseqs = require('parseqs');
  29657. var inherit = require('component-inherit');
  29658. var debug = require('debug')('engine.io-client:websocket');
  29659. /**
  29660. * `ws` exposes a WebSocket-compatible interface in
  29661. * Node, or the `WebSocket` or `MozWebSocket` globals
  29662. * in the browser.
  29663. */
  29664. var WebSocket = require('ws');
  29665. /**
  29666. * Module exports.
  29667. */
  29668. module.exports = WS;
  29669. /**
  29670. * WebSocket transport constructor.
  29671. *
  29672. * @api {Object} connection options
  29673. * @api public
  29674. */
  29675. function WS(opts){
  29676. var forceBase64 = (opts && opts.forceBase64);
  29677. if (forceBase64) {
  29678. this.supportsBinary = false;
  29679. }
  29680. Transport.call(this, opts);
  29681. }
  29682. /**
  29683. * Inherits from Transport.
  29684. */
  29685. inherit(WS, Transport);
  29686. /**
  29687. * Transport name.
  29688. *
  29689. * @api public
  29690. */
  29691. WS.prototype.name = 'websocket';
  29692. /*
  29693. * WebSockets support binary
  29694. */
  29695. WS.prototype.supportsBinary = true;
  29696. /**
  29697. * Opens socket.
  29698. *
  29699. * @api private
  29700. */
  29701. WS.prototype.doOpen = function(){
  29702. if (!this.check()) {
  29703. // let probe timeout
  29704. return;
  29705. }
  29706. var self = this;
  29707. var uri = this.uri();
  29708. var protocols = void(0);
  29709. var opts = { agent: this.agent };
  29710. // SSL options for Node.js client
  29711. opts.pfx = this.pfx;
  29712. opts.key = this.key;
  29713. opts.passphrase = this.passphrase;
  29714. opts.cert = this.cert;
  29715. opts.ca = this.ca;
  29716. opts.ciphers = this.ciphers;
  29717. opts.rejectUnauthorized = this.rejectUnauthorized;
  29718. this.ws = new WebSocket(uri, protocols, opts);
  29719. if (this.ws.binaryType === undefined) {
  29720. this.supportsBinary = false;
  29721. }
  29722. this.ws.binaryType = 'arraybuffer';
  29723. this.addEventListeners();
  29724. };
  29725. /**
  29726. * Adds event listeners to the socket
  29727. *
  29728. * @api private
  29729. */
  29730. WS.prototype.addEventListeners = function(){
  29731. var self = this;
  29732. this.ws.onopen = function(){
  29733. self.onOpen();
  29734. };
  29735. this.ws.onclose = function(){
  29736. self.onClose();
  29737. };
  29738. this.ws.onmessage = function(ev){
  29739. self.onData(ev.data);
  29740. };
  29741. this.ws.onerror = function(e){
  29742. self.onError('websocket error', e);
  29743. };
  29744. };
  29745. /**
  29746. * Override `onData` to use a timer on iOS.
  29747. * See: https://gist.github.com/mloughran/2052006
  29748. *
  29749. * @api private
  29750. */
  29751. if ('undefined' != typeof navigator
  29752. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  29753. WS.prototype.onData = function(data){
  29754. var self = this;
  29755. setTimeout(function(){
  29756. Transport.prototype.onData.call(self, data);
  29757. }, 0);
  29758. };
  29759. }
  29760. /**
  29761. * Writes data to socket.
  29762. *
  29763. * @param {Array} array of packets.
  29764. * @api private
  29765. */
  29766. WS.prototype.write = function(packets){
  29767. var self = this;
  29768. this.writable = false;
  29769. // encodePacket efficient as it uses WS framing
  29770. // no need for encodePayload
  29771. for (var i = 0, l = packets.length; i < l; i++) {
  29772. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  29773. //Sometimes the websocket has already been closed but the browser didn't
  29774. //have a chance of informing us about it yet, in that case send will
  29775. //throw an error
  29776. try {
  29777. self.ws.send(data);
  29778. } catch (e){
  29779. debug('websocket closed before onclose event');
  29780. }
  29781. });
  29782. }
  29783. function ondrain() {
  29784. self.writable = true;
  29785. self.emit('drain');
  29786. }
  29787. // fake drain
  29788. // defer to next tick to allow Socket to clear writeBuffer
  29789. setTimeout(ondrain, 0);
  29790. };
  29791. /**
  29792. * Called upon close
  29793. *
  29794. * @api private
  29795. */
  29796. WS.prototype.onClose = function(){
  29797. Transport.prototype.onClose.call(this);
  29798. };
  29799. /**
  29800. * Closes socket.
  29801. *
  29802. * @api private
  29803. */
  29804. WS.prototype.doClose = function(){
  29805. if (typeof this.ws !== 'undefined') {
  29806. this.ws.close();
  29807. }
  29808. };
  29809. /**
  29810. * Generates uri for connection.
  29811. *
  29812. * @api private
  29813. */
  29814. WS.prototype.uri = function(){
  29815. var query = this.query || {};
  29816. var schema = this.secure ? 'wss' : 'ws';
  29817. var port = '';
  29818. // avoid port if default for schema
  29819. if (this.port && (('wss' == schema && this.port != 443)
  29820. || ('ws' == schema && this.port != 80))) {
  29821. port = ':' + this.port;
  29822. }
  29823. // append timestamp to URI
  29824. if (this.timestampRequests) {
  29825. query[this.timestampParam] = +new Date;
  29826. }
  29827. // communicate binary support capabilities
  29828. if (!this.supportsBinary) {
  29829. query.b64 = 1;
  29830. }
  29831. query = parseqs.encode(query);
  29832. // prepend ? to query
  29833. if (query.length) {
  29834. query = '?' + query;
  29835. }
  29836. return schema + '://' + this.hostname + port + this.path + query;
  29837. };
  29838. /**
  29839. * Feature detection for WebSocket.
  29840. *
  29841. * @return {Boolean} whether this transport is available.
  29842. * @api public
  29843. */
  29844. WS.prototype.check = function(){
  29845. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  29846. };
  29847. },{"../transport":114,"component-inherit":121,"debug":122,"engine.io-parser":125,"parseqs":137,"ws":139}],120:[function(require,module,exports){
  29848. // browser shim for xmlhttprequest module
  29849. var hasCORS = require('has-cors');
  29850. module.exports = function(opts) {
  29851. var xdomain = opts.xdomain;
  29852. // scheme must be same when usign XDomainRequest
  29853. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  29854. var xscheme = opts.xscheme;
  29855. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  29856. // https://github.com/Automattic/engine.io-client/pull/217
  29857. var enablesXDR = opts.enablesXDR;
  29858. // XMLHttpRequest can be disabled on IE
  29859. try {
  29860. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  29861. return new XMLHttpRequest();
  29862. }
  29863. } catch (e) { }
  29864. // Use XDomainRequest for IE8 if enablesXDR is true
  29865. // because loading bar keeps flashing when using jsonp-polling
  29866. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  29867. try {
  29868. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  29869. return new XDomainRequest();
  29870. }
  29871. } catch (e) { }
  29872. if (!xdomain) {
  29873. try {
  29874. return new ActiveXObject('Microsoft.XMLHTTP');
  29875. } catch(e) { }
  29876. }
  29877. }
  29878. },{"has-cors":134}],121:[function(require,module,exports){
  29879. module.exports = function(a, b){
  29880. var fn = function(){};
  29881. fn.prototype = b.prototype;
  29882. a.prototype = new fn;
  29883. a.prototype.constructor = a;
  29884. };
  29885. },{}],122:[function(require,module,exports){
  29886. /**
  29887. * This is the web browser implementation of `debug()`.
  29888. *
  29889. * Expose `debug()` as the module.
  29890. */
  29891. exports = module.exports = require('./debug');
  29892. exports.log = log;
  29893. exports.formatArgs = formatArgs;
  29894. exports.save = save;
  29895. exports.load = load;
  29896. exports.useColors = useColors;
  29897. /**
  29898. * Colors.
  29899. */
  29900. exports.colors = [
  29901. 'lightseagreen',
  29902. 'forestgreen',
  29903. 'goldenrod',
  29904. 'dodgerblue',
  29905. 'darkorchid',
  29906. 'crimson'
  29907. ];
  29908. /**
  29909. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  29910. * and the Firebug extension (any Firefox version) are known
  29911. * to support "%c" CSS customizations.
  29912. *
  29913. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  29914. */
  29915. function useColors() {
  29916. // is webkit? http://stackoverflow.com/a/16459606/376773
  29917. return ('WebkitAppearance' in document.documentElement.style) ||
  29918. // is firebug? http://stackoverflow.com/a/398120/376773
  29919. (window.console && (console.firebug || (console.exception && console.table))) ||
  29920. // is firefox >= v31?
  29921. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  29922. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  29923. }
  29924. /**
  29925. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  29926. */
  29927. exports.formatters.j = function(v) {
  29928. return JSON.stringify(v);
  29929. };
  29930. /**
  29931. * Colorize log arguments if enabled.
  29932. *
  29933. * @api public
  29934. */
  29935. function formatArgs() {
  29936. var args = arguments;
  29937. var useColors = this.useColors;
  29938. args[0] = (useColors ? '%c' : '')
  29939. + this.namespace
  29940. + (useColors ? ' %c' : ' ')
  29941. + args[0]
  29942. + (useColors ? '%c ' : ' ')
  29943. + '+' + exports.humanize(this.diff);
  29944. if (!useColors) return args;
  29945. var c = 'color: ' + this.color;
  29946. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  29947. // the final "%c" is somewhat tricky, because there could be other
  29948. // arguments passed either before or after the %c, so we need to
  29949. // figure out the correct index to insert the CSS into
  29950. var index = 0;
  29951. var lastC = 0;
  29952. args[0].replace(/%[a-z%]/g, function(match) {
  29953. if ('%%' === match) return;
  29954. index++;
  29955. if ('%c' === match) {
  29956. // we only are interested in the *last* %c
  29957. // (the user may have provided their own)
  29958. lastC = index;
  29959. }
  29960. });
  29961. args.splice(lastC, 0, c);
  29962. return args;
  29963. }
  29964. /**
  29965. * Invokes `console.log()` when available.
  29966. * No-op when `console.log` is not a "function".
  29967. *
  29968. * @api public
  29969. */
  29970. function log() {
  29971. // This hackery is required for IE8,
  29972. // where the `console.log` function doesn't have 'apply'
  29973. return 'object' == typeof console
  29974. && 'function' == typeof console.log
  29975. && Function.prototype.apply.call(console.log, console, arguments);
  29976. }
  29977. /**
  29978. * Save `namespaces`.
  29979. *
  29980. * @param {String} namespaces
  29981. * @api private
  29982. */
  29983. function save(namespaces) {
  29984. try {
  29985. if (null == namespaces) {
  29986. localStorage.removeItem('debug');
  29987. } else {
  29988. localStorage.debug = namespaces;
  29989. }
  29990. } catch(e) {}
  29991. }
  29992. /**
  29993. * Load `namespaces`.
  29994. *
  29995. * @return {String} returns the previously persisted debug modes
  29996. * @api private
  29997. */
  29998. function load() {
  29999. var r;
  30000. try {
  30001. r = localStorage.debug;
  30002. } catch(e) {}
  30003. return r;
  30004. }
  30005. /**
  30006. * Enable namespaces listed in `localStorage.debug` initially.
  30007. */
  30008. exports.enable(load());
  30009. },{"./debug":123}],123:[function(require,module,exports){
  30010. /**
  30011. * This is the common logic for both the Node.js and web browser
  30012. * implementations of `debug()`.
  30013. *
  30014. * Expose `debug()` as the module.
  30015. */
  30016. exports = module.exports = debug;
  30017. exports.coerce = coerce;
  30018. exports.disable = disable;
  30019. exports.enable = enable;
  30020. exports.enabled = enabled;
  30021. exports.humanize = require('ms');
  30022. /**
  30023. * The currently active debug mode names, and names to skip.
  30024. */
  30025. exports.names = [];
  30026. exports.skips = [];
  30027. /**
  30028. * Map of special "%n" handling functions, for the debug "format" argument.
  30029. *
  30030. * Valid key names are a single, lowercased letter, i.e. "n".
  30031. */
  30032. exports.formatters = {};
  30033. /**
  30034. * Previously assigned color.
  30035. */
  30036. var prevColor = 0;
  30037. /**
  30038. * Previous log timestamp.
  30039. */
  30040. var prevTime;
  30041. /**
  30042. * Select a color.
  30043. *
  30044. * @return {Number}
  30045. * @api private
  30046. */
  30047. function selectColor() {
  30048. return exports.colors[prevColor++ % exports.colors.length];
  30049. }
  30050. /**
  30051. * Create a debugger with the given `namespace`.
  30052. *
  30053. * @param {String} namespace
  30054. * @return {Function}
  30055. * @api public
  30056. */
  30057. function debug(namespace) {
  30058. // define the `disabled` version
  30059. function disabled() {
  30060. }
  30061. disabled.enabled = false;
  30062. // define the `enabled` version
  30063. function enabled() {
  30064. var self = enabled;
  30065. // set `diff` timestamp
  30066. var curr = +new Date();
  30067. var ms = curr - (prevTime || curr);
  30068. self.diff = ms;
  30069. self.prev = prevTime;
  30070. self.curr = curr;
  30071. prevTime = curr;
  30072. // add the `color` if not set
  30073. if (null == self.useColors) self.useColors = exports.useColors();
  30074. if (null == self.color && self.useColors) self.color = selectColor();
  30075. var args = Array.prototype.slice.call(arguments);
  30076. args[0] = exports.coerce(args[0]);
  30077. if ('string' !== typeof args[0]) {
  30078. // anything else let's inspect with %o
  30079. args = ['%o'].concat(args);
  30080. }
  30081. // apply any `formatters` transformations
  30082. var index = 0;
  30083. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  30084. // if we encounter an escaped % then don't increase the array index
  30085. if (match === '%%') return match;
  30086. index++;
  30087. var formatter = exports.formatters[format];
  30088. if ('function' === typeof formatter) {
  30089. var val = args[index];
  30090. match = formatter.call(self, val);
  30091. // now we need to remove `args[index]` since it's inlined in the `format`
  30092. args.splice(index, 1);
  30093. index--;
  30094. }
  30095. return match;
  30096. });
  30097. if ('function' === typeof exports.formatArgs) {
  30098. args = exports.formatArgs.apply(self, args);
  30099. }
  30100. var logFn = enabled.log || exports.log || console.log.bind(console);
  30101. logFn.apply(self, args);
  30102. }
  30103. enabled.enabled = true;
  30104. var fn = exports.enabled(namespace) ? enabled : disabled;
  30105. fn.namespace = namespace;
  30106. return fn;
  30107. }
  30108. /**
  30109. * Enables a debug mode by namespaces. This can include modes
  30110. * separated by a colon and wildcards.
  30111. *
  30112. * @param {String} namespaces
  30113. * @api public
  30114. */
  30115. function enable(namespaces) {
  30116. exports.save(namespaces);
  30117. var split = (namespaces || '').split(/[\s,]+/);
  30118. var len = split.length;
  30119. for (var i = 0; i < len; i++) {
  30120. if (!split[i]) continue; // ignore empty strings
  30121. namespaces = split[i].replace(/\*/g, '.*?');
  30122. if (namespaces[0] === '-') {
  30123. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  30124. } else {
  30125. exports.names.push(new RegExp('^' + namespaces + '$'));
  30126. }
  30127. }
  30128. }
  30129. /**
  30130. * Disable debug output.
  30131. *
  30132. * @api public
  30133. */
  30134. function disable() {
  30135. exports.enable('');
  30136. }
  30137. /**
  30138. * Returns true if the given mode name is enabled, false otherwise.
  30139. *
  30140. * @param {String} name
  30141. * @return {Boolean}
  30142. * @api public
  30143. */
  30144. function enabled(name) {
  30145. var i, len;
  30146. for (i = 0, len = exports.skips.length; i < len; i++) {
  30147. if (exports.skips[i].test(name)) {
  30148. return false;
  30149. }
  30150. }
  30151. for (i = 0, len = exports.names.length; i < len; i++) {
  30152. if (exports.names[i].test(name)) {
  30153. return true;
  30154. }
  30155. }
  30156. return false;
  30157. }
  30158. /**
  30159. * Coerce `val`.
  30160. *
  30161. * @param {Mixed} val
  30162. * @return {Mixed}
  30163. * @api private
  30164. */
  30165. function coerce(val) {
  30166. if (val instanceof Error) return val.stack || val.message;
  30167. return val;
  30168. }
  30169. },{"ms":124}],124:[function(require,module,exports){
  30170. /**
  30171. * Helpers.
  30172. */
  30173. var s = 1000;
  30174. var m = s * 60;
  30175. var h = m * 60;
  30176. var d = h * 24;
  30177. var y = d * 365.25;
  30178. /**
  30179. * Parse or format the given `val`.
  30180. *
  30181. * Options:
  30182. *
  30183. * - `long` verbose formatting [false]
  30184. *
  30185. * @param {String|Number} val
  30186. * @param {Object} options
  30187. * @return {String|Number}
  30188. * @api public
  30189. */
  30190. module.exports = function(val, options){
  30191. options = options || {};
  30192. if ('string' == typeof val) return parse(val);
  30193. return options.long
  30194. ? long(val)
  30195. : short(val);
  30196. };
  30197. /**
  30198. * Parse the given `str` and return milliseconds.
  30199. *
  30200. * @param {String} str
  30201. * @return {Number}
  30202. * @api private
  30203. */
  30204. function parse(str) {
  30205. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  30206. if (!match) return;
  30207. var n = parseFloat(match[1]);
  30208. var type = (match[2] || 'ms').toLowerCase();
  30209. switch (type) {
  30210. case 'years':
  30211. case 'year':
  30212. case 'y':
  30213. return n * y;
  30214. case 'days':
  30215. case 'day':
  30216. case 'd':
  30217. return n * d;
  30218. case 'hours':
  30219. case 'hour':
  30220. case 'h':
  30221. return n * h;
  30222. case 'minutes':
  30223. case 'minute':
  30224. case 'm':
  30225. return n * m;
  30226. case 'seconds':
  30227. case 'second':
  30228. case 's':
  30229. return n * s;
  30230. case 'ms':
  30231. return n;
  30232. }
  30233. }
  30234. /**
  30235. * Short format for `ms`.
  30236. *
  30237. * @param {Number} ms
  30238. * @return {String}
  30239. * @api private
  30240. */
  30241. function short(ms) {
  30242. if (ms >= d) return Math.round(ms / d) + 'd';
  30243. if (ms >= h) return Math.round(ms / h) + 'h';
  30244. if (ms >= m) return Math.round(ms / m) + 'm';
  30245. if (ms >= s) return Math.round(ms / s) + 's';
  30246. return ms + 'ms';
  30247. }
  30248. /**
  30249. * Long format for `ms`.
  30250. *
  30251. * @param {Number} ms
  30252. * @return {String}
  30253. * @api private
  30254. */
  30255. function long(ms) {
  30256. return plural(ms, d, 'day')
  30257. || plural(ms, h, 'hour')
  30258. || plural(ms, m, 'minute')
  30259. || plural(ms, s, 'second')
  30260. || ms + ' ms';
  30261. }
  30262. /**
  30263. * Pluralization helper.
  30264. */
  30265. function plural(ms, n, name) {
  30266. if (ms < n) return;
  30267. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  30268. return Math.ceil(ms / n) + ' ' + name + 's';
  30269. }
  30270. },{}],125:[function(require,module,exports){
  30271. (function (global){
  30272. /**
  30273. * Module dependencies.
  30274. */
  30275. var keys = require('./keys');
  30276. var hasBinary = require('has-binary');
  30277. var sliceBuffer = require('arraybuffer.slice');
  30278. var base64encoder = require('base64-arraybuffer');
  30279. var after = require('after');
  30280. var utf8 = require('utf8');
  30281. /**
  30282. * Check if we are running an android browser. That requires us to use
  30283. * ArrayBuffer with polling transports...
  30284. *
  30285. * http://ghinda.net/jpeg-blob-ajax-android/
  30286. */
  30287. var isAndroid = navigator.userAgent.match(/Android/i);
  30288. /**
  30289. * Check if we are running in PhantomJS.
  30290. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  30291. * https://github.com/ariya/phantomjs/issues/11395
  30292. * @type boolean
  30293. */
  30294. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  30295. /**
  30296. * When true, avoids using Blobs to encode payloads.
  30297. * @type boolean
  30298. */
  30299. var dontSendBlobs = isAndroid || isPhantomJS;
  30300. /**
  30301. * Current protocol version.
  30302. */
  30303. exports.protocol = 3;
  30304. /**
  30305. * Packet types.
  30306. */
  30307. var packets = exports.packets = {
  30308. open: 0 // non-ws
  30309. , close: 1 // non-ws
  30310. , ping: 2
  30311. , pong: 3
  30312. , message: 4
  30313. , upgrade: 5
  30314. , noop: 6
  30315. };
  30316. var packetslist = keys(packets);
  30317. /**
  30318. * Premade error packet.
  30319. */
  30320. var err = { type: 'error', data: 'parser error' };
  30321. /**
  30322. * Create a blob api even for blob builder when vendor prefixes exist
  30323. */
  30324. var Blob = require('blob');
  30325. /**
  30326. * Encodes a packet.
  30327. *
  30328. * <packet type id> [ <data> ]
  30329. *
  30330. * Example:
  30331. *
  30332. * 5hello world
  30333. * 3
  30334. * 4
  30335. *
  30336. * Binary is encoded in an identical principle
  30337. *
  30338. * @api private
  30339. */
  30340. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  30341. if ('function' == typeof supportsBinary) {
  30342. callback = supportsBinary;
  30343. supportsBinary = false;
  30344. }
  30345. if ('function' == typeof utf8encode) {
  30346. callback = utf8encode;
  30347. utf8encode = null;
  30348. }
  30349. var data = (packet.data === undefined)
  30350. ? undefined
  30351. : packet.data.buffer || packet.data;
  30352. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  30353. return encodeArrayBuffer(packet, supportsBinary, callback);
  30354. } else if (Blob && data instanceof global.Blob) {
  30355. return encodeBlob(packet, supportsBinary, callback);
  30356. }
  30357. // might be an object with { base64: true, data: dataAsBase64String }
  30358. if (data && data.base64) {
  30359. return encodeBase64Object(packet, callback);
  30360. }
  30361. // Sending data as a utf-8 string
  30362. var encoded = packets[packet.type];
  30363. // data fragment is optional
  30364. if (undefined !== packet.data) {
  30365. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  30366. }
  30367. return callback('' + encoded);
  30368. };
  30369. function encodeBase64Object(packet, callback) {
  30370. // packet data is an object { base64: true, data: dataAsBase64String }
  30371. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  30372. return callback(message);
  30373. }
  30374. /**
  30375. * Encode packet helpers for binary types
  30376. */
  30377. function encodeArrayBuffer(packet, supportsBinary, callback) {
  30378. if (!supportsBinary) {
  30379. return exports.encodeBase64Packet(packet, callback);
  30380. }
  30381. var data = packet.data;
  30382. var contentArray = new Uint8Array(data);
  30383. var resultBuffer = new Uint8Array(1 + data.byteLength);
  30384. resultBuffer[0] = packets[packet.type];
  30385. for (var i = 0; i < contentArray.length; i++) {
  30386. resultBuffer[i+1] = contentArray[i];
  30387. }
  30388. return callback(resultBuffer.buffer);
  30389. }
  30390. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  30391. if (!supportsBinary) {
  30392. return exports.encodeBase64Packet(packet, callback);
  30393. }
  30394. var fr = new FileReader();
  30395. fr.onload = function() {
  30396. packet.data = fr.result;
  30397. exports.encodePacket(packet, supportsBinary, true, callback);
  30398. };
  30399. return fr.readAsArrayBuffer(packet.data);
  30400. }
  30401. function encodeBlob(packet, supportsBinary, callback) {
  30402. if (!supportsBinary) {
  30403. return exports.encodeBase64Packet(packet, callback);
  30404. }
  30405. if (dontSendBlobs) {
  30406. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  30407. }
  30408. var length = new Uint8Array(1);
  30409. length[0] = packets[packet.type];
  30410. var blob = new Blob([length.buffer, packet.data]);
  30411. return callback(blob);
  30412. }
  30413. /**
  30414. * Encodes a packet with binary data in a base64 string
  30415. *
  30416. * @param {Object} packet, has `type` and `data`
  30417. * @return {String} base64 encoded message
  30418. */
  30419. exports.encodeBase64Packet = function(packet, callback) {
  30420. var message = 'b' + exports.packets[packet.type];
  30421. if (Blob && packet.data instanceof Blob) {
  30422. var fr = new FileReader();
  30423. fr.onload = function() {
  30424. var b64 = fr.result.split(',')[1];
  30425. callback(message + b64);
  30426. };
  30427. return fr.readAsDataURL(packet.data);
  30428. }
  30429. var b64data;
  30430. try {
  30431. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  30432. } catch (e) {
  30433. // iPhone Safari doesn't let you apply with typed arrays
  30434. var typed = new Uint8Array(packet.data);
  30435. var basic = new Array(typed.length);
  30436. for (var i = 0; i < typed.length; i++) {
  30437. basic[i] = typed[i];
  30438. }
  30439. b64data = String.fromCharCode.apply(null, basic);
  30440. }
  30441. message += global.btoa(b64data);
  30442. return callback(message);
  30443. };
  30444. /**
  30445. * Decodes a packet. Changes format to Blob if requested.
  30446. *
  30447. * @return {Object} with `type` and `data` (if any)
  30448. * @api private
  30449. */
  30450. exports.decodePacket = function (data, binaryType, utf8decode) {
  30451. // String data
  30452. if (typeof data == 'string' || data === undefined) {
  30453. if (data.charAt(0) == 'b') {
  30454. return exports.decodeBase64Packet(data.substr(1), binaryType);
  30455. }
  30456. if (utf8decode) {
  30457. try {
  30458. data = utf8.decode(data);
  30459. } catch (e) {
  30460. return err;
  30461. }
  30462. }
  30463. var type = data.charAt(0);
  30464. if (Number(type) != type || !packetslist[type]) {
  30465. return err;
  30466. }
  30467. if (data.length > 1) {
  30468. return { type: packetslist[type], data: data.substring(1) };
  30469. } else {
  30470. return { type: packetslist[type] };
  30471. }
  30472. }
  30473. var asArray = new Uint8Array(data);
  30474. var type = asArray[0];
  30475. var rest = sliceBuffer(data, 1);
  30476. if (Blob && binaryType === 'blob') {
  30477. rest = new Blob([rest]);
  30478. }
  30479. return { type: packetslist[type], data: rest };
  30480. };
  30481. /**
  30482. * Decodes a packet encoded in a base64 string
  30483. *
  30484. * @param {String} base64 encoded message
  30485. * @return {Object} with `type` and `data` (if any)
  30486. */
  30487. exports.decodeBase64Packet = function(msg, binaryType) {
  30488. var type = packetslist[msg.charAt(0)];
  30489. if (!global.ArrayBuffer) {
  30490. return { type: type, data: { base64: true, data: msg.substr(1) } };
  30491. }
  30492. var data = base64encoder.decode(msg.substr(1));
  30493. if (binaryType === 'blob' && Blob) {
  30494. data = new Blob([data]);
  30495. }
  30496. return { type: type, data: data };
  30497. };
  30498. /**
  30499. * Encodes multiple messages (payload).
  30500. *
  30501. * <length>:data
  30502. *
  30503. * Example:
  30504. *
  30505. * 11:hello world2:hi
  30506. *
  30507. * If any contents are binary, they will be encoded as base64 strings. Base64
  30508. * encoded strings are marked with a b before the length specifier
  30509. *
  30510. * @param {Array} packets
  30511. * @api private
  30512. */
  30513. exports.encodePayload = function (packets, supportsBinary, callback) {
  30514. if (typeof supportsBinary == 'function') {
  30515. callback = supportsBinary;
  30516. supportsBinary = null;
  30517. }
  30518. var isBinary = hasBinary(packets);
  30519. if (supportsBinary && isBinary) {
  30520. if (Blob && !dontSendBlobs) {
  30521. return exports.encodePayloadAsBlob(packets, callback);
  30522. }
  30523. return exports.encodePayloadAsArrayBuffer(packets, callback);
  30524. }
  30525. if (!packets.length) {
  30526. return callback('0:');
  30527. }
  30528. function setLengthHeader(message) {
  30529. return message.length + ':' + message;
  30530. }
  30531. function encodeOne(packet, doneCallback) {
  30532. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  30533. doneCallback(null, setLengthHeader(message));
  30534. });
  30535. }
  30536. map(packets, encodeOne, function(err, results) {
  30537. return callback(results.join(''));
  30538. });
  30539. };
  30540. /**
  30541. * Async array map using after
  30542. */
  30543. function map(ary, each, done) {
  30544. var result = new Array(ary.length);
  30545. var next = after(ary.length, done);
  30546. var eachWithIndex = function(i, el, cb) {
  30547. each(el, function(error, msg) {
  30548. result[i] = msg;
  30549. cb(error, result);
  30550. });
  30551. };
  30552. for (var i = 0; i < ary.length; i++) {
  30553. eachWithIndex(i, ary[i], next);
  30554. }
  30555. }
  30556. /*
  30557. * Decodes data when a payload is maybe expected. Possible binary contents are
  30558. * decoded from their base64 representation
  30559. *
  30560. * @param {String} data, callback method
  30561. * @api public
  30562. */
  30563. exports.decodePayload = function (data, binaryType, callback) {
  30564. if (typeof data != 'string') {
  30565. return exports.decodePayloadAsBinary(data, binaryType, callback);
  30566. }
  30567. if (typeof binaryType === 'function') {
  30568. callback = binaryType;
  30569. binaryType = null;
  30570. }
  30571. var packet;
  30572. if (data == '') {
  30573. // parser error - ignoring payload
  30574. return callback(err, 0, 1);
  30575. }
  30576. var length = ''
  30577. , n, msg;
  30578. for (var i = 0, l = data.length; i < l; i++) {
  30579. var chr = data.charAt(i);
  30580. if (':' != chr) {
  30581. length += chr;
  30582. } else {
  30583. if ('' == length || (length != (n = Number(length)))) {
  30584. // parser error - ignoring payload
  30585. return callback(err, 0, 1);
  30586. }
  30587. msg = data.substr(i + 1, n);
  30588. if (length != msg.length) {
  30589. // parser error - ignoring payload
  30590. return callback(err, 0, 1);
  30591. }
  30592. if (msg.length) {
  30593. packet = exports.decodePacket(msg, binaryType, true);
  30594. if (err.type == packet.type && err.data == packet.data) {
  30595. // parser error in individual packet - ignoring payload
  30596. return callback(err, 0, 1);
  30597. }
  30598. var ret = callback(packet, i + n, l);
  30599. if (false === ret) return;
  30600. }
  30601. // advance cursor
  30602. i += n;
  30603. length = '';
  30604. }
  30605. }
  30606. if (length != '') {
  30607. // parser error - ignoring payload
  30608. return callback(err, 0, 1);
  30609. }
  30610. };
  30611. /**
  30612. * Encodes multiple messages (payload) as binary.
  30613. *
  30614. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  30615. * 255><data>
  30616. *
  30617. * Example:
  30618. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  30619. *
  30620. * @param {Array} packets
  30621. * @return {ArrayBuffer} encoded payload
  30622. * @api private
  30623. */
  30624. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  30625. if (!packets.length) {
  30626. return callback(new ArrayBuffer(0));
  30627. }
  30628. function encodeOne(packet, doneCallback) {
  30629. exports.encodePacket(packet, true, true, function(data) {
  30630. return doneCallback(null, data);
  30631. });
  30632. }
  30633. map(packets, encodeOne, function(err, encodedPackets) {
  30634. var totalLength = encodedPackets.reduce(function(acc, p) {
  30635. var len;
  30636. if (typeof p === 'string'){
  30637. len = p.length;
  30638. } else {
  30639. len = p.byteLength;
  30640. }
  30641. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  30642. }, 0);
  30643. var resultArray = new Uint8Array(totalLength);
  30644. var bufferIndex = 0;
  30645. encodedPackets.forEach(function(p) {
  30646. var isString = typeof p === 'string';
  30647. var ab = p;
  30648. if (isString) {
  30649. var view = new Uint8Array(p.length);
  30650. for (var i = 0; i < p.length; i++) {
  30651. view[i] = p.charCodeAt(i);
  30652. }
  30653. ab = view.buffer;
  30654. }
  30655. if (isString) { // not true binary
  30656. resultArray[bufferIndex++] = 0;
  30657. } else { // true binary
  30658. resultArray[bufferIndex++] = 1;
  30659. }
  30660. var lenStr = ab.byteLength.toString();
  30661. for (var i = 0; i < lenStr.length; i++) {
  30662. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  30663. }
  30664. resultArray[bufferIndex++] = 255;
  30665. var view = new Uint8Array(ab);
  30666. for (var i = 0; i < view.length; i++) {
  30667. resultArray[bufferIndex++] = view[i];
  30668. }
  30669. });
  30670. return callback(resultArray.buffer);
  30671. });
  30672. };
  30673. /**
  30674. * Encode as Blob
  30675. */
  30676. exports.encodePayloadAsBlob = function(packets, callback) {
  30677. function encodeOne(packet, doneCallback) {
  30678. exports.encodePacket(packet, true, true, function(encoded) {
  30679. var binaryIdentifier = new Uint8Array(1);
  30680. binaryIdentifier[0] = 1;
  30681. if (typeof encoded === 'string') {
  30682. var view = new Uint8Array(encoded.length);
  30683. for (var i = 0; i < encoded.length; i++) {
  30684. view[i] = encoded.charCodeAt(i);
  30685. }
  30686. encoded = view.buffer;
  30687. binaryIdentifier[0] = 0;
  30688. }
  30689. var len = (encoded instanceof ArrayBuffer)
  30690. ? encoded.byteLength
  30691. : encoded.size;
  30692. var lenStr = len.toString();
  30693. var lengthAry = new Uint8Array(lenStr.length + 1);
  30694. for (var i = 0; i < lenStr.length; i++) {
  30695. lengthAry[i] = parseInt(lenStr[i]);
  30696. }
  30697. lengthAry[lenStr.length] = 255;
  30698. if (Blob) {
  30699. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  30700. doneCallback(null, blob);
  30701. }
  30702. });
  30703. }
  30704. map(packets, encodeOne, function(err, results) {
  30705. return callback(new Blob(results));
  30706. });
  30707. };
  30708. /*
  30709. * Decodes data when a payload is maybe expected. Strings are decoded by
  30710. * interpreting each byte as a key code for entries marked to start with 0. See
  30711. * description of encodePayloadAsBinary
  30712. *
  30713. * @param {ArrayBuffer} data, callback method
  30714. * @api public
  30715. */
  30716. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  30717. if (typeof binaryType === 'function') {
  30718. callback = binaryType;
  30719. binaryType = null;
  30720. }
  30721. var bufferTail = data;
  30722. var buffers = [];
  30723. var numberTooLong = false;
  30724. while (bufferTail.byteLength > 0) {
  30725. var tailArray = new Uint8Array(bufferTail);
  30726. var isString = tailArray[0] === 0;
  30727. var msgLength = '';
  30728. for (var i = 1; ; i++) {
  30729. if (tailArray[i] == 255) break;
  30730. if (msgLength.length > 310) {
  30731. numberTooLong = true;
  30732. break;
  30733. }
  30734. msgLength += tailArray[i];
  30735. }
  30736. if(numberTooLong) return callback(err, 0, 1);
  30737. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  30738. msgLength = parseInt(msgLength);
  30739. var msg = sliceBuffer(bufferTail, 0, msgLength);
  30740. if (isString) {
  30741. try {
  30742. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  30743. } catch (e) {
  30744. // iPhone Safari doesn't let you apply to typed arrays
  30745. var typed = new Uint8Array(msg);
  30746. msg = '';
  30747. for (var i = 0; i < typed.length; i++) {
  30748. msg += String.fromCharCode(typed[i]);
  30749. }
  30750. }
  30751. }
  30752. buffers.push(msg);
  30753. bufferTail = sliceBuffer(bufferTail, msgLength);
  30754. }
  30755. var total = buffers.length;
  30756. buffers.forEach(function(buffer, i) {
  30757. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  30758. });
  30759. };
  30760. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30761. },{"./keys":126,"after":127,"arraybuffer.slice":128,"base64-arraybuffer":129,"blob":130,"has-binary":131,"utf8":133}],126:[function(require,module,exports){
  30762. /**
  30763. * Gets the keys for an object.
  30764. *
  30765. * @return {Array} keys
  30766. * @api private
  30767. */
  30768. module.exports = Object.keys || function keys (obj){
  30769. var arr = [];
  30770. var has = Object.prototype.hasOwnProperty;
  30771. for (var i in obj) {
  30772. if (has.call(obj, i)) {
  30773. arr.push(i);
  30774. }
  30775. }
  30776. return arr;
  30777. };
  30778. },{}],127:[function(require,module,exports){
  30779. module.exports = after
  30780. function after(count, callback, err_cb) {
  30781. var bail = false
  30782. err_cb = err_cb || noop
  30783. proxy.count = count
  30784. return (count === 0) ? callback() : proxy
  30785. function proxy(err, result) {
  30786. if (proxy.count <= 0) {
  30787. throw new Error('after called too many times')
  30788. }
  30789. --proxy.count
  30790. // after first error, rest are passed to err_cb
  30791. if (err) {
  30792. bail = true
  30793. callback(err)
  30794. // future error callbacks will go to error handler
  30795. callback = err_cb
  30796. } else if (proxy.count === 0 && !bail) {
  30797. callback(null, result)
  30798. }
  30799. }
  30800. }
  30801. function noop() {}
  30802. },{}],128:[function(require,module,exports){
  30803. /**
  30804. * An abstraction for slicing an arraybuffer even when
  30805. * ArrayBuffer.prototype.slice is not supported
  30806. *
  30807. * @api public
  30808. */
  30809. module.exports = function(arraybuffer, start, end) {
  30810. var bytes = arraybuffer.byteLength;
  30811. start = start || 0;
  30812. end = end || bytes;
  30813. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  30814. if (start < 0) { start += bytes; }
  30815. if (end < 0) { end += bytes; }
  30816. if (end > bytes) { end = bytes; }
  30817. if (start >= bytes || start >= end || bytes === 0) {
  30818. return new ArrayBuffer(0);
  30819. }
  30820. var abv = new Uint8Array(arraybuffer);
  30821. var result = new Uint8Array(end - start);
  30822. for (var i = start, ii = 0; i < end; i++, ii++) {
  30823. result[ii] = abv[i];
  30824. }
  30825. return result.buffer;
  30826. };
  30827. },{}],129:[function(require,module,exports){
  30828. /*
  30829. * base64-arraybuffer
  30830. * https://github.com/niklasvh/base64-arraybuffer
  30831. *
  30832. * Copyright (c) 2012 Niklas von Hertzen
  30833. * Licensed under the MIT license.
  30834. */
  30835. (function(chars){
  30836. "use strict";
  30837. exports.encode = function(arraybuffer) {
  30838. var bytes = new Uint8Array(arraybuffer),
  30839. i, len = bytes.length, base64 = "";
  30840. for (i = 0; i < len; i+=3) {
  30841. base64 += chars[bytes[i] >> 2];
  30842. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  30843. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  30844. base64 += chars[bytes[i + 2] & 63];
  30845. }
  30846. if ((len % 3) === 2) {
  30847. base64 = base64.substring(0, base64.length - 1) + "=";
  30848. } else if (len % 3 === 1) {
  30849. base64 = base64.substring(0, base64.length - 2) + "==";
  30850. }
  30851. return base64;
  30852. };
  30853. exports.decode = function(base64) {
  30854. var bufferLength = base64.length * 0.75,
  30855. len = base64.length, i, p = 0,
  30856. encoded1, encoded2, encoded3, encoded4;
  30857. if (base64[base64.length - 1] === "=") {
  30858. bufferLength--;
  30859. if (base64[base64.length - 2] === "=") {
  30860. bufferLength--;
  30861. }
  30862. }
  30863. var arraybuffer = new ArrayBuffer(bufferLength),
  30864. bytes = new Uint8Array(arraybuffer);
  30865. for (i = 0; i < len; i+=4) {
  30866. encoded1 = chars.indexOf(base64[i]);
  30867. encoded2 = chars.indexOf(base64[i+1]);
  30868. encoded3 = chars.indexOf(base64[i+2]);
  30869. encoded4 = chars.indexOf(base64[i+3]);
  30870. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  30871. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  30872. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  30873. }
  30874. return arraybuffer;
  30875. };
  30876. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  30877. },{}],130:[function(require,module,exports){
  30878. (function (global){
  30879. /**
  30880. * Create a blob builder even when vendor prefixes exist
  30881. */
  30882. var BlobBuilder = global.BlobBuilder
  30883. || global.WebKitBlobBuilder
  30884. || global.MSBlobBuilder
  30885. || global.MozBlobBuilder;
  30886. /**
  30887. * Check if Blob constructor is supported
  30888. */
  30889. var blobSupported = (function() {
  30890. try {
  30891. var b = new Blob(['hi']);
  30892. return b.size == 2;
  30893. } catch(e) {
  30894. return false;
  30895. }
  30896. })();
  30897. /**
  30898. * Check if BlobBuilder is supported
  30899. */
  30900. var blobBuilderSupported = BlobBuilder
  30901. && BlobBuilder.prototype.append
  30902. && BlobBuilder.prototype.getBlob;
  30903. function BlobBuilderConstructor(ary, options) {
  30904. options = options || {};
  30905. var bb = new BlobBuilder();
  30906. for (var i = 0; i < ary.length; i++) {
  30907. bb.append(ary[i]);
  30908. }
  30909. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  30910. };
  30911. module.exports = (function() {
  30912. if (blobSupported) {
  30913. return global.Blob;
  30914. } else if (blobBuilderSupported) {
  30915. return BlobBuilderConstructor;
  30916. } else {
  30917. return undefined;
  30918. }
  30919. })();
  30920. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30921. },{}],131:[function(require,module,exports){
  30922. (function (global){
  30923. /*
  30924. * Module requirements.
  30925. */
  30926. var isArray = require('isarray');
  30927. /**
  30928. * Module exports.
  30929. */
  30930. module.exports = hasBinary;
  30931. /**
  30932. * Checks for binary data.
  30933. *
  30934. * Right now only Buffer and ArrayBuffer are supported..
  30935. *
  30936. * @param {Object} anything
  30937. * @api public
  30938. */
  30939. function hasBinary(data) {
  30940. function _hasBinary(obj) {
  30941. if (!obj) return false;
  30942. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  30943. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  30944. (global.Blob && obj instanceof Blob) ||
  30945. (global.File && obj instanceof File)
  30946. ) {
  30947. return true;
  30948. }
  30949. if (isArray(obj)) {
  30950. for (var i = 0; i < obj.length; i++) {
  30951. if (_hasBinary(obj[i])) {
  30952. return true;
  30953. }
  30954. }
  30955. } else if (obj && 'object' == typeof obj) {
  30956. if (obj.toJSON) {
  30957. obj = obj.toJSON();
  30958. }
  30959. for (var key in obj) {
  30960. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  30961. return true;
  30962. }
  30963. }
  30964. }
  30965. return false;
  30966. }
  30967. return _hasBinary(data);
  30968. }
  30969. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30970. },{"isarray":132}],132:[function(require,module,exports){
  30971. module.exports = Array.isArray || function (arr) {
  30972. return Object.prototype.toString.call(arr) == '[object Array]';
  30973. };
  30974. },{}],133:[function(require,module,exports){
  30975. (function (global){
  30976. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  30977. ;(function(root) {
  30978. // Detect free variables `exports`
  30979. var freeExports = typeof exports == 'object' && exports;
  30980. // Detect free variable `module`
  30981. var freeModule = typeof module == 'object' && module &&
  30982. module.exports == freeExports && module;
  30983. // Detect free variable `global`, from Node.js or Browserified code,
  30984. // and use it as `root`
  30985. var freeGlobal = typeof global == 'object' && global;
  30986. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  30987. root = freeGlobal;
  30988. }
  30989. /*--------------------------------------------------------------------------*/
  30990. var stringFromCharCode = String.fromCharCode;
  30991. // Taken from http://mths.be/punycode
  30992. function ucs2decode(string) {
  30993. var output = [];
  30994. var counter = 0;
  30995. var length = string.length;
  30996. var value;
  30997. var extra;
  30998. while (counter < length) {
  30999. value = string.charCodeAt(counter++);
  31000. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  31001. // high surrogate, and there is a next character
  31002. extra = string.charCodeAt(counter++);
  31003. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  31004. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  31005. } else {
  31006. // unmatched surrogate; only append this code unit, in case the next
  31007. // code unit is the high surrogate of a surrogate pair
  31008. output.push(value);
  31009. counter--;
  31010. }
  31011. } else {
  31012. output.push(value);
  31013. }
  31014. }
  31015. return output;
  31016. }
  31017. // Taken from http://mths.be/punycode
  31018. function ucs2encode(array) {
  31019. var length = array.length;
  31020. var index = -1;
  31021. var value;
  31022. var output = '';
  31023. while (++index < length) {
  31024. value = array[index];
  31025. if (value > 0xFFFF) {
  31026. value -= 0x10000;
  31027. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  31028. value = 0xDC00 | value & 0x3FF;
  31029. }
  31030. output += stringFromCharCode(value);
  31031. }
  31032. return output;
  31033. }
  31034. /*--------------------------------------------------------------------------*/
  31035. function createByte(codePoint, shift) {
  31036. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  31037. }
  31038. function encodeCodePoint(codePoint) {
  31039. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  31040. return stringFromCharCode(codePoint);
  31041. }
  31042. var symbol = '';
  31043. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  31044. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  31045. }
  31046. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  31047. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  31048. symbol += createByte(codePoint, 6);
  31049. }
  31050. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  31051. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  31052. symbol += createByte(codePoint, 12);
  31053. symbol += createByte(codePoint, 6);
  31054. }
  31055. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  31056. return symbol;
  31057. }
  31058. function utf8encode(string) {
  31059. var codePoints = ucs2decode(string);
  31060. // console.log(JSON.stringify(codePoints.map(function(x) {
  31061. // return 'U+' + x.toString(16).toUpperCase();
  31062. // })));
  31063. var length = codePoints.length;
  31064. var index = -1;
  31065. var codePoint;
  31066. var byteString = '';
  31067. while (++index < length) {
  31068. codePoint = codePoints[index];
  31069. byteString += encodeCodePoint(codePoint);
  31070. }
  31071. return byteString;
  31072. }
  31073. /*--------------------------------------------------------------------------*/
  31074. function readContinuationByte() {
  31075. if (byteIndex >= byteCount) {
  31076. throw Error('Invalid byte index');
  31077. }
  31078. var continuationByte = byteArray[byteIndex] & 0xFF;
  31079. byteIndex++;
  31080. if ((continuationByte & 0xC0) == 0x80) {
  31081. return continuationByte & 0x3F;
  31082. }
  31083. // If we end up here, it’s not a continuation byte
  31084. throw Error('Invalid continuation byte');
  31085. }
  31086. function decodeSymbol() {
  31087. var byte1;
  31088. var byte2;
  31089. var byte3;
  31090. var byte4;
  31091. var codePoint;
  31092. if (byteIndex > byteCount) {
  31093. throw Error('Invalid byte index');
  31094. }
  31095. if (byteIndex == byteCount) {
  31096. return false;
  31097. }
  31098. // Read first byte
  31099. byte1 = byteArray[byteIndex] & 0xFF;
  31100. byteIndex++;
  31101. // 1-byte sequence (no continuation bytes)
  31102. if ((byte1 & 0x80) == 0) {
  31103. return byte1;
  31104. }
  31105. // 2-byte sequence
  31106. if ((byte1 & 0xE0) == 0xC0) {
  31107. var byte2 = readContinuationByte();
  31108. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  31109. if (codePoint >= 0x80) {
  31110. return codePoint;
  31111. } else {
  31112. throw Error('Invalid continuation byte');
  31113. }
  31114. }
  31115. // 3-byte sequence (may include unpaired surrogates)
  31116. if ((byte1 & 0xF0) == 0xE0) {
  31117. byte2 = readContinuationByte();
  31118. byte3 = readContinuationByte();
  31119. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  31120. if (codePoint >= 0x0800) {
  31121. return codePoint;
  31122. } else {
  31123. throw Error('Invalid continuation byte');
  31124. }
  31125. }
  31126. // 4-byte sequence
  31127. if ((byte1 & 0xF8) == 0xF0) {
  31128. byte2 = readContinuationByte();
  31129. byte3 = readContinuationByte();
  31130. byte4 = readContinuationByte();
  31131. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  31132. (byte3 << 0x06) | byte4;
  31133. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  31134. return codePoint;
  31135. }
  31136. }
  31137. throw Error('Invalid UTF-8 detected');
  31138. }
  31139. var byteArray;
  31140. var byteCount;
  31141. var byteIndex;
  31142. function utf8decode(byteString) {
  31143. byteArray = ucs2decode(byteString);
  31144. byteCount = byteArray.length;
  31145. byteIndex = 0;
  31146. var codePoints = [];
  31147. var tmp;
  31148. while ((tmp = decodeSymbol()) !== false) {
  31149. codePoints.push(tmp);
  31150. }
  31151. return ucs2encode(codePoints);
  31152. }
  31153. /*--------------------------------------------------------------------------*/
  31154. var utf8 = {
  31155. 'version': '2.0.0',
  31156. 'encode': utf8encode,
  31157. 'decode': utf8decode
  31158. };
  31159. // Some AMD build optimizers, like r.js, check for specific condition patterns
  31160. // like the following:
  31161. if (
  31162. typeof define == 'function' &&
  31163. typeof define.amd == 'object' &&
  31164. define.amd
  31165. ) {
  31166. define(function() {
  31167. return utf8;
  31168. });
  31169. } else if (freeExports && !freeExports.nodeType) {
  31170. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  31171. freeModule.exports = utf8;
  31172. } else { // in Narwhal or RingoJS v0.7.0-
  31173. var object = {};
  31174. var hasOwnProperty = object.hasOwnProperty;
  31175. for (var key in utf8) {
  31176. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  31177. }
  31178. }
  31179. } else { // in Rhino or a web browser
  31180. root.utf8 = utf8;
  31181. }
  31182. }(this));
  31183. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31184. },{}],134:[function(require,module,exports){
  31185. /**
  31186. * Module dependencies.
  31187. */
  31188. var global = require('global');
  31189. /**
  31190. * Module exports.
  31191. *
  31192. * Logic borrowed from Modernizr:
  31193. *
  31194. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  31195. */
  31196. try {
  31197. module.exports = 'XMLHttpRequest' in global &&
  31198. 'withCredentials' in new global.XMLHttpRequest();
  31199. } catch (err) {
  31200. // if XMLHttp support is disabled in IE then it will throw
  31201. // when trying to create
  31202. module.exports = false;
  31203. }
  31204. },{"global":135}],135:[function(require,module,exports){
  31205. /**
  31206. * Returns `this`. Execute this without a "context" (i.e. without it being
  31207. * attached to an object of the left-hand side), and `this` points to the
  31208. * "global" scope of the current JS execution.
  31209. */
  31210. module.exports = (function () { return this; })();
  31211. },{}],136:[function(require,module,exports){
  31212. (function (global){
  31213. /**
  31214. * JSON parse.
  31215. *
  31216. * @see Based on jQuery#parseJSON (MIT) and JSON2
  31217. * @api private
  31218. */
  31219. var rvalidchars = /^[\],:{}\s]*$/;
  31220. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  31221. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  31222. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  31223. var rtrimLeft = /^\s+/;
  31224. var rtrimRight = /\s+$/;
  31225. module.exports = function parsejson(data) {
  31226. if ('string' != typeof data || !data) {
  31227. return null;
  31228. }
  31229. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  31230. // Attempt to parse using the native JSON parser first
  31231. if (global.JSON && JSON.parse) {
  31232. return JSON.parse(data);
  31233. }
  31234. if (rvalidchars.test(data.replace(rvalidescape, '@')
  31235. .replace(rvalidtokens, ']')
  31236. .replace(rvalidbraces, ''))) {
  31237. return (new Function('return ' + data))();
  31238. }
  31239. };
  31240. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31241. },{}],137:[function(require,module,exports){
  31242. /**
  31243. * Compiles a querystring
  31244. * Returns string representation of the object
  31245. *
  31246. * @param {Object}
  31247. * @api private
  31248. */
  31249. exports.encode = function (obj) {
  31250. var str = '';
  31251. for (var i in obj) {
  31252. if (obj.hasOwnProperty(i)) {
  31253. if (str.length) str += '&';
  31254. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  31255. }
  31256. }
  31257. return str;
  31258. };
  31259. /**
  31260. * Parses a simple querystring into an object
  31261. *
  31262. * @param {String} qs
  31263. * @api private
  31264. */
  31265. exports.decode = function(qs){
  31266. var qry = {};
  31267. var pairs = qs.split('&');
  31268. for (var i = 0, l = pairs.length; i < l; i++) {
  31269. var pair = pairs[i].split('=');
  31270. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  31271. }
  31272. return qry;
  31273. };
  31274. },{}],138:[function(require,module,exports){
  31275. /**
  31276. * Parses an URI
  31277. *
  31278. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  31279. * @api private
  31280. */
  31281. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  31282. var parts = [
  31283. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  31284. ];
  31285. module.exports = function parseuri(str) {
  31286. var src = str,
  31287. b = str.indexOf('['),
  31288. e = str.indexOf(']');
  31289. if (b != -1 && e != -1) {
  31290. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  31291. }
  31292. var m = re.exec(str || ''),
  31293. uri = {},
  31294. i = 14;
  31295. while (i--) {
  31296. uri[parts[i]] = m[i] || '';
  31297. }
  31298. if (b != -1 && e != -1) {
  31299. uri.source = src;
  31300. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  31301. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  31302. uri.ipv6uri = true;
  31303. }
  31304. return uri;
  31305. };
  31306. },{}],139:[function(require,module,exports){
  31307. /**
  31308. * Module dependencies.
  31309. */
  31310. var global = (function() { return this; })();
  31311. /**
  31312. * WebSocket constructor.
  31313. */
  31314. var WebSocket = global.WebSocket || global.MozWebSocket;
  31315. /**
  31316. * Module exports.
  31317. */
  31318. module.exports = WebSocket ? ws : null;
  31319. /**
  31320. * WebSocket constructor.
  31321. *
  31322. * The third `opts` options object gets ignored in web browsers, since it's
  31323. * non-standard, and throws a TypeError if passed to the constructor.
  31324. * See: https://github.com/einaros/ws/issues/227
  31325. *
  31326. * @param {String} uri
  31327. * @param {Array} protocols (optional)
  31328. * @param {Object) opts (optional)
  31329. * @api public
  31330. */
  31331. function ws(uri, protocols, opts) {
  31332. var instance;
  31333. if (protocols) {
  31334. instance = new WebSocket(uri, protocols);
  31335. } else {
  31336. instance = new WebSocket(uri);
  31337. }
  31338. return instance;
  31339. }
  31340. if (WebSocket) ws.prototype = WebSocket.prototype;
  31341. },{}],140:[function(require,module,exports){
  31342. (function (global){
  31343. /*
  31344. * Module requirements.
  31345. */
  31346. var isArray = require('isarray');
  31347. /**
  31348. * Module exports.
  31349. */
  31350. module.exports = hasBinary;
  31351. /**
  31352. * Checks for binary data.
  31353. *
  31354. * Right now only Buffer and ArrayBuffer are supported..
  31355. *
  31356. * @param {Object} anything
  31357. * @api public
  31358. */
  31359. function hasBinary(data) {
  31360. function _hasBinary(obj) {
  31361. if (!obj) return false;
  31362. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  31363. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  31364. (global.Blob && obj instanceof Blob) ||
  31365. (global.File && obj instanceof File)
  31366. ) {
  31367. return true;
  31368. }
  31369. if (isArray(obj)) {
  31370. for (var i = 0; i < obj.length; i++) {
  31371. if (_hasBinary(obj[i])) {
  31372. return true;
  31373. }
  31374. }
  31375. } else if (obj && 'object' == typeof obj) {
  31376. if (obj.toJSON) {
  31377. obj = obj.toJSON();
  31378. }
  31379. for (var key in obj) {
  31380. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  31381. return true;
  31382. }
  31383. }
  31384. }
  31385. return false;
  31386. }
  31387. return _hasBinary(data);
  31388. }
  31389. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31390. },{"isarray":141}],141:[function(require,module,exports){
  31391. arguments[4][132][0].apply(exports,arguments)
  31392. },{"dup":132}],142:[function(require,module,exports){
  31393. var indexOf = [].indexOf;
  31394. module.exports = function(arr, obj){
  31395. if (indexOf) return arr.indexOf(obj);
  31396. for (var i = 0; i < arr.length; ++i) {
  31397. if (arr[i] === obj) return i;
  31398. }
  31399. return -1;
  31400. };
  31401. },{}],143:[function(require,module,exports){
  31402. /**
  31403. * HOP ref.
  31404. */
  31405. var has = Object.prototype.hasOwnProperty;
  31406. /**
  31407. * Return own keys in `obj`.
  31408. *
  31409. * @param {Object} obj
  31410. * @return {Array}
  31411. * @api public
  31412. */
  31413. exports.keys = Object.keys || function(obj){
  31414. var keys = [];
  31415. for (var key in obj) {
  31416. if (has.call(obj, key)) {
  31417. keys.push(key);
  31418. }
  31419. }
  31420. return keys;
  31421. };
  31422. /**
  31423. * Return own values in `obj`.
  31424. *
  31425. * @param {Object} obj
  31426. * @return {Array}
  31427. * @api public
  31428. */
  31429. exports.values = function(obj){
  31430. var vals = [];
  31431. for (var key in obj) {
  31432. if (has.call(obj, key)) {
  31433. vals.push(obj[key]);
  31434. }
  31435. }
  31436. return vals;
  31437. };
  31438. /**
  31439. * Merge `b` into `a`.
  31440. *
  31441. * @param {Object} a
  31442. * @param {Object} b
  31443. * @return {Object} a
  31444. * @api public
  31445. */
  31446. exports.merge = function(a, b){
  31447. for (var key in b) {
  31448. if (has.call(b, key)) {
  31449. a[key] = b[key];
  31450. }
  31451. }
  31452. return a;
  31453. };
  31454. /**
  31455. * Return length of `obj`.
  31456. *
  31457. * @param {Object} obj
  31458. * @return {Number}
  31459. * @api public
  31460. */
  31461. exports.length = function(obj){
  31462. return exports.keys(obj).length;
  31463. };
  31464. /**
  31465. * Check if `obj` is empty.
  31466. *
  31467. * @param {Object} obj
  31468. * @return {Boolean}
  31469. * @api public
  31470. */
  31471. exports.isEmpty = function(obj){
  31472. return 0 == exports.length(obj);
  31473. };
  31474. },{}],144:[function(require,module,exports){
  31475. /**
  31476. * Parses an URI
  31477. *
  31478. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  31479. * @api private
  31480. */
  31481. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  31482. var parts = [
  31483. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  31484. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  31485. ];
  31486. module.exports = function parseuri(str) {
  31487. var m = re.exec(str || '')
  31488. , uri = {}
  31489. , i = 14;
  31490. while (i--) {
  31491. uri[parts[i]] = m[i] || '';
  31492. }
  31493. return uri;
  31494. };
  31495. },{}],145:[function(require,module,exports){
  31496. (function (global){
  31497. /*global Blob,File*/
  31498. /**
  31499. * Module requirements
  31500. */
  31501. var isArray = require('isarray');
  31502. var isBuf = require('./is-buffer');
  31503. /**
  31504. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  31505. * Anything with blobs or files should be fed through removeBlobs before coming
  31506. * here.
  31507. *
  31508. * @param {Object} packet - socket.io event packet
  31509. * @return {Object} with deconstructed packet and list of buffers
  31510. * @api public
  31511. */
  31512. exports.deconstructPacket = function(packet){
  31513. var buffers = [];
  31514. var packetData = packet.data;
  31515. function _deconstructPacket(data) {
  31516. if (!data) return data;
  31517. if (isBuf(data)) {
  31518. var placeholder = { _placeholder: true, num: buffers.length };
  31519. buffers.push(data);
  31520. return placeholder;
  31521. } else if (isArray(data)) {
  31522. var newData = new Array(data.length);
  31523. for (var i = 0; i < data.length; i++) {
  31524. newData[i] = _deconstructPacket(data[i]);
  31525. }
  31526. return newData;
  31527. } else if ('object' == typeof data && !(data instanceof Date)) {
  31528. var newData = {};
  31529. for (var key in data) {
  31530. newData[key] = _deconstructPacket(data[key]);
  31531. }
  31532. return newData;
  31533. }
  31534. return data;
  31535. }
  31536. var pack = packet;
  31537. pack.data = _deconstructPacket(packetData);
  31538. pack.attachments = buffers.length; // number of binary 'attachments'
  31539. return {packet: pack, buffers: buffers};
  31540. };
  31541. /**
  31542. * Reconstructs a binary packet from its placeholder packet and buffers
  31543. *
  31544. * @param {Object} packet - event packet with placeholders
  31545. * @param {Array} buffers - binary buffers to put in placeholder positions
  31546. * @return {Object} reconstructed packet
  31547. * @api public
  31548. */
  31549. exports.reconstructPacket = function(packet, buffers) {
  31550. var curPlaceHolder = 0;
  31551. function _reconstructPacket(data) {
  31552. if (data && data._placeholder) {
  31553. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  31554. return buf;
  31555. } else if (isArray(data)) {
  31556. for (var i = 0; i < data.length; i++) {
  31557. data[i] = _reconstructPacket(data[i]);
  31558. }
  31559. return data;
  31560. } else if (data && 'object' == typeof data) {
  31561. for (var key in data) {
  31562. data[key] = _reconstructPacket(data[key]);
  31563. }
  31564. return data;
  31565. }
  31566. return data;
  31567. }
  31568. packet.data = _reconstructPacket(packet.data);
  31569. packet.attachments = undefined; // no longer useful
  31570. return packet;
  31571. };
  31572. /**
  31573. * Asynchronously removes Blobs or Files from data via
  31574. * FileReader's readAsArrayBuffer method. Used before encoding
  31575. * data as msgpack. Calls callback with the blobless data.
  31576. *
  31577. * @param {Object} data
  31578. * @param {Function} callback
  31579. * @api private
  31580. */
  31581. exports.removeBlobs = function(data, callback) {
  31582. function _removeBlobs(obj, curKey, containingObject) {
  31583. if (!obj) return obj;
  31584. // convert any blob
  31585. if ((global.Blob && obj instanceof Blob) ||
  31586. (global.File && obj instanceof File)) {
  31587. pendingBlobs++;
  31588. // async filereader
  31589. var fileReader = new FileReader();
  31590. fileReader.onload = function() { // this.result == arraybuffer
  31591. if (containingObject) {
  31592. containingObject[curKey] = this.result;
  31593. }
  31594. else {
  31595. bloblessData = this.result;
  31596. }
  31597. // if nothing pending its callback time
  31598. if(! --pendingBlobs) {
  31599. callback(bloblessData);
  31600. }
  31601. };
  31602. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  31603. } else if (isArray(obj)) { // handle array
  31604. for (var i = 0; i < obj.length; i++) {
  31605. _removeBlobs(obj[i], i, obj);
  31606. }
  31607. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  31608. for (var key in obj) {
  31609. _removeBlobs(obj[key], key, obj);
  31610. }
  31611. }
  31612. }
  31613. var pendingBlobs = 0;
  31614. var bloblessData = data;
  31615. _removeBlobs(bloblessData);
  31616. if (!pendingBlobs) {
  31617. callback(bloblessData);
  31618. }
  31619. };
  31620. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31621. },{"./is-buffer":147,"isarray":148}],146:[function(require,module,exports){
  31622. /**
  31623. * Module dependencies.
  31624. */
  31625. var debug = require('debug')('socket.io-parser');
  31626. var json = require('json3');
  31627. var isArray = require('isarray');
  31628. var Emitter = require('component-emitter');
  31629. var binary = require('./binary');
  31630. var isBuf = require('./is-buffer');
  31631. /**
  31632. * Protocol version.
  31633. *
  31634. * @api public
  31635. */
  31636. exports.protocol = 4;
  31637. /**
  31638. * Packet types.
  31639. *
  31640. * @api public
  31641. */
  31642. exports.types = [
  31643. 'CONNECT',
  31644. 'DISCONNECT',
  31645. 'EVENT',
  31646. 'BINARY_EVENT',
  31647. 'ACK',
  31648. 'BINARY_ACK',
  31649. 'ERROR'
  31650. ];
  31651. /**
  31652. * Packet type `connect`.
  31653. *
  31654. * @api public
  31655. */
  31656. exports.CONNECT = 0;
  31657. /**
  31658. * Packet type `disconnect`.
  31659. *
  31660. * @api public
  31661. */
  31662. exports.DISCONNECT = 1;
  31663. /**
  31664. * Packet type `event`.
  31665. *
  31666. * @api public
  31667. */
  31668. exports.EVENT = 2;
  31669. /**
  31670. * Packet type `ack`.
  31671. *
  31672. * @api public
  31673. */
  31674. exports.ACK = 3;
  31675. /**
  31676. * Packet type `error`.
  31677. *
  31678. * @api public
  31679. */
  31680. exports.ERROR = 4;
  31681. /**
  31682. * Packet type 'binary event'
  31683. *
  31684. * @api public
  31685. */
  31686. exports.BINARY_EVENT = 5;
  31687. /**
  31688. * Packet type `binary ack`. For acks with binary arguments.
  31689. *
  31690. * @api public
  31691. */
  31692. exports.BINARY_ACK = 6;
  31693. /**
  31694. * Encoder constructor.
  31695. *
  31696. * @api public
  31697. */
  31698. exports.Encoder = Encoder;
  31699. /**
  31700. * Decoder constructor.
  31701. *
  31702. * @api public
  31703. */
  31704. exports.Decoder = Decoder;
  31705. /**
  31706. * A socket.io Encoder instance
  31707. *
  31708. * @api public
  31709. */
  31710. function Encoder() {}
  31711. /**
  31712. * Encode a packet as a single string if non-binary, or as a
  31713. * buffer sequence, depending on packet type.
  31714. *
  31715. * @param {Object} obj - packet object
  31716. * @param {Function} callback - function to handle encodings (likely engine.write)
  31717. * @return Calls callback with Array of encodings
  31718. * @api public
  31719. */
  31720. Encoder.prototype.encode = function(obj, callback){
  31721. debug('encoding packet %j', obj);
  31722. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  31723. encodeAsBinary(obj, callback);
  31724. }
  31725. else {
  31726. var encoding = encodeAsString(obj);
  31727. callback([encoding]);
  31728. }
  31729. };
  31730. /**
  31731. * Encode packet as string.
  31732. *
  31733. * @param {Object} packet
  31734. * @return {String} encoded
  31735. * @api private
  31736. */
  31737. function encodeAsString(obj) {
  31738. var str = '';
  31739. var nsp = false;
  31740. // first is type
  31741. str += obj.type;
  31742. // attachments if we have them
  31743. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  31744. str += obj.attachments;
  31745. str += '-';
  31746. }
  31747. // if we have a namespace other than `/`
  31748. // we append it followed by a comma `,`
  31749. if (obj.nsp && '/' != obj.nsp) {
  31750. nsp = true;
  31751. str += obj.nsp;
  31752. }
  31753. // immediately followed by the id
  31754. if (null != obj.id) {
  31755. if (nsp) {
  31756. str += ',';
  31757. nsp = false;
  31758. }
  31759. str += obj.id;
  31760. }
  31761. // json data
  31762. if (null != obj.data) {
  31763. if (nsp) str += ',';
  31764. str += json.stringify(obj.data);
  31765. }
  31766. debug('encoded %j as %s', obj, str);
  31767. return str;
  31768. }
  31769. /**
  31770. * Encode packet as 'buffer sequence' by removing blobs, and
  31771. * deconstructing packet into object with placeholders and
  31772. * a list of buffers.
  31773. *
  31774. * @param {Object} packet
  31775. * @return {Buffer} encoded
  31776. * @api private
  31777. */
  31778. function encodeAsBinary(obj, callback) {
  31779. function writeEncoding(bloblessData) {
  31780. var deconstruction = binary.deconstructPacket(bloblessData);
  31781. var pack = encodeAsString(deconstruction.packet);
  31782. var buffers = deconstruction.buffers;
  31783. buffers.unshift(pack); // add packet info to beginning of data list
  31784. callback(buffers); // write all the buffers
  31785. }
  31786. binary.removeBlobs(obj, writeEncoding);
  31787. }
  31788. /**
  31789. * A socket.io Decoder instance
  31790. *
  31791. * @return {Object} decoder
  31792. * @api public
  31793. */
  31794. function Decoder() {
  31795. this.reconstructor = null;
  31796. }
  31797. /**
  31798. * Mix in `Emitter` with Decoder.
  31799. */
  31800. Emitter(Decoder.prototype);
  31801. /**
  31802. * Decodes an ecoded packet string into packet JSON.
  31803. *
  31804. * @param {String} obj - encoded packet
  31805. * @return {Object} packet
  31806. * @api public
  31807. */
  31808. Decoder.prototype.add = function(obj) {
  31809. var packet;
  31810. if ('string' == typeof obj) {
  31811. packet = decodeString(obj);
  31812. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  31813. this.reconstructor = new BinaryReconstructor(packet);
  31814. // no attachments, labeled binary but no binary data to follow
  31815. if (this.reconstructor.reconPack.attachments === 0) {
  31816. this.emit('decoded', packet);
  31817. }
  31818. } else { // non-binary full packet
  31819. this.emit('decoded', packet);
  31820. }
  31821. }
  31822. else if (isBuf(obj) || obj.base64) { // raw binary data
  31823. if (!this.reconstructor) {
  31824. throw new Error('got binary data when not reconstructing a packet');
  31825. } else {
  31826. packet = this.reconstructor.takeBinaryData(obj);
  31827. if (packet) { // received final buffer
  31828. this.reconstructor = null;
  31829. this.emit('decoded', packet);
  31830. }
  31831. }
  31832. }
  31833. else {
  31834. throw new Error('Unknown type: ' + obj);
  31835. }
  31836. };
  31837. /**
  31838. * Decode a packet String (JSON data)
  31839. *
  31840. * @param {String} str
  31841. * @return {Object} packet
  31842. * @api private
  31843. */
  31844. function decodeString(str) {
  31845. var p = {};
  31846. var i = 0;
  31847. // look up type
  31848. p.type = Number(str.charAt(0));
  31849. if (null == exports.types[p.type]) return error();
  31850. // look up attachments if type binary
  31851. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  31852. var buf = '';
  31853. while (str.charAt(++i) != '-') {
  31854. buf += str.charAt(i);
  31855. if (i == str.length) break;
  31856. }
  31857. if (buf != Number(buf) || str.charAt(i) != '-') {
  31858. throw new Error('Illegal attachments');
  31859. }
  31860. p.attachments = Number(buf);
  31861. }
  31862. // look up namespace (if any)
  31863. if ('/' == str.charAt(i + 1)) {
  31864. p.nsp = '';
  31865. while (++i) {
  31866. var c = str.charAt(i);
  31867. if (',' == c) break;
  31868. p.nsp += c;
  31869. if (i == str.length) break;
  31870. }
  31871. } else {
  31872. p.nsp = '/';
  31873. }
  31874. // look up id
  31875. var next = str.charAt(i + 1);
  31876. if ('' !== next && Number(next) == next) {
  31877. p.id = '';
  31878. while (++i) {
  31879. var c = str.charAt(i);
  31880. if (null == c || Number(c) != c) {
  31881. --i;
  31882. break;
  31883. }
  31884. p.id += str.charAt(i);
  31885. if (i == str.length) break;
  31886. }
  31887. p.id = Number(p.id);
  31888. }
  31889. // look up json data
  31890. if (str.charAt(++i)) {
  31891. try {
  31892. p.data = json.parse(str.substr(i));
  31893. } catch(e){
  31894. return error();
  31895. }
  31896. }
  31897. debug('decoded %s as %j', str, p);
  31898. return p;
  31899. }
  31900. /**
  31901. * Deallocates a parser's resources
  31902. *
  31903. * @api public
  31904. */
  31905. Decoder.prototype.destroy = function() {
  31906. if (this.reconstructor) {
  31907. this.reconstructor.finishedReconstruction();
  31908. }
  31909. };
  31910. /**
  31911. * A manager of a binary event's 'buffer sequence'. Should
  31912. * be constructed whenever a packet of type BINARY_EVENT is
  31913. * decoded.
  31914. *
  31915. * @param {Object} packet
  31916. * @return {BinaryReconstructor} initialized reconstructor
  31917. * @api private
  31918. */
  31919. function BinaryReconstructor(packet) {
  31920. this.reconPack = packet;
  31921. this.buffers = [];
  31922. }
  31923. /**
  31924. * Method to be called when binary data received from connection
  31925. * after a BINARY_EVENT packet.
  31926. *
  31927. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  31928. * @return {null | Object} returns null if more binary data is expected or
  31929. * a reconstructed packet object if all buffers have been received.
  31930. * @api private
  31931. */
  31932. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  31933. this.buffers.push(binData);
  31934. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  31935. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  31936. this.finishedReconstruction();
  31937. return packet;
  31938. }
  31939. return null;
  31940. };
  31941. /**
  31942. * Cleans up binary packet reconstruction variables.
  31943. *
  31944. * @api private
  31945. */
  31946. BinaryReconstructor.prototype.finishedReconstruction = function() {
  31947. this.reconPack = null;
  31948. this.buffers = [];
  31949. };
  31950. function error(data){
  31951. return {
  31952. type: exports.ERROR,
  31953. data: 'parser error'
  31954. };
  31955. }
  31956. },{"./binary":145,"./is-buffer":147,"component-emitter":109,"debug":110,"isarray":148,"json3":149}],147:[function(require,module,exports){
  31957. (function (global){
  31958. module.exports = isBuf;
  31959. /**
  31960. * Returns true if obj is a buffer or an arraybuffer.
  31961. *
  31962. * @api private
  31963. */
  31964. function isBuf(obj) {
  31965. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  31966. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  31967. }
  31968. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31969. },{}],148:[function(require,module,exports){
  31970. arguments[4][132][0].apply(exports,arguments)
  31971. },{"dup":132}],149:[function(require,module,exports){
  31972. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  31973. ;(function (window) {
  31974. // Convenience aliases.
  31975. var getClass = {}.toString, isProperty, forEach, undef;
  31976. // Detect the `define` function exposed by asynchronous module loaders. The
  31977. // strict `define` check is necessary for compatibility with `r.js`.
  31978. var isLoader = typeof define === "function" && define.amd;
  31979. // Detect native implementations.
  31980. var nativeJSON = typeof JSON == "object" && JSON;
  31981. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  31982. // available.
  31983. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  31984. if (JSON3 && nativeJSON) {
  31985. // Explicitly delegate to the native `stringify` and `parse`
  31986. // implementations in CommonJS environments.
  31987. JSON3.stringify = nativeJSON.stringify;
  31988. JSON3.parse = nativeJSON.parse;
  31989. } else {
  31990. // Export for web browsers, JavaScript engines, and asynchronous module
  31991. // loaders, using the global `JSON` object if available.
  31992. JSON3 = window.JSON = nativeJSON || {};
  31993. }
  31994. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  31995. var isExtended = new Date(-3509827334573292);
  31996. try {
  31997. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  31998. // results for certain dates in Opera >= 10.53.
  31999. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  32000. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  32001. // but clips the values returned by the date methods to the range of
  32002. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  32003. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  32004. } catch (exception) {}
  32005. // Internal: Determines whether the native `JSON.stringify` and `parse`
  32006. // implementations are spec-compliant. Based on work by Ken Snyder.
  32007. function has(name) {
  32008. if (has[name] !== undef) {
  32009. // Return cached feature test result.
  32010. return has[name];
  32011. }
  32012. var isSupported;
  32013. if (name == "bug-string-char-index") {
  32014. // IE <= 7 doesn't support accessing string characters using square
  32015. // bracket notation. IE 8 only supports this for primitives.
  32016. isSupported = "a"[0] != "a";
  32017. } else if (name == "json") {
  32018. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  32019. // supported.
  32020. isSupported = has("json-stringify") && has("json-parse");
  32021. } else {
  32022. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  32023. // Test `JSON.stringify`.
  32024. if (name == "json-stringify") {
  32025. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  32026. if (stringifySupported) {
  32027. // A test function object with a custom `toJSON` method.
  32028. (value = function () {
  32029. return 1;
  32030. }).toJSON = value;
  32031. try {
  32032. stringifySupported =
  32033. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  32034. // primitives as object literals.
  32035. stringify(0) === "0" &&
  32036. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  32037. // literals.
  32038. stringify(new Number()) === "0" &&
  32039. stringify(new String()) == '""' &&
  32040. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  32041. // does not define a canonical JSON representation (this applies to
  32042. // objects with `toJSON` properties as well, *unless* they are nested
  32043. // within an object or array).
  32044. stringify(getClass) === undef &&
  32045. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  32046. // FF 3.1b3 pass this test.
  32047. stringify(undef) === undef &&
  32048. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  32049. // respectively, if the value is omitted entirely.
  32050. stringify() === undef &&
  32051. // FF 3.1b1, 2 throw an error if the given value is not a number,
  32052. // string, array, object, Boolean, or `null` literal. This applies to
  32053. // objects with custom `toJSON` methods as well, unless they are nested
  32054. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  32055. // methods entirely.
  32056. stringify(value) === "1" &&
  32057. stringify([value]) == "[1]" &&
  32058. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  32059. // `"[null]"`.
  32060. stringify([undef]) == "[null]" &&
  32061. // YUI 3.0.0b1 fails to serialize `null` literals.
  32062. stringify(null) == "null" &&
  32063. // FF 3.1b1, 2 halts serialization if an array contains a function:
  32064. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  32065. // elides non-JSON values from objects and arrays, unless they
  32066. // define custom `toJSON` methods.
  32067. stringify([undef, getClass, null]) == "[null,null,null]" &&
  32068. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  32069. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  32070. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  32071. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  32072. stringify(null, value) === "1" &&
  32073. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  32074. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  32075. // serialize extended years.
  32076. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  32077. // The milliseconds are optional in ES 5, but required in 5.1.
  32078. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  32079. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  32080. // four-digit years instead of six-digit years. Credits: @Yaffle.
  32081. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  32082. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  32083. // values less than 1000. Credits: @Yaffle.
  32084. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  32085. } catch (exception) {
  32086. stringifySupported = false;
  32087. }
  32088. }
  32089. isSupported = stringifySupported;
  32090. }
  32091. // Test `JSON.parse`.
  32092. if (name == "json-parse") {
  32093. var parse = JSON3.parse;
  32094. if (typeof parse == "function") {
  32095. try {
  32096. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  32097. // Conforming implementations should also coerce the initial argument to
  32098. // a string prior to parsing.
  32099. if (parse("0") === 0 && !parse(false)) {
  32100. // Simple parsing test.
  32101. value = parse(serialized);
  32102. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  32103. if (parseSupported) {
  32104. try {
  32105. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  32106. parseSupported = !parse('"\t"');
  32107. } catch (exception) {}
  32108. if (parseSupported) {
  32109. try {
  32110. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  32111. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  32112. // certain octal literals.
  32113. parseSupported = parse("01") !== 1;
  32114. } catch (exception) {}
  32115. }
  32116. if (parseSupported) {
  32117. try {
  32118. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  32119. // points. These environments, along with FF 3.1b1 and 2,
  32120. // also allow trailing commas in JSON objects and arrays.
  32121. parseSupported = parse("1.") !== 1;
  32122. } catch (exception) {}
  32123. }
  32124. }
  32125. }
  32126. } catch (exception) {
  32127. parseSupported = false;
  32128. }
  32129. }
  32130. isSupported = parseSupported;
  32131. }
  32132. }
  32133. return has[name] = !!isSupported;
  32134. }
  32135. if (!has("json")) {
  32136. // Common `[[Class]]` name aliases.
  32137. var functionClass = "[object Function]";
  32138. var dateClass = "[object Date]";
  32139. var numberClass = "[object Number]";
  32140. var stringClass = "[object String]";
  32141. var arrayClass = "[object Array]";
  32142. var booleanClass = "[object Boolean]";
  32143. // Detect incomplete support for accessing string characters by index.
  32144. var charIndexBuggy = has("bug-string-char-index");
  32145. // Define additional utility methods if the `Date` methods are buggy.
  32146. if (!isExtended) {
  32147. var floor = Math.floor;
  32148. // A mapping between the months of the year and the number of days between
  32149. // January 1st and the first of the respective month.
  32150. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  32151. // Internal: Calculates the number of days between the Unix epoch and the
  32152. // first day of the given month.
  32153. var getDay = function (year, month) {
  32154. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  32155. };
  32156. }
  32157. // Internal: Determines if a property is a direct property of the given
  32158. // object. Delegates to the native `Object#hasOwnProperty` method.
  32159. if (!(isProperty = {}.hasOwnProperty)) {
  32160. isProperty = function (property) {
  32161. var members = {}, constructor;
  32162. if ((members.__proto__ = null, members.__proto__ = {
  32163. // The *proto* property cannot be set multiple times in recent
  32164. // versions of Firefox and SeaMonkey.
  32165. "toString": 1
  32166. }, members).toString != getClass) {
  32167. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  32168. // supports the mutable *proto* property.
  32169. isProperty = function (property) {
  32170. // Capture and break the object's prototype chain (see section 8.6.2
  32171. // of the ES 5.1 spec). The parenthesized expression prevents an
  32172. // unsafe transformation by the Closure Compiler.
  32173. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  32174. // Restore the original prototype chain.
  32175. this.__proto__ = original;
  32176. return result;
  32177. };
  32178. } else {
  32179. // Capture a reference to the top-level `Object` constructor.
  32180. constructor = members.constructor;
  32181. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  32182. // other environments.
  32183. isProperty = function (property) {
  32184. var parent = (this.constructor || constructor).prototype;
  32185. return property in this && !(property in parent && this[property] === parent[property]);
  32186. };
  32187. }
  32188. members = null;
  32189. return isProperty.call(this, property);
  32190. };
  32191. }
  32192. // Internal: A set of primitive types used by `isHostType`.
  32193. var PrimitiveTypes = {
  32194. 'boolean': 1,
  32195. 'number': 1,
  32196. 'string': 1,
  32197. 'undefined': 1
  32198. };
  32199. // Internal: Determines if the given object `property` value is a
  32200. // non-primitive.
  32201. var isHostType = function (object, property) {
  32202. var type = typeof object[property];
  32203. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  32204. };
  32205. // Internal: Normalizes the `for...in` iteration algorithm across
  32206. // environments. Each enumerated key is yielded to a `callback` function.
  32207. forEach = function (object, callback) {
  32208. var size = 0, Properties, members, property;
  32209. // Tests for bugs in the current environment's `for...in` algorithm. The
  32210. // `valueOf` property inherits the non-enumerable flag from
  32211. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  32212. (Properties = function () {
  32213. this.valueOf = 0;
  32214. }).prototype.valueOf = 0;
  32215. // Iterate over a new instance of the `Properties` class.
  32216. members = new Properties();
  32217. for (property in members) {
  32218. // Ignore all properties inherited from `Object.prototype`.
  32219. if (isProperty.call(members, property)) {
  32220. size++;
  32221. }
  32222. }
  32223. Properties = members = null;
  32224. // Normalize the iteration algorithm.
  32225. if (!size) {
  32226. // A list of non-enumerable properties inherited from `Object.prototype`.
  32227. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  32228. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  32229. // properties.
  32230. forEach = function (object, callback) {
  32231. var isFunction = getClass.call(object) == functionClass, property, length;
  32232. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  32233. for (property in object) {
  32234. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  32235. // certain conditions; IE does not.
  32236. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  32237. callback(property);
  32238. }
  32239. }
  32240. // Manually invoke the callback for each non-enumerable property.
  32241. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  32242. };
  32243. } else if (size == 2) {
  32244. // Safari <= 2.0.4 enumerates shadowed properties twice.
  32245. forEach = function (object, callback) {
  32246. // Create a set of iterated properties.
  32247. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  32248. for (property in object) {
  32249. // Store each property name to prevent double enumeration. The
  32250. // `prototype` property of functions is not enumerated due to cross-
  32251. // environment inconsistencies.
  32252. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  32253. callback(property);
  32254. }
  32255. }
  32256. };
  32257. } else {
  32258. // No bugs detected; use the standard `for...in` algorithm.
  32259. forEach = function (object, callback) {
  32260. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  32261. for (property in object) {
  32262. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  32263. callback(property);
  32264. }
  32265. }
  32266. // Manually invoke the callback for the `constructor` property due to
  32267. // cross-environment inconsistencies.
  32268. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  32269. callback(property);
  32270. }
  32271. };
  32272. }
  32273. return forEach(object, callback);
  32274. };
  32275. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  32276. // `filter` argument may specify either a function that alters how object and
  32277. // array members are serialized, or an array of strings and numbers that
  32278. // indicates which properties should be serialized. The optional `width`
  32279. // argument may be either a string or number that specifies the indentation
  32280. // level of the output.
  32281. if (!has("json-stringify")) {
  32282. // Internal: A map of control characters and their escaped equivalents.
  32283. var Escapes = {
  32284. 92: "\\\\",
  32285. 34: '\\"',
  32286. 8: "\\b",
  32287. 12: "\\f",
  32288. 10: "\\n",
  32289. 13: "\\r",
  32290. 9: "\\t"
  32291. };
  32292. // Internal: Converts `value` into a zero-padded string such that its
  32293. // length is at least equal to `width`. The `width` must be <= 6.
  32294. var leadingZeroes = "000000";
  32295. var toPaddedString = function (width, value) {
  32296. // The `|| 0` expression is necessary to work around a bug in
  32297. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  32298. return (leadingZeroes + (value || 0)).slice(-width);
  32299. };
  32300. // Internal: Double-quotes a string `value`, replacing all ASCII control
  32301. // characters (characters with code unit values between 0 and 31) with
  32302. // their escaped equivalents. This is an implementation of the
  32303. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  32304. var unicodePrefix = "\\u00";
  32305. var quote = function (value) {
  32306. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  32307. if (isLarge) {
  32308. symbols = value.split("");
  32309. }
  32310. for (; index < length; index++) {
  32311. var charCode = value.charCodeAt(index);
  32312. // If the character is a control character, append its Unicode or
  32313. // shorthand escape sequence; otherwise, append the character as-is.
  32314. switch (charCode) {
  32315. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  32316. result += Escapes[charCode];
  32317. break;
  32318. default:
  32319. if (charCode < 32) {
  32320. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  32321. break;
  32322. }
  32323. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  32324. }
  32325. }
  32326. return result + '"';
  32327. };
  32328. // Internal: Recursively serializes an object. Implements the
  32329. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  32330. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  32331. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  32332. try {
  32333. // Necessary for host object support.
  32334. value = object[property];
  32335. } catch (exception) {}
  32336. if (typeof value == "object" && value) {
  32337. className = getClass.call(value);
  32338. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  32339. if (value > -1 / 0 && value < 1 / 0) {
  32340. // Dates are serialized according to the `Date#toJSON` method
  32341. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  32342. // for the ISO 8601 date time string format.
  32343. if (getDay) {
  32344. // Manually compute the year, month, date, hours, minutes,
  32345. // seconds, and milliseconds if the `getUTC*` methods are
  32346. // buggy. Adapted from @Yaffle's `date-shim` project.
  32347. date = floor(value / 864e5);
  32348. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  32349. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  32350. date = 1 + date - getDay(year, month);
  32351. // The `time` value specifies the time within the day (see ES
  32352. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  32353. // to compute `A modulo B`, as the `%` operator does not
  32354. // correspond to the `modulo` operation for negative numbers.
  32355. time = (value % 864e5 + 864e5) % 864e5;
  32356. // The hours, minutes, seconds, and milliseconds are obtained by
  32357. // decomposing the time within the day. See section 15.9.1.10.
  32358. hours = floor(time / 36e5) % 24;
  32359. minutes = floor(time / 6e4) % 60;
  32360. seconds = floor(time / 1e3) % 60;
  32361. milliseconds = time % 1e3;
  32362. } else {
  32363. year = value.getUTCFullYear();
  32364. month = value.getUTCMonth();
  32365. date = value.getUTCDate();
  32366. hours = value.getUTCHours();
  32367. minutes = value.getUTCMinutes();
  32368. seconds = value.getUTCSeconds();
  32369. milliseconds = value.getUTCMilliseconds();
  32370. }
  32371. // Serialize extended years correctly.
  32372. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  32373. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  32374. // Months, dates, hours, minutes, and seconds should have two
  32375. // digits; milliseconds should have three.
  32376. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  32377. // Milliseconds are optional in ES 5.0, but required in 5.1.
  32378. "." + toPaddedString(3, milliseconds) + "Z";
  32379. } else {
  32380. value = null;
  32381. }
  32382. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  32383. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  32384. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  32385. // ignores all `toJSON` methods on these objects unless they are
  32386. // defined directly on an instance.
  32387. value = value.toJSON(property);
  32388. }
  32389. }
  32390. if (callback) {
  32391. // If a replacement function was provided, call it to obtain the value
  32392. // for serialization.
  32393. value = callback.call(object, property, value);
  32394. }
  32395. if (value === null) {
  32396. return "null";
  32397. }
  32398. className = getClass.call(value);
  32399. if (className == booleanClass) {
  32400. // Booleans are represented literally.
  32401. return "" + value;
  32402. } else if (className == numberClass) {
  32403. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  32404. // `"null"`.
  32405. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  32406. } else if (className == stringClass) {
  32407. // Strings are double-quoted and escaped.
  32408. return quote("" + value);
  32409. }
  32410. // Recursively serialize objects and arrays.
  32411. if (typeof value == "object") {
  32412. // Check for cyclic structures. This is a linear search; performance
  32413. // is inversely proportional to the number of unique nested objects.
  32414. for (length = stack.length; length--;) {
  32415. if (stack[length] === value) {
  32416. // Cyclic structures cannot be serialized by `JSON.stringify`.
  32417. throw TypeError();
  32418. }
  32419. }
  32420. // Add the object to the stack of traversed objects.
  32421. stack.push(value);
  32422. results = [];
  32423. // Save the current indentation level and indent one additional level.
  32424. prefix = indentation;
  32425. indentation += whitespace;
  32426. if (className == arrayClass) {
  32427. // Recursively serialize array elements.
  32428. for (index = 0, length = value.length; index < length; index++) {
  32429. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  32430. results.push(element === undef ? "null" : element);
  32431. }
  32432. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  32433. } else {
  32434. // Recursively serialize object members. Members are selected from
  32435. // either a user-specified list of property names, or the object
  32436. // itself.
  32437. forEach(properties || value, function (property) {
  32438. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  32439. if (element !== undef) {
  32440. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  32441. // is not the empty string, let `member` {quote(property) + ":"}
  32442. // be the concatenation of `member` and the `space` character."
  32443. // The "`space` character" refers to the literal space
  32444. // character, not the `space` {width} argument provided to
  32445. // `JSON.stringify`.
  32446. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  32447. }
  32448. });
  32449. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  32450. }
  32451. // Remove the object from the traversed object stack.
  32452. stack.pop();
  32453. return result;
  32454. }
  32455. };
  32456. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  32457. JSON3.stringify = function (source, filter, width) {
  32458. var whitespace, callback, properties, className;
  32459. if (typeof filter == "function" || typeof filter == "object" && filter) {
  32460. if ((className = getClass.call(filter)) == functionClass) {
  32461. callback = filter;
  32462. } else if (className == arrayClass) {
  32463. // Convert the property names array into a makeshift set.
  32464. properties = {};
  32465. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  32466. }
  32467. }
  32468. if (width) {
  32469. if ((className = getClass.call(width)) == numberClass) {
  32470. // Convert the `width` to an integer and create a string containing
  32471. // `width` number of space characters.
  32472. if ((width -= width % 1) > 0) {
  32473. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  32474. }
  32475. } else if (className == stringClass) {
  32476. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  32477. }
  32478. }
  32479. // Opera <= 7.54u2 discards the values associated with empty string keys
  32480. // (`""`) only if they are used directly within an object member list
  32481. // (e.g., `!("" in { "": 1})`).
  32482. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  32483. };
  32484. }
  32485. // Public: Parses a JSON source string.
  32486. if (!has("json-parse")) {
  32487. var fromCharCode = String.fromCharCode;
  32488. // Internal: A map of escaped control characters and their unescaped
  32489. // equivalents.
  32490. var Unescapes = {
  32491. 92: "\\",
  32492. 34: '"',
  32493. 47: "/",
  32494. 98: "\b",
  32495. 116: "\t",
  32496. 110: "\n",
  32497. 102: "\f",
  32498. 114: "\r"
  32499. };
  32500. // Internal: Stores the parser state.
  32501. var Index, Source;
  32502. // Internal: Resets the parser state and throws a `SyntaxError`.
  32503. var abort = function() {
  32504. Index = Source = null;
  32505. throw SyntaxError();
  32506. };
  32507. // Internal: Returns the next token, or `"$"` if the parser has reached
  32508. // the end of the source string. A token may be a string, number, `null`
  32509. // literal, or Boolean literal.
  32510. var lex = function () {
  32511. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  32512. while (Index < length) {
  32513. charCode = source.charCodeAt(Index);
  32514. switch (charCode) {
  32515. case 9: case 10: case 13: case 32:
  32516. // Skip whitespace tokens, including tabs, carriage returns, line
  32517. // feeds, and space characters.
  32518. Index++;
  32519. break;
  32520. case 123: case 125: case 91: case 93: case 58: case 44:
  32521. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  32522. // the current position.
  32523. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  32524. Index++;
  32525. return value;
  32526. case 34:
  32527. // `"` delimits a JSON string; advance to the next character and
  32528. // begin parsing the string. String tokens are prefixed with the
  32529. // sentinel `@` character to distinguish them from punctuators and
  32530. // end-of-string tokens.
  32531. for (value = "@", Index++; Index < length;) {
  32532. charCode = source.charCodeAt(Index);
  32533. if (charCode < 32) {
  32534. // Unescaped ASCII control characters (those with a code unit
  32535. // less than the space character) are not permitted.
  32536. abort();
  32537. } else if (charCode == 92) {
  32538. // A reverse solidus (`\`) marks the beginning of an escaped
  32539. // control character (including `"`, `\`, and `/`) or Unicode
  32540. // escape sequence.
  32541. charCode = source.charCodeAt(++Index);
  32542. switch (charCode) {
  32543. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  32544. // Revive escaped control characters.
  32545. value += Unescapes[charCode];
  32546. Index++;
  32547. break;
  32548. case 117:
  32549. // `\u` marks the beginning of a Unicode escape sequence.
  32550. // Advance to the first character and validate the
  32551. // four-digit code point.
  32552. begin = ++Index;
  32553. for (position = Index + 4; Index < position; Index++) {
  32554. charCode = source.charCodeAt(Index);
  32555. // A valid sequence comprises four hexdigits (case-
  32556. // insensitive) that form a single hexadecimal value.
  32557. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  32558. // Invalid Unicode escape sequence.
  32559. abort();
  32560. }
  32561. }
  32562. // Revive the escaped character.
  32563. value += fromCharCode("0x" + source.slice(begin, Index));
  32564. break;
  32565. default:
  32566. // Invalid escape sequence.
  32567. abort();
  32568. }
  32569. } else {
  32570. if (charCode == 34) {
  32571. // An unescaped double-quote character marks the end of the
  32572. // string.
  32573. break;
  32574. }
  32575. charCode = source.charCodeAt(Index);
  32576. begin = Index;
  32577. // Optimize for the common case where a string is valid.
  32578. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  32579. charCode = source.charCodeAt(++Index);
  32580. }
  32581. // Append the string as-is.
  32582. value += source.slice(begin, Index);
  32583. }
  32584. }
  32585. if (source.charCodeAt(Index) == 34) {
  32586. // Advance to the next character and return the revived string.
  32587. Index++;
  32588. return value;
  32589. }
  32590. // Unterminated string.
  32591. abort();
  32592. default:
  32593. // Parse numbers and literals.
  32594. begin = Index;
  32595. // Advance past the negative sign, if one is specified.
  32596. if (charCode == 45) {
  32597. isSigned = true;
  32598. charCode = source.charCodeAt(++Index);
  32599. }
  32600. // Parse an integer or floating-point value.
  32601. if (charCode >= 48 && charCode <= 57) {
  32602. // Leading zeroes are interpreted as octal literals.
  32603. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  32604. // Illegal octal literal.
  32605. abort();
  32606. }
  32607. isSigned = false;
  32608. // Parse the integer component.
  32609. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  32610. // Floats cannot contain a leading decimal point; however, this
  32611. // case is already accounted for by the parser.
  32612. if (source.charCodeAt(Index) == 46) {
  32613. position = ++Index;
  32614. // Parse the decimal component.
  32615. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  32616. if (position == Index) {
  32617. // Illegal trailing decimal.
  32618. abort();
  32619. }
  32620. Index = position;
  32621. }
  32622. // Parse exponents. The `e` denoting the exponent is
  32623. // case-insensitive.
  32624. charCode = source.charCodeAt(Index);
  32625. if (charCode == 101 || charCode == 69) {
  32626. charCode = source.charCodeAt(++Index);
  32627. // Skip past the sign following the exponent, if one is
  32628. // specified.
  32629. if (charCode == 43 || charCode == 45) {
  32630. Index++;
  32631. }
  32632. // Parse the exponential component.
  32633. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  32634. if (position == Index) {
  32635. // Illegal empty exponent.
  32636. abort();
  32637. }
  32638. Index = position;
  32639. }
  32640. // Coerce the parsed value to a JavaScript number.
  32641. return +source.slice(begin, Index);
  32642. }
  32643. // A negative sign may only precede numbers.
  32644. if (isSigned) {
  32645. abort();
  32646. }
  32647. // `true`, `false`, and `null` literals.
  32648. if (source.slice(Index, Index + 4) == "true") {
  32649. Index += 4;
  32650. return true;
  32651. } else if (source.slice(Index, Index + 5) == "false") {
  32652. Index += 5;
  32653. return false;
  32654. } else if (source.slice(Index, Index + 4) == "null") {
  32655. Index += 4;
  32656. return null;
  32657. }
  32658. // Unrecognized token.
  32659. abort();
  32660. }
  32661. }
  32662. // Return the sentinel `$` character if the parser has reached the end
  32663. // of the source string.
  32664. return "$";
  32665. };
  32666. // Internal: Parses a JSON `value` token.
  32667. var get = function (value) {
  32668. var results, hasMembers;
  32669. if (value == "$") {
  32670. // Unexpected end of input.
  32671. abort();
  32672. }
  32673. if (typeof value == "string") {
  32674. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  32675. // Remove the sentinel `@` character.
  32676. return value.slice(1);
  32677. }
  32678. // Parse object and array literals.
  32679. if (value == "[") {
  32680. // Parses a JSON array, returning a new JavaScript array.
  32681. results = [];
  32682. for (;; hasMembers || (hasMembers = true)) {
  32683. value = lex();
  32684. // A closing square bracket marks the end of the array literal.
  32685. if (value == "]") {
  32686. break;
  32687. }
  32688. // If the array literal contains elements, the current token
  32689. // should be a comma separating the previous element from the
  32690. // next.
  32691. if (hasMembers) {
  32692. if (value == ",") {
  32693. value = lex();
  32694. if (value == "]") {
  32695. // Unexpected trailing `,` in array literal.
  32696. abort();
  32697. }
  32698. } else {
  32699. // A `,` must separate each array element.
  32700. abort();
  32701. }
  32702. }
  32703. // Elisions and leading commas are not permitted.
  32704. if (value == ",") {
  32705. abort();
  32706. }
  32707. results.push(get(value));
  32708. }
  32709. return results;
  32710. } else if (value == "{") {
  32711. // Parses a JSON object, returning a new JavaScript object.
  32712. results = {};
  32713. for (;; hasMembers || (hasMembers = true)) {
  32714. value = lex();
  32715. // A closing curly brace marks the end of the object literal.
  32716. if (value == "}") {
  32717. break;
  32718. }
  32719. // If the object literal contains members, the current token
  32720. // should be a comma separator.
  32721. if (hasMembers) {
  32722. if (value == ",") {
  32723. value = lex();
  32724. if (value == "}") {
  32725. // Unexpected trailing `,` in object literal.
  32726. abort();
  32727. }
  32728. } else {
  32729. // A `,` must separate each object member.
  32730. abort();
  32731. }
  32732. }
  32733. // Leading commas are not permitted, object property names must be
  32734. // double-quoted strings, and a `:` must separate each property
  32735. // name and value.
  32736. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  32737. abort();
  32738. }
  32739. results[value.slice(1)] = get(lex());
  32740. }
  32741. return results;
  32742. }
  32743. // Unexpected token encountered.
  32744. abort();
  32745. }
  32746. return value;
  32747. };
  32748. // Internal: Updates a traversed object member.
  32749. var update = function(source, property, callback) {
  32750. var element = walk(source, property, callback);
  32751. if (element === undef) {
  32752. delete source[property];
  32753. } else {
  32754. source[property] = element;
  32755. }
  32756. };
  32757. // Internal: Recursively traverses a parsed JSON object, invoking the
  32758. // `callback` function for each value. This is an implementation of the
  32759. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  32760. var walk = function (source, property, callback) {
  32761. var value = source[property], length;
  32762. if (typeof value == "object" && value) {
  32763. // `forEach` can't be used to traverse an array in Opera <= 8.54
  32764. // because its `Object#hasOwnProperty` implementation returns `false`
  32765. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  32766. if (getClass.call(value) == arrayClass) {
  32767. for (length = value.length; length--;) {
  32768. update(value, length, callback);
  32769. }
  32770. } else {
  32771. forEach(value, function (property) {
  32772. update(value, property, callback);
  32773. });
  32774. }
  32775. }
  32776. return callback.call(source, property, value);
  32777. };
  32778. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  32779. JSON3.parse = function (source, callback) {
  32780. var result, value;
  32781. Index = 0;
  32782. Source = "" + source;
  32783. result = get(lex());
  32784. // If a JSON string contains multiple tokens, it is invalid.
  32785. if (lex() != "$") {
  32786. abort();
  32787. }
  32788. // Reset the parser state.
  32789. Index = Source = null;
  32790. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  32791. };
  32792. }
  32793. }
  32794. // Export for asynchronous module loaders.
  32795. if (isLoader) {
  32796. define(function () {
  32797. return JSON3;
  32798. });
  32799. }
  32800. }(this));
  32801. },{}],150:[function(require,module,exports){
  32802. module.exports = toArray
  32803. function toArray(list, index) {
  32804. var array = []
  32805. index = index || 0
  32806. for (var i = index || 0; i < list.length; i++) {
  32807. array[i - index] = list[i]
  32808. }
  32809. return array
  32810. }
  32811. },{}],151:[function(require,module,exports){
  32812. var MediaStreamType = {
  32813. VIDEO_TYPE: "Video",
  32814. AUDIO_TYPE: "Audio"
  32815. };
  32816. module.exports = MediaStreamType;
  32817. },{}],152:[function(require,module,exports){
  32818. var RTCEvents = {
  32819. RTC_READY: "rtc.ready",
  32820. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  32821. LASTN_CHANGED: "rtc.lastn_changed",
  32822. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  32823. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  32824. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  32825. AUDIO_MUTE: "rtc.audio_mute",
  32826. VIDEO_MUTE: "rtc.video_mute"
  32827. };
  32828. module.exports = RTCEvents;
  32829. },{}],153:[function(require,module,exports){
  32830. var Resolutions = {
  32831. "1080": {
  32832. width: 1920,
  32833. height: 1080,
  32834. order: 7
  32835. },
  32836. "fullhd": {
  32837. width: 1920,
  32838. height: 1080,
  32839. order: 7
  32840. },
  32841. "720": {
  32842. width: 1280,
  32843. height: 720,
  32844. order: 6
  32845. },
  32846. "hd": {
  32847. width: 1280,
  32848. height: 720,
  32849. order: 6
  32850. },
  32851. "960": {
  32852. width: 960,
  32853. height: 720,
  32854. order: 5
  32855. },
  32856. "640": {
  32857. width: 640,
  32858. height: 480,
  32859. order: 4
  32860. },
  32861. "vga": {
  32862. width: 640,
  32863. height: 480,
  32864. order: 4
  32865. },
  32866. "360": {
  32867. width: 640,
  32868. height: 360,
  32869. order: 3
  32870. },
  32871. "320": {
  32872. width: 320,
  32873. height: 240,
  32874. order: 2
  32875. },
  32876. "180": {
  32877. width: 320,
  32878. height: 180,
  32879. order: 1
  32880. }
  32881. };
  32882. module.exports = Resolutions;
  32883. },{}],154:[function(require,module,exports){
  32884. var StreamEventTypes = {
  32885. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  32886. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  32887. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  32888. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  32889. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  32890. };
  32891. module.exports = StreamEventTypes;
  32892. },{}],155:[function(require,module,exports){
  32893. var UIEvents = {
  32894. NICKNAME_CHANGED: "UI.nickname_changed",
  32895. SELECTED_ENDPOINT: "UI.selected_endpoint",
  32896. PINNED_ENDPOINT: "UI.pinned_endpoint",
  32897. LARGEVIDEO_INIT: "UI.largevideo_init"
  32898. };
  32899. module.exports = UIEvents;
  32900. },{}],156:[function(require,module,exports){
  32901. var AuthenticationEvents = {
  32902. /**
  32903. * Event callback arguments:
  32904. * function(authenticationEnabled, userIdentity)
  32905. * authenticationEnabled - indicates whether authentication has been enabled
  32906. * in this session
  32907. * userIdentity - if user has been logged in then it contains user name. If
  32908. * contains 'null' or 'undefined' then user is not logged in.
  32909. */
  32910. IDENTITY_UPDATED: "authentication.identity_updated"
  32911. };
  32912. module.exports = AuthenticationEvents;
  32913. },{}],157:[function(require,module,exports){
  32914. var CQEvents = {
  32915. LOCALSTATS_UPDATED: "cq.localstats_updated",
  32916. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  32917. STOP: "cq.stop"
  32918. };
  32919. module.exports = CQEvents;
  32920. },{}],158:[function(require,module,exports){
  32921. var DesktopSharingEventTypes = {
  32922. INIT: "ds.init",
  32923. SWITCHING_DONE: "ds.switching_done",
  32924. NEW_STREAM_CREATED: "ds.new_stream_created"
  32925. };
  32926. module.exports = DesktopSharingEventTypes;
  32927. },{}],159:[function(require,module,exports){
  32928. var Events = {
  32929. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  32930. };
  32931. module.exports = Events;
  32932. },{}],160:[function(require,module,exports){
  32933. module.exports = {
  32934. getLanguages : function () {
  32935. var languages = [];
  32936. for(var lang in this)
  32937. {
  32938. if(typeof this[lang] === "string")
  32939. languages.push(this[lang]);
  32940. }
  32941. return languages;
  32942. },
  32943. EN: "en",
  32944. BG: "bg",
  32945. DE: "de",
  32946. TR: "tr",
  32947. FR: "fr"
  32948. }
  32949. },{}],161:[function(require,module,exports){
  32950. var XMPPEvents = {
  32951. CONNECTION_FAILED: "xmpp.connection.failed",
  32952. // Indicates an interrupted connection event.
  32953. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  32954. // Indicates a restored connection event.
  32955. CONNECTION_RESTORED: "xmpp.connection.restored",
  32956. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  32957. CALL_INCOMING: "xmpp.callincoming.jingle",
  32958. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  32959. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  32960. KICKED: "xmpp.kicked",
  32961. BRIDGE_DOWN: "xmpp.bridge_down",
  32962. USER_ID_CHANGED: "xmpp.user_id_changed",
  32963. // We joined the MUC
  32964. MUC_JOINED: "xmpp.muc_joined",
  32965. // A member joined the MUC
  32966. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  32967. // A member left the MUC
  32968. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  32969. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  32970. MUC_DESTROYED: "xmpp.muc_destroyed",
  32971. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  32972. REMOTE_STATS: "xmpp.remote_stats",
  32973. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  32974. PRESENCE_STATUS: "xmpp.presence_status",
  32975. RESERVATION_ERROR: "xmpp.room_reservation_error",
  32976. SUBJECT_CHANGED: "xmpp.subject_changed",
  32977. MESSAGE_RECEIVED: "xmpp.message_received",
  32978. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  32979. PASSWORD_REQUIRED: "xmpp.password_required",
  32980. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  32981. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  32982. ETHERPAD: "xmpp.etherpad",
  32983. DEVICE_AVAILABLE: "xmpp.device_available",
  32984. VIDEO_TYPE: "xmpp.video_type",
  32985. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  32986. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  32987. AUDIO_MUTED: "xmpp.audio_muted",
  32988. VIDEO_MUTED: "xmpp.video_muted",
  32989. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  32990. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  32991. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  32992. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  32993. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  32994. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  32995. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  32996. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  32997. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  32998. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  32999. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  33000. // xmpp is connected and obtained user media
  33001. READY_TO_JOIN: 'xmpp.ready_to_join'
  33002. };
  33003. module.exports = XMPPEvents;
  33004. },{}],162:[function(require,module,exports){
  33005. // Copyright Joyent, Inc. and other Node contributors.
  33006. //
  33007. // Permission is hereby granted, free of charge, to any person obtaining a
  33008. // copy of this software and associated documentation files (the
  33009. // "Software"), to deal in the Software without restriction, including
  33010. // without limitation the rights to use, copy, modify, merge, publish,
  33011. // distribute, sublicense, and/or sell copies of the Software, and to permit
  33012. // persons to whom the Software is furnished to do so, subject to the
  33013. // following conditions:
  33014. //
  33015. // The above copyright notice and this permission notice shall be included
  33016. // in all copies or substantial portions of the Software.
  33017. //
  33018. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  33019. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  33020. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  33021. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  33022. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  33023. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  33024. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  33025. function EventEmitter() {
  33026. this._events = this._events || {};
  33027. this._maxListeners = this._maxListeners || undefined;
  33028. }
  33029. module.exports = EventEmitter;
  33030. // Backwards-compat with node 0.10.x
  33031. EventEmitter.EventEmitter = EventEmitter;
  33032. EventEmitter.prototype._events = undefined;
  33033. EventEmitter.prototype._maxListeners = undefined;
  33034. // By default EventEmitters will print a warning if more than 10 listeners are
  33035. // added to it. This is a useful default which helps finding memory leaks.
  33036. EventEmitter.defaultMaxListeners = 10;
  33037. // Obviously not all Emitters should be limited to 10. This function allows
  33038. // that to be increased. Set to zero for unlimited.
  33039. EventEmitter.prototype.setMaxListeners = function(n) {
  33040. if (!isNumber(n) || n < 0 || isNaN(n))
  33041. throw TypeError('n must be a positive number');
  33042. this._maxListeners = n;
  33043. return this;
  33044. };
  33045. EventEmitter.prototype.emit = function(type) {
  33046. var er, handler, len, args, i, listeners;
  33047. if (!this._events)
  33048. this._events = {};
  33049. // If there is no 'error' event listener then throw.
  33050. if (type === 'error') {
  33051. if (!this._events.error ||
  33052. (isObject(this._events.error) && !this._events.error.length)) {
  33053. er = arguments[1];
  33054. if (er instanceof Error) {
  33055. throw er; // Unhandled 'error' event
  33056. }
  33057. throw TypeError('Uncaught, unspecified "error" event.');
  33058. }
  33059. }
  33060. handler = this._events[type];
  33061. if (isUndefined(handler))
  33062. return false;
  33063. if (isFunction(handler)) {
  33064. switch (arguments.length) {
  33065. // fast cases
  33066. case 1:
  33067. handler.call(this);
  33068. break;
  33069. case 2:
  33070. handler.call(this, arguments[1]);
  33071. break;
  33072. case 3:
  33073. handler.call(this, arguments[1], arguments[2]);
  33074. break;
  33075. // slower
  33076. default:
  33077. len = arguments.length;
  33078. args = new Array(len - 1);
  33079. for (i = 1; i < len; i++)
  33080. args[i - 1] = arguments[i];
  33081. handler.apply(this, args);
  33082. }
  33083. } else if (isObject(handler)) {
  33084. len = arguments.length;
  33085. args = new Array(len - 1);
  33086. for (i = 1; i < len; i++)
  33087. args[i - 1] = arguments[i];
  33088. listeners = handler.slice();
  33089. len = listeners.length;
  33090. for (i = 0; i < len; i++)
  33091. listeners[i].apply(this, args);
  33092. }
  33093. return true;
  33094. };
  33095. EventEmitter.prototype.addListener = function(type, listener) {
  33096. var m;
  33097. if (!isFunction(listener))
  33098. throw TypeError('listener must be a function');
  33099. if (!this._events)
  33100. this._events = {};
  33101. // To avoid recursion in the case that type === "newListener"! Before
  33102. // adding it to the listeners, first emit "newListener".
  33103. if (this._events.newListener)
  33104. this.emit('newListener', type,
  33105. isFunction(listener.listener) ?
  33106. listener.listener : listener);
  33107. if (!this._events[type])
  33108. // Optimize the case of one listener. Don't need the extra array object.
  33109. this._events[type] = listener;
  33110. else if (isObject(this._events[type]))
  33111. // If we've already got an array, just append.
  33112. this._events[type].push(listener);
  33113. else
  33114. // Adding the second element, need to change to array.
  33115. this._events[type] = [this._events[type], listener];
  33116. // Check for listener leak
  33117. if (isObject(this._events[type]) && !this._events[type].warned) {
  33118. var m;
  33119. if (!isUndefined(this._maxListeners)) {
  33120. m = this._maxListeners;
  33121. } else {
  33122. m = EventEmitter.defaultMaxListeners;
  33123. }
  33124. if (m && m > 0 && this._events[type].length > m) {
  33125. this._events[type].warned = true;
  33126. console.error('(node) warning: possible EventEmitter memory ' +
  33127. 'leak detected. %d listeners added. ' +
  33128. 'Use emitter.setMaxListeners() to increase limit.',
  33129. this._events[type].length);
  33130. if (typeof console.trace === 'function') {
  33131. // not supported in IE 10
  33132. console.trace();
  33133. }
  33134. }
  33135. }
  33136. return this;
  33137. };
  33138. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  33139. EventEmitter.prototype.once = function(type, listener) {
  33140. if (!isFunction(listener))
  33141. throw TypeError('listener must be a function');
  33142. var fired = false;
  33143. function g() {
  33144. this.removeListener(type, g);
  33145. if (!fired) {
  33146. fired = true;
  33147. listener.apply(this, arguments);
  33148. }
  33149. }
  33150. g.listener = listener;
  33151. this.on(type, g);
  33152. return this;
  33153. };
  33154. // emits a 'removeListener' event iff the listener was removed
  33155. EventEmitter.prototype.removeListener = function(type, listener) {
  33156. var list, position, length, i;
  33157. if (!isFunction(listener))
  33158. throw TypeError('listener must be a function');
  33159. if (!this._events || !this._events[type])
  33160. return this;
  33161. list = this._events[type];
  33162. length = list.length;
  33163. position = -1;
  33164. if (list === listener ||
  33165. (isFunction(list.listener) && list.listener === listener)) {
  33166. delete this._events[type];
  33167. if (this._events.removeListener)
  33168. this.emit('removeListener', type, listener);
  33169. } else if (isObject(list)) {
  33170. for (i = length; i-- > 0;) {
  33171. if (list[i] === listener ||
  33172. (list[i].listener && list[i].listener === listener)) {
  33173. position = i;
  33174. break;
  33175. }
  33176. }
  33177. if (position < 0)
  33178. return this;
  33179. if (list.length === 1) {
  33180. list.length = 0;
  33181. delete this._events[type];
  33182. } else {
  33183. list.splice(position, 1);
  33184. }
  33185. if (this._events.removeListener)
  33186. this.emit('removeListener', type, listener);
  33187. }
  33188. return this;
  33189. };
  33190. EventEmitter.prototype.removeAllListeners = function(type) {
  33191. var key, listeners;
  33192. if (!this._events)
  33193. return this;
  33194. // not listening for removeListener, no need to emit
  33195. if (!this._events.removeListener) {
  33196. if (arguments.length === 0)
  33197. this._events = {};
  33198. else if (this._events[type])
  33199. delete this._events[type];
  33200. return this;
  33201. }
  33202. // emit removeListener for all listeners on all events
  33203. if (arguments.length === 0) {
  33204. for (key in this._events) {
  33205. if (key === 'removeListener') continue;
  33206. this.removeAllListeners(key);
  33207. }
  33208. this.removeAllListeners('removeListener');
  33209. this._events = {};
  33210. return this;
  33211. }
  33212. listeners = this._events[type];
  33213. if (isFunction(listeners)) {
  33214. this.removeListener(type, listeners);
  33215. } else {
  33216. // LIFO order
  33217. while (listeners.length)
  33218. this.removeListener(type, listeners[listeners.length - 1]);
  33219. }
  33220. delete this._events[type];
  33221. return this;
  33222. };
  33223. EventEmitter.prototype.listeners = function(type) {
  33224. var ret;
  33225. if (!this._events || !this._events[type])
  33226. ret = [];
  33227. else if (isFunction(this._events[type]))
  33228. ret = [this._events[type]];
  33229. else
  33230. ret = this._events[type].slice();
  33231. return ret;
  33232. };
  33233. EventEmitter.listenerCount = function(emitter, type) {
  33234. var ret;
  33235. if (!emitter._events || !emitter._events[type])
  33236. ret = 0;
  33237. else if (isFunction(emitter._events[type]))
  33238. ret = 1;
  33239. else
  33240. ret = emitter._events[type].length;
  33241. return ret;
  33242. };
  33243. function isFunction(arg) {
  33244. return typeof arg === 'function';
  33245. }
  33246. function isNumber(arg) {
  33247. return typeof arg === 'number';
  33248. }
  33249. function isObject(arg) {
  33250. return typeof arg === 'object' && arg !== null;
  33251. }
  33252. function isUndefined(arg) {
  33253. return arg === void 0;
  33254. }
  33255. },{}],163:[function(require,module,exports){
  33256. // shim for using process in browser
  33257. var process = module.exports = {};
  33258. var queue = [];
  33259. var draining = false;
  33260. function drainQueue() {
  33261. if (draining) {
  33262. return;
  33263. }
  33264. draining = true;
  33265. var currentQueue;
  33266. var len = queue.length;
  33267. while(len) {
  33268. currentQueue = queue;
  33269. queue = [];
  33270. var i = -1;
  33271. while (++i < len) {
  33272. currentQueue[i]();
  33273. }
  33274. len = queue.length;
  33275. }
  33276. draining = false;
  33277. }
  33278. process.nextTick = function (fun) {
  33279. queue.push(fun);
  33280. if (!draining) {
  33281. setTimeout(drainQueue, 0);
  33282. }
  33283. };
  33284. process.title = 'browser';
  33285. process.browser = true;
  33286. process.env = {};
  33287. process.argv = [];
  33288. process.version = ''; // empty string to avoid regexp issues
  33289. function noop() {}
  33290. process.on = noop;
  33291. process.addListener = noop;
  33292. process.once = noop;
  33293. process.off = noop;
  33294. process.removeListener = noop;
  33295. process.removeAllListeners = noop;
  33296. process.emit = noop;
  33297. process.binding = function (name) {
  33298. throw new Error('process.binding is not supported');
  33299. };
  33300. // TODO(shtylman)
  33301. process.cwd = function () { return '/' };
  33302. process.chdir = function (dir) {
  33303. throw new Error('process.chdir is not supported');
  33304. };
  33305. process.umask = function() { return 0; };
  33306. },{}]},{},[1])(1)
  33307. });