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

ChatRoom.js 29KB

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