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

ChatRoom.js 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. /* global Strophe, $, $pres, $iq, $msg */
  2. /* jshint -W101,-W069 */
  3. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5. var MediaType = require("../../service/RTC/MediaType");
  6. var Moderator = require("./moderator");
  7. var EventEmitter = require("events");
  8. var Recorder = require("./recording");
  9. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  10. var parser = {
  11. packet2JSON: function (packet, nodes) {
  12. var self = this;
  13. $(packet).children().each(function (index) {
  14. var tagName = $(this).prop("tagName");
  15. var node = {
  16. tagName: tagName
  17. };
  18. node.attributes = {};
  19. $($(this)[0].attributes).each(function( index, attr ) {
  20. node.attributes[ attr.name ] = attr.value;
  21. });
  22. var text = Strophe.getText($(this)[0]);
  23. if (text) {
  24. node.value = text;
  25. }
  26. node.children = [];
  27. nodes.push(node);
  28. self.packet2JSON($(this), node.children);
  29. });
  30. },
  31. JSON2packet: function (nodes, packet) {
  32. for(var i = 0; i < nodes.length; i++) {
  33. var node = nodes[i];
  34. if(!node || node === null){
  35. continue;
  36. }
  37. packet.c(node.tagName, node.attributes);
  38. if(node.value)
  39. packet.t(node.value);
  40. if(node.children)
  41. this.JSON2packet(node.children, packet);
  42. packet.up();
  43. }
  44. // packet.up();
  45. }
  46. };
  47. /**
  48. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  49. * @param pres the presence JSON
  50. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  51. */
  52. function filterNodeFromPresenceJSON(pres, nodeName){
  53. var res = [];
  54. for(var i = 0; i < pres.length; i++)
  55. if(pres[i].tagName === nodeName)
  56. res.push(pres[i]);
  57. return res;
  58. }
  59. function ChatRoom(connection, jid, password, XMPP, options, settings) {
  60. this.eventEmitter = new EventEmitter();
  61. this.xmpp = XMPP;
  62. this.connection = connection;
  63. this.roomjid = Strophe.getBareJidFromJid(jid);
  64. this.myroomjid = jid;
  65. this.password = password;
  66. logger.info("Joined MUC as " + this.myroomjid);
  67. this.members = {};
  68. this.presMap = {};
  69. this.presHandlers = {};
  70. this.joined = false;
  71. this.role = 'none';
  72. this.focusMucJid = null;
  73. this.bridgeIsDown = false;
  74. this.options = options || {};
  75. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
  76. settings, {connection: this.xmpp.options, conference: this.options});
  77. this.initPresenceMap();
  78. this.session = null;
  79. var self = this;
  80. this.lastPresences = {};
  81. this.phoneNumber = null;
  82. this.phonePin = null;
  83. this.connectionTimes = {};
  84. }
  85. ChatRoom.prototype.initPresenceMap = function () {
  86. this.presMap['to'] = this.myroomjid;
  87. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  88. this.presMap["nodes"] = [];
  89. this.presMap["nodes"].push( {
  90. "tagName": "user-agent",
  91. "value": navigator.userAgent,
  92. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  93. });
  94. };
  95. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  96. this.presMap["nodes"].push( {
  97. "tagName": "devices",
  98. "children": [
  99. {
  100. "tagName": "audio",
  101. "value": devices.audio,
  102. },
  103. {
  104. "tagName": "video",
  105. "value": devices.video,
  106. }
  107. ]
  108. });
  109. };
  110. ChatRoom.prototype.join = function (password) {
  111. if(password)
  112. this.password = password;
  113. var self = this;
  114. this.moderator.allocateConferenceFocus(function () {
  115. self.sendPresence(true);
  116. });
  117. };
  118. ChatRoom.prototype.sendPresence = function (fromJoin) {
  119. var to = this.presMap['to'];
  120. if (!to || (!this.joined && !fromJoin)) {
  121. // Too early to send presence - not initialized
  122. return;
  123. }
  124. var pres = $pres({to: to });
  125. pres.c('x', {xmlns: this.presMap['xns']});
  126. if (this.password) {
  127. pres.c('password').t(this.password).up();
  128. }
  129. pres.up();
  130. // Send XEP-0115 'c' stanza that contains our capabilities info
  131. var connection = this.connection;
  132. var caps = connection.caps;
  133. if (caps) {
  134. caps.node = this.xmpp.options.clientNode;
  135. pres.c('c', caps.generateCapsAttrs()).up();
  136. }
  137. parser.JSON2packet(this.presMap.nodes, pres);
  138. connection.send(pres);
  139. if (fromJoin) {
  140. // XXX We're pressed for time here because we're beginning a complex
  141. // and/or lengthy conference-establishment process which supposedly
  142. // involves multiple RTTs. We don't have the time to wait for Strophe to
  143. // decide to send our IQ.
  144. connection.flush();
  145. }
  146. };
  147. ChatRoom.prototype.doLeave = function () {
  148. logger.log("do leave", this.myroomjid);
  149. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  150. this.presMap.length = 0;
  151. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  152. // means that there may not be enough time to send the unavailable presence.
  153. // Switching Strophe to synchronous sending is not much of an option because
  154. // it may lead to a noticeable delay in navigating away from the current
  155. // location. As a compromise, we will try to increase the chances of sending
  156. // the unavailable presence within the short time span that we have upon
  157. // unloading by invoking flush() on the connection. We flush() once before
  158. // sending/queuing the unavailable presence in order to attemtp to have the
  159. // unavailable presence at the top of the send queue. We flush() once more
  160. // after sending/queuing the unavailable presence in order to attempt to
  161. // have it sent as soon as possible.
  162. this.connection.flush();
  163. this.connection.send(pres);
  164. this.connection.flush();
  165. };
  166. ChatRoom.prototype.createNonAnonymousRoom = function () {
  167. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  168. var getForm = $iq({type: 'get', to: this.roomjid})
  169. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  170. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  171. var self = this;
  172. this.connection.sendIQ(getForm, function (form) {
  173. if (!$(form).find(
  174. '>query>x[xmlns="jabber:x:data"]' +
  175. '>field[var="muc#roomconfig_whois"]').length) {
  176. logger.error('non-anonymous rooms not supported');
  177. return;
  178. }
  179. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  180. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  181. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  182. formSubmit.c('field', {'var': 'FORM_TYPE'})
  183. .c('value')
  184. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  185. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  186. .c('value').t('anyone').up().up();
  187. self.connection.sendIQ(formSubmit);
  188. }, function (error) {
  189. logger.error("Error getting room configuration form");
  190. });
  191. };
  192. ChatRoom.prototype.onPresence = function (pres) {
  193. var from = pres.getAttribute('from');
  194. // Parse roles.
  195. var member = {};
  196. member.show = $(pres).find('>show').text();
  197. member.status = $(pres).find('>status').text();
  198. var mucUserItem
  199. = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  200. member.affiliation = mucUserItem.attr('affiliation');
  201. member.role = mucUserItem.attr('role');
  202. // Focus recognition
  203. var jid = mucUserItem.attr('jid');
  204. member.jid = jid;
  205. member.isFocus
  206. = !!jid && jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0;
  207. $(pres).find(">x").remove();
  208. var nodes = [];
  209. parser.packet2JSON(pres, nodes);
  210. this.lastPresences[from] = nodes;
  211. var jibri = null;
  212. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  213. // events
  214. for(var i = 0; i < nodes.length; i++)
  215. {
  216. var node = nodes[i];
  217. switch(node.tagName)
  218. {
  219. case "nick":
  220. member.nick = node.value;
  221. break;
  222. case "userId":
  223. member.id = node.value;
  224. break;
  225. }
  226. }
  227. if (from == this.myroomjid) {
  228. if (member.affiliation == 'owner' && this.role !== member.role) {
  229. this.role = member.role;
  230. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  231. }
  232. if (!this.joined) {
  233. this.joined = true;
  234. var now = this.connectionTimes["muc.joined"] =
  235. window.performance.now();
  236. logger.log("(TIME) MUC joined:\t", now);
  237. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  238. }
  239. } else if (this.members[from] === undefined) {
  240. // new participant
  241. this.members[from] = member;
  242. logger.log('entered', from, member);
  243. if (member.isFocus) {
  244. this.focusMucJid = from;
  245. if(!this.recording) {
  246. this.recording = new Recorder(this.options.recordingType,
  247. this.eventEmitter, this.connection, this.focusMucJid,
  248. this.options.jirecon, this.roomjid);
  249. if(this.lastJibri)
  250. this.recording.handleJibriPresence(this.lastJibri);
  251. }
  252. logger.info("Ignore focus: " + from + ", real JID: " + jid);
  253. }
  254. else {
  255. this.eventEmitter.emit(
  256. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  257. }
  258. } else {
  259. // Presence update for existing participant
  260. // Watch role change:
  261. var memberOfThis = this.members[from];
  262. if (memberOfThis.role != member.role) {
  263. memberOfThis.role = member.role;
  264. this.eventEmitter.emit(
  265. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  266. }
  267. // store the new display name
  268. if(member.displayName)
  269. memberOfThis.displayName = member.displayName;
  270. }
  271. // after we had fired member or room joined events, lets fire events
  272. // for the rest info we got in presence
  273. for(var i = 0; i < nodes.length; i++)
  274. {
  275. var node = nodes[i];
  276. switch(node.tagName)
  277. {
  278. case "nick":
  279. if(!member.isFocus) {
  280. var displayName = !this.xmpp.options.displayJids
  281. ? member.nick : Strophe.getResourceFromJid(from);
  282. if (displayName && displayName.length > 0) {
  283. this.eventEmitter.emit(
  284. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  285. }
  286. }
  287. break;
  288. case "bridgeIsDown":
  289. if(!this.bridgeIsDown) {
  290. this.bridgeIsDown = true;
  291. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  292. }
  293. break;
  294. case "jibri-recording-status":
  295. var jibri = node;
  296. break;
  297. case "call-control":
  298. var att = node.attributes;
  299. if(!att)
  300. break;
  301. this.phoneNumber = att.phone || null;
  302. this.phonePin = att.pin || null;
  303. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  304. break;
  305. default :
  306. this.processNode(node, from);
  307. }
  308. }
  309. // Trigger status message update
  310. if (member.status) {
  311. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member.status);
  312. }
  313. if(jibri)
  314. {
  315. this.lastJibri = jibri;
  316. if(this.recording)
  317. this.recording.handleJibriPresence(jibri);
  318. }
  319. };
  320. ChatRoom.prototype.processNode = function (node, from) {
  321. // make sure we catch all errors coming from any handler
  322. // otherwise we can remove the presence handler from strophe
  323. try {
  324. if(this.presHandlers[node.tagName])
  325. this.presHandlers[node.tagName](
  326. node, Strophe.getResourceFromJid(from), from);
  327. } catch (e) {
  328. logger.error('Error processing:' + node.tagName
  329. + ' node.', e);
  330. }
  331. };
  332. ChatRoom.prototype.sendMessage = function (body, nickname) {
  333. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  334. msg.c('body', body).up();
  335. if (nickname) {
  336. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  337. }
  338. this.connection.send(msg);
  339. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  340. };
  341. ChatRoom.prototype.setSubject = function (subject) {
  342. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  343. msg.c('subject', subject);
  344. this.connection.send(msg);
  345. };
  346. ChatRoom.prototype.onParticipantLeft = function (jid) {
  347. delete this.lastPresences[jid];
  348. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  349. this.moderator.onMucMemberLeft(jid);
  350. };
  351. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  352. // room destroyed ?
  353. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  354. '>destroy').length) {
  355. var reason;
  356. var reasonSelect = $(pres).find(
  357. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  358. '>destroy>reason');
  359. if (reasonSelect.length) {
  360. reason = reasonSelect.text();
  361. }
  362. this.leave();
  363. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  364. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  365. return true;
  366. }
  367. // Status code 110 indicates that this notification is "self-presence".
  368. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  369. delete this.members[from];
  370. this.onParticipantLeft(from);
  371. }
  372. // If the status code is 110 this means we're leaving and we would like
  373. // to remove everyone else from our view, so we trigger the event.
  374. else if (Object.keys(this.members).length > 1) {
  375. for (var i in this.members) {
  376. var member = this.members[i];
  377. delete this.members[i];
  378. this.onParticipantLeft(member);
  379. }
  380. }
  381. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  382. if (this.myroomjid === from) {
  383. this.leave();
  384. this.eventEmitter.emit(XMPPEvents.KICKED);
  385. }
  386. }
  387. };
  388. ChatRoom.prototype.onMessage = function (msg, from) {
  389. var nick =
  390. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  391. .text() ||
  392. Strophe.getResourceFromJid(from);
  393. var txt = $(msg).find('>body').text();
  394. var type = msg.getAttribute("type");
  395. if (type == "error") {
  396. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  397. $(msg).find('>text').text(), txt);
  398. return true;
  399. }
  400. var subject = $(msg).find('>subject');
  401. if (subject.length) {
  402. var subjectText = subject.text();
  403. if (subjectText || subjectText === "") {
  404. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  405. logger.log("Subject is changed to " + subjectText);
  406. }
  407. }
  408. // xep-0203 delay
  409. var stamp = $(msg).find('>delay').attr('stamp');
  410. if (!stamp) {
  411. // or xep-0091 delay, UTC timestamp
  412. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  413. if (stamp) {
  414. // the format is CCYYMMDDThh:mm:ss
  415. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  416. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  417. }
  418. }
  419. if (txt) {
  420. logger.log('chat', nick, txt);
  421. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  422. from, nick, txt, this.myroomjid, stamp);
  423. }
  424. };
  425. ChatRoom.prototype.onPresenceError = function (pres, from) {
  426. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  427. logger.log('on password required', from);
  428. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  429. } else if ($(pres).find(
  430. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  431. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  432. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  433. // enter the room by replying with 'not-authorized'. This would
  434. // result in reconnection from authorized domain.
  435. // We're either missing Jicofo/Prosody config for anonymous
  436. // domains or something is wrong.
  437. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  438. } else {
  439. logger.warn('onPresError ', pres);
  440. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  441. }
  442. } else if($(pres).find('>error>service-unavailable').length) {
  443. logger.warn('Maximum users limit for the room has been reached',
  444. pres);
  445. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR, pres);
  446. } else {
  447. logger.warn('onPresError ', pres);
  448. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  449. }
  450. };
  451. ChatRoom.prototype.kick = function (jid) {
  452. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  453. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  454. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  455. .c('reason').t('You have been kicked.').up().up().up();
  456. this.connection.sendIQ(
  457. kickIQ,
  458. function (result) {
  459. logger.log('Kick participant with jid: ', jid, result);
  460. },
  461. function (error) {
  462. logger.log('Kick participant error: ', error);
  463. });
  464. };
  465. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  466. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  467. var ob = this;
  468. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  469. function (res) {
  470. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  471. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  472. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  473. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  474. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  475. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  476. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  477. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  478. ob.connection.sendIQ(formsubmit,
  479. onSuccess,
  480. onError);
  481. } else {
  482. onNotSupported();
  483. }
  484. }, onError);
  485. };
  486. ChatRoom.prototype.addToPresence = function (key, values) {
  487. values.tagName = key;
  488. this.presMap["nodes"].push(values);
  489. };
  490. ChatRoom.prototype.removeFromPresence = function (key) {
  491. for(var i = 0; i < this.presMap.nodes.length; i++)
  492. {
  493. if(key === this.presMap.nodes[i].tagName)
  494. this.presMap.nodes.splice(i, 1);
  495. }
  496. };
  497. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  498. this.presHandlers[name] = handler;
  499. };
  500. ChatRoom.prototype.removePresenceListener = function (name) {
  501. delete this.presHandlers[name];
  502. };
  503. /**
  504. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  505. * focus.
  506. * @param mucJid the full MUC address of the user to be checked.
  507. * @returns {boolean} <tt>true</tt> if MUC user is the conference focus.
  508. */
  509. ChatRoom.prototype.isFocus = function (mucJid) {
  510. var member = this.members[mucJid];
  511. if (member) {
  512. return member.isFocus;
  513. } else {
  514. return null;
  515. }
  516. };
  517. ChatRoom.prototype.isModerator = function () {
  518. return this.role === 'moderator';
  519. };
  520. ChatRoom.prototype.getMemberRole = function (peerJid) {
  521. if (this.members[peerJid]) {
  522. return this.members[peerJid].role;
  523. }
  524. return null;
  525. };
  526. ChatRoom.prototype.setJingleSession = function(session){
  527. this.session = session;
  528. };
  529. ChatRoom.prototype.removeStream = function (stream, callback, ssrcInfo) {
  530. if(!this.session) {
  531. callback();
  532. return;
  533. }
  534. this.session.removeStream(stream, callback, ssrcInfo);
  535. };
  536. /**
  537. * Adds stream.
  538. * @param stream new stream that will be added.
  539. * @param callback callback executed after successful stream addition.
  540. * @param ssrcInfo object with information about the SSRCs associated with the
  541. * stream.
  542. * @param dontModifySources {boolean} if true _modifySources won't be called.
  543. * Used for streams added before the call start.
  544. */
  545. ChatRoom.prototype.addStream = function (stream, callback, ssrcInfo,
  546. dontModifySources) {
  547. if(this.session) {
  548. // FIXME: will block switchInProgress on true value in case of exception
  549. this.session.addStream(stream, callback, ssrcInfo, dontModifySources);
  550. } else {
  551. // We are done immediately
  552. logger.warn("No conference handler or conference not started yet");
  553. callback();
  554. }
  555. };
  556. /**
  557. * Generate ssrc info object for a stream with the following properties:
  558. * - ssrcs - Array of the ssrcs associated with the stream.
  559. * - groups - Array of the groups associated with the stream.
  560. */
  561. ChatRoom.prototype.generateNewStreamSSRCInfo = function () {
  562. if(!this.session) {
  563. logger.warn("The call haven't been started. " +
  564. "Cannot generate ssrc info at the moment!");
  565. return null;
  566. }
  567. return this.session.generateNewStreamSSRCInfo();
  568. };
  569. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  570. this.sendVideoInfoPresence(mute);
  571. if(callback)
  572. callback(mute);
  573. };
  574. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  575. return this.sendAudioInfoPresence(mute, callback);
  576. };
  577. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  578. this.removeFromPresence("audiomuted");
  579. this.addToPresence("audiomuted",
  580. {attributes:
  581. {"xmlns": "http://jitsi.org/jitmeet/audio"},
  582. value: mute.toString()});
  583. };
  584. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  585. this.addAudioInfoToPresence(mute);
  586. if(this.connection) {
  587. this.sendPresence();
  588. }
  589. if(callback)
  590. callback();
  591. };
  592. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  593. this.removeFromPresence("videomuted");
  594. this.addToPresence("videomuted",
  595. {attributes:
  596. {"xmlns": "http://jitsi.org/jitmeet/video"},
  597. value: mute.toString()});
  598. };
  599. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  600. this.addVideoInfoToPresence(mute);
  601. if(!this.connection)
  602. return;
  603. this.sendPresence();
  604. };
  605. ChatRoom.prototype.addListener = function(type, listener) {
  606. this.eventEmitter.on(type, listener);
  607. };
  608. ChatRoom.prototype.removeListener = function (type, listener) {
  609. this.eventEmitter.removeListener(type, listener);
  610. };
  611. ChatRoom.prototype.remoteTrackAdded = function(data) {
  612. // Will figure out current muted status by looking up owner's presence
  613. var pres = this.lastPresences[data.owner];
  614. var mediaType = data.mediaType;
  615. if(pres) {
  616. var mutedNode = null;
  617. if (mediaType === MediaType.AUDIO) {
  618. mutedNode = filterNodeFromPresenceJSON(pres, "audiomuted");
  619. } else if (mediaType === MediaType.VIDEO) {
  620. mutedNode = filterNodeFromPresenceJSON(pres, "videomuted");
  621. } else {
  622. logger.warn("Unsupported media type: " + mediaType);
  623. data.muted= null;
  624. }
  625. if (mutedNode) {
  626. data.muted = !!(mutedNode.length > 0 &&
  627. mutedNode[0] && mutedNode[0]["value"] === "true");
  628. }
  629. }
  630. this.eventEmitter.emit(XMPPEvents.REMOTE_TRACK_ADDED, data);
  631. };
  632. /**
  633. * Returns true if the recording is supproted and false if not.
  634. */
  635. ChatRoom.prototype.isRecordingSupported = function () {
  636. if(this.recording)
  637. return this.recording.isSupported();
  638. return false;
  639. };
  640. /**
  641. * Returns null if the recording is not supported, "on" if the recording started
  642. * and "off" if the recording is not started.
  643. */
  644. ChatRoom.prototype.getRecordingState = function () {
  645. if(this.recording)
  646. return this.recording.getState();
  647. return "off";
  648. };
  649. /**
  650. * Returns the url of the recorded video.
  651. */
  652. ChatRoom.prototype.getRecordingURL = function () {
  653. if(this.recording)
  654. return this.recording.getURL();
  655. return null;
  656. };
  657. /**
  658. * Starts/stops the recording
  659. * @param token token for authentication
  660. * @param statusChangeHandler {function} receives the new status as argument.
  661. */
  662. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  663. if(this.recording)
  664. return this.recording.toggleRecording(options, statusChangeHandler);
  665. return statusChangeHandler("error",
  666. new Error("The conference is not created yet!"));
  667. };
  668. /**
  669. * Returns true if the SIP calls are supported and false otherwise
  670. */
  671. ChatRoom.prototype.isSIPCallingSupported = function () {
  672. if(this.moderator)
  673. return this.moderator.isSipGatewayEnabled();
  674. return false;
  675. };
  676. /**
  677. * Dials a number.
  678. * @param number the number
  679. */
  680. ChatRoom.prototype.dial = function (number) {
  681. return this.connection.rayo.dial(number, "fromnumber",
  682. Strophe.getNodeFromJid(this.myroomjid), this.password,
  683. this.focusMucJid);
  684. };
  685. /**
  686. * Hangup an existing call
  687. */
  688. ChatRoom.prototype.hangup = function () {
  689. return this.connection.rayo.hangup();
  690. };
  691. /**
  692. * Returns the phone number for joining the conference.
  693. */
  694. ChatRoom.prototype.getPhoneNumber = function () {
  695. return this.phoneNumber;
  696. };
  697. /**
  698. * Returns the pin for joining the conference with phone.
  699. */
  700. ChatRoom.prototype.getPhonePin = function () {
  701. return this.phonePin;
  702. };
  703. /**
  704. * Returns the connection state for the current session.
  705. */
  706. ChatRoom.prototype.getConnectionState = function () {
  707. if(!this.session)
  708. return null;
  709. return this.session.getIceConnectionState();
  710. };
  711. /**
  712. * Mutes remote participant.
  713. * @param jid of the participant
  714. * @param mute
  715. */
  716. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  717. logger.info("set mute", mute);
  718. var iqToFocus = $iq(
  719. {to: this.focusMucJid, type: 'set'})
  720. .c('mute', {
  721. xmlns: 'http://jitsi.org/jitmeet/audio',
  722. jid: jid
  723. })
  724. .t(mute.toString())
  725. .up();
  726. this.connection.sendIQ(
  727. iqToFocus,
  728. function (result) {
  729. logger.log('set mute', result);
  730. },
  731. function (error) {
  732. logger.log('set mute error', error);
  733. });
  734. };
  735. ChatRoom.prototype.onMute = function (iq) {
  736. var from = iq.getAttribute('from');
  737. if (from !== this.focusMucJid) {
  738. logger.warn("Ignored mute from non focus peer");
  739. return false;
  740. }
  741. var mute = $(iq).find('mute');
  742. if (mute.length) {
  743. var doMuteAudio = mute.text() === "true";
  744. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  745. }
  746. return true;
  747. };
  748. /**
  749. * Leaves the room. Closes the jingle session.
  750. */
  751. ChatRoom.prototype.leave = function () {
  752. if (this.session) {
  753. this.session.close();
  754. }
  755. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  756. this.doLeave();
  757. this.connection.emuc.doLeave(this.roomjid);
  758. };
  759. module.exports = ChatRoom;