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