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

xmpp.bundle.js 189KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128
  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.xmpp=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. var TraceablePeerConnection = require("./TraceablePeerConnection");
  4. var SDPDiffer = require("./SDPDiffer");
  5. var SDPUtil = require("./SDPUtil");
  6. var SDP = require("./SDP");
  7. // Jingle stuff
  8. function JingleSession(me, sid, connection, service) {
  9. this.me = me;
  10. this.sid = sid;
  11. this.connection = connection;
  12. this.initiator = null;
  13. this.responder = null;
  14. this.isInitiator = null;
  15. this.peerjid = null;
  16. this.state = null;
  17. this.localSDP = null;
  18. this.remoteSDP = null;
  19. this.relayedStreams = [];
  20. this.startTime = null;
  21. this.stopTime = null;
  22. this.media_constraints = null;
  23. this.pc_constraints = null;
  24. this.ice_config = {};
  25. this.drip_container = [];
  26. this.service = service;
  27. this.usetrickle = true;
  28. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  29. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  30. this.hadstuncandidate = false;
  31. this.hadturncandidate = false;
  32. this.lasticecandidate = false;
  33. this.statsinterval = null;
  34. this.reason = null;
  35. this.addssrc = [];
  36. this.removessrc = [];
  37. this.pendingop = null;
  38. this.switchstreams = false;
  39. this.wait = true;
  40. this.localStreamsSSRC = null;
  41. /**
  42. * The indicator which determines whether the (local) video has been muted
  43. * in response to a user command in contrast to an automatic decision made
  44. * by the application logic.
  45. */
  46. this.videoMuteByUser = false;
  47. }
  48. //TODO: this array must be removed when firefox implement multistream support
  49. JingleSession.notReceivedSSRCs = [];
  50. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  51. var self = this;
  52. if (this.state !== null) {
  53. console.error('attempt to initiate on session ' + this.sid +
  54. 'in state ' + this.state);
  55. return;
  56. }
  57. this.isInitiator = isInitiator;
  58. this.state = 'pending';
  59. this.initiator = isInitiator ? this.me : peerjid;
  60. this.responder = !isInitiator ? this.me : peerjid;
  61. this.peerjid = peerjid;
  62. this.hadstuncandidate = false;
  63. this.hadturncandidate = false;
  64. this.lasticecandidate = false;
  65. this.peerconnection
  66. = new TraceablePeerConnection(
  67. this.connection.jingle.ice_config,
  68. this.connection.jingle.pc_constraints );
  69. this.peerconnection.onicecandidate = function (event) {
  70. self.sendIceCandidate(event.candidate);
  71. };
  72. this.peerconnection.onaddstream = function (event) {
  73. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  74. self.remoteStreamAdded(event);
  75. };
  76. this.peerconnection.onremovestream = function (event) {
  77. // Remove the stream from remoteStreams
  78. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  79. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  80. };
  81. this.peerconnection.onsignalingstatechange = function (event) {
  82. if (!(self && self.peerconnection)) return;
  83. };
  84. this.peerconnection.oniceconnectionstatechange = function (event) {
  85. if (!(self && self.peerconnection)) return;
  86. switch (self.peerconnection.iceConnectionState) {
  87. case 'connected':
  88. this.startTime = new Date();
  89. break;
  90. case 'disconnected':
  91. this.stopTime = new Date();
  92. break;
  93. }
  94. onIceConnectionStateChange(self.sid, self);
  95. };
  96. // add any local and relayed stream
  97. RTC.localStreams.forEach(function(stream) {
  98. self.peerconnection.addStream(stream.getOriginalStream());
  99. });
  100. this.relayedStreams.forEach(function(stream) {
  101. self.peerconnection.addStream(stream);
  102. });
  103. };
  104. function onIceConnectionStateChange(sid, session) {
  105. switch (session.peerconnection.iceConnectionState) {
  106. case 'checking':
  107. session.timeChecking = (new Date()).getTime();
  108. session.firstconnect = true;
  109. break;
  110. case 'completed': // on caller side
  111. case 'connected':
  112. if (session.firstconnect) {
  113. session.firstconnect = false;
  114. var metadata = {};
  115. metadata.setupTime
  116. = (new Date()).getTime() - session.timeChecking;
  117. session.peerconnection.getStats(function (res) {
  118. if(res && res.result) {
  119. res.result().forEach(function (report) {
  120. if (report.type == 'googCandidatePair' &&
  121. report.stat('googActiveConnection') == 'true') {
  122. metadata.localCandidateType
  123. = report.stat('googLocalCandidateType');
  124. metadata.remoteCandidateType
  125. = report.stat('googRemoteCandidateType');
  126. // log pair as well so we can get nice pie
  127. // charts
  128. metadata.candidatePair
  129. = report.stat('googLocalCandidateType') +
  130. ';' +
  131. report.stat('googRemoteCandidateType');
  132. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  133. {
  134. metadata.ipv6 = true;
  135. }
  136. }
  137. });
  138. }
  139. });
  140. }
  141. break;
  142. }
  143. }
  144. JingleSession.prototype.accept = function () {
  145. var self = this;
  146. this.state = 'active';
  147. var pranswer = this.peerconnection.localDescription;
  148. if (!pranswer || pranswer.type != 'pranswer') {
  149. return;
  150. }
  151. console.log('going from pranswer to answer');
  152. if (this.usetrickle) {
  153. // remove candidates already sent from session-accept
  154. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  155. for (var i = 0; i < lines.length; i++) {
  156. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  157. }
  158. }
  159. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  160. // FIXME: change any inactive to sendrecv or whatever they were originally
  161. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  162. }
  163. pranswer = simulcast.reverseTransformLocalDescription(pranswer);
  164. var prsdp = new SDP(pranswer.sdp);
  165. var accept = $iq({to: this.peerjid,
  166. type: 'set'})
  167. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  168. action: 'session-accept',
  169. initiator: this.initiator,
  170. responder: this.responder,
  171. sid: this.sid });
  172. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  173. var sdp = this.peerconnection.localDescription.sdp;
  174. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  175. // FIXME: change any inactive to sendrecv or whatever they were originally
  176. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  177. }
  178. var self = this;
  179. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  180. function () {
  181. //console.log('setLocalDescription success');
  182. self.setLocalDescription();
  183. self.connection.sendIQ(accept,
  184. function () {
  185. var ack = {};
  186. ack.source = 'answer';
  187. $(document).trigger('ack.jingle', [self.sid, ack]);
  188. },
  189. function (stanza) {
  190. var error = ($(stanza).find('error').length) ? {
  191. code: $(stanza).find('error').attr('code'),
  192. reason: $(stanza).find('error :first')[0].tagName
  193. }:{};
  194. error.source = 'answer';
  195. JingleSession.onJingleError(self.sid, error);
  196. },
  197. 10000);
  198. },
  199. function (e) {
  200. console.error('setLocalDescription failed', e);
  201. }
  202. );
  203. };
  204. JingleSession.prototype.terminate = function (reason) {
  205. this.state = 'ended';
  206. this.reason = reason;
  207. this.peerconnection.close();
  208. if (this.statsinterval !== null) {
  209. window.clearInterval(this.statsinterval);
  210. this.statsinterval = null;
  211. }
  212. };
  213. JingleSession.prototype.active = function () {
  214. return this.state == 'active';
  215. };
  216. JingleSession.prototype.sendIceCandidate = function (candidate) {
  217. var self = this;
  218. if (candidate && !this.lasticecandidate) {
  219. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  220. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  221. if (!(ice && jcand)) {
  222. console.error('failed to get ice && jcand');
  223. return;
  224. }
  225. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  226. if (jcand.type === 'srflx') {
  227. this.hadstuncandidate = true;
  228. } else if (jcand.type === 'relay') {
  229. this.hadturncandidate = true;
  230. }
  231. if (this.usetrickle) {
  232. if (this.usedrip) {
  233. if (this.drip_container.length === 0) {
  234. // start 20ms callout
  235. window.setTimeout(function () {
  236. if (self.drip_container.length === 0) return;
  237. self.sendIceCandidates(self.drip_container);
  238. self.drip_container = [];
  239. }, 20);
  240. }
  241. this.drip_container.push(candidate);
  242. return;
  243. } else {
  244. self.sendIceCandidate([candidate]);
  245. }
  246. }
  247. } else {
  248. //console.log('sendIceCandidate: last candidate.');
  249. if (!this.usetrickle) {
  250. //console.log('should send full offer now...');
  251. var init = $iq({to: this.peerjid,
  252. type: 'set'})
  253. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  254. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  255. initiator: this.initiator,
  256. sid: this.sid});
  257. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  258. var self = this;
  259. var sendJingle = function (ssrc) {
  260. if(!ssrc)
  261. ssrc = {};
  262. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  263. self.connection.sendIQ(init,
  264. function () {
  265. //console.log('session initiate ack');
  266. var ack = {};
  267. ack.source = 'offer';
  268. $(document).trigger('ack.jingle', [self.sid, ack]);
  269. },
  270. function (stanza) {
  271. self.state = 'error';
  272. self.peerconnection.close();
  273. var error = ($(stanza).find('error').length) ? {
  274. code: $(stanza).find('error').attr('code'),
  275. reason: $(stanza).find('error :first')[0].tagName,
  276. }:{};
  277. error.source = 'offer';
  278. JingleSession.onJingleError(self.sid, error);
  279. },
  280. 10000);
  281. }
  282. sendJingle();
  283. }
  284. this.lasticecandidate = true;
  285. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  286. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  287. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  288. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  289. }
  290. }
  291. };
  292. JingleSession.prototype.sendIceCandidates = function (candidates) {
  293. console.log('sendIceCandidates', candidates);
  294. var cand = $iq({to: this.peerjid, type: 'set'})
  295. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  296. action: 'transport-info',
  297. initiator: this.initiator,
  298. sid: this.sid});
  299. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  300. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  301. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  302. if (cands.length > 0) {
  303. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  304. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  305. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  306. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  307. }).c('transport', ice);
  308. for (var i = 0; i < cands.length; i++) {
  309. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  310. }
  311. // add fingerprint
  312. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  313. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  314. tmp.required = true;
  315. cand.c(
  316. 'fingerprint',
  317. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  318. .t(tmp.fingerprint);
  319. delete tmp.fingerprint;
  320. cand.attrs(tmp);
  321. cand.up();
  322. }
  323. cand.up(); // transport
  324. cand.up(); // content
  325. }
  326. }
  327. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  328. //console.log('was this the last candidate', this.lasticecandidate);
  329. this.connection.sendIQ(cand,
  330. function () {
  331. var ack = {};
  332. ack.source = 'transportinfo';
  333. $(document).trigger('ack.jingle', [this.sid, ack]);
  334. },
  335. function (stanza) {
  336. var error = ($(stanza).find('error').length) ? {
  337. code: $(stanza).find('error').attr('code'),
  338. reason: $(stanza).find('error :first')[0].tagName,
  339. }:{};
  340. error.source = 'transportinfo';
  341. JingleSession.onJingleError(this.sid, error);
  342. },
  343. 10000);
  344. };
  345. JingleSession.prototype.sendOffer = function () {
  346. //console.log('sendOffer...');
  347. var self = this;
  348. this.peerconnection.createOffer(function (sdp) {
  349. self.createdOffer(sdp);
  350. },
  351. function (e) {
  352. console.error('createOffer failed', e);
  353. },
  354. this.media_constraints
  355. );
  356. };
  357. JingleSession.prototype.createdOffer = function (sdp) {
  358. //console.log('createdOffer', sdp);
  359. var self = this;
  360. this.localSDP = new SDP(sdp.sdp);
  361. //this.localSDP.mangle();
  362. var sendJingle = function () {
  363. var init = $iq({to: this.peerjid,
  364. type: 'set'})
  365. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  366. action: 'session-initiate',
  367. initiator: this.initiator,
  368. sid: this.sid});
  369. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  370. self.connection.sendIQ(init,
  371. function () {
  372. var ack = {};
  373. ack.source = 'offer';
  374. $(document).trigger('ack.jingle', [self.sid, ack]);
  375. },
  376. function (stanza) {
  377. self.state = 'error';
  378. self.peerconnection.close();
  379. var error = ($(stanza).find('error').length) ? {
  380. code: $(stanza).find('error').attr('code'),
  381. reason: $(stanza).find('error :first')[0].tagName,
  382. }:{};
  383. error.source = 'offer';
  384. JingleSession.onJingleError(self.sid, error);
  385. },
  386. 10000);
  387. }
  388. sdp.sdp = this.localSDP.raw;
  389. this.peerconnection.setLocalDescription(sdp,
  390. function () {
  391. if(self.usetrickle)
  392. {
  393. sendJingle();
  394. }
  395. self.setLocalDescription();
  396. //console.log('setLocalDescription success');
  397. },
  398. function (e) {
  399. console.error('setLocalDescription failed', e);
  400. }
  401. );
  402. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  403. for (var i = 0; i < cands.length; i++) {
  404. var cand = SDPUtil.parse_icecandidate(cands[i]);
  405. if (cand.type == 'srflx') {
  406. this.hadstuncandidate = true;
  407. } else if (cand.type == 'relay') {
  408. this.hadturncandidate = true;
  409. }
  410. }
  411. };
  412. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  413. //console.log('setting remote description... ', desctype);
  414. this.remoteSDP = new SDP('');
  415. this.remoteSDP.fromJingle(elem);
  416. if (this.peerconnection.remoteDescription !== null) {
  417. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  418. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  419. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  420. for (var i = 0; i < pranswer.media.length; i++) {
  421. // make sure we have ice ufrag and pwd
  422. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  423. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  424. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  425. } else {
  426. console.warn('no ice ufrag?');
  427. }
  428. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  429. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  430. } else {
  431. console.warn('no ice pwd?');
  432. }
  433. }
  434. // copy over candidates
  435. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  436. for (var j = 0; j < lines.length; j++) {
  437. this.remoteSDP.media[i] += lines[j] + '\r\n';
  438. }
  439. }
  440. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  441. }
  442. }
  443. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  444. this.peerconnection.setRemoteDescription(remotedesc,
  445. function () {
  446. //console.log('setRemoteDescription success');
  447. },
  448. function (e) {
  449. console.error('setRemoteDescription error', e);
  450. JingleSession.onJingleFatalError(self, e);
  451. }
  452. );
  453. };
  454. JingleSession.prototype.addIceCandidate = function (elem) {
  455. var self = this;
  456. if (this.peerconnection.signalingState == 'closed') {
  457. return;
  458. }
  459. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  460. console.log('trickle ice candidate arriving before session accept...');
  461. // create a PRANSWER for setRemoteDescription
  462. if (!this.remoteSDP) {
  463. var cobbled = 'v=0\r\n' +
  464. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  465. 's=-\r\n' +
  466. 't=0 0\r\n';
  467. // first, take some things from the local description
  468. for (var i = 0; i < this.localSDP.media.length; i++) {
  469. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  470. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  471. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  472. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  473. }
  474. cobbled += 'a=inactive\r\n';
  475. }
  476. this.remoteSDP = new SDP(cobbled);
  477. }
  478. // then add things like ice and dtls from remote candidate
  479. elem.each(function () {
  480. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  481. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  482. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  483. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  484. var tmp = $(this).find('transport');
  485. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  486. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  487. tmp = $(this).find('transport>fingerprint');
  488. if (tmp.length) {
  489. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  490. } else {
  491. console.log('no dtls fingerprint (webrtc issue #1718?)');
  492. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  493. }
  494. break;
  495. }
  496. }
  497. }
  498. });
  499. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  500. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  501. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  502. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  503. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  504. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  505. }).length == this.remoteSDP.media.length;
  506. if (iscomplete) {
  507. console.log('setting pranswer');
  508. try {
  509. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  510. function() {
  511. },
  512. function(e) {
  513. console.log('setRemoteDescription pranswer failed', e.toString());
  514. });
  515. } catch (e) {
  516. console.error('setting pranswer failed', e);
  517. }
  518. } else {
  519. //console.log('not yet setting pranswer');
  520. }
  521. }
  522. // operate on each content element
  523. elem.each(function () {
  524. // would love to deactivate this, but firefox still requires it
  525. var idx = -1;
  526. var i;
  527. for (i = 0; i < self.remoteSDP.media.length; i++) {
  528. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  529. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  530. idx = i;
  531. break;
  532. }
  533. }
  534. if (idx == -1) { // fall back to localdescription
  535. for (i = 0; i < self.localSDP.media.length; i++) {
  536. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  537. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  538. idx = i;
  539. break;
  540. }
  541. }
  542. }
  543. var name = $(this).attr('name');
  544. // TODO: check ice-pwd and ice-ufrag?
  545. $(this).find('transport>candidate').each(function () {
  546. var line, candidate;
  547. line = SDPUtil.candidateFromJingle(this);
  548. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  549. sdpMid: name,
  550. candidate: line});
  551. try {
  552. self.peerconnection.addIceCandidate(candidate);
  553. } catch (e) {
  554. console.error('addIceCandidate failed', e.toString(), line);
  555. }
  556. });
  557. });
  558. };
  559. JingleSession.prototype.sendAnswer = function (provisional) {
  560. //console.log('createAnswer', provisional);
  561. var self = this;
  562. this.peerconnection.createAnswer(
  563. function (sdp) {
  564. self.createdAnswer(sdp, provisional);
  565. },
  566. function (e) {
  567. console.error('createAnswer failed', e);
  568. },
  569. this.media_constraints
  570. );
  571. };
  572. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  573. //console.log('createAnswer callback');
  574. var self = this;
  575. this.localSDP = new SDP(sdp.sdp);
  576. //this.localSDP.mangle();
  577. this.usepranswer = provisional === true;
  578. if (this.usetrickle) {
  579. if (this.usepranswer) {
  580. sdp.type = 'pranswer';
  581. for (var i = 0; i < this.localSDP.media.length; i++) {
  582. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  583. }
  584. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  585. }
  586. }
  587. var self = this;
  588. var sendJingle = function (ssrcs) {
  589. var accept = $iq({to: self.peerjid,
  590. type: 'set'})
  591. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  592. action: 'session-accept',
  593. initiator: self.initiator,
  594. responder: self.responder,
  595. sid: self.sid });
  596. var publicLocalDesc = simulcast.reverseTransformLocalDescription(sdp);
  597. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  598. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  599. self.connection.sendIQ(accept,
  600. function () {
  601. var ack = {};
  602. ack.source = 'answer';
  603. $(document).trigger('ack.jingle', [self.sid, ack]);
  604. },
  605. function (stanza) {
  606. var error = ($(stanza).find('error').length) ? {
  607. code: $(stanza).find('error').attr('code'),
  608. reason: $(stanza).find('error :first')[0].tagName,
  609. }:{};
  610. error.source = 'answer';
  611. JingleSession.onJingleError(self.sid, error);
  612. },
  613. 10000);
  614. }
  615. sdp.sdp = this.localSDP.raw;
  616. this.peerconnection.setLocalDescription(sdp,
  617. function () {
  618. //console.log('setLocalDescription success');
  619. if (self.usetrickle && !self.usepranswer) {
  620. sendJingle();
  621. }
  622. self.setLocalDescription();
  623. },
  624. function (e) {
  625. console.error('setLocalDescription failed', e);
  626. }
  627. );
  628. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  629. for (var j = 0; j < cands.length; j++) {
  630. var cand = SDPUtil.parse_icecandidate(cands[j]);
  631. if (cand.type == 'srflx') {
  632. this.hadstuncandidate = true;
  633. } else if (cand.type == 'relay') {
  634. this.hadturncandidate = true;
  635. }
  636. }
  637. };
  638. JingleSession.prototype.sendTerminate = function (reason, text) {
  639. var self = this,
  640. term = $iq({to: this.peerjid,
  641. type: 'set'})
  642. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  643. action: 'session-terminate',
  644. initiator: this.initiator,
  645. sid: this.sid})
  646. .c('reason')
  647. .c(reason || 'success');
  648. if (text) {
  649. term.up().c('text').t(text);
  650. }
  651. this.connection.sendIQ(term,
  652. function () {
  653. self.peerconnection.close();
  654. self.peerconnection = null;
  655. self.terminate();
  656. var ack = {};
  657. ack.source = 'terminate';
  658. $(document).trigger('ack.jingle', [self.sid, ack]);
  659. },
  660. function (stanza) {
  661. var error = ($(stanza).find('error').length) ? {
  662. code: $(stanza).find('error').attr('code'),
  663. reason: $(stanza).find('error :first')[0].tagName,
  664. }:{};
  665. $(document).trigger('ack.jingle', [self.sid, error]);
  666. },
  667. 10000);
  668. if (this.statsinterval !== null) {
  669. window.clearInterval(this.statsinterval);
  670. this.statsinterval = null;
  671. }
  672. };
  673. JingleSession.prototype.addSource = function (elem, fromJid) {
  674. var self = this;
  675. // FIXME: dirty waiting
  676. if (!this.peerconnection.localDescription)
  677. {
  678. console.warn("addSource - localDescription not ready yet")
  679. setTimeout(function()
  680. {
  681. self.addSource(elem, fromJid);
  682. },
  683. 200
  684. );
  685. return;
  686. }
  687. console.log('addssrc', new Date().getTime());
  688. console.log('ice', this.peerconnection.iceConnectionState);
  689. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  690. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  691. $(elem).each(function (idx, content) {
  692. var name = $(content).attr('name');
  693. var lines = '';
  694. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  695. var semantics = this.getAttribute('semantics');
  696. var ssrcs = $(this).find('>source').map(function () {
  697. return this.getAttribute('ssrc');
  698. }).get();
  699. if (ssrcs.length != 0) {
  700. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  701. }
  702. });
  703. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  704. tmp.each(function () {
  705. var ssrc = $(this).attr('ssrc');
  706. if(mySdp.containsSSRC(ssrc)){
  707. /**
  708. * This happens when multiple participants change their streams at the same time and
  709. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  710. * addssrc are scheduled for update IQ. See
  711. */
  712. console.warn("Got add stream request for my own ssrc: "+ssrc);
  713. return;
  714. }
  715. $(this).find('>parameter').each(function () {
  716. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  717. if ($(this).attr('value') && $(this).attr('value').length)
  718. lines += ':' + $(this).attr('value');
  719. lines += '\r\n';
  720. });
  721. });
  722. sdp.media.forEach(function(media, idx) {
  723. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  724. return;
  725. sdp.media[idx] += lines;
  726. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  727. self.addssrc[idx] += lines;
  728. });
  729. sdp.raw = sdp.session + sdp.media.join('');
  730. });
  731. this.modifySources();
  732. };
  733. JingleSession.prototype.removeSource = function (elem, fromJid) {
  734. var self = this;
  735. // FIXME: dirty waiting
  736. if (!this.peerconnection.localDescription)
  737. {
  738. console.warn("removeSource - localDescription not ready yet")
  739. setTimeout(function()
  740. {
  741. self.removeSource(elem, fromJid);
  742. },
  743. 200
  744. );
  745. return;
  746. }
  747. console.log('removessrc', new Date().getTime());
  748. console.log('ice', this.peerconnection.iceConnectionState);
  749. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  750. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  751. $(elem).each(function (idx, content) {
  752. var name = $(content).attr('name');
  753. var lines = '';
  754. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  755. var semantics = this.getAttribute('semantics');
  756. var ssrcs = $(this).find('>source').map(function () {
  757. return this.getAttribute('ssrc');
  758. }).get();
  759. if (ssrcs.length != 0) {
  760. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  761. }
  762. });
  763. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  764. tmp.each(function () {
  765. var ssrc = $(this).attr('ssrc');
  766. // This should never happen, but can be useful for bug detection
  767. if(mySdp.containsSSRC(ssrc)){
  768. console.error("Got remove stream request for my own ssrc: "+ssrc);
  769. return;
  770. }
  771. $(this).find('>parameter').each(function () {
  772. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  773. if ($(this).attr('value') && $(this).attr('value').length)
  774. lines += ':' + $(this).attr('value');
  775. lines += '\r\n';
  776. });
  777. });
  778. sdp.media.forEach(function(media, idx) {
  779. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  780. return;
  781. sdp.media[idx] += lines;
  782. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  783. self.removessrc[idx] += lines;
  784. });
  785. sdp.raw = sdp.session + sdp.media.join('');
  786. });
  787. this.modifySources();
  788. };
  789. JingleSession.prototype.modifySources = function (successCallback) {
  790. var self = this;
  791. if (this.peerconnection.signalingState == 'closed') return;
  792. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  793. // There is nothing to do since scheduled job might have been executed by another succeeding call
  794. this.setLocalDescription();
  795. if(successCallback){
  796. successCallback();
  797. }
  798. return;
  799. }
  800. // FIXME: this is a big hack
  801. // https://code.google.com/p/webrtc/issues/detail?id=2688
  802. // ^ has been fixed.
  803. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  804. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  805. this.wait = true;
  806. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  807. return;
  808. }
  809. if (this.wait) {
  810. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  811. this.wait = false;
  812. return;
  813. }
  814. // Reset switch streams flag
  815. this.switchstreams = false;
  816. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  817. // add sources
  818. this.addssrc.forEach(function(lines, idx) {
  819. sdp.media[idx] += lines;
  820. });
  821. this.addssrc = [];
  822. // remove sources
  823. this.removessrc.forEach(function(lines, idx) {
  824. lines = lines.split('\r\n');
  825. lines.pop(); // remove empty last element;
  826. lines.forEach(function(line) {
  827. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  828. });
  829. });
  830. this.removessrc = [];
  831. // FIXME:
  832. // this was a hack for the situation when only one peer exists
  833. // in the conference.
  834. // check if still required and remove
  835. if (sdp.media[0])
  836. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  837. if (sdp.media[1])
  838. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  839. sdp.raw = sdp.session + sdp.media.join('');
  840. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  841. function() {
  842. if(self.signalingState == 'closed') {
  843. console.error("createAnswer attempt on closed state");
  844. return;
  845. }
  846. self.peerconnection.createAnswer(
  847. function(modifiedAnswer) {
  848. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  849. if (self.pendingop !== null) {
  850. var sdp = new SDP(modifiedAnswer.sdp);
  851. if (sdp.media.length > 1) {
  852. switch(self.pendingop) {
  853. case 'mute':
  854. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  855. break;
  856. case 'unmute':
  857. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  858. break;
  859. }
  860. sdp.raw = sdp.session + sdp.media.join('');
  861. modifiedAnswer.sdp = sdp.raw;
  862. }
  863. self.pendingop = null;
  864. }
  865. // FIXME: pushing down an answer while ice connection state
  866. // is still checking is bad...
  867. //console.log(self.peerconnection.iceConnectionState);
  868. // trying to work around another chrome bug
  869. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  870. self.peerconnection.setLocalDescription(modifiedAnswer,
  871. function() {
  872. //console.log('modified setLocalDescription ok');
  873. self.setLocalDescription();
  874. if(successCallback){
  875. successCallback();
  876. }
  877. },
  878. function(error) {
  879. console.error('modified setLocalDescription failed', error);
  880. }
  881. );
  882. },
  883. function(error) {
  884. console.error('modified answer failed', error);
  885. }
  886. );
  887. },
  888. function(error) {
  889. console.error('modify failed', error);
  890. }
  891. );
  892. };
  893. /**
  894. * Switches video streams.
  895. * @param new_stream new stream that will be used as video of this session.
  896. * @param oldStream old video stream of this session.
  897. * @param success_callback callback executed after successful stream switch.
  898. */
  899. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  900. var self = this;
  901. // Remember SDP to figure out added/removed SSRCs
  902. var oldSdp = null;
  903. if(self.peerconnection) {
  904. if(self.peerconnection.localDescription) {
  905. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  906. }
  907. self.peerconnection.removeStream(oldStream, true);
  908. self.peerconnection.addStream(new_stream);
  909. }
  910. RTC.switchVideoStreams(new_stream, oldStream);
  911. // Conference is not active
  912. if(!oldSdp || !self.peerconnection) {
  913. success_callback();
  914. return;
  915. }
  916. self.switchstreams = true;
  917. self.modifySources(function() {
  918. console.log('modify sources done');
  919. success_callback();
  920. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  921. console.log("SDPs", oldSdp, newSdp);
  922. self.notifyMySSRCUpdate(oldSdp, newSdp);
  923. });
  924. };
  925. /**
  926. * Figures out added/removed ssrcs and send update IQs.
  927. * @param old_sdp SDP object for old description.
  928. * @param new_sdp SDP object for new description.
  929. */
  930. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  931. if (!(this.peerconnection.signalingState == 'stable' &&
  932. this.peerconnection.iceConnectionState == 'connected')){
  933. console.log("Too early to send updates");
  934. return;
  935. }
  936. // send source-remove IQ.
  937. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  938. var remove = $iq({to: this.peerjid, type: 'set'})
  939. .c('jingle', {
  940. xmlns: 'urn:xmpp:jingle:1',
  941. action: 'source-remove',
  942. initiator: this.initiator,
  943. sid: this.sid
  944. }
  945. );
  946. var removed = sdpDiffer.toJingle(remove);
  947. if (removed) {
  948. this.connection.sendIQ(remove,
  949. function (res) {
  950. console.info('got remove result', res);
  951. },
  952. function (err) {
  953. console.error('got remove error', err);
  954. }
  955. );
  956. } else {
  957. console.log('removal not necessary');
  958. }
  959. // send source-add IQ.
  960. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  961. var add = $iq({to: this.peerjid, type: 'set'})
  962. .c('jingle', {
  963. xmlns: 'urn:xmpp:jingle:1',
  964. action: 'source-add',
  965. initiator: this.initiator,
  966. sid: this.sid
  967. }
  968. );
  969. var added = sdpDiffer.toJingle(add);
  970. if (added) {
  971. this.connection.sendIQ(add,
  972. function (res) {
  973. console.info('got add result', res);
  974. },
  975. function (err) {
  976. console.error('got add error', err);
  977. }
  978. );
  979. } else {
  980. console.log('addition not necessary');
  981. }
  982. };
  983. /**
  984. * Determines whether the (local) video is mute i.e. all video tracks are
  985. * disabled.
  986. *
  987. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  988. * disabled; otherwise, <tt>false</tt>
  989. */
  990. JingleSession.prototype.isVideoMute = function () {
  991. var tracks = RTC.localVideo.getVideoTracks();
  992. var mute = true;
  993. for (var i = 0; i < tracks.length; ++i) {
  994. if (tracks[i].enabled) {
  995. mute = false;
  996. break;
  997. }
  998. }
  999. return mute;
  1000. };
  1001. /**
  1002. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  1003. *
  1004. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  1005. * tracks; otherwise, <tt>false</tt>
  1006. * @param callback a function to be invoked with <tt>mute</tt> after all video
  1007. * tracks have been enabled/disabled. The function may, optionally, return
  1008. * another function which is to be invoked after the whole mute/unmute operation
  1009. * has completed successfully.
  1010. * @param options an object which specifies optional arguments such as the
  1011. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1012. * specifies whether the method was initiated in response to a user command (in
  1013. * contrast to an automatic decision made by the application logic)
  1014. */
  1015. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  1016. var byUser;
  1017. if (options) {
  1018. byUser = options.byUser;
  1019. if (typeof byUser === 'undefined') {
  1020. byUser = true;
  1021. }
  1022. } else {
  1023. byUser = true;
  1024. }
  1025. // The user's command to mute the (local) video takes precedence over any
  1026. // automatic decision made by the application logic.
  1027. if (byUser) {
  1028. this.videoMuteByUser = mute;
  1029. } else if (this.videoMuteByUser) {
  1030. return;
  1031. }
  1032. var self = this;
  1033. var localCallback = function (mute) {
  1034. self.connection.emuc.addVideoInfoToPresence(mute);
  1035. self.connection.emuc.sendPresence();
  1036. return callback(mute)
  1037. };
  1038. if (mute == RTC.localVideo.isMuted())
  1039. {
  1040. // Even if no change occurs, the specified callback is to be executed.
  1041. // The specified callback may, optionally, return a successCallback
  1042. // which is to be executed as well.
  1043. var successCallback = localCallback(mute);
  1044. if (successCallback) {
  1045. successCallback();
  1046. }
  1047. } else {
  1048. RTC.localVideo.setMute(!mute);
  1049. this.hardMuteVideo(mute);
  1050. this.modifySources(localCallback(mute));
  1051. }
  1052. };
  1053. // SDP-based mute by going recvonly/sendrecv
  1054. // FIXME: should probably black out the screen as well
  1055. JingleSession.prototype.toggleVideoMute = function (callback) {
  1056. this.service.setVideoMute(RTC.localVideo.isMuted(), callback);
  1057. };
  1058. JingleSession.prototype.hardMuteVideo = function (muted) {
  1059. this.pendingop = muted ? 'mute' : 'unmute';
  1060. };
  1061. JingleSession.prototype.sendMute = function (muted, content) {
  1062. var info = $iq({to: this.peerjid,
  1063. type: 'set'})
  1064. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1065. action: 'session-info',
  1066. initiator: this.initiator,
  1067. sid: this.sid });
  1068. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1069. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  1070. if (content) {
  1071. info.attrs({'name': content});
  1072. }
  1073. this.connection.send(info);
  1074. };
  1075. JingleSession.prototype.sendRinging = function () {
  1076. var info = $iq({to: this.peerjid,
  1077. type: 'set'})
  1078. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1079. action: 'session-info',
  1080. initiator: this.initiator,
  1081. sid: this.sid });
  1082. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1083. this.connection.send(info);
  1084. };
  1085. JingleSession.prototype.getStats = function (interval) {
  1086. var self = this;
  1087. var recv = {audio: 0, video: 0};
  1088. var lost = {audio: 0, video: 0};
  1089. var lastrecv = {audio: 0, video: 0};
  1090. var lastlost = {audio: 0, video: 0};
  1091. var loss = {audio: 0, video: 0};
  1092. var delta = {audio: 0, video: 0};
  1093. this.statsinterval = window.setInterval(function () {
  1094. if (self && self.peerconnection && self.peerconnection.getStats) {
  1095. self.peerconnection.getStats(function (stats) {
  1096. var results = stats.result();
  1097. // TODO: there are so much statistics you can get from this..
  1098. for (var i = 0; i < results.length; ++i) {
  1099. if (results[i].type == 'ssrc') {
  1100. var packetsrecv = results[i].stat('packetsReceived');
  1101. var packetslost = results[i].stat('packetsLost');
  1102. if (packetsrecv && packetslost) {
  1103. packetsrecv = parseInt(packetsrecv, 10);
  1104. packetslost = parseInt(packetslost, 10);
  1105. if (results[i].stat('googFrameRateReceived')) {
  1106. lastlost.video = lost.video;
  1107. lastrecv.video = recv.video;
  1108. recv.video = packetsrecv;
  1109. lost.video = packetslost;
  1110. } else {
  1111. lastlost.audio = lost.audio;
  1112. lastrecv.audio = recv.audio;
  1113. recv.audio = packetsrecv;
  1114. lost.audio = packetslost;
  1115. }
  1116. }
  1117. }
  1118. }
  1119. delta.audio = recv.audio - lastrecv.audio;
  1120. delta.video = recv.video - lastrecv.video;
  1121. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  1122. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  1123. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  1124. });
  1125. }
  1126. }, interval || 3000);
  1127. return this.statsinterval;
  1128. };
  1129. JingleSession.onJingleError = function (session, error)
  1130. {
  1131. console.error("Jingle error", error);
  1132. }
  1133. JingleSession.onJingleFatalError = function (session, error)
  1134. {
  1135. this.service.sessionTerminated = true;
  1136. connection.emuc.doLeave();
  1137. UI.messageHandler.showError( "Sorry",
  1138. "Internal application error[setRemoteDescription]");
  1139. }
  1140. JingleSession.prototype.setLocalDescription = function () {
  1141. // put our ssrcs into presence so other clients can identify our stream
  1142. var newssrcs = [];
  1143. var media = simulcast.parseMedia(this.peerconnection.localDescription);
  1144. media.forEach(function (media) {
  1145. if(Object.keys(media.sources).length > 0) {
  1146. // TODO(gp) maybe exclude FID streams?
  1147. Object.keys(media.sources).forEach(function (ssrc) {
  1148. newssrcs.push({
  1149. 'ssrc': ssrc,
  1150. 'type': media.type,
  1151. 'direction': media.direction
  1152. });
  1153. });
  1154. }
  1155. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  1156. {
  1157. newssrcs.push({
  1158. 'ssrc': this.localStreamsSSRC[media.type],
  1159. 'type': media.type,
  1160. 'direction': media.direction
  1161. });
  1162. }
  1163. });
  1164. console.log('new ssrcs', newssrcs);
  1165. // Have to clear presence map to get rid of removed streams
  1166. this.connection.emuc.clearPresenceMedia();
  1167. if (newssrcs.length > 0) {
  1168. for (var i = 1; i <= newssrcs.length; i ++) {
  1169. // Change video type to screen
  1170. if (newssrcs[i-1].type === 'video' && desktopsharing.isUsingScreenStream()) {
  1171. newssrcs[i-1].type = 'screen';
  1172. }
  1173. this.connection.emuc.addMediaToPresence(i,
  1174. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  1175. }
  1176. this.connection.emuc.sendPresence();
  1177. }
  1178. }
  1179. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1180. function sendKeyframe(pc) {
  1181. console.log('sendkeyframe', pc.iceConnectionState);
  1182. if (pc.iceConnectionState !== 'connected') return; // safe...
  1183. pc.setRemoteDescription(
  1184. pc.remoteDescription,
  1185. function () {
  1186. pc.createAnswer(
  1187. function (modifiedAnswer) {
  1188. pc.setLocalDescription(
  1189. modifiedAnswer,
  1190. function () {
  1191. // noop
  1192. },
  1193. function (error) {
  1194. console.log('triggerKeyframe setLocalDescription failed', error);
  1195. UI.messageHandler.showError();
  1196. }
  1197. );
  1198. },
  1199. function (error) {
  1200. console.log('triggerKeyframe createAnswer failed', error);
  1201. UI.messageHandler.showError();
  1202. }
  1203. );
  1204. },
  1205. function (error) {
  1206. console.log('triggerKeyframe setRemoteDescription failed', error);
  1207. UI.messageHandler.showError();
  1208. }
  1209. );
  1210. }
  1211. JingleSession.prototype.remoteStreamAdded = function (data) {
  1212. var self = this;
  1213. var thessrc;
  1214. var ssrc2jid = this.connection.emuc.ssrc2jid;
  1215. // look up an associated JID for a stream id
  1216. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  1217. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  1218. var ssrclines
  1219. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  1220. ssrclines = ssrclines.filter(function (line) {
  1221. // NOTE(gp) previously we filtered on the mslabel, but that property
  1222. // is not always present.
  1223. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  1224. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  1225. });
  1226. if (ssrclines.length) {
  1227. thessrc = ssrclines[0].substring(7).split(' ')[0];
  1228. // We signal our streams (through Jingle to the focus) before we set
  1229. // our presence (through which peers associate remote streams to
  1230. // jids). So, it might arrive that a remote stream is added but
  1231. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  1232. // successfully set. Here we wait for up to a second for the
  1233. // presence to arrive.
  1234. if (!ssrc2jid[thessrc]) {
  1235. // TODO(gp) limit wait duration to 1 sec.
  1236. setTimeout(function(d) {
  1237. return function() {
  1238. self.remoteStreamAdded(d);
  1239. }
  1240. }(data), 250);
  1241. return;
  1242. }
  1243. // ok to overwrite the one from focus? might save work in colibri.js
  1244. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  1245. if (ssrc2jid[thessrc]) {
  1246. data.peerjid = ssrc2jid[thessrc];
  1247. }
  1248. }
  1249. }
  1250. //TODO: this code should be removed when firefox implement multistream support
  1251. if(RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  1252. {
  1253. if((JingleSession.notReceivedSSRCs.length == 0) ||
  1254. !ssrc2jid[JingleSession.notReceivedSSRCs[JingleSession.notReceivedSSRCs.length - 1]])
  1255. {
  1256. // TODO(gp) limit wait duration to 1 sec.
  1257. setTimeout(function(d) {
  1258. return function() {
  1259. self.remoteStreamAdded(d);
  1260. }
  1261. }(data), 250);
  1262. return;
  1263. }
  1264. thessrc = JingleSession.notReceivedSSRCs.pop();
  1265. if (ssrc2jid[thessrc]) {
  1266. data.peerjid = ssrc2jid[thessrc];
  1267. }
  1268. }
  1269. RTC.createRemoteStream(data, this.sid, thessrc);
  1270. var isVideo = data.stream.getVideoTracks().length > 0;
  1271. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1272. if (isVideo &&
  1273. data.peerjid && this.peerjid === data.peerjid &&
  1274. data.stream.getVideoTracks().length === 0 &&
  1275. RTC.localVideo.getTracks().length > 0) {
  1276. window.setTimeout(function () {
  1277. sendKeyframe(self.peerconnection);
  1278. }, 3000);
  1279. }
  1280. }
  1281. module.exports = JingleSession;
  1282. },{"./SDP":2,"./SDPDiffer":3,"./SDPUtil":4,"./TraceablePeerConnection":5}],2:[function(require,module,exports){
  1283. /* jshint -W117 */
  1284. var SDPUtil = require("./SDPUtil");
  1285. // SDP STUFF
  1286. function SDP(sdp) {
  1287. this.media = sdp.split('\r\nm=');
  1288. for (var i = 1; i < this.media.length; i++) {
  1289. this.media[i] = 'm=' + this.media[i];
  1290. if (i != this.media.length - 1) {
  1291. this.media[i] += '\r\n';
  1292. }
  1293. }
  1294. this.session = this.media.shift() + '\r\n';
  1295. this.raw = this.session + this.media.join('');
  1296. }
  1297. /**
  1298. * Returns map of MediaChannel mapped per channel idx.
  1299. */
  1300. SDP.prototype.getMediaSsrcMap = function() {
  1301. var self = this;
  1302. var media_ssrcs = {};
  1303. var tmp;
  1304. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  1305. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  1306. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  1307. var media = {
  1308. mediaindex: mediaindex,
  1309. mid: mid,
  1310. ssrcs: {},
  1311. ssrcGroups: []
  1312. };
  1313. media_ssrcs[mediaindex] = media;
  1314. tmp.forEach(function (line) {
  1315. var linessrc = line.substring(7).split(' ')[0];
  1316. // allocate new ChannelSsrc
  1317. if(!media.ssrcs[linessrc]) {
  1318. media.ssrcs[linessrc] = {
  1319. ssrc: linessrc,
  1320. lines: []
  1321. };
  1322. }
  1323. media.ssrcs[linessrc].lines.push(line);
  1324. });
  1325. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  1326. tmp.forEach(function(line){
  1327. var semantics = line.substr(0, idx).substr(13);
  1328. var ssrcs = line.substr(14 + semantics.length).split(' ');
  1329. if (ssrcs.length != 0) {
  1330. media.ssrcGroups.push({
  1331. semantics: semantics,
  1332. ssrcs: ssrcs
  1333. });
  1334. }
  1335. });
  1336. }
  1337. return media_ssrcs;
  1338. };
  1339. /**
  1340. * Returns <tt>true</tt> if this SDP contains given SSRC.
  1341. * @param ssrc the ssrc to check.
  1342. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  1343. */
  1344. SDP.prototype.containsSSRC = function(ssrc) {
  1345. var medias = this.getMediaSsrcMap();
  1346. var contains = false;
  1347. Object.keys(medias).forEach(function(mediaindex){
  1348. var media = medias[mediaindex];
  1349. //console.log("Check", channel, ssrc);
  1350. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  1351. contains = true;
  1352. }
  1353. });
  1354. return contains;
  1355. };
  1356. // remove iSAC and CN from SDP
  1357. SDP.prototype.mangle = function () {
  1358. var i, j, mline, lines, rtpmap, newdesc;
  1359. for (i = 0; i < this.media.length; i++) {
  1360. lines = this.media[i].split('\r\n');
  1361. lines.pop(); // remove empty last element
  1362. mline = SDPUtil.parse_mline(lines.shift());
  1363. if (mline.media != 'audio')
  1364. continue;
  1365. newdesc = '';
  1366. mline.fmt.length = 0;
  1367. for (j = 0; j < lines.length; j++) {
  1368. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  1369. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  1370. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  1371. continue;
  1372. mline.fmt.push(rtpmap.id);
  1373. newdesc += lines[j] + '\r\n';
  1374. } else {
  1375. newdesc += lines[j] + '\r\n';
  1376. }
  1377. }
  1378. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  1379. this.media[i] += newdesc;
  1380. }
  1381. this.raw = this.session + this.media.join('');
  1382. };
  1383. // remove lines matching prefix from session section
  1384. SDP.prototype.removeSessionLines = function(prefix) {
  1385. var self = this;
  1386. var lines = SDPUtil.find_lines(this.session, prefix);
  1387. lines.forEach(function(line) {
  1388. self.session = self.session.replace(line + '\r\n', '');
  1389. });
  1390. this.raw = this.session + this.media.join('');
  1391. return lines;
  1392. }
  1393. // remove lines matching prefix from a media section specified by mediaindex
  1394. // TODO: non-numeric mediaindex could match mid
  1395. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  1396. var self = this;
  1397. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  1398. lines.forEach(function(line) {
  1399. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  1400. });
  1401. this.raw = this.session + this.media.join('');
  1402. return lines;
  1403. }
  1404. // add content's to a jingle element
  1405. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  1406. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  1407. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  1408. var self = this;
  1409. // new bundle plan
  1410. if (SDPUtil.find_line(this.session, 'a=group:')) {
  1411. lines = SDPUtil.find_lines(this.session, 'a=group:');
  1412. for (i = 0; i < lines.length; i++) {
  1413. tmp = lines[i].split(' ');
  1414. var semantics = tmp.shift().substr(8);
  1415. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  1416. for (j = 0; j < tmp.length; j++) {
  1417. elem.c('content', {name: tmp[j]}).up();
  1418. }
  1419. elem.up();
  1420. }
  1421. }
  1422. for (i = 0; i < this.media.length; i++) {
  1423. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  1424. if (!(mline.media === 'audio' ||
  1425. mline.media === 'video' ||
  1426. mline.media === 'application'))
  1427. {
  1428. continue;
  1429. }
  1430. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  1431. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  1432. } else {
  1433. if(ssrcs && ssrcs[mline.media])
  1434. {
  1435. ssrc = ssrcs[mline.media];
  1436. }
  1437. else
  1438. ssrc = false;
  1439. }
  1440. elem.c('content', {creator: thecreator, name: mline.media});
  1441. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  1442. // prefer identifier from a=mid if present
  1443. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  1444. elem.attrs({ name: mid });
  1445. }
  1446. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  1447. {
  1448. elem.c('description',
  1449. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  1450. media: mline.media });
  1451. if (ssrc) {
  1452. elem.attrs({ssrc: ssrc});
  1453. }
  1454. for (j = 0; j < mline.fmt.length; j++) {
  1455. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  1456. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  1457. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  1458. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  1459. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  1460. for (k = 0; k < tmp.length; k++) {
  1461. elem.c('parameter', tmp[k]).up();
  1462. }
  1463. }
  1464. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  1465. elem.up();
  1466. }
  1467. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  1468. elem.c('encryption', {required: 1});
  1469. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  1470. crypto.forEach(function(line) {
  1471. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  1472. });
  1473. elem.up(); // end of encryption
  1474. }
  1475. if (ssrc) {
  1476. // new style mapping
  1477. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  1478. // FIXME: group by ssrc and support multiple different ssrcs
  1479. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  1480. if(ssrclines.length > 0) {
  1481. ssrclines.forEach(function (line) {
  1482. idx = line.indexOf(' ');
  1483. var linessrc = line.substr(0, idx).substr(7);
  1484. if (linessrc != ssrc) {
  1485. elem.up();
  1486. ssrc = linessrc;
  1487. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  1488. }
  1489. var kv = line.substr(idx + 1);
  1490. elem.c('parameter');
  1491. if (kv.indexOf(':') == -1) {
  1492. elem.attrs({ name: kv });
  1493. } else {
  1494. elem.attrs({ name: kv.split(':', 2)[0] });
  1495. elem.attrs({ value: kv.split(':', 2)[1] });
  1496. }
  1497. elem.up();
  1498. });
  1499. elem.up();
  1500. }
  1501. else
  1502. {
  1503. elem.up();
  1504. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  1505. elem.c('parameter');
  1506. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  1507. elem.up();
  1508. var msid = null;
  1509. if(mline.media == "audio")
  1510. {
  1511. msid = RTC.localAudio.getId();
  1512. }
  1513. else
  1514. {
  1515. msid = RTC.localVideo.getId();
  1516. }
  1517. if(msid != null)
  1518. {
  1519. msid = msid.replace(/[\{,\}]/g,"");
  1520. elem.c('parameter');
  1521. elem.attrs({name: "msid", value:msid});
  1522. elem.up();
  1523. elem.c('parameter');
  1524. elem.attrs({name: "mslabel", value:msid});
  1525. elem.up();
  1526. elem.c('parameter');
  1527. elem.attrs({name: "label", value:msid});
  1528. elem.up();
  1529. elem.up();
  1530. }
  1531. }
  1532. // XEP-0339 handle ssrc-group attributes
  1533. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  1534. ssrc_group_lines.forEach(function(line) {
  1535. idx = line.indexOf(' ');
  1536. var semantics = line.substr(0, idx).substr(13);
  1537. var ssrcs = line.substr(14 + semantics.length).split(' ');
  1538. if (ssrcs.length != 0) {
  1539. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  1540. ssrcs.forEach(function(ssrc) {
  1541. elem.c('source', { ssrc: ssrc })
  1542. .up();
  1543. });
  1544. elem.up();
  1545. }
  1546. });
  1547. }
  1548. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  1549. elem.c('rtcp-mux').up();
  1550. }
  1551. // XEP-0293 -- map a=rtcp-fb:*
  1552. this.RtcpFbToJingle(i, elem, '*');
  1553. // XEP-0294
  1554. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  1555. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  1556. for (j = 0; j < lines.length; j++) {
  1557. tmp = SDPUtil.parse_extmap(lines[j]);
  1558. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  1559. uri: tmp.uri,
  1560. id: tmp.value });
  1561. if (tmp.hasOwnProperty('direction')) {
  1562. switch (tmp.direction) {
  1563. case 'sendonly':
  1564. elem.attrs({senders: 'responder'});
  1565. break;
  1566. case 'recvonly':
  1567. elem.attrs({senders: 'initiator'});
  1568. break;
  1569. case 'sendrecv':
  1570. elem.attrs({senders: 'both'});
  1571. break;
  1572. case 'inactive':
  1573. elem.attrs({senders: 'none'});
  1574. break;
  1575. }
  1576. }
  1577. // TODO: handle params
  1578. elem.up();
  1579. }
  1580. }
  1581. elem.up(); // end of description
  1582. }
  1583. // map ice-ufrag/pwd, dtls fingerprint, candidates
  1584. this.TransportToJingle(i, elem);
  1585. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  1586. elem.attrs({senders: 'both'});
  1587. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  1588. elem.attrs({senders: 'initiator'});
  1589. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  1590. elem.attrs({senders: 'responder'});
  1591. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  1592. elem.attrs({senders: 'none'});
  1593. }
  1594. if (mline.port == '0') {
  1595. // estos hack to reject an m-line
  1596. elem.attrs({senders: 'rejected'});
  1597. }
  1598. elem.up(); // end of content
  1599. }
  1600. elem.up();
  1601. return elem;
  1602. };
  1603. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  1604. var i = mediaindex;
  1605. var tmp;
  1606. var self = this;
  1607. elem.c('transport');
  1608. // XEP-0343 DTLS/SCTP
  1609. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  1610. {
  1611. var sctpmap = SDPUtil.find_line(
  1612. this.media[i], 'a=sctpmap:', self.session);
  1613. if (sctpmap)
  1614. {
  1615. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  1616. elem.c('sctpmap',
  1617. {
  1618. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  1619. number: sctpAttrs[0], /* SCTP port */
  1620. protocol: sctpAttrs[1], /* protocol */
  1621. });
  1622. // Optional stream count attribute
  1623. if (sctpAttrs.length > 2)
  1624. elem.attrs({ streams: sctpAttrs[2]});
  1625. elem.up();
  1626. }
  1627. }
  1628. // XEP-0320
  1629. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  1630. fingerprints.forEach(function(line) {
  1631. tmp = SDPUtil.parse_fingerprint(line);
  1632. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  1633. elem.c('fingerprint').t(tmp.fingerprint);
  1634. delete tmp.fingerprint;
  1635. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  1636. if (line) {
  1637. tmp.setup = line.substr(8);
  1638. }
  1639. elem.attrs(tmp);
  1640. elem.up(); // end of fingerprint
  1641. });
  1642. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  1643. if (tmp) {
  1644. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  1645. elem.attrs(tmp);
  1646. // XEP-0176
  1647. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  1648. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  1649. lines.forEach(function (line) {
  1650. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  1651. });
  1652. }
  1653. }
  1654. elem.up(); // end of transport
  1655. }
  1656. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  1657. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  1658. lines.forEach(function (line) {
  1659. var tmp = SDPUtil.parse_rtcpfb(line);
  1660. if (tmp.type == 'trr-int') {
  1661. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  1662. elem.up();
  1663. } else {
  1664. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  1665. if (tmp.params.length > 0) {
  1666. elem.attrs({'subtype': tmp.params[0]});
  1667. }
  1668. elem.up();
  1669. }
  1670. });
  1671. };
  1672. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  1673. var media = '';
  1674. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  1675. if (tmp.length) {
  1676. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  1677. if (tmp.attr('value')) {
  1678. media += tmp.attr('value');
  1679. } else {
  1680. media += '0';
  1681. }
  1682. media += '\r\n';
  1683. }
  1684. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  1685. tmp.each(function () {
  1686. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  1687. if ($(this).attr('subtype')) {
  1688. media += ' ' + $(this).attr('subtype');
  1689. }
  1690. media += '\r\n';
  1691. });
  1692. return media;
  1693. };
  1694. // construct an SDP from a jingle stanza
  1695. SDP.prototype.fromJingle = function (jingle) {
  1696. var self = this;
  1697. this.raw = 'v=0\r\n' +
  1698. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  1699. 's=-\r\n' +
  1700. 't=0 0\r\n';
  1701. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  1702. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  1703. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  1704. var contents = $(group).find('>content').map(function (idx, content) {
  1705. return content.getAttribute('name');
  1706. }).get();
  1707. if (contents.length > 0) {
  1708. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  1709. }
  1710. });
  1711. }
  1712. this.session = this.raw;
  1713. jingle.find('>content').each(function () {
  1714. var m = self.jingle2media($(this));
  1715. self.media.push(m);
  1716. });
  1717. // reconstruct msid-semantic -- apparently not necessary
  1718. /*
  1719. var msid = SDPUtil.parse_ssrc(this.raw);
  1720. if (msid.hasOwnProperty('mslabel')) {
  1721. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  1722. }
  1723. */
  1724. this.raw = this.session + this.media.join('');
  1725. };
  1726. // translate a jingle content element into an an SDP media part
  1727. SDP.prototype.jingle2media = function (content) {
  1728. var media = '',
  1729. desc = content.find('description'),
  1730. ssrc = desc.attr('ssrc'),
  1731. self = this,
  1732. tmp;
  1733. var sctp = content.find(
  1734. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  1735. tmp = { media: desc.attr('media') };
  1736. tmp.port = '1';
  1737. if (content.attr('senders') == 'rejected') {
  1738. // estos hack to reject an m-line.
  1739. tmp.port = '0';
  1740. }
  1741. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  1742. if (sctp.length)
  1743. tmp.proto = 'DTLS/SCTP';
  1744. else
  1745. tmp.proto = 'RTP/SAVPF';
  1746. } else {
  1747. tmp.proto = 'RTP/AVPF';
  1748. }
  1749. if (!sctp.length)
  1750. {
  1751. tmp.fmt = desc.find('payload-type').map(
  1752. function () { return this.getAttribute('id'); }).get();
  1753. media += SDPUtil.build_mline(tmp) + '\r\n';
  1754. }
  1755. else
  1756. {
  1757. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  1758. media += 'a=sctpmap:' + sctp.attr('number') +
  1759. ' ' + sctp.attr('protocol');
  1760. var streamCount = sctp.attr('streams');
  1761. if (streamCount)
  1762. media += ' ' + streamCount + '\r\n';
  1763. else
  1764. media += '\r\n';
  1765. }
  1766. media += 'c=IN IP4 0.0.0.0\r\n';
  1767. if (!sctp.length)
  1768. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  1769. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  1770. if (tmp.length) {
  1771. if (tmp.attr('ufrag')) {
  1772. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  1773. }
  1774. if (tmp.attr('pwd')) {
  1775. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  1776. }
  1777. tmp.find('>fingerprint').each(function () {
  1778. // FIXME: check namespace at some point
  1779. media += 'a=fingerprint:' + this.getAttribute('hash');
  1780. media += ' ' + $(this).text();
  1781. media += '\r\n';
  1782. if (this.getAttribute('setup')) {
  1783. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  1784. }
  1785. });
  1786. }
  1787. switch (content.attr('senders')) {
  1788. case 'initiator':
  1789. media += 'a=sendonly\r\n';
  1790. break;
  1791. case 'responder':
  1792. media += 'a=recvonly\r\n';
  1793. break;
  1794. case 'none':
  1795. media += 'a=inactive\r\n';
  1796. break;
  1797. case 'both':
  1798. media += 'a=sendrecv\r\n';
  1799. break;
  1800. }
  1801. media += 'a=mid:' + content.attr('name') + '\r\n';
  1802. // <description><rtcp-mux/></description>
  1803. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  1804. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  1805. if (desc.find('rtcp-mux').length) {
  1806. media += 'a=rtcp-mux\r\n';
  1807. }
  1808. if (desc.find('encryption').length) {
  1809. desc.find('encryption>crypto').each(function () {
  1810. media += 'a=crypto:' + this.getAttribute('tag');
  1811. media += ' ' + this.getAttribute('crypto-suite');
  1812. media += ' ' + this.getAttribute('key-params');
  1813. if (this.getAttribute('session-params')) {
  1814. media += ' ' + this.getAttribute('session-params');
  1815. }
  1816. media += '\r\n';
  1817. });
  1818. }
  1819. desc.find('payload-type').each(function () {
  1820. media += SDPUtil.build_rtpmap(this) + '\r\n';
  1821. if ($(this).find('>parameter').length) {
  1822. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  1823. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  1824. media += '\r\n';
  1825. }
  1826. // xep-0293
  1827. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  1828. });
  1829. // xep-0293
  1830. media += self.RtcpFbFromJingle(desc, '*');
  1831. // xep-0294
  1832. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  1833. tmp.each(function () {
  1834. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  1835. });
  1836. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  1837. media += SDPUtil.candidateFromJingle(this);
  1838. });
  1839. // XEP-0339 handle ssrc-group attributes
  1840. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  1841. var semantics = this.getAttribute('semantics');
  1842. var ssrcs = $(this).find('>source').map(function() {
  1843. return this.getAttribute('ssrc');
  1844. }).get();
  1845. if (ssrcs.length != 0) {
  1846. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  1847. }
  1848. });
  1849. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1850. tmp.each(function () {
  1851. var ssrc = this.getAttribute('ssrc');
  1852. $(this).find('>parameter').each(function () {
  1853. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  1854. if (this.getAttribute('value') && this.getAttribute('value').length)
  1855. media += ':' + this.getAttribute('value');
  1856. media += '\r\n';
  1857. });
  1858. });
  1859. return media;
  1860. };
  1861. module.exports = SDP;
  1862. },{"./SDPUtil":4}],3:[function(require,module,exports){
  1863. function SDPDiffer(mySDP, otherSDP) {
  1864. this.mySDP = mySDP;
  1865. this.otherSDP = otherSDP;
  1866. }
  1867. /**
  1868. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  1869. * @param otherSdp the other SDP to check ssrc with.
  1870. */
  1871. SDPDiffer.prototype.getNewMedia = function() {
  1872. // this could be useful in Array.prototype.
  1873. function arrayEquals(array) {
  1874. // if the other array is a falsy value, return
  1875. if (!array)
  1876. return false;
  1877. // compare lengths - can save a lot of time
  1878. if (this.length != array.length)
  1879. return false;
  1880. for (var i = 0, l=this.length; i < l; i++) {
  1881. // Check if we have nested arrays
  1882. if (this[i] instanceof Array && array[i] instanceof Array) {
  1883. // recurse into the nested arrays
  1884. if (!this[i].equals(array[i]))
  1885. return false;
  1886. }
  1887. else if (this[i] != array[i]) {
  1888. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  1889. return false;
  1890. }
  1891. }
  1892. return true;
  1893. }
  1894. var myMedias = this.mySDP.getMediaSsrcMap();
  1895. var othersMedias = this.otherSDP.getMediaSsrcMap();
  1896. var newMedia = {};
  1897. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  1898. var myMedia = myMedias[othersMediaIdx];
  1899. var othersMedia = othersMedias[othersMediaIdx];
  1900. if(!myMedia && othersMedia) {
  1901. // Add whole channel
  1902. newMedia[othersMediaIdx] = othersMedia;
  1903. return;
  1904. }
  1905. // Look for new ssrcs accross the channel
  1906. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  1907. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  1908. // Allocate channel if we've found ssrc that doesn't exist in our channel
  1909. if(!newMedia[othersMediaIdx]){
  1910. newMedia[othersMediaIdx] = {
  1911. mediaindex: othersMedia.mediaindex,
  1912. mid: othersMedia.mid,
  1913. ssrcs: {},
  1914. ssrcGroups: []
  1915. };
  1916. }
  1917. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  1918. }
  1919. });
  1920. // Look for new ssrc groups across the channels
  1921. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  1922. // try to match the other ssrc-group with an ssrc-group of ours
  1923. var matched = false;
  1924. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  1925. var mySsrcGroup = myMedia.ssrcGroups[i];
  1926. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  1927. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  1928. matched = true;
  1929. break;
  1930. }
  1931. }
  1932. if (!matched) {
  1933. // Allocate channel if we've found an ssrc-group that doesn't
  1934. // exist in our channel
  1935. if(!newMedia[othersMediaIdx]){
  1936. newMedia[othersMediaIdx] = {
  1937. mediaindex: othersMedia.mediaindex,
  1938. mid: othersMedia.mid,
  1939. ssrcs: {},
  1940. ssrcGroups: []
  1941. };
  1942. }
  1943. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  1944. }
  1945. });
  1946. });
  1947. return newMedia;
  1948. };
  1949. /**
  1950. * Sends SSRC update IQ.
  1951. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  1952. * @param sid session identifier that will be put into the IQ.
  1953. * @param initiator initiator identifier.
  1954. * @param toJid destination Jid
  1955. * @param isAdd indicates if this is remove or add operation.
  1956. */
  1957. SDPDiffer.prototype.toJingle = function(modify) {
  1958. var sdpMediaSsrcs = this.getNewMedia();
  1959. var self = this;
  1960. // FIXME: only announce video ssrcs since we mix audio and dont need
  1961. // the audio ssrcs therefore
  1962. var modified = false;
  1963. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  1964. modified = true;
  1965. var media = sdpMediaSsrcs[mediaindex];
  1966. modify.c('content', {name: media.mid});
  1967. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  1968. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  1969. // generate sources from lines
  1970. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  1971. var mediaSsrc = media.ssrcs[ssrcNum];
  1972. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  1973. modify.attrs({ssrc: mediaSsrc.ssrc});
  1974. // iterate over ssrc lines
  1975. mediaSsrc.lines.forEach(function (line) {
  1976. var idx = line.indexOf(' ');
  1977. var kv = line.substr(idx + 1);
  1978. modify.c('parameter');
  1979. if (kv.indexOf(':') == -1) {
  1980. modify.attrs({ name: kv });
  1981. } else {
  1982. modify.attrs({ name: kv.split(':', 2)[0] });
  1983. modify.attrs({ value: kv.split(':', 2)[1] });
  1984. }
  1985. modify.up(); // end of parameter
  1986. });
  1987. modify.up(); // end of source
  1988. });
  1989. // generate source groups from lines
  1990. media.ssrcGroups.forEach(function(ssrcGroup) {
  1991. if (ssrcGroup.ssrcs.length != 0) {
  1992. modify.c('ssrc-group', {
  1993. semantics: ssrcGroup.semantics,
  1994. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  1995. });
  1996. ssrcGroup.ssrcs.forEach(function (ssrc) {
  1997. modify.c('source', { ssrc: ssrc })
  1998. .up(); // end of source
  1999. });
  2000. modify.up(); // end of ssrc-group
  2001. }
  2002. });
  2003. modify.up(); // end of description
  2004. modify.up(); // end of content
  2005. });
  2006. return modified;
  2007. };
  2008. module.exports = SDPDiffer;
  2009. },{}],4:[function(require,module,exports){
  2010. SDPUtil = {
  2011. iceparams: function (mediadesc, sessiondesc) {
  2012. var data = null;
  2013. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  2014. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  2015. data = {
  2016. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  2017. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  2018. };
  2019. }
  2020. return data;
  2021. },
  2022. parse_iceufrag: function (line) {
  2023. return line.substring(12);
  2024. },
  2025. build_iceufrag: function (frag) {
  2026. return 'a=ice-ufrag:' + frag;
  2027. },
  2028. parse_icepwd: function (line) {
  2029. return line.substring(10);
  2030. },
  2031. build_icepwd: function (pwd) {
  2032. return 'a=ice-pwd:' + pwd;
  2033. },
  2034. parse_mid: function (line) {
  2035. return line.substring(6);
  2036. },
  2037. parse_mline: function (line) {
  2038. var parts = line.substring(2).split(' '),
  2039. data = {};
  2040. data.media = parts.shift();
  2041. data.port = parts.shift();
  2042. data.proto = parts.shift();
  2043. if (parts[parts.length - 1] === '') { // trailing whitespace
  2044. parts.pop();
  2045. }
  2046. data.fmt = parts;
  2047. return data;
  2048. },
  2049. build_mline: function (mline) {
  2050. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  2051. },
  2052. parse_rtpmap: function (line) {
  2053. var parts = line.substring(9).split(' '),
  2054. data = {};
  2055. data.id = parts.shift();
  2056. parts = parts[0].split('/');
  2057. data.name = parts.shift();
  2058. data.clockrate = parts.shift();
  2059. data.channels = parts.length ? parts.shift() : '1';
  2060. return data;
  2061. },
  2062. /**
  2063. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  2064. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  2065. * @returns [SCTP port number, protocol, streams]
  2066. */
  2067. parse_sctpmap: function (line)
  2068. {
  2069. var parts = line.substring(10).split(' ');
  2070. var sctpPort = parts[0];
  2071. var protocol = parts[1];
  2072. // Stream count is optional
  2073. var streamCount = parts.length > 2 ? parts[2] : null;
  2074. return [sctpPort, protocol, streamCount];// SCTP port
  2075. },
  2076. build_rtpmap: function (el) {
  2077. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  2078. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  2079. line += '/' + el.getAttribute('channels');
  2080. }
  2081. return line;
  2082. },
  2083. parse_crypto: function (line) {
  2084. var parts = line.substring(9).split(' '),
  2085. data = {};
  2086. data.tag = parts.shift();
  2087. data['crypto-suite'] = parts.shift();
  2088. data['key-params'] = parts.shift();
  2089. if (parts.length) {
  2090. data['session-params'] = parts.join(' ');
  2091. }
  2092. return data;
  2093. },
  2094. parse_fingerprint: function (line) { // RFC 4572
  2095. var parts = line.substring(14).split(' '),
  2096. data = {};
  2097. data.hash = parts.shift();
  2098. data.fingerprint = parts.shift();
  2099. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  2100. return data;
  2101. },
  2102. parse_fmtp: function (line) {
  2103. var parts = line.split(' '),
  2104. i, key, value,
  2105. data = [];
  2106. parts.shift();
  2107. parts = parts.join(' ').split(';');
  2108. for (i = 0; i < parts.length; i++) {
  2109. key = parts[i].split('=')[0];
  2110. while (key.length && key[0] == ' ') {
  2111. key = key.substring(1);
  2112. }
  2113. value = parts[i].split('=')[1];
  2114. if (key && value) {
  2115. data.push({name: key, value: value});
  2116. } else if (key) {
  2117. // rfc 4733 (DTMF) style stuff
  2118. data.push({name: '', value: key});
  2119. }
  2120. }
  2121. return data;
  2122. },
  2123. parse_icecandidate: function (line) {
  2124. var candidate = {},
  2125. elems = line.split(' ');
  2126. candidate.foundation = elems[0].substring(12);
  2127. candidate.component = elems[1];
  2128. candidate.protocol = elems[2].toLowerCase();
  2129. candidate.priority = elems[3];
  2130. candidate.ip = elems[4];
  2131. candidate.port = elems[5];
  2132. // elems[6] => "typ"
  2133. candidate.type = elems[7];
  2134. candidate.generation = 0; // default value, may be overwritten below
  2135. for (var i = 8; i < elems.length; i += 2) {
  2136. switch (elems[i]) {
  2137. case 'raddr':
  2138. candidate['rel-addr'] = elems[i + 1];
  2139. break;
  2140. case 'rport':
  2141. candidate['rel-port'] = elems[i + 1];
  2142. break;
  2143. case 'generation':
  2144. candidate.generation = elems[i + 1];
  2145. break;
  2146. case 'tcptype':
  2147. candidate.tcptype = elems[i + 1];
  2148. break;
  2149. default: // TODO
  2150. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  2151. }
  2152. }
  2153. candidate.network = '1';
  2154. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  2155. return candidate;
  2156. },
  2157. build_icecandidate: function (cand) {
  2158. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  2159. line += ' ';
  2160. switch (cand.type) {
  2161. case 'srflx':
  2162. case 'prflx':
  2163. case 'relay':
  2164. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  2165. line += 'raddr';
  2166. line += ' ';
  2167. line += cand['rel-addr'];
  2168. line += ' ';
  2169. line += 'rport';
  2170. line += ' ';
  2171. line += cand['rel-port'];
  2172. line += ' ';
  2173. }
  2174. break;
  2175. }
  2176. if (cand.hasOwnAttribute('tcptype')) {
  2177. line += 'tcptype';
  2178. line += ' ';
  2179. line += cand.tcptype;
  2180. line += ' ';
  2181. }
  2182. line += 'generation';
  2183. line += ' ';
  2184. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  2185. return line;
  2186. },
  2187. parse_ssrc: function (desc) {
  2188. // proprietary mapping of a=ssrc lines
  2189. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  2190. // and parse according to that
  2191. var lines = desc.split('\r\n'),
  2192. data = {};
  2193. for (var i = 0; i < lines.length; i++) {
  2194. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  2195. var idx = lines[i].indexOf(' ');
  2196. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  2197. }
  2198. }
  2199. return data;
  2200. },
  2201. parse_rtcpfb: function (line) {
  2202. var parts = line.substr(10).split(' ');
  2203. var data = {};
  2204. data.pt = parts.shift();
  2205. data.type = parts.shift();
  2206. data.params = parts;
  2207. return data;
  2208. },
  2209. parse_extmap: function (line) {
  2210. var parts = line.substr(9).split(' ');
  2211. var data = {};
  2212. data.value = parts.shift();
  2213. if (data.value.indexOf('/') != -1) {
  2214. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  2215. data.value = data.value.substr(0, data.value.indexOf('/'));
  2216. } else {
  2217. data.direction = 'both';
  2218. }
  2219. data.uri = parts.shift();
  2220. data.params = parts;
  2221. return data;
  2222. },
  2223. find_line: function (haystack, needle, sessionpart) {
  2224. var lines = haystack.split('\r\n');
  2225. for (var i = 0; i < lines.length; i++) {
  2226. if (lines[i].substring(0, needle.length) == needle) {
  2227. return lines[i];
  2228. }
  2229. }
  2230. if (!sessionpart) {
  2231. return false;
  2232. }
  2233. // search session part
  2234. lines = sessionpart.split('\r\n');
  2235. for (var j = 0; j < lines.length; j++) {
  2236. if (lines[j].substring(0, needle.length) == needle) {
  2237. return lines[j];
  2238. }
  2239. }
  2240. return false;
  2241. },
  2242. find_lines: function (haystack, needle, sessionpart) {
  2243. var lines = haystack.split('\r\n'),
  2244. needles = [];
  2245. for (var i = 0; i < lines.length; i++) {
  2246. if (lines[i].substring(0, needle.length) == needle)
  2247. needles.push(lines[i]);
  2248. }
  2249. if (needles.length || !sessionpart) {
  2250. return needles;
  2251. }
  2252. // search session part
  2253. lines = sessionpart.split('\r\n');
  2254. for (var j = 0; j < lines.length; j++) {
  2255. if (lines[j].substring(0, needle.length) == needle) {
  2256. needles.push(lines[j]);
  2257. }
  2258. }
  2259. return needles;
  2260. },
  2261. candidateToJingle: function (line) {
  2262. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  2263. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  2264. if (line.indexOf('candidate:') === 0) {
  2265. line = 'a=' + line;
  2266. } else if (line.substring(0, 12) != 'a=candidate:') {
  2267. console.log('parseCandidate called with a line that is not a candidate line');
  2268. console.log(line);
  2269. return null;
  2270. }
  2271. if (line.substring(line.length - 2) == '\r\n') // chomp it
  2272. line = line.substring(0, line.length - 2);
  2273. var candidate = {},
  2274. elems = line.split(' '),
  2275. i;
  2276. if (elems[6] != 'typ') {
  2277. console.log('did not find typ in the right place');
  2278. console.log(line);
  2279. return null;
  2280. }
  2281. candidate.foundation = elems[0].substring(12);
  2282. candidate.component = elems[1];
  2283. candidate.protocol = elems[2].toLowerCase();
  2284. candidate.priority = elems[3];
  2285. candidate.ip = elems[4];
  2286. candidate.port = elems[5];
  2287. // elems[6] => "typ"
  2288. candidate.type = elems[7];
  2289. candidate.generation = '0'; // default, may be overwritten below
  2290. for (i = 8; i < elems.length; i += 2) {
  2291. switch (elems[i]) {
  2292. case 'raddr':
  2293. candidate['rel-addr'] = elems[i + 1];
  2294. break;
  2295. case 'rport':
  2296. candidate['rel-port'] = elems[i + 1];
  2297. break;
  2298. case 'generation':
  2299. candidate.generation = elems[i + 1];
  2300. break;
  2301. case 'tcptype':
  2302. candidate.tcptype = elems[i + 1];
  2303. break;
  2304. default: // TODO
  2305. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  2306. }
  2307. }
  2308. candidate.network = '1';
  2309. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  2310. return candidate;
  2311. },
  2312. candidateFromJingle: function (cand) {
  2313. var line = 'a=candidate:';
  2314. line += cand.getAttribute('foundation');
  2315. line += ' ';
  2316. line += cand.getAttribute('component');
  2317. line += ' ';
  2318. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  2319. line += ' ';
  2320. line += cand.getAttribute('priority');
  2321. line += ' ';
  2322. line += cand.getAttribute('ip');
  2323. line += ' ';
  2324. line += cand.getAttribute('port');
  2325. line += ' ';
  2326. line += 'typ';
  2327. line += ' ' + cand.getAttribute('type');
  2328. line += ' ';
  2329. switch (cand.getAttribute('type')) {
  2330. case 'srflx':
  2331. case 'prflx':
  2332. case 'relay':
  2333. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  2334. line += 'raddr';
  2335. line += ' ';
  2336. line += cand.getAttribute('rel-addr');
  2337. line += ' ';
  2338. line += 'rport';
  2339. line += ' ';
  2340. line += cand.getAttribute('rel-port');
  2341. line += ' ';
  2342. }
  2343. break;
  2344. }
  2345. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  2346. line += 'tcptype';
  2347. line += ' ';
  2348. line += cand.getAttribute('tcptype');
  2349. line += ' ';
  2350. }
  2351. line += 'generation';
  2352. line += ' ';
  2353. line += cand.getAttribute('generation') || '0';
  2354. return line + '\r\n';
  2355. }
  2356. };
  2357. module.exports = SDPUtil;
  2358. },{}],5:[function(require,module,exports){
  2359. function TraceablePeerConnection(ice_config, constraints) {
  2360. var self = this;
  2361. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  2362. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  2363. this.updateLog = [];
  2364. this.stats = {};
  2365. this.statsinterval = null;
  2366. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  2367. // override as desired
  2368. this.trace = function (what, info) {
  2369. //console.warn('WTRACE', what, info);
  2370. self.updateLog.push({
  2371. time: new Date(),
  2372. type: what,
  2373. value: info || ""
  2374. });
  2375. };
  2376. this.onicecandidate = null;
  2377. this.peerconnection.onicecandidate = function (event) {
  2378. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  2379. if (self.onicecandidate !== null) {
  2380. self.onicecandidate(event);
  2381. }
  2382. };
  2383. this.onaddstream = null;
  2384. this.peerconnection.onaddstream = function (event) {
  2385. self.trace('onaddstream', event.stream.id);
  2386. if (self.onaddstream !== null) {
  2387. self.onaddstream(event);
  2388. }
  2389. };
  2390. this.onremovestream = null;
  2391. this.peerconnection.onremovestream = function (event) {
  2392. self.trace('onremovestream', event.stream.id);
  2393. if (self.onremovestream !== null) {
  2394. self.onremovestream(event);
  2395. }
  2396. };
  2397. this.onsignalingstatechange = null;
  2398. this.peerconnection.onsignalingstatechange = function (event) {
  2399. self.trace('onsignalingstatechange', self.signalingState);
  2400. if (self.onsignalingstatechange !== null) {
  2401. self.onsignalingstatechange(event);
  2402. }
  2403. };
  2404. this.oniceconnectionstatechange = null;
  2405. this.peerconnection.oniceconnectionstatechange = function (event) {
  2406. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  2407. if (self.oniceconnectionstatechange !== null) {
  2408. self.oniceconnectionstatechange(event);
  2409. }
  2410. };
  2411. this.onnegotiationneeded = null;
  2412. this.peerconnection.onnegotiationneeded = function (event) {
  2413. self.trace('onnegotiationneeded');
  2414. if (self.onnegotiationneeded !== null) {
  2415. self.onnegotiationneeded(event);
  2416. }
  2417. };
  2418. self.ondatachannel = null;
  2419. this.peerconnection.ondatachannel = function (event) {
  2420. self.trace('ondatachannel', event);
  2421. if (self.ondatachannel !== null) {
  2422. self.ondatachannel(event);
  2423. }
  2424. };
  2425. if (!navigator.mozGetUserMedia && this.maxstats) {
  2426. this.statsinterval = window.setInterval(function() {
  2427. self.peerconnection.getStats(function(stats) {
  2428. var results = stats.result();
  2429. for (var i = 0; i < results.length; ++i) {
  2430. //console.log(results[i].type, results[i].id, results[i].names())
  2431. var now = new Date();
  2432. results[i].names().forEach(function (name) {
  2433. var id = results[i].id + '-' + name;
  2434. if (!self.stats[id]) {
  2435. self.stats[id] = {
  2436. startTime: now,
  2437. endTime: now,
  2438. values: [],
  2439. times: []
  2440. };
  2441. }
  2442. self.stats[id].values.push(results[i].stat(name));
  2443. self.stats[id].times.push(now.getTime());
  2444. if (self.stats[id].values.length > self.maxstats) {
  2445. self.stats[id].values.shift();
  2446. self.stats[id].times.shift();
  2447. }
  2448. self.stats[id].endTime = now;
  2449. });
  2450. }
  2451. });
  2452. }, 1000);
  2453. }
  2454. };
  2455. dumpSDP = function(description) {
  2456. return 'type: ' + description.type + '\r\n' + description.sdp;
  2457. }
  2458. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  2459. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  2460. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  2461. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  2462. var publicLocalDescription = simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  2463. return publicLocalDescription;
  2464. });
  2465. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  2466. var publicRemoteDescription = simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  2467. return publicRemoteDescription;
  2468. });
  2469. }
  2470. TraceablePeerConnection.prototype.addStream = function (stream) {
  2471. this.trace('addStream', stream.id);
  2472. simulcast.resetSender();
  2473. try
  2474. {
  2475. this.peerconnection.addStream(stream);
  2476. }
  2477. catch (e)
  2478. {
  2479. console.error(e);
  2480. return;
  2481. }
  2482. };
  2483. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  2484. this.trace('removeStream', stream.id);
  2485. simulcast.resetSender();
  2486. if(stopStreams) {
  2487. stream.getAudioTracks().forEach(function (track) {
  2488. track.stop();
  2489. });
  2490. stream.getVideoTracks().forEach(function (track) {
  2491. track.stop();
  2492. });
  2493. }
  2494. this.peerconnection.removeStream(stream);
  2495. };
  2496. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  2497. this.trace('createDataChannel', label, opts);
  2498. return this.peerconnection.createDataChannel(label, opts);
  2499. };
  2500. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  2501. var self = this;
  2502. description = simulcast.transformLocalDescription(description);
  2503. this.trace('setLocalDescription', dumpSDP(description));
  2504. this.peerconnection.setLocalDescription(description,
  2505. function () {
  2506. self.trace('setLocalDescriptionOnSuccess');
  2507. successCallback();
  2508. },
  2509. function (err) {
  2510. self.trace('setLocalDescriptionOnFailure', err);
  2511. failureCallback(err);
  2512. }
  2513. );
  2514. /*
  2515. if (this.statsinterval === null && this.maxstats > 0) {
  2516. // start gathering stats
  2517. }
  2518. */
  2519. };
  2520. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  2521. var self = this;
  2522. description = simulcast.transformRemoteDescription(description);
  2523. this.trace('setRemoteDescription', dumpSDP(description));
  2524. this.peerconnection.setRemoteDescription(description,
  2525. function () {
  2526. self.trace('setRemoteDescriptionOnSuccess');
  2527. successCallback();
  2528. },
  2529. function (err) {
  2530. self.trace('setRemoteDescriptionOnFailure', err);
  2531. failureCallback(err);
  2532. }
  2533. );
  2534. /*
  2535. if (this.statsinterval === null && this.maxstats > 0) {
  2536. // start gathering stats
  2537. }
  2538. */
  2539. };
  2540. TraceablePeerConnection.prototype.close = function () {
  2541. this.trace('stop');
  2542. if (this.statsinterval !== null) {
  2543. window.clearInterval(this.statsinterval);
  2544. this.statsinterval = null;
  2545. }
  2546. this.peerconnection.close();
  2547. };
  2548. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  2549. var self = this;
  2550. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  2551. this.peerconnection.createOffer(
  2552. function (offer) {
  2553. self.trace('createOfferOnSuccess', dumpSDP(offer));
  2554. successCallback(offer);
  2555. },
  2556. function(err) {
  2557. self.trace('createOfferOnFailure', err);
  2558. failureCallback(err);
  2559. },
  2560. constraints
  2561. );
  2562. };
  2563. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  2564. var self = this;
  2565. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  2566. this.peerconnection.createAnswer(
  2567. function (answer) {
  2568. answer = simulcast.transformAnswer(answer);
  2569. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  2570. successCallback(answer);
  2571. },
  2572. function(err) {
  2573. self.trace('createAnswerOnFailure', err);
  2574. failureCallback(err);
  2575. },
  2576. constraints
  2577. );
  2578. };
  2579. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  2580. var self = this;
  2581. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  2582. this.peerconnection.addIceCandidate(candidate);
  2583. /* maybe later
  2584. this.peerconnection.addIceCandidate(candidate,
  2585. function () {
  2586. self.trace('addIceCandidateOnSuccess');
  2587. successCallback();
  2588. },
  2589. function (err) {
  2590. self.trace('addIceCandidateOnFailure', err);
  2591. failureCallback(err);
  2592. }
  2593. );
  2594. */
  2595. };
  2596. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  2597. if (navigator.mozGetUserMedia) {
  2598. // ignore for now...
  2599. if(!errback)
  2600. errback = function () {
  2601. }
  2602. this.peerconnection.getStats(null,callback,errback);
  2603. } else {
  2604. this.peerconnection.getStats(callback);
  2605. }
  2606. };
  2607. module.exports = TraceablePeerConnection;
  2608. },{}],6:[function(require,module,exports){
  2609. /* global $, $iq, config, connection, UI, messageHandler,
  2610. roomName, sessionTerminated, Strophe, Util */
  2611. /**
  2612. * Contains logic responsible for enabling/disabling functionality available
  2613. * only to moderator users.
  2614. */
  2615. var connection = null;
  2616. var focusUserJid;
  2617. var getNextTimeout = Util.createExpBackoffTimer(1000);
  2618. var getNextErrorTimeout = Util.createExpBackoffTimer(1000);
  2619. // External authentication stuff
  2620. var externalAuthEnabled = false;
  2621. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  2622. // it will be enabled automatically if focus detects the component through
  2623. // service discovery.
  2624. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  2625. var Moderator = {
  2626. isModerator: function () {
  2627. return connection && connection.emuc.isModerator();
  2628. },
  2629. isPeerModerator: function (peerJid) {
  2630. return connection &&
  2631. connection.emuc.getMemberRole(peerJid) === 'moderator';
  2632. },
  2633. isExternalAuthEnabled: function () {
  2634. return externalAuthEnabled;
  2635. },
  2636. isSipGatewayEnabled: function () {
  2637. return sipGatewayEnabled;
  2638. },
  2639. setConnection: function (con) {
  2640. connection = con;
  2641. },
  2642. init: function (xmpp) {
  2643. this.xmppService = xmpp;
  2644. this.onLocalRoleChange = function (from, member, pres) {
  2645. UI.onModeratorStatusChanged(Moderator.isModerator());
  2646. };
  2647. },
  2648. onMucLeft: function (jid) {
  2649. console.info("Someone left is it focus ? " + jid);
  2650. var resource = Strophe.getResourceFromJid(jid);
  2651. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  2652. console.info(
  2653. "Focus has left the room - leaving conference");
  2654. //hangUp();
  2655. // We'd rather reload to have everything re-initialized
  2656. // FIXME: show some message before reload
  2657. location.reload();
  2658. }
  2659. },
  2660. setFocusUserJid: function (focusJid) {
  2661. if (!focusUserJid) {
  2662. focusUserJid = focusJid;
  2663. console.info("Focus jid set to: " + focusUserJid);
  2664. }
  2665. },
  2666. getFocusUserJid: function () {
  2667. return focusUserJid;
  2668. },
  2669. getFocusComponent: function () {
  2670. // Get focus component address
  2671. var focusComponent = config.hosts.focus;
  2672. // If not specified use default: 'focus.domain'
  2673. if (!focusComponent) {
  2674. focusComponent = 'focus.' + config.hosts.domain;
  2675. }
  2676. return focusComponent;
  2677. },
  2678. createConferenceIq: function (roomName) {
  2679. // Generate create conference IQ
  2680. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  2681. elem.c('conference', {
  2682. xmlns: 'http://jitsi.org/protocol/focus',
  2683. room: roomName
  2684. });
  2685. if (config.hosts.bridge !== undefined) {
  2686. elem.c(
  2687. 'property',
  2688. { name: 'bridge', value: config.hosts.bridge})
  2689. .up();
  2690. }
  2691. // Tell the focus we have Jigasi configured
  2692. if (config.hosts.call_control !== undefined) {
  2693. elem.c(
  2694. 'property',
  2695. { name: 'call_control', value: config.hosts.call_control})
  2696. .up();
  2697. }
  2698. if (config.channelLastN !== undefined) {
  2699. elem.c(
  2700. 'property',
  2701. { name: 'channelLastN', value: config.channelLastN})
  2702. .up();
  2703. }
  2704. if (config.adaptiveLastN !== undefined) {
  2705. elem.c(
  2706. 'property',
  2707. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  2708. .up();
  2709. }
  2710. if (config.adaptiveSimulcast !== undefined) {
  2711. elem.c(
  2712. 'property',
  2713. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  2714. .up();
  2715. }
  2716. if (config.openSctp !== undefined) {
  2717. elem.c(
  2718. 'property',
  2719. { name: 'openSctp', value: config.openSctp})
  2720. .up();
  2721. }
  2722. if (config.enableFirefoxSupport !== undefined) {
  2723. elem.c(
  2724. 'property',
  2725. { name: 'enableFirefoxHacks',
  2726. value: config.enableFirefoxSupport})
  2727. .up();
  2728. }
  2729. elem.up();
  2730. return elem;
  2731. },
  2732. parseConfigOptions: function (resultIq) {
  2733. Moderator.setFocusUserJid(
  2734. $(resultIq).find('conference').attr('focusjid'));
  2735. var extAuthParam
  2736. = $(resultIq).find('>conference>property[name=\'externalAuth\']');
  2737. if (extAuthParam.length) {
  2738. externalAuthEnabled = extAuthParam.attr('value') === 'true';
  2739. }
  2740. console.info("External authentication enabled: " + externalAuthEnabled);
  2741. // Check if focus has auto-detected Jigasi component(this will be also
  2742. // included if we have passed our host from the config)
  2743. if ($(resultIq).find(
  2744. '>conference>property[name=\'sipGatewayEnabled\']').length) {
  2745. sipGatewayEnabled = true;
  2746. }
  2747. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  2748. },
  2749. // FIXME: we need to show the fact that we're waiting for the focus
  2750. // to the user(or that focus is not available)
  2751. allocateConferenceFocus: function (roomName, callback) {
  2752. // Try to use focus user JID from the config
  2753. Moderator.setFocusUserJid(config.focusUserJid);
  2754. // Send create conference IQ
  2755. var iq = Moderator.createConferenceIq(roomName);
  2756. var self = this;
  2757. connection.sendIQ(
  2758. iq,
  2759. function (result) {
  2760. if ('true' === $(result).find('conference').attr('ready')) {
  2761. // Reset both timers
  2762. getNextTimeout(true);
  2763. getNextErrorTimeout(true);
  2764. // Setup config options
  2765. Moderator.parseConfigOptions(result);
  2766. // Exec callback
  2767. callback();
  2768. } else {
  2769. var waitMs = getNextTimeout();
  2770. console.info("Waiting for the focus... " + waitMs);
  2771. // Reset error timeout
  2772. getNextErrorTimeout(true);
  2773. window.setTimeout(
  2774. function () {
  2775. Moderator.allocateConferenceFocus(
  2776. roomName, callback);
  2777. }, waitMs);
  2778. }
  2779. },
  2780. function (error) {
  2781. // Not authorized to create new room
  2782. if ($(error).find('>error>not-authorized').length) {
  2783. console.warn("Unauthorized to start the conference");
  2784. var toDomain
  2785. = Strophe.getDomainFromJid(error.getAttribute('to'));
  2786. if (toDomain === config.hosts.anonymousdomain) {
  2787. // we are connected with anonymous domain and
  2788. // only non anonymous users can create rooms
  2789. // we must authorize the user
  2790. self.xmppService.promptLogin();
  2791. } else {
  2792. // External authentication mode
  2793. UI.onAuthenticationRequired(function () {
  2794. Moderator.allocateConferenceFocus(
  2795. roomName, callback);
  2796. });
  2797. }
  2798. return;
  2799. }
  2800. var waitMs = getNextErrorTimeout();
  2801. console.error("Focus error, retry after " + waitMs, error);
  2802. // Show message
  2803. UI.messageHandler.notify(
  2804. 'Conference focus', 'disconnected',
  2805. Moderator.getFocusComponent() +
  2806. ' not available - retry in ' +
  2807. (waitMs / 1000) + ' sec');
  2808. // Reset response timeout
  2809. getNextTimeout(true);
  2810. window.setTimeout(
  2811. function () {
  2812. Moderator.allocateConferenceFocus(roomName, callback);
  2813. }, waitMs);
  2814. }
  2815. );
  2816. },
  2817. getAuthUrl: function (roomName, urlCallback) {
  2818. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  2819. iq.c('auth-url', {
  2820. xmlns: 'http://jitsi.org/protocol/focus',
  2821. room: roomName
  2822. });
  2823. connection.sendIQ(
  2824. iq,
  2825. function (result) {
  2826. var url = $(result).find('auth-url').attr('url');
  2827. if (url) {
  2828. console.info("Got auth url: " + url);
  2829. urlCallback(url);
  2830. } else {
  2831. console.error(
  2832. "Failed to get auth url fro mthe focus", result);
  2833. }
  2834. },
  2835. function (error) {
  2836. console.error("Get auth url error", error);
  2837. }
  2838. );
  2839. }
  2840. };
  2841. module.exports = Moderator;
  2842. },{}],7:[function(require,module,exports){
  2843. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  2844. Toolbar, Util */
  2845. var Moderator = require("./moderator");
  2846. var recordingToken = null;
  2847. var recordingEnabled;
  2848. /**
  2849. * Whether to use a jirecon component for recording, or use the videobridge
  2850. * through COLIBRI.
  2851. */
  2852. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  2853. /**
  2854. * The ID of the jirecon recording session. Jirecon generates it when we
  2855. * initially start recording, and it needs to be used in subsequent requests
  2856. * to jirecon.
  2857. */
  2858. var jireconRid = null;
  2859. function setRecordingToken(token) {
  2860. recordingToken = token;
  2861. }
  2862. function setRecording(state, token, callback, connection) {
  2863. if (useJirecon){
  2864. setRecordingJirecon(state, token, callback, connection);
  2865. } else {
  2866. setRecordingColibri(state, token, callback, connection);
  2867. }
  2868. }
  2869. function setRecordingJirecon(state, token, callback, connection) {
  2870. if (state == recordingEnabled){
  2871. return;
  2872. }
  2873. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  2874. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  2875. action: state ? 'start' : 'stop',
  2876. mucjid: connection.emuc.roomjid});
  2877. if (!state){
  2878. iq.attrs({rid: jireconRid});
  2879. }
  2880. console.log('Start recording');
  2881. connection.sendIQ(
  2882. iq,
  2883. function (result) {
  2884. // TODO wait for an IQ with the real status, since this is
  2885. // provisional?
  2886. jireconRid = $(result).find('recording').attr('rid');
  2887. console.log('Recording ' + (state ? 'started' : 'stopped') +
  2888. '(jirecon)' + result);
  2889. recordingEnabled = state;
  2890. if (!state){
  2891. jireconRid = null;
  2892. }
  2893. callback(state);
  2894. },
  2895. function (error) {
  2896. console.log('Failed to start recording, error: ', error);
  2897. callback(recordingEnabled);
  2898. });
  2899. }
  2900. // Sends a COLIBRI message which enables or disables (according to 'state')
  2901. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  2902. // with the new recording state, according to the IQ.
  2903. function setRecordingColibri(state, token, callback, connection) {
  2904. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  2905. elem.c('conference', {
  2906. xmlns: 'http://jitsi.org/protocol/colibri'
  2907. });
  2908. elem.c('recording', {state: state, token: token});
  2909. connection.sendIQ(elem,
  2910. function (result) {
  2911. console.log('Set recording "', state, '". Result:', result);
  2912. var recordingElem = $(result).find('>conference>recording');
  2913. var newState = ('true' === recordingElem.attr('state'));
  2914. recordingEnabled = newState;
  2915. callback(newState);
  2916. },
  2917. function (error) {
  2918. console.warn(error);
  2919. callback(recordingEnabled);
  2920. }
  2921. );
  2922. }
  2923. var Recording = {
  2924. toggleRecording: function (tokenEmptyCallback,
  2925. startingCallback, startedCallback, connection) {
  2926. if (!Moderator.isModerator()) {
  2927. console.log(
  2928. 'non-focus, or conference not yet organized:' +
  2929. ' not enabling recording');
  2930. return;
  2931. }
  2932. // Jirecon does not (currently) support a token.
  2933. if (!recordingToken && !useJirecon) {
  2934. tokenEmptyCallback(function (value) {
  2935. setRecordingToken(value);
  2936. this.toggleRecording();
  2937. });
  2938. return;
  2939. }
  2940. var oldState = recordingEnabled;
  2941. startingCallback(!oldState);
  2942. setRecording(!oldState,
  2943. recordingToken,
  2944. function (state) {
  2945. console.log("New recording state: ", state);
  2946. if (state === oldState) {
  2947. // FIXME: new focus:
  2948. // this will not work when moderator changes
  2949. // during active session. Then it will assume that
  2950. // recording status has changed to true, but it might have
  2951. // been already true(and we only received actual status from
  2952. // the focus).
  2953. //
  2954. // SO we start with status null, so that it is initialized
  2955. // here and will fail only after second click, so if invalid
  2956. // token was used we have to press the button twice before
  2957. // current status will be fetched and token will be reset.
  2958. //
  2959. // Reliable way would be to return authentication error.
  2960. // Or status update when moderator connects.
  2961. // Or we have to stop recording session when current
  2962. // moderator leaves the room.
  2963. // Failed to change, reset the token because it might
  2964. // have been wrong
  2965. setRecordingToken(null);
  2966. }
  2967. startedCallback(state);
  2968. },
  2969. connection
  2970. );
  2971. }
  2972. }
  2973. module.exports = Recording;
  2974. },{"./moderator":6}],8:[function(require,module,exports){
  2975. /* jshint -W117 */
  2976. /* a simple MUC connection plugin
  2977. * can only handle a single MUC room
  2978. */
  2979. var bridgeIsDown = false;
  2980. var Moderator = require("./moderator");
  2981. var JingleSession = require("./JingleSession");
  2982. module.exports = function(XMPP, eventEmitter) {
  2983. Strophe.addConnectionPlugin('emuc', {
  2984. connection: null,
  2985. roomjid: null,
  2986. myroomjid: null,
  2987. members: {},
  2988. list_members: [], // so we can elect a new focus
  2989. presMap: {},
  2990. preziMap: {},
  2991. joined: false,
  2992. isOwner: false,
  2993. role: null,
  2994. focusMucJid: null,
  2995. ssrc2jid: {},
  2996. init: function (conn) {
  2997. this.connection = conn;
  2998. },
  2999. initPresenceMap: function (myroomjid) {
  3000. this.presMap['to'] = myroomjid;
  3001. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  3002. },
  3003. doJoin: function (jid, password) {
  3004. this.myroomjid = jid;
  3005. console.info("Joined MUC as " + this.myroomjid);
  3006. this.initPresenceMap(this.myroomjid);
  3007. if (!this.roomjid) {
  3008. this.roomjid = Strophe.getBareJidFromJid(jid);
  3009. // add handlers (just once)
  3010. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  3011. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  3012. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  3013. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  3014. }
  3015. if (password !== undefined) {
  3016. this.presMap['password'] = password;
  3017. }
  3018. this.sendPresence();
  3019. },
  3020. doLeave: function () {
  3021. console.log("do leave", this.myroomjid);
  3022. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  3023. this.presMap.length = 0;
  3024. this.connection.send(pres);
  3025. },
  3026. createNonAnonymousRoom: function () {
  3027. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  3028. var getForm = $iq({type: 'get', to: this.roomjid})
  3029. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  3030. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3031. var self = this;
  3032. this.connection.sendIQ(getForm, function (form) {
  3033. if (!$(form).find(
  3034. '>query>x[xmlns="jabber:x:data"]' +
  3035. '>field[var="muc#roomconfig_whois"]').length) {
  3036. console.error('non-anonymous rooms not supported');
  3037. return;
  3038. }
  3039. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  3040. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3041. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3042. formSubmit.c('field', {'var': 'FORM_TYPE'})
  3043. .c('value')
  3044. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3045. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  3046. .c('value').t('anyone').up().up();
  3047. self.connection.sendIQ(formSubmit);
  3048. }, function (error) {
  3049. console.error("Error getting room configuration form");
  3050. });
  3051. },
  3052. onPresence: function (pres) {
  3053. var from = pres.getAttribute('from');
  3054. // What is this for? A workaround for something?
  3055. if (pres.getAttribute('type')) {
  3056. return true;
  3057. }
  3058. // Parse etherpad tag.
  3059. var etherpad = $(pres).find('>etherpad');
  3060. if (etherpad.length) {
  3061. if (config.etherpad_base && !Moderator.isModerator()) {
  3062. UI.initEtherpad(etherpad.text());
  3063. }
  3064. }
  3065. // Parse prezi tag.
  3066. var presentation = $(pres).find('>prezi');
  3067. if (presentation.length) {
  3068. var url = presentation.attr('url');
  3069. var current = presentation.find('>current').text();
  3070. console.log('presentation info received from', from, url);
  3071. if (this.preziMap[from] == null) {
  3072. this.preziMap[from] = url;
  3073. $(document).trigger('presentationadded.muc', [from, url, current]);
  3074. }
  3075. else {
  3076. $(document).trigger('gotoslide.muc', [from, url, current]);
  3077. }
  3078. }
  3079. else if (this.preziMap[from] != null) {
  3080. var url = this.preziMap[from];
  3081. delete this.preziMap[from];
  3082. $(document).trigger('presentationremoved.muc', [from, url]);
  3083. }
  3084. // Parse audio info tag.
  3085. var audioMuted = $(pres).find('>audiomuted');
  3086. if (audioMuted.length) {
  3087. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  3088. }
  3089. // Parse video info tag.
  3090. var videoMuted = $(pres).find('>videomuted');
  3091. if (videoMuted.length) {
  3092. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  3093. }
  3094. var stats = $(pres).find('>stats');
  3095. if (stats.length) {
  3096. var statsObj = {};
  3097. Strophe.forEachChild(stats[0], "stat", function (el) {
  3098. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  3099. });
  3100. connectionquality.updateRemoteStats(from, statsObj);
  3101. }
  3102. // Parse status.
  3103. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  3104. this.isOwner = true;
  3105. this.createNonAnonymousRoom();
  3106. }
  3107. // Parse roles.
  3108. var member = {};
  3109. member.show = $(pres).find('>show').text();
  3110. member.status = $(pres).find('>status').text();
  3111. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  3112. member.affiliation = tmp.attr('affiliation');
  3113. member.role = tmp.attr('role');
  3114. // Focus recognition
  3115. member.jid = tmp.attr('jid');
  3116. member.isFocus = false;
  3117. if (member.jid
  3118. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  3119. member.isFocus = true;
  3120. }
  3121. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  3122. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  3123. if (from == this.myroomjid) {
  3124. if (member.affiliation == 'owner') this.isOwner = true;
  3125. if (this.role !== member.role) {
  3126. this.role = member.role;
  3127. if (Moderator.onLocalRoleChange)
  3128. Moderator.onLocalRoleChange(from, member, pres);
  3129. UI.onLocalRoleChange(from, member, pres);
  3130. }
  3131. if (!this.joined) {
  3132. this.joined = true;
  3133. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  3134. this.list_members.push(from);
  3135. }
  3136. } else if (this.members[from] === undefined) {
  3137. // new participant
  3138. this.members[from] = member;
  3139. this.list_members.push(from);
  3140. console.log('entered', from, member);
  3141. if (member.isFocus) {
  3142. this.focusMucJid = from;
  3143. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  3144. }
  3145. else {
  3146. var id = $(pres).find('>userID').text();
  3147. var email = $(pres).find('>email');
  3148. if (email.length > 0) {
  3149. id = email.text();
  3150. }
  3151. UI.onMucEntered(from, id, member.displayName);
  3152. API.triggerEvent("participantJoined", {jid: from});
  3153. }
  3154. } else {
  3155. // Presence update for existing participant
  3156. // Watch role change:
  3157. if (this.members[from].role != member.role) {
  3158. this.members[from].role = member.role;
  3159. UI.onMucRoleChanged(member.role, member.displayName);
  3160. }
  3161. }
  3162. // Always trigger presence to update bindings
  3163. $(document).trigger('presence.muc', [from, member, pres]);
  3164. this.parsePresence(from, member, pres);
  3165. // Trigger status message update
  3166. if (member.status) {
  3167. UI.onMucPresenceStatus(from, member);
  3168. }
  3169. return true;
  3170. },
  3171. onPresenceUnavailable: function (pres) {
  3172. var from = pres.getAttribute('from');
  3173. // Status code 110 indicates that this notification is "self-presence".
  3174. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  3175. delete this.members[from];
  3176. this.list_members.splice(this.list_members.indexOf(from), 1);
  3177. this.onParticipantLeft(from);
  3178. }
  3179. // If the status code is 110 this means we're leaving and we would like
  3180. // to remove everyone else from our view, so we trigger the event.
  3181. else if (this.list_members.length > 1) {
  3182. for (var i = 0; i < this.list_members.length; i++) {
  3183. var member = this.list_members[i];
  3184. delete this.members[i];
  3185. this.list_members.splice(i, 1);
  3186. this.onParticipantLeft(member);
  3187. }
  3188. }
  3189. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  3190. $(document).trigger('kicked.muc', [from]);
  3191. if (this.myroomjid === from) {
  3192. XMPP.disposeConference(false);
  3193. eventEmitter.emit(XMPPEvents.KICKED);
  3194. }
  3195. }
  3196. return true;
  3197. },
  3198. onPresenceError: function (pres) {
  3199. var from = pres.getAttribute('from');
  3200. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3201. console.log('on password required', from);
  3202. var self = this;
  3203. UI.onPasswordReqiured(function (value) {
  3204. self.doJoin(from, value);
  3205. });
  3206. } else if ($(pres).find(
  3207. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3208. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  3209. if (toDomain === config.hosts.anonymousdomain) {
  3210. // enter the room by replying with 'not-authorized'. This would
  3211. // result in reconnection from authorized domain.
  3212. // We're either missing Jicofo/Prosody config for anonymous
  3213. // domains or something is wrong.
  3214. // XMPP.promptLogin();
  3215. UI.messageHandler.openReportDialog(null,
  3216. 'Oops ! We couldn`t join the conference.' +
  3217. ' There might be some problem with security' +
  3218. ' configuration. Please contact service' +
  3219. ' administrator.', pres);
  3220. } else {
  3221. console.warn('onPresError ', pres);
  3222. UI.messageHandler.openReportDialog(null,
  3223. 'Oops! Something went wrong and we couldn`t connect to the conference.',
  3224. pres);
  3225. }
  3226. } else {
  3227. console.warn('onPresError ', pres);
  3228. UI.messageHandler.openReportDialog(null,
  3229. 'Oops! Something went wrong and we couldn`t connect to the conference.',
  3230. pres);
  3231. }
  3232. return true;
  3233. },
  3234. sendMessage: function (body, nickname) {
  3235. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3236. msg.c('body', body).up();
  3237. if (nickname) {
  3238. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  3239. }
  3240. this.connection.send(msg);
  3241. API.triggerEvent("outgoingMessage", {"message": body});
  3242. },
  3243. setSubject: function (subject) {
  3244. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3245. msg.c('subject', subject);
  3246. this.connection.send(msg);
  3247. console.log("topic changed to " + subject);
  3248. },
  3249. onMessage: function (msg) {
  3250. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  3251. var from = msg.getAttribute('from');
  3252. var nick = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]').text() || Strophe.getResourceFromJid(from);
  3253. var txt = $(msg).find('>body').text();
  3254. var type = msg.getAttribute("type");
  3255. if (type == "error") {
  3256. UI.chatAddError($(msg).find('>text').text(), txt);
  3257. return true;
  3258. }
  3259. var subject = $(msg).find('>subject');
  3260. if (subject.length) {
  3261. var subjectText = subject.text();
  3262. if (subjectText || subjectText == "") {
  3263. UI.chatSetSubject(subjectText);
  3264. console.log("Subject is changed to " + subjectText);
  3265. }
  3266. }
  3267. if (txt) {
  3268. console.log('chat', nick, txt);
  3269. UI.updateChatConversation(from, nick, txt);
  3270. if (from != this.myroomjid)
  3271. API.triggerEvent("incomingMessage",
  3272. {"from": from, "nick": nick, "message": txt});
  3273. }
  3274. return true;
  3275. },
  3276. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  3277. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  3278. var ob = this;
  3279. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  3280. function (res) {
  3281. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  3282. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3283. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3284. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3285. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  3286. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  3287. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  3288. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  3289. ob.connection.sendIQ(formsubmit,
  3290. onSuccess,
  3291. onError);
  3292. } else {
  3293. onNotSupported();
  3294. }
  3295. }, onError);
  3296. },
  3297. kick: function (jid) {
  3298. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  3299. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  3300. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  3301. .c('reason').t('You have been kicked.').up().up().up();
  3302. this.connection.sendIQ(
  3303. kickIQ,
  3304. function (result) {
  3305. console.log('Kick participant with jid: ', jid, result);
  3306. },
  3307. function (error) {
  3308. console.log('Kick participant error: ', error);
  3309. });
  3310. },
  3311. sendPresence: function () {
  3312. var pres = $pres({to: this.presMap['to'] });
  3313. pres.c('x', {xmlns: this.presMap['xns']});
  3314. if (this.presMap['password']) {
  3315. pres.c('password').t(this.presMap['password']).up();
  3316. }
  3317. pres.up();
  3318. // Send XEP-0115 'c' stanza that contains our capabilities info
  3319. if (this.connection.caps) {
  3320. this.connection.caps.node = config.clientNode;
  3321. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  3322. }
  3323. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  3324. .t(navigator.userAgent).up();
  3325. if (this.presMap['bridgeIsDown']) {
  3326. pres.c('bridgeIsDown').up();
  3327. }
  3328. if (this.presMap['email']) {
  3329. pres.c('email').t(this.presMap['email']).up();
  3330. }
  3331. if (this.presMap['userId']) {
  3332. pres.c('userId').t(this.presMap['userId']).up();
  3333. }
  3334. if (this.presMap['displayName']) {
  3335. // XEP-0172
  3336. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  3337. .t(this.presMap['displayName']).up();
  3338. }
  3339. if (this.presMap['audions']) {
  3340. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  3341. .t(this.presMap['audiomuted']).up();
  3342. }
  3343. if (this.presMap['videons']) {
  3344. pres.c('videomuted', {xmlns: this.presMap['videons']})
  3345. .t(this.presMap['videomuted']).up();
  3346. }
  3347. if (this.presMap['statsns']) {
  3348. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  3349. for (var stat in this.presMap["stats"])
  3350. if (this.presMap["stats"][stat] != null)
  3351. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  3352. pres.up();
  3353. }
  3354. if (this.presMap['prezins']) {
  3355. pres.c('prezi',
  3356. {xmlns: this.presMap['prezins'],
  3357. 'url': this.presMap['preziurl']})
  3358. .c('current').t(this.presMap['prezicurrent']).up().up();
  3359. }
  3360. if (this.presMap['etherpadns']) {
  3361. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  3362. .t(this.presMap['etherpadname']).up();
  3363. }
  3364. if (this.presMap['medians']) {
  3365. pres.c('media', {xmlns: this.presMap['medians']});
  3366. var sourceNumber = 0;
  3367. Object.keys(this.presMap).forEach(function (key) {
  3368. if (key.indexOf('source') >= 0) {
  3369. sourceNumber++;
  3370. }
  3371. });
  3372. if (sourceNumber > 0)
  3373. for (var i = 1; i <= sourceNumber / 3; i++) {
  3374. pres.c('source',
  3375. {type: this.presMap['source' + i + '_type'],
  3376. ssrc: this.presMap['source' + i + '_ssrc'],
  3377. direction: this.presMap['source' + i + '_direction']
  3378. || 'sendrecv' }
  3379. ).up();
  3380. }
  3381. }
  3382. pres.up();
  3383. // console.debug(pres.toString());
  3384. this.connection.send(pres);
  3385. },
  3386. addDisplayNameToPresence: function (displayName) {
  3387. this.presMap['displayName'] = displayName;
  3388. },
  3389. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  3390. if (!this.presMap['medians'])
  3391. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  3392. this.presMap['source' + sourceNumber + '_type'] = mtype;
  3393. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  3394. this.presMap['source' + sourceNumber + '_direction'] = direction;
  3395. },
  3396. clearPresenceMedia: function () {
  3397. var self = this;
  3398. Object.keys(this.presMap).forEach(function (key) {
  3399. if (key.indexOf('source') != -1) {
  3400. delete self.presMap[key];
  3401. }
  3402. });
  3403. },
  3404. addPreziToPresence: function (url, currentSlide) {
  3405. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  3406. this.presMap['preziurl'] = url;
  3407. this.presMap['prezicurrent'] = currentSlide;
  3408. },
  3409. removePreziFromPresence: function () {
  3410. delete this.presMap['prezins'];
  3411. delete this.presMap['preziurl'];
  3412. delete this.presMap['prezicurrent'];
  3413. },
  3414. addCurrentSlideToPresence: function (currentSlide) {
  3415. this.presMap['prezicurrent'] = currentSlide;
  3416. },
  3417. getPrezi: function (roomjid) {
  3418. return this.preziMap[roomjid];
  3419. },
  3420. addEtherpadToPresence: function (etherpadName) {
  3421. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  3422. this.presMap['etherpadname'] = etherpadName;
  3423. },
  3424. addAudioInfoToPresence: function (isMuted) {
  3425. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  3426. this.presMap['audiomuted'] = isMuted.toString();
  3427. },
  3428. addVideoInfoToPresence: function (isMuted) {
  3429. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  3430. this.presMap['videomuted'] = isMuted.toString();
  3431. },
  3432. addConnectionInfoToPresence: function (stats) {
  3433. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  3434. this.presMap['stats'] = stats;
  3435. },
  3436. findJidFromResource: function (resourceJid) {
  3437. if (resourceJid &&
  3438. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  3439. return this.myroomjid;
  3440. }
  3441. var peerJid = null;
  3442. Object.keys(this.members).some(function (jid) {
  3443. peerJid = jid;
  3444. return Strophe.getResourceFromJid(jid) === resourceJid;
  3445. });
  3446. return peerJid;
  3447. },
  3448. addBridgeIsDownToPresence: function () {
  3449. this.presMap['bridgeIsDown'] = true;
  3450. },
  3451. addEmailToPresence: function (email) {
  3452. this.presMap['email'] = email;
  3453. },
  3454. addUserIdToPresence: function (userId) {
  3455. this.presMap['userId'] = userId;
  3456. },
  3457. isModerator: function () {
  3458. return this.role === 'moderator';
  3459. },
  3460. getMemberRole: function (peerJid) {
  3461. if (this.members[peerJid]) {
  3462. return this.members[peerJid].role;
  3463. }
  3464. return null;
  3465. },
  3466. onParticipantLeft: function (jid) {
  3467. UI.onMucLeft(jid);
  3468. API.triggerEvent("participantLeft", {jid: jid});
  3469. this.connection.jingle.terminateByJid(jid);
  3470. if (this.getPrezi(jid)) {
  3471. $(document).trigger('presentationremoved.muc',
  3472. [jid, this.getPrezi(jid)]);
  3473. }
  3474. Moderator.onMucLeft(jid);
  3475. },
  3476. parsePresence: function (from, memeber, pres) {
  3477. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  3478. bridgeIsDown = true;
  3479. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  3480. }
  3481. if(memeber.isFocus)
  3482. return;
  3483. var self = this;
  3484. // Remove old ssrcs coming from the jid
  3485. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  3486. if (self.ssrc2jid[ssrc] == jid) {
  3487. delete self.ssrc2jid[ssrc];
  3488. }
  3489. });
  3490. var changedStreams = [];
  3491. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  3492. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  3493. var ssrcV = ssrc.getAttribute('ssrc');
  3494. self.ssrc2jid[ssrcV] = from;
  3495. JingleSession.notReceivedSSRCs.push(ssrcV);
  3496. var type = ssrc.getAttribute('type');
  3497. var direction = ssrc.getAttribute('direction');
  3498. changedStreams.push({type: type, direction: direction});
  3499. });
  3500. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  3501. var displayName = !config.displayJids
  3502. ? memeber.displayName : Strophe.getResourceFromJid(from);
  3503. if (displayName && displayName.length > 0)
  3504. {
  3505. // $(document).trigger('displaynamechanged',
  3506. // [jid, displayName]);
  3507. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  3508. }
  3509. var id = $(pres).find('>userID').text();
  3510. var email = $(pres).find('>email');
  3511. if(email.length > 0) {
  3512. id = email.text();
  3513. }
  3514. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  3515. }
  3516. });
  3517. };
  3518. },{"./JingleSession":1,"./moderator":6}],9:[function(require,module,exports){
  3519. /* jshint -W117 */
  3520. var JingleSession = require("./JingleSession");
  3521. module.exports = function(XMPP)
  3522. {
  3523. function CallIncomingJingle(sid, connection) {
  3524. var sess = connection.jingle.sessions[sid];
  3525. // TODO: do we check activecall == null?
  3526. connection.jingle.activecall = sess;
  3527. statistics.onConferenceCreated(sess);
  3528. RTC.onConferenceCreated(sess);
  3529. // TODO: check affiliation and/or role
  3530. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  3531. sess.usedrip = true; // not-so-naive trickle ice
  3532. sess.sendAnswer();
  3533. sess.accept();
  3534. };
  3535. Strophe.addConnectionPlugin('jingle', {
  3536. connection: null,
  3537. sessions: {},
  3538. jid2session: {},
  3539. ice_config: {iceServers: []},
  3540. pc_constraints: {},
  3541. activecall: null,
  3542. media_constraints: {
  3543. mandatory: {
  3544. 'OfferToReceiveAudio': true,
  3545. 'OfferToReceiveVideo': true
  3546. }
  3547. // MozDontOfferDataChannel: true when this is firefox
  3548. },
  3549. init: function (conn) {
  3550. this.connection = conn;
  3551. if (this.connection.disco) {
  3552. // http://xmpp.org/extensions/xep-0167.html#support
  3553. // http://xmpp.org/extensions/xep-0176.html#support
  3554. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  3555. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  3556. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  3557. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  3558. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  3559. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  3560. // this is dealt with by SDP O/A so we don't need to annouce this
  3561. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  3562. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  3563. if (config.useRtcpMux) {
  3564. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  3565. }
  3566. if (config.useBundle) {
  3567. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  3568. }
  3569. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  3570. }
  3571. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  3572. },
  3573. onJingle: function (iq) {
  3574. var sid = $(iq).find('jingle').attr('sid');
  3575. var action = $(iq).find('jingle').attr('action');
  3576. var fromJid = iq.getAttribute('from');
  3577. // send ack first
  3578. var ack = $iq({type: 'result',
  3579. to: fromJid,
  3580. id: iq.getAttribute('id')
  3581. });
  3582. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  3583. var sess = this.sessions[sid];
  3584. if ('session-initiate' != action) {
  3585. if (sess === null) {
  3586. ack.type = 'error';
  3587. ack.c('error', {type: 'cancel'})
  3588. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  3589. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  3590. this.connection.send(ack);
  3591. return true;
  3592. }
  3593. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  3594. // local jid is not checked
  3595. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  3596. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  3597. ack.type = 'error';
  3598. ack.c('error', {type: 'cancel'})
  3599. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  3600. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  3601. this.connection.send(ack);
  3602. return true;
  3603. }
  3604. } else if (sess !== undefined) {
  3605. // existing session with same session id
  3606. // this might be out-of-order if the sess.peerjid is the same as from
  3607. ack.type = 'error';
  3608. ack.c('error', {type: 'cancel'})
  3609. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  3610. console.warn('duplicate session id', sid);
  3611. this.connection.send(ack);
  3612. return true;
  3613. }
  3614. // FIXME: check for a defined action
  3615. this.connection.send(ack);
  3616. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  3617. switch (action) {
  3618. case 'session-initiate':
  3619. sess = new JingleSession(
  3620. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  3621. this.connection, XMPP);
  3622. // configure session
  3623. sess.media_constraints = this.media_constraints;
  3624. sess.pc_constraints = this.pc_constraints;
  3625. sess.ice_config = this.ice_config;
  3626. sess.initiate(fromJid, false);
  3627. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  3628. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  3629. this.sessions[sess.sid] = sess;
  3630. this.jid2session[sess.peerjid] = sess;
  3631. // the callback should either
  3632. // .sendAnswer and .accept
  3633. // or .sendTerminate -- not necessarily synchronus
  3634. CallIncomingJingle(sess.sid, this.connection);
  3635. break;
  3636. case 'session-accept':
  3637. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  3638. sess.accept();
  3639. $(document).trigger('callaccepted.jingle', [sess.sid]);
  3640. break;
  3641. case 'session-terminate':
  3642. // If this is not the focus sending the terminate, we have
  3643. // nothing more to do here.
  3644. if (Object.keys(this.sessions).length < 1
  3645. || !(this.sessions[Object.keys(this.sessions)[0]]
  3646. instanceof JingleSession))
  3647. {
  3648. break;
  3649. }
  3650. console.log('terminating...', sess.sid);
  3651. sess.terminate();
  3652. this.terminate(sess.sid);
  3653. if ($(iq).find('>jingle>reason').length) {
  3654. $(document).trigger('callterminated.jingle', [
  3655. sess.sid,
  3656. sess.peerjid,
  3657. $(iq).find('>jingle>reason>:first')[0].tagName,
  3658. $(iq).find('>jingle>reason>text').text()
  3659. ]);
  3660. } else {
  3661. $(document).trigger('callterminated.jingle',
  3662. [sess.sid, sess.peerjid]);
  3663. }
  3664. break;
  3665. case 'transport-info':
  3666. sess.addIceCandidate($(iq).find('>jingle>content'));
  3667. break;
  3668. case 'session-info':
  3669. var affected;
  3670. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  3671. $(document).trigger('ringing.jingle', [sess.sid]);
  3672. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  3673. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  3674. $(document).trigger('mute.jingle', [sess.sid, affected]);
  3675. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  3676. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  3677. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  3678. }
  3679. break;
  3680. case 'addsource': // FIXME: proprietary, un-jingleish
  3681. case 'source-add': // FIXME: proprietary
  3682. sess.addSource($(iq).find('>jingle>content'), fromJid);
  3683. break;
  3684. case 'removesource': // FIXME: proprietary, un-jingleish
  3685. case 'source-remove': // FIXME: proprietary
  3686. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  3687. break;
  3688. default:
  3689. console.warn('jingle action not implemented', action);
  3690. break;
  3691. }
  3692. return true;
  3693. },
  3694. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  3695. var sess = new JingleSession(myjid || this.connection.jid,
  3696. Math.random().toString(36).substr(2, 12), // random string
  3697. this.connection, XMPP);
  3698. // configure session
  3699. sess.media_constraints = this.media_constraints;
  3700. sess.pc_constraints = this.pc_constraints;
  3701. sess.ice_config = this.ice_config;
  3702. sess.initiate(peerjid, true);
  3703. this.sessions[sess.sid] = sess;
  3704. this.jid2session[sess.peerjid] = sess;
  3705. sess.sendOffer();
  3706. return sess;
  3707. },
  3708. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  3709. if (sid === null || sid === undefined) {
  3710. for (sid in this.sessions) {
  3711. if (this.sessions[sid].state != 'ended') {
  3712. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  3713. this.sessions[sid].terminate();
  3714. }
  3715. delete this.jid2session[this.sessions[sid].peerjid];
  3716. delete this.sessions[sid];
  3717. }
  3718. } else if (this.sessions.hasOwnProperty(sid)) {
  3719. if (this.sessions[sid].state != 'ended') {
  3720. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  3721. this.sessions[sid].terminate();
  3722. }
  3723. delete this.jid2session[this.sessions[sid].peerjid];
  3724. delete this.sessions[sid];
  3725. }
  3726. },
  3727. // Used to terminate a session when an unavailable presence is received.
  3728. terminateByJid: function (jid) {
  3729. if (this.jid2session.hasOwnProperty(jid)) {
  3730. var sess = this.jid2session[jid];
  3731. if (sess) {
  3732. sess.terminate();
  3733. console.log('peer went away silently', jid);
  3734. delete this.sessions[sess.sid];
  3735. delete this.jid2session[jid];
  3736. $(document).trigger('callterminated.jingle',
  3737. [sess.sid, jid], 'gone');
  3738. }
  3739. }
  3740. },
  3741. terminateRemoteByJid: function (jid, reason) {
  3742. if (this.jid2session.hasOwnProperty(jid)) {
  3743. var sess = this.jid2session[jid];
  3744. if (sess) {
  3745. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  3746. sess.terminate();
  3747. console.log('terminate peer with jid', sess.sid, jid);
  3748. delete this.sessions[sess.sid];
  3749. delete this.jid2session[jid];
  3750. $(document).trigger('callterminated.jingle',
  3751. [sess.sid, jid, 'kicked']);
  3752. }
  3753. }
  3754. },
  3755. getStunAndTurnCredentials: function () {
  3756. // get stun and turn configuration from server via xep-0215
  3757. // uses time-limited credentials as described in
  3758. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  3759. //
  3760. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  3761. // for a prosody module which implements this
  3762. //
  3763. // currently, this doesn't work with updateIce and therefore credentials with a long
  3764. // validity have to be fetched before creating the peerconnection
  3765. // TODO: implement refresh via updateIce as described in
  3766. // https://code.google.com/p/webrtc/issues/detail?id=1650
  3767. var self = this;
  3768. this.connection.sendIQ(
  3769. $iq({type: 'get', to: this.connection.domain})
  3770. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  3771. function (res) {
  3772. var iceservers = [];
  3773. $(res).find('>services>service').each(function (idx, el) {
  3774. el = $(el);
  3775. var dict = {};
  3776. var type = el.attr('type');
  3777. switch (type) {
  3778. case 'stun':
  3779. dict.url = 'stun:' + el.attr('host');
  3780. if (el.attr('port')) {
  3781. dict.url += ':' + el.attr('port');
  3782. }
  3783. iceservers.push(dict);
  3784. break;
  3785. case 'turn':
  3786. case 'turns':
  3787. dict.url = type + ':';
  3788. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  3789. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  3790. dict.url += el.attr('username') + '@';
  3791. } else {
  3792. dict.username = el.attr('username'); // only works in M28
  3793. }
  3794. }
  3795. dict.url += el.attr('host');
  3796. if (el.attr('port') && el.attr('port') != '3478') {
  3797. dict.url += ':' + el.attr('port');
  3798. }
  3799. if (el.attr('transport') && el.attr('transport') != 'udp') {
  3800. dict.url += '?transport=' + el.attr('transport');
  3801. }
  3802. if (el.attr('password')) {
  3803. dict.credential = el.attr('password');
  3804. }
  3805. iceservers.push(dict);
  3806. break;
  3807. }
  3808. });
  3809. self.ice_config.iceServers = iceservers;
  3810. },
  3811. function (err) {
  3812. console.warn('getting turn credentials failed', err);
  3813. console.warn('is mod_turncredentials or similar installed?');
  3814. }
  3815. );
  3816. // implement push?
  3817. },
  3818. /**
  3819. * Populates the log data
  3820. */
  3821. populateData: function () {
  3822. var data = {};
  3823. Object.keys(this.sessions).forEach(function (sid) {
  3824. var session = this.sessions[sid];
  3825. if (session.peerconnection && session.peerconnection.updateLog) {
  3826. // FIXME: should probably be a .dump call
  3827. data["jingle_" + session.sid] = {
  3828. updateLog: session.peerconnection.updateLog,
  3829. stats: session.peerconnection.stats,
  3830. url: window.location.href
  3831. };
  3832. }
  3833. });
  3834. return data;
  3835. }
  3836. });
  3837. };
  3838. },{"./JingleSession":1}],10:[function(require,module,exports){
  3839. /* global Strophe */
  3840. module.exports = function () {
  3841. Strophe.addConnectionPlugin('logger', {
  3842. // logs raw stanzas and makes them available for download as JSON
  3843. connection: null,
  3844. log: [],
  3845. init: function (conn) {
  3846. this.connection = conn;
  3847. this.connection.rawInput = this.log_incoming.bind(this);
  3848. this.connection.rawOutput = this.log_outgoing.bind(this);
  3849. },
  3850. log_incoming: function (stanza) {
  3851. this.log.push([new Date().getTime(), 'incoming', stanza]);
  3852. },
  3853. log_outgoing: function (stanza) {
  3854. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  3855. }
  3856. });
  3857. };
  3858. },{}],11:[function(require,module,exports){
  3859. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  3860. setAudioMuted, Strophe */
  3861. /**
  3862. * Moderate connection plugin.
  3863. */
  3864. module.exports = function (XMPP) {
  3865. Strophe.addConnectionPlugin('moderate', {
  3866. connection: null,
  3867. init: function (conn) {
  3868. this.connection = conn;
  3869. this.connection.addHandler(this.onMute.bind(this),
  3870. 'http://jitsi.org/jitmeet/audio',
  3871. 'iq',
  3872. 'set',
  3873. null,
  3874. null);
  3875. },
  3876. setMute: function (jid, mute) {
  3877. console.info("set mute", mute);
  3878. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  3879. .c('mute', {
  3880. xmlns: 'http://jitsi.org/jitmeet/audio',
  3881. jid: jid
  3882. })
  3883. .t(mute.toString())
  3884. .up();
  3885. this.connection.sendIQ(
  3886. iqToFocus,
  3887. function (result) {
  3888. console.log('set mute', result);
  3889. },
  3890. function (error) {
  3891. console.log('set mute error', error);
  3892. });
  3893. },
  3894. onMute: function (iq) {
  3895. var from = iq.getAttribute('from');
  3896. if (from !== this.connection.emuc.focusMucJid) {
  3897. console.warn("Ignored mute from non focus peer");
  3898. return false;
  3899. }
  3900. var mute = $(iq).find('mute');
  3901. if (mute.length) {
  3902. var doMuteAudio = mute.text() === "true";
  3903. UI.setAudioMuted(doMuteAudio);
  3904. XMPP.forceMuted = doMuteAudio;
  3905. }
  3906. return true;
  3907. },
  3908. eject: function (jid) {
  3909. // We're not the focus, so can't terminate
  3910. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  3911. this.connection.emuc.kick(jid);
  3912. }
  3913. });
  3914. }
  3915. },{}],12:[function(require,module,exports){
  3916. /* jshint -W117 */
  3917. module.exports = function() {
  3918. Strophe.addConnectionPlugin('rayo',
  3919. {
  3920. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  3921. connection: null,
  3922. init: function (conn) {
  3923. this.connection = conn;
  3924. if (this.connection.disco) {
  3925. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  3926. }
  3927. this.connection.addHandler(
  3928. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  3929. },
  3930. onRayo: function (iq) {
  3931. console.info("Rayo IQ", iq);
  3932. },
  3933. dial: function (to, from, roomName, roomPass) {
  3934. var self = this;
  3935. var req = $iq(
  3936. {
  3937. type: 'set',
  3938. to: this.connection.emuc.focusMucJid
  3939. }
  3940. );
  3941. req.c('dial',
  3942. {
  3943. xmlns: this.RAYO_XMLNS,
  3944. to: to,
  3945. from: from
  3946. });
  3947. req.c('header',
  3948. {
  3949. name: 'JvbRoomName',
  3950. value: roomName
  3951. }).up();
  3952. if (roomPass !== null && roomPass.length) {
  3953. req.c('header',
  3954. {
  3955. name: 'JvbRoomPassword',
  3956. value: roomPass
  3957. }).up();
  3958. }
  3959. this.connection.sendIQ(
  3960. req,
  3961. function (result) {
  3962. console.info('Dial result ', result);
  3963. var resource = $(result).find('ref').attr('uri');
  3964. this.call_resource = resource.substr('xmpp:'.length);
  3965. console.info(
  3966. "Received call resource: " + this.call_resource);
  3967. },
  3968. function (error) {
  3969. console.info('Dial error ', error);
  3970. }
  3971. );
  3972. },
  3973. hang_up: function () {
  3974. if (!this.call_resource) {
  3975. console.warn("No call in progress");
  3976. return;
  3977. }
  3978. var self = this;
  3979. var req = $iq(
  3980. {
  3981. type: 'set',
  3982. to: this.call_resource
  3983. }
  3984. );
  3985. req.c('hangup',
  3986. {
  3987. xmlns: this.RAYO_XMLNS
  3988. });
  3989. this.connection.sendIQ(
  3990. req,
  3991. function (result) {
  3992. console.info('Hangup result ', result);
  3993. self.call_resource = null;
  3994. },
  3995. function (error) {
  3996. console.info('Hangup error ', error);
  3997. self.call_resource = null;
  3998. }
  3999. );
  4000. }
  4001. }
  4002. );
  4003. };
  4004. },{}],13:[function(require,module,exports){
  4005. /**
  4006. * Strophe logger implementation. Logs from level WARN and above.
  4007. */
  4008. module.exports = function () {
  4009. Strophe.log = function (level, msg) {
  4010. switch (level) {
  4011. case Strophe.LogLevel.WARN:
  4012. console.warn("Strophe: " + msg);
  4013. break;
  4014. case Strophe.LogLevel.ERROR:
  4015. case Strophe.LogLevel.FATAL:
  4016. console.error("Strophe: " + msg);
  4017. break;
  4018. }
  4019. };
  4020. Strophe.getStatusString = function (status) {
  4021. switch (status) {
  4022. case Strophe.Status.ERROR:
  4023. return "ERROR";
  4024. case Strophe.Status.CONNECTING:
  4025. return "CONNECTING";
  4026. case Strophe.Status.CONNFAIL:
  4027. return "CONNFAIL";
  4028. case Strophe.Status.AUTHENTICATING:
  4029. return "AUTHENTICATING";
  4030. case Strophe.Status.AUTHFAIL:
  4031. return "AUTHFAIL";
  4032. case Strophe.Status.CONNECTED:
  4033. return "CONNECTED";
  4034. case Strophe.Status.DISCONNECTED:
  4035. return "DISCONNECTED";
  4036. case Strophe.Status.DISCONNECTING:
  4037. return "DISCONNECTING";
  4038. case Strophe.Status.ATTACHED:
  4039. return "ATTACHED";
  4040. default:
  4041. return "unknown";
  4042. }
  4043. };
  4044. };
  4045. },{}],14:[function(require,module,exports){
  4046. var Moderator = require("./moderator");
  4047. var EventEmitter = require("events");
  4048. var Recording = require("./recording");
  4049. var SDP = require("./SDP");
  4050. var eventEmitter = new EventEmitter();
  4051. var connection = null;
  4052. var authenticatedUser = false;
  4053. function connect(jid, password, uiCredentials) {
  4054. var bosh
  4055. = uiCredentials.bosh || config.bosh || '/http-bind';
  4056. connection = new Strophe.Connection(bosh);
  4057. Moderator.setConnection(connection);
  4058. var settings = UI.getSettings();
  4059. var email = settings.email;
  4060. var displayName = settings.displayName;
  4061. if(email) {
  4062. connection.emuc.addEmailToPresence(email);
  4063. } else {
  4064. connection.emuc.addUserIdToPresence(settings.uid);
  4065. }
  4066. if(displayName) {
  4067. connection.emuc.addDisplayNameToPresence(displayName);
  4068. }
  4069. if (connection.disco) {
  4070. // for chrome, add multistream cap
  4071. }
  4072. connection.jingle.pc_constraints = RTC.getPCConstraints();
  4073. if (config.useIPv6) {
  4074. // https://code.google.com/p/webrtc/issues/detail?id=2828
  4075. if (!connection.jingle.pc_constraints.optional)
  4076. connection.jingle.pc_constraints.optional = [];
  4077. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  4078. }
  4079. if(!password)
  4080. password = uiCredentials.password;
  4081. var anonymousConnectionFailed = false;
  4082. connection.connect(jid, password, function (status, msg) {
  4083. console.log('Strophe status changed to',
  4084. Strophe.getStatusString(status));
  4085. if (status === Strophe.Status.CONNECTED) {
  4086. if (config.useStunTurn) {
  4087. connection.jingle.getStunAndTurnCredentials();
  4088. }
  4089. UI.disableConnect();
  4090. console.info("My Jabber ID: " + connection.jid);
  4091. if(password)
  4092. authenticatedUser = true;
  4093. maybeDoJoin();
  4094. } else if (status === Strophe.Status.CONNFAIL) {
  4095. if(msg === 'x-strophe-bad-non-anon-jid') {
  4096. anonymousConnectionFailed = true;
  4097. }
  4098. } else if (status === Strophe.Status.DISCONNECTED) {
  4099. if(anonymousConnectionFailed) {
  4100. // prompt user for username and password
  4101. XMPP.promptLogin();
  4102. }
  4103. } else if (status === Strophe.Status.AUTHFAIL) {
  4104. // wrong password or username, prompt user
  4105. XMPP.promptLogin();
  4106. }
  4107. });
  4108. }
  4109. function maybeDoJoin() {
  4110. if (connection && connection.connected &&
  4111. Strophe.getResourceFromJid(connection.jid)
  4112. && (RTC.localAudio || RTC.localVideo)) {
  4113. // .connected is true while connecting?
  4114. doJoin();
  4115. }
  4116. }
  4117. function doJoin() {
  4118. var roomName = UI.generateRoomName();
  4119. Moderator.allocateConferenceFocus(
  4120. roomName, UI.checkForNicknameAndJoin);
  4121. }
  4122. function initStrophePlugins()
  4123. {
  4124. require("./strophe.emuc")(XMPP, eventEmitter);
  4125. require("./strophe.jingle")();
  4126. require("./strophe.moderate")(XMPP);
  4127. require("./strophe.util")();
  4128. require("./strophe.rayo")();
  4129. require("./strophe.logger")();
  4130. }
  4131. function registerListeners() {
  4132. RTC.addStreamListener(maybeDoJoin,
  4133. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  4134. }
  4135. function setupEvents() {
  4136. $(window).bind('beforeunload', function () {
  4137. if (connection && connection.connected) {
  4138. // ensure signout
  4139. $.ajax({
  4140. type: 'POST',
  4141. url: config.bosh,
  4142. async: false,
  4143. cache: false,
  4144. contentType: 'application/xml',
  4145. data: "<body rid='" + (connection.rid || connection._proto.rid)
  4146. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  4147. + (connection.sid || connection._proto.sid)
  4148. + "' type='terminate'>" +
  4149. "<presence xmlns='jabber:client' type='unavailable'/>" +
  4150. "</body>",
  4151. success: function (data) {
  4152. console.log('signed out');
  4153. console.log(data);
  4154. },
  4155. error: function (XMLHttpRequest, textStatus, errorThrown) {
  4156. console.log('signout error',
  4157. textStatus + ' (' + errorThrown + ')');
  4158. }
  4159. });
  4160. }
  4161. XMPP.disposeConference(true);
  4162. });
  4163. }
  4164. var XMPP = {
  4165. sessionTerminated: false,
  4166. /**
  4167. * Remembers if we were muted by the focus.
  4168. * @type {boolean}
  4169. */
  4170. forceMuted: false,
  4171. start: function (uiCredentials) {
  4172. setupEvents();
  4173. initStrophePlugins();
  4174. registerListeners();
  4175. Moderator.init();
  4176. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  4177. // Force authenticated domain if room is appended with '?login=true'
  4178. if (config.hosts.anonymousdomain &&
  4179. window.location.search.indexOf("login=true") !== -1) {
  4180. configDomain = config.hosts.domain;
  4181. }
  4182. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  4183. connect(jid, null, uiCredentials);
  4184. },
  4185. promptLogin: function () {
  4186. UI.showLoginPopup(connect);
  4187. },
  4188. joinRooom: function(roomName, useNicks, nick)
  4189. {
  4190. var roomjid;
  4191. roomjid = roomName;
  4192. if (useNicks) {
  4193. if (nick) {
  4194. roomjid += '/' + nick;
  4195. } else {
  4196. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  4197. }
  4198. } else {
  4199. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  4200. if(!authenticatedUser)
  4201. tmpJid = tmpJid.substr(0, 8);
  4202. roomjid += '/' + tmpJid;
  4203. }
  4204. connection.emuc.doJoin(roomjid);
  4205. },
  4206. myJid: function () {
  4207. if(!connection)
  4208. return null;
  4209. return connection.emuc.myroomjid;
  4210. },
  4211. myResource: function () {
  4212. if(!connection || ! connection.emuc.myroomjid)
  4213. return null;
  4214. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  4215. },
  4216. disposeConference: function (onUnload) {
  4217. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  4218. var handler = connection.jingle.activecall;
  4219. if (handler && handler.peerconnection) {
  4220. // FIXME: probably removing streams is not required and close() should
  4221. // be enough
  4222. if (RTC.localAudio) {
  4223. handler.peerconnection.removeStream(RTC.localAudio.getOriginalStream(), onUnload);
  4224. }
  4225. if (RTC.localVideo) {
  4226. handler.peerconnection.removeStream(RTC.localVideo.getOriginalStream(), onUnload);
  4227. }
  4228. handler.peerconnection.close();
  4229. }
  4230. connection.jingle.activecall = null;
  4231. if(!onUnload)
  4232. {
  4233. this.sessionTerminated = true;
  4234. connection.emuc.doLeave();
  4235. }
  4236. },
  4237. addListener: function(type, listener)
  4238. {
  4239. eventEmitter.on(type, listener);
  4240. },
  4241. removeListener: function (type, listener) {
  4242. eventEmitter.removeListener(type, listener);
  4243. },
  4244. allocateConferenceFocus: function(roomName, callback) {
  4245. Moderator.allocateConferenceFocus(roomName, callback);
  4246. },
  4247. isModerator: function () {
  4248. return Moderator.isModerator();
  4249. },
  4250. isSipGatewayEnabled: function () {
  4251. return Moderator.isSipGatewayEnabled();
  4252. },
  4253. isExternalAuthEnabled: function () {
  4254. return Moderator.isExternalAuthEnabled();
  4255. },
  4256. switchStreams: function (stream, oldStream, callback) {
  4257. if (connection && connection.jingle.activecall) {
  4258. // FIXME: will block switchInProgress on true value in case of exception
  4259. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  4260. } else {
  4261. // We are done immediately
  4262. console.error("No conference handler");
  4263. UI.messageHandler.showError('Error',
  4264. 'Unable to switch video stream.');
  4265. callback();
  4266. }
  4267. },
  4268. setVideoMute: function (mute, callback, options) {
  4269. if(connection && RTC.localVideo && connection.jingle.activecall)
  4270. {
  4271. connection.jingle.activecall.setVideoMute(mute, callback, options);
  4272. }
  4273. },
  4274. setAudioMute: function (mute, callback) {
  4275. if (!(connection && RTC.localAudio)) {
  4276. return false;
  4277. }
  4278. if (this.forceMuted && !mute) {
  4279. console.info("Asking focus for unmute");
  4280. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  4281. // FIXME: wait for result before resetting muted status
  4282. this.forceMuted = false;
  4283. }
  4284. if (mute == RTC.localAudio.isMuted()) {
  4285. // Nothing to do
  4286. return true;
  4287. }
  4288. // It is not clear what is the right way to handle multiple tracks.
  4289. // So at least make sure that they are all muted or all unmuted and
  4290. // that we send presence just once.
  4291. RTC.localAudio.mute();
  4292. // isMuted is the opposite of audioEnabled
  4293. connection.emuc.addAudioInfoToPresence(mute);
  4294. connection.emuc.sendPresence();
  4295. callback();
  4296. return true;
  4297. },
  4298. // Really mute video, i.e. dont even send black frames
  4299. muteVideo: function (pc, unmute) {
  4300. // FIXME: this probably needs another of those lovely state safeguards...
  4301. // which checks for iceconn == connected and sigstate == stable
  4302. pc.setRemoteDescription(pc.remoteDescription,
  4303. function () {
  4304. pc.createAnswer(
  4305. function (answer) {
  4306. var sdp = new SDP(answer.sdp);
  4307. if (sdp.media.length > 1) {
  4308. if (unmute)
  4309. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  4310. else
  4311. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  4312. sdp.raw = sdp.session + sdp.media.join('');
  4313. answer.sdp = sdp.raw;
  4314. }
  4315. pc.setLocalDescription(answer,
  4316. function () {
  4317. console.log('mute SLD ok');
  4318. },
  4319. function (error) {
  4320. console.log('mute SLD error');
  4321. UI.messageHandler.showError('Error',
  4322. 'Oops! Something went wrong and we failed to ' +
  4323. 'mute! (SLD Failure)');
  4324. }
  4325. );
  4326. },
  4327. function (error) {
  4328. console.log(error);
  4329. UI.messageHandler.showError();
  4330. }
  4331. );
  4332. },
  4333. function (error) {
  4334. console.log('muteVideo SRD error');
  4335. UI.messageHandler.showError('Error',
  4336. 'Oops! Something went wrong and we failed to stop video!' +
  4337. '(SRD Failure)');
  4338. }
  4339. );
  4340. },
  4341. toggleRecording: function (tokenEmptyCallback,
  4342. startingCallback, startedCallback) {
  4343. Recording.toggleRecording(tokenEmptyCallback,
  4344. startingCallback, startedCallback, connection);
  4345. },
  4346. addToPresence: function (name, value, dontSend) {
  4347. switch (name)
  4348. {
  4349. case "displayName":
  4350. connection.emuc.addDisplayNameToPresence(value);
  4351. break;
  4352. case "etherpad":
  4353. connection.emuc.addEtherpadToPresence(value);
  4354. break;
  4355. case "prezi":
  4356. connection.emuc.addPreziToPresence(value, 0);
  4357. break;
  4358. case "preziSlide":
  4359. connection.emuc.addCurrentSlideToPresence(value);
  4360. break;
  4361. case "connectionQuality":
  4362. connection.emuc.addConnectionInfoToPresence(value);
  4363. break;
  4364. case "email":
  4365. connection.emuc.addEmailToPresence(value);
  4366. default :
  4367. console.log("Unknown tag for presence.");
  4368. return;
  4369. }
  4370. if(!dontSend)
  4371. connection.emuc.sendPresence();
  4372. },
  4373. sendLogs: function (data) {
  4374. if(!connection.emuc.focusMucJid)
  4375. return;
  4376. var deflate = true;
  4377. var content = JSON.stringify(data);
  4378. if (deflate) {
  4379. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  4380. }
  4381. content = Base64.encode(content);
  4382. // XEP-0337-ish
  4383. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  4384. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  4385. id: 'PeerConnectionStats'});
  4386. message.c('message').t(content).up();
  4387. if (deflate) {
  4388. message.c('tag', {name: "deflated", value: "true"}).up();
  4389. }
  4390. message.up();
  4391. connection.send(message);
  4392. },
  4393. populateData: function () {
  4394. var data = {};
  4395. if (connection.jingle) {
  4396. data = connection.jingle.populateData();
  4397. }
  4398. return data;
  4399. },
  4400. getLogger: function () {
  4401. if(connection.logger)
  4402. return connection.logger.log;
  4403. return null;
  4404. },
  4405. getPrezi: function () {
  4406. return connection.emuc.getPrezi(this.myJid());
  4407. },
  4408. removePreziFromPresence: function () {
  4409. connection.emuc.removePreziFromPresence();
  4410. connection.emuc.sendPresence();
  4411. },
  4412. sendChatMessage: function (message, nickname) {
  4413. connection.emuc.sendMessage(message, nickname);
  4414. },
  4415. setSubject: function (topic) {
  4416. connection.emuc.setSubject(topic);
  4417. },
  4418. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  4419. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  4420. },
  4421. dial: function (to, from, roomName,roomPass) {
  4422. connection.rayo.dial(to, from, roomName,roomPass);
  4423. },
  4424. setMute: function (jid, mute) {
  4425. connection.moderate.setMute(jid, mute);
  4426. },
  4427. eject: function (jid) {
  4428. connection.moderate.eject(jid);
  4429. },
  4430. findJidFromResource: function (resource) {
  4431. return connection.emuc.findJidFromResource(resource);
  4432. },
  4433. getMembers: function () {
  4434. return connection.emuc.members;
  4435. },
  4436. getJidFromSSRC: function (ssrc) {
  4437. if(!connection)
  4438. return null;
  4439. return connection.emuc.ssrc2jid[ssrc];
  4440. }
  4441. };
  4442. module.exports = XMPP;
  4443. },{"./SDP":2,"./moderator":6,"./recording":7,"./strophe.emuc":8,"./strophe.jingle":9,"./strophe.logger":10,"./strophe.moderate":11,"./strophe.rayo":12,"./strophe.util":13,"events":15}],15:[function(require,module,exports){
  4444. // Copyright Joyent, Inc. and other Node contributors.
  4445. //
  4446. // Permission is hereby granted, free of charge, to any person obtaining a
  4447. // copy of this software and associated documentation files (the
  4448. // "Software"), to deal in the Software without restriction, including
  4449. // without limitation the rights to use, copy, modify, merge, publish,
  4450. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4451. // persons to whom the Software is furnished to do so, subject to the
  4452. // following conditions:
  4453. //
  4454. // The above copyright notice and this permission notice shall be included
  4455. // in all copies or substantial portions of the Software.
  4456. //
  4457. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4458. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4459. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4460. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4461. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4462. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4463. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4464. function EventEmitter() {
  4465. this._events = this._events || {};
  4466. this._maxListeners = this._maxListeners || undefined;
  4467. }
  4468. module.exports = EventEmitter;
  4469. // Backwards-compat with node 0.10.x
  4470. EventEmitter.EventEmitter = EventEmitter;
  4471. EventEmitter.prototype._events = undefined;
  4472. EventEmitter.prototype._maxListeners = undefined;
  4473. // By default EventEmitters will print a warning if more than 10 listeners are
  4474. // added to it. This is a useful default which helps finding memory leaks.
  4475. EventEmitter.defaultMaxListeners = 10;
  4476. // Obviously not all Emitters should be limited to 10. This function allows
  4477. // that to be increased. Set to zero for unlimited.
  4478. EventEmitter.prototype.setMaxListeners = function(n) {
  4479. if (!isNumber(n) || n < 0 || isNaN(n))
  4480. throw TypeError('n must be a positive number');
  4481. this._maxListeners = n;
  4482. return this;
  4483. };
  4484. EventEmitter.prototype.emit = function(type) {
  4485. var er, handler, len, args, i, listeners;
  4486. if (!this._events)
  4487. this._events = {};
  4488. // If there is no 'error' event listener then throw.
  4489. if (type === 'error') {
  4490. if (!this._events.error ||
  4491. (isObject(this._events.error) && !this._events.error.length)) {
  4492. er = arguments[1];
  4493. if (er instanceof Error) {
  4494. throw er; // Unhandled 'error' event
  4495. } else {
  4496. throw TypeError('Uncaught, unspecified "error" event.');
  4497. }
  4498. return false;
  4499. }
  4500. }
  4501. handler = this._events[type];
  4502. if (isUndefined(handler))
  4503. return false;
  4504. if (isFunction(handler)) {
  4505. switch (arguments.length) {
  4506. // fast cases
  4507. case 1:
  4508. handler.call(this);
  4509. break;
  4510. case 2:
  4511. handler.call(this, arguments[1]);
  4512. break;
  4513. case 3:
  4514. handler.call(this, arguments[1], arguments[2]);
  4515. break;
  4516. // slower
  4517. default:
  4518. len = arguments.length;
  4519. args = new Array(len - 1);
  4520. for (i = 1; i < len; i++)
  4521. args[i - 1] = arguments[i];
  4522. handler.apply(this, args);
  4523. }
  4524. } else if (isObject(handler)) {
  4525. len = arguments.length;
  4526. args = new Array(len - 1);
  4527. for (i = 1; i < len; i++)
  4528. args[i - 1] = arguments[i];
  4529. listeners = handler.slice();
  4530. len = listeners.length;
  4531. for (i = 0; i < len; i++)
  4532. listeners[i].apply(this, args);
  4533. }
  4534. return true;
  4535. };
  4536. EventEmitter.prototype.addListener = function(type, listener) {
  4537. var m;
  4538. if (!isFunction(listener))
  4539. throw TypeError('listener must be a function');
  4540. if (!this._events)
  4541. this._events = {};
  4542. // To avoid recursion in the case that type === "newListener"! Before
  4543. // adding it to the listeners, first emit "newListener".
  4544. if (this._events.newListener)
  4545. this.emit('newListener', type,
  4546. isFunction(listener.listener) ?
  4547. listener.listener : listener);
  4548. if (!this._events[type])
  4549. // Optimize the case of one listener. Don't need the extra array object.
  4550. this._events[type] = listener;
  4551. else if (isObject(this._events[type]))
  4552. // If we've already got an array, just append.
  4553. this._events[type].push(listener);
  4554. else
  4555. // Adding the second element, need to change to array.
  4556. this._events[type] = [this._events[type], listener];
  4557. // Check for listener leak
  4558. if (isObject(this._events[type]) && !this._events[type].warned) {
  4559. var m;
  4560. if (!isUndefined(this._maxListeners)) {
  4561. m = this._maxListeners;
  4562. } else {
  4563. m = EventEmitter.defaultMaxListeners;
  4564. }
  4565. if (m && m > 0 && this._events[type].length > m) {
  4566. this._events[type].warned = true;
  4567. console.error('(node) warning: possible EventEmitter memory ' +
  4568. 'leak detected. %d listeners added. ' +
  4569. 'Use emitter.setMaxListeners() to increase limit.',
  4570. this._events[type].length);
  4571. if (typeof console.trace === 'function') {
  4572. // not supported in IE 10
  4573. console.trace();
  4574. }
  4575. }
  4576. }
  4577. return this;
  4578. };
  4579. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  4580. EventEmitter.prototype.once = function(type, listener) {
  4581. if (!isFunction(listener))
  4582. throw TypeError('listener must be a function');
  4583. var fired = false;
  4584. function g() {
  4585. this.removeListener(type, g);
  4586. if (!fired) {
  4587. fired = true;
  4588. listener.apply(this, arguments);
  4589. }
  4590. }
  4591. g.listener = listener;
  4592. this.on(type, g);
  4593. return this;
  4594. };
  4595. // emits a 'removeListener' event iff the listener was removed
  4596. EventEmitter.prototype.removeListener = function(type, listener) {
  4597. var list, position, length, i;
  4598. if (!isFunction(listener))
  4599. throw TypeError('listener must be a function');
  4600. if (!this._events || !this._events[type])
  4601. return this;
  4602. list = this._events[type];
  4603. length = list.length;
  4604. position = -1;
  4605. if (list === listener ||
  4606. (isFunction(list.listener) && list.listener === listener)) {
  4607. delete this._events[type];
  4608. if (this._events.removeListener)
  4609. this.emit('removeListener', type, listener);
  4610. } else if (isObject(list)) {
  4611. for (i = length; i-- > 0;) {
  4612. if (list[i] === listener ||
  4613. (list[i].listener && list[i].listener === listener)) {
  4614. position = i;
  4615. break;
  4616. }
  4617. }
  4618. if (position < 0)
  4619. return this;
  4620. if (list.length === 1) {
  4621. list.length = 0;
  4622. delete this._events[type];
  4623. } else {
  4624. list.splice(position, 1);
  4625. }
  4626. if (this._events.removeListener)
  4627. this.emit('removeListener', type, listener);
  4628. }
  4629. return this;
  4630. };
  4631. EventEmitter.prototype.removeAllListeners = function(type) {
  4632. var key, listeners;
  4633. if (!this._events)
  4634. return this;
  4635. // not listening for removeListener, no need to emit
  4636. if (!this._events.removeListener) {
  4637. if (arguments.length === 0)
  4638. this._events = {};
  4639. else if (this._events[type])
  4640. delete this._events[type];
  4641. return this;
  4642. }
  4643. // emit removeListener for all listeners on all events
  4644. if (arguments.length === 0) {
  4645. for (key in this._events) {
  4646. if (key === 'removeListener') continue;
  4647. this.removeAllListeners(key);
  4648. }
  4649. this.removeAllListeners('removeListener');
  4650. this._events = {};
  4651. return this;
  4652. }
  4653. listeners = this._events[type];
  4654. if (isFunction(listeners)) {
  4655. this.removeListener(type, listeners);
  4656. } else {
  4657. // LIFO order
  4658. while (listeners.length)
  4659. this.removeListener(type, listeners[listeners.length - 1]);
  4660. }
  4661. delete this._events[type];
  4662. return this;
  4663. };
  4664. EventEmitter.prototype.listeners = function(type) {
  4665. var ret;
  4666. if (!this._events || !this._events[type])
  4667. ret = [];
  4668. else if (isFunction(this._events[type]))
  4669. ret = [this._events[type]];
  4670. else
  4671. ret = this._events[type].slice();
  4672. return ret;
  4673. };
  4674. EventEmitter.listenerCount = function(emitter, type) {
  4675. var ret;
  4676. if (!emitter._events || !emitter._events[type])
  4677. ret = 0;
  4678. else if (isFunction(emitter._events[type]))
  4679. ret = 1;
  4680. else
  4681. ret = emitter._events[type].length;
  4682. return ret;
  4683. };
  4684. function isFunction(arg) {
  4685. return typeof arg === 'function';
  4686. }
  4687. function isNumber(arg) {
  4688. return typeof arg === 'number';
  4689. }
  4690. function isObject(arg) {
  4691. return typeof arg === 'object' && arg !== null;
  4692. }
  4693. function isUndefined(arg) {
  4694. return arg === void 0;
  4695. }
  4696. },{}]},{},[14])(14)
  4697. });