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

ChatRoom.js 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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 = null;
  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. var newRole = member.affiliation == "owner"? member.role : "none";
  241. if (this.role !== newRole) {
  242. this.role = newRole;
  243. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  244. }
  245. if (!this.joined) {
  246. this.joined = true;
  247. var now = this.connectionTimes["muc.joined"] =
  248. window.performance.now();
  249. logger.log("(TIME) MUC joined:\t", now);
  250. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  251. }
  252. } else if (this.members[from] === undefined) {
  253. // new participant
  254. this.members[from] = member;
  255. logger.log('entered', from, member);
  256. if (member.isFocus) {
  257. this.focusMucJid = from;
  258. if(!this.recording) {
  259. this.recording = new Recorder(this.options.recordingType,
  260. this.eventEmitter, this.connection, this.focusMucJid,
  261. this.options.jirecon, this.roomjid);
  262. if(this.lastJibri)
  263. this.recording.handleJibriPresence(this.lastJibri);
  264. }
  265. logger.info("Ignore focus: " + from + ", real JID: " + jid);
  266. }
  267. else {
  268. this.eventEmitter.emit(
  269. XMPPEvents.MUC_MEMBER_JOINED,
  270. from, member.nick, member.role, member.isHiddenDomain);
  271. }
  272. } else {
  273. // Presence update for existing participant
  274. // Watch role change:
  275. var memberOfThis = this.members[from];
  276. if (memberOfThis.role != member.role) {
  277. memberOfThis.role = member.role;
  278. this.eventEmitter.emit(
  279. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  280. }
  281. // store the new display name
  282. if(member.displayName)
  283. memberOfThis.displayName = member.displayName;
  284. }
  285. // after we had fired member or room joined events, lets fire events
  286. // for the rest info we got in presence
  287. for(var i = 0; i < nodes.length; i++)
  288. {
  289. var node = nodes[i];
  290. switch(node.tagName)
  291. {
  292. case "nick":
  293. if(!member.isFocus) {
  294. var displayName = this.xmpp.options.displayJids
  295. ? Strophe.getResourceFromJid(from) : member.nick;
  296. if (displayName && displayName.length > 0) {
  297. this.eventEmitter.emit(
  298. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  299. }
  300. }
  301. break;
  302. case "bridgeIsDown":
  303. if (member.isFocus && !this.bridgeIsDown) {
  304. this.bridgeIsDown = true;
  305. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  306. }
  307. break;
  308. case "jibri-recording-status":
  309. var jibri = node;
  310. break;
  311. case "call-control":
  312. var att = node.attributes;
  313. if(!att)
  314. break;
  315. this.phoneNumber = att.phone || null;
  316. this.phonePin = att.pin || null;
  317. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  318. break;
  319. default:
  320. this.processNode(node, from);
  321. }
  322. }
  323. // Trigger status message update
  324. if (member.status) {
  325. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member.status);
  326. }
  327. if(jibri)
  328. {
  329. this.lastJibri = jibri;
  330. if(this.recording)
  331. this.recording.handleJibriPresence(jibri);
  332. }
  333. };
  334. /**
  335. * Sets the special listener to be used for "command"s whose name starts with
  336. * "jitsi_participant_".
  337. */
  338. ChatRoom.prototype.setParticipantPropertyListener = function (listener) {
  339. this.participantPropertyListener = listener;
  340. };
  341. ChatRoom.prototype.processNode = function (node, from) {
  342. // make sure we catch all errors coming from any handler
  343. // otherwise we can remove the presence handler from strophe
  344. try {
  345. var tagHandler = this.presHandlers[node.tagName];
  346. if (node.tagName.startsWith("jitsi_participant_")) {
  347. tagHandler = this.participantPropertyListener;
  348. }
  349. if(tagHandler) {
  350. tagHandler(node, Strophe.getResourceFromJid(from), from);
  351. }
  352. } catch (e) {
  353. GlobalOnErrorHandler.callErrorHandler(e);
  354. logger.error('Error processing:' + node.tagName + ' node.', e);
  355. }
  356. };
  357. ChatRoom.prototype.sendMessage = function (body, nickname) {
  358. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  359. msg.c('body', body).up();
  360. if (nickname) {
  361. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  362. }
  363. this.connection.send(msg);
  364. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  365. };
  366. ChatRoom.prototype.setSubject = function (subject) {
  367. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  368. msg.c('subject', subject);
  369. this.connection.send(msg);
  370. };
  371. ChatRoom.prototype.onParticipantLeft = function (jid) {
  372. delete this.lastPresences[jid];
  373. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  374. this.moderator.onMucMemberLeft(jid);
  375. };
  376. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  377. // room destroyed ?
  378. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  379. '>destroy').length) {
  380. var reason;
  381. var reasonSelect = $(pres).find(
  382. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  383. '>destroy>reason');
  384. if (reasonSelect.length) {
  385. reason = reasonSelect.text();
  386. }
  387. this.leave();
  388. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  389. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  390. return true;
  391. }
  392. // Status code 110 indicates that this notification is "self-presence".
  393. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  394. delete this.members[from];
  395. this.onParticipantLeft(from);
  396. }
  397. // If the status code is 110 this means we're leaving and we would like
  398. // to remove everyone else from our view, so we trigger the event.
  399. else if (Object.keys(this.members).length > 1) {
  400. for (var i in this.members) {
  401. var member = this.members[i];
  402. delete this.members[i];
  403. this.onParticipantLeft(member);
  404. }
  405. }
  406. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  407. if (this.myroomjid === from) {
  408. this.leave();
  409. this.eventEmitter.emit(XMPPEvents.KICKED);
  410. }
  411. }
  412. };
  413. ChatRoom.prototype.onMessage = function (msg, from) {
  414. var nick =
  415. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  416. .text() ||
  417. Strophe.getResourceFromJid(from);
  418. var txt = $(msg).find('>body').text();
  419. var type = msg.getAttribute("type");
  420. if (type == "error") {
  421. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  422. $(msg).find('>text').text(), txt);
  423. return true;
  424. }
  425. var subject = $(msg).find('>subject');
  426. if (subject.length) {
  427. var subjectText = subject.text();
  428. if (subjectText || subjectText === "") {
  429. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  430. logger.log("Subject is changed to " + subjectText);
  431. }
  432. }
  433. // xep-0203 delay
  434. var stamp = $(msg).find('>delay').attr('stamp');
  435. if (!stamp) {
  436. // or xep-0091 delay, UTC timestamp
  437. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  438. if (stamp) {
  439. // the format is CCYYMMDDThh:mm:ss
  440. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  441. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  442. }
  443. }
  444. if (txt) {
  445. logger.log('chat', nick, txt);
  446. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  447. from, nick, txt, this.myroomjid, stamp);
  448. }
  449. };
  450. ChatRoom.prototype.onPresenceError = function (pres, from) {
  451. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  452. logger.log('on password required', from);
  453. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  454. } else if ($(pres).find(
  455. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  456. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  457. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  458. // enter the room by replying with 'not-authorized'. This would
  459. // result in reconnection from authorized domain.
  460. // We're either missing Jicofo/Prosody config for anonymous
  461. // domains or something is wrong.
  462. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  463. } else {
  464. logger.warn('onPresError ', pres);
  465. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  466. }
  467. } else if($(pres).find('>error>service-unavailable').length) {
  468. logger.warn('Maximum users limit for the room has been reached',
  469. pres);
  470. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR, pres);
  471. } else {
  472. logger.warn('onPresError ', pres);
  473. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  474. }
  475. };
  476. ChatRoom.prototype.kick = function (jid) {
  477. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  478. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  479. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  480. .c('reason').t('You have been kicked.').up().up().up();
  481. this.connection.sendIQ(
  482. kickIQ,
  483. function (result) {
  484. logger.log('Kick participant with jid: ', jid, result);
  485. },
  486. function (error) {
  487. logger.log('Kick participant error: ', error);
  488. });
  489. };
  490. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  491. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  492. var ob = this;
  493. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  494. function (res) {
  495. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  496. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  497. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  498. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  499. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  500. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  501. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  502. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  503. ob.connection.sendIQ(formsubmit,
  504. onSuccess,
  505. onError);
  506. } else {
  507. onNotSupported();
  508. }
  509. }, onError);
  510. };
  511. ChatRoom.prototype.addToPresence = function (key, values) {
  512. values.tagName = key;
  513. this.removeFromPresence(key);
  514. this.presMap.nodes.push(values);
  515. };
  516. ChatRoom.prototype.removeFromPresence = function (key) {
  517. var nodes = this.presMap.nodes.filter(function(node) {
  518. return key !== node.tagName;});
  519. this.presMap.nodes = nodes;
  520. };
  521. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  522. this.presHandlers[name] = handler;
  523. };
  524. ChatRoom.prototype.removePresenceListener = function (name) {
  525. delete this.presHandlers[name];
  526. };
  527. /**
  528. * Exports the current state of the ChatRoom instance.
  529. * @returns {object}
  530. */
  531. ChatRoom.prototype.exportState = function () {
  532. return {
  533. presHandlers: this.presHandlers,
  534. presMapNodes: this.presMap.nodes
  535. }
  536. }
  537. /**
  538. * Loads previously exported state object from ChatRoom instance into current
  539. * ChatRoom instance.
  540. * @param state {object} the state received by ChatRoom.exportState method.
  541. */
  542. ChatRoom.prototype.loadState = function (state) {
  543. if(!state || !state.presHandlers || !state.presMapNodes)
  544. throw new Error("Invalid state object passed");
  545. this.presHandlers = state.presHandlers;
  546. this.presMap.nodes = state.presMapNodes;
  547. }
  548. /**
  549. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  550. * focus.
  551. * @param mucJid the full MUC address of the user to be checked.
  552. * @returns {boolean} <tt>true</tt> if MUC user is the conference focus.
  553. */
  554. ChatRoom.prototype.isFocus = function (mucJid) {
  555. var member = this.members[mucJid];
  556. if (member) {
  557. return member.isFocus;
  558. } else {
  559. return null;
  560. }
  561. };
  562. ChatRoom.prototype.isModerator = function () {
  563. return this.role === 'moderator';
  564. };
  565. ChatRoom.prototype.getMemberRole = function (peerJid) {
  566. if (this.members[peerJid]) {
  567. return this.members[peerJid].role;
  568. }
  569. return null;
  570. };
  571. ChatRoom.prototype.setJingleSession = function(session){
  572. this.session = session;
  573. };
  574. /**
  575. * Remove stream.
  576. * @param stream stream that will be removed.
  577. * @param callback callback executed after successful stream removal.
  578. * @param errorCallback callback executed if stream removal fail.
  579. * @param ssrcInfo object with information about the SSRCs associated with the
  580. * stream.
  581. */
  582. ChatRoom.prototype.removeStream = function (stream, callback, errorCallback,
  583. ssrcInfo) {
  584. if(!this.session) {
  585. callback();
  586. return;
  587. }
  588. this.session.removeStream(stream, callback, errorCallback, ssrcInfo);
  589. };
  590. /**
  591. * Adds stream.
  592. * @param stream new stream that will be added.
  593. * @param callback callback executed after successful stream addition.
  594. * @param errorCallback callback executed if stream addition fail.
  595. * @param ssrcInfo object with information about the SSRCs associated with the
  596. * stream.
  597. * @param dontModifySources {boolean} if true _modifySources won't be called.
  598. * Used for streams added before the call start.
  599. */
  600. ChatRoom.prototype.addStream = function (stream, callback, errorCallback,
  601. ssrcInfo, dontModifySources) {
  602. if(this.session) {
  603. // FIXME: will block switchInProgress on true value in case of exception
  604. this.session.addStream(stream, callback, errorCallback, ssrcInfo,
  605. dontModifySources);
  606. } else {
  607. // We are done immediately
  608. logger.warn("No conference handler or conference not started yet");
  609. callback();
  610. }
  611. };
  612. /**
  613. * Generate ssrc info object for a stream with the following properties:
  614. * - ssrcs - Array of the ssrcs associated with the stream.
  615. * - groups - Array of the groups associated with the stream.
  616. */
  617. ChatRoom.prototype.generateNewStreamSSRCInfo = function () {
  618. if(!this.session) {
  619. logger.warn("The call haven't been started. " +
  620. "Cannot generate ssrc info at the moment!");
  621. return null;
  622. }
  623. return this.session.generateNewStreamSSRCInfo();
  624. };
  625. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  626. this.sendVideoInfoPresence(mute);
  627. if(callback)
  628. callback(mute);
  629. };
  630. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  631. return this.sendAudioInfoPresence(mute, callback);
  632. };
  633. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  634. this.removeFromPresence("audiomuted");
  635. this.addToPresence("audiomuted",
  636. {attributes:
  637. {"xmlns": "http://jitsi.org/jitmeet/audio"},
  638. value: mute.toString()});
  639. };
  640. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  641. this.addAudioInfoToPresence(mute);
  642. if(this.connection) {
  643. this.sendPresence();
  644. }
  645. if(callback)
  646. callback();
  647. };
  648. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  649. this.removeFromPresence("videomuted");
  650. this.addToPresence("videomuted",
  651. {attributes:
  652. {"xmlns": "http://jitsi.org/jitmeet/video"},
  653. value: mute.toString()});
  654. };
  655. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  656. this.addVideoInfoToPresence(mute);
  657. if(!this.connection)
  658. return;
  659. this.sendPresence();
  660. };
  661. ChatRoom.prototype.addListener = function(type, listener) {
  662. this.eventEmitter.on(type, listener);
  663. };
  664. ChatRoom.prototype.removeListener = function (type, listener) {
  665. this.eventEmitter.removeListener(type, listener);
  666. };
  667. ChatRoom.prototype.remoteTrackAdded = function(data) {
  668. // Will figure out current muted status by looking up owner's presence
  669. var pres = this.lastPresences[data.owner];
  670. if(pres) {
  671. var mediaType = data.mediaType;
  672. var mutedNode = null;
  673. if (mediaType === MediaType.AUDIO) {
  674. mutedNode = filterNodeFromPresenceJSON(pres, "audiomuted");
  675. } else if (mediaType === MediaType.VIDEO) {
  676. mutedNode = filterNodeFromPresenceJSON(pres, "videomuted");
  677. } else {
  678. logger.warn("Unsupported media type: " + mediaType);
  679. data.muted = null;
  680. }
  681. if (mutedNode) {
  682. data.muted = mutedNode.length > 0 &&
  683. mutedNode[0] &&
  684. mutedNode[0]["value"] === "true";
  685. }
  686. }
  687. this.eventEmitter.emit(XMPPEvents.REMOTE_TRACK_ADDED, data);
  688. };
  689. /**
  690. * Returns true if the recording is supproted and false if not.
  691. */
  692. ChatRoom.prototype.isRecordingSupported = function () {
  693. if(this.recording)
  694. return this.recording.isSupported();
  695. return false;
  696. };
  697. /**
  698. * Returns null if the recording is not supported, "on" if the recording started
  699. * and "off" if the recording is not started.
  700. */
  701. ChatRoom.prototype.getRecordingState = function () {
  702. return (this.recording) ? this.recording.getState() : undefined;
  703. }
  704. /**
  705. * Returns the url of the recorded video.
  706. */
  707. ChatRoom.prototype.getRecordingURL = function () {
  708. return (this.recording) ? this.recording.getURL() : null;
  709. }
  710. /**
  711. * Starts/stops the recording
  712. * @param token token for authentication
  713. * @param statusChangeHandler {function} receives the new status as argument.
  714. */
  715. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  716. if(this.recording)
  717. return this.recording.toggleRecording(options, statusChangeHandler);
  718. return statusChangeHandler("error",
  719. new Error("The conference is not created yet!"));
  720. };
  721. /**
  722. * Returns true if the SIP calls are supported and false otherwise
  723. */
  724. ChatRoom.prototype.isSIPCallingSupported = function () {
  725. if(this.moderator)
  726. return this.moderator.isSipGatewayEnabled();
  727. return false;
  728. };
  729. /**
  730. * Dials a number.
  731. * @param number the number
  732. */
  733. ChatRoom.prototype.dial = function (number) {
  734. return this.connection.rayo.dial(number, "fromnumber",
  735. Strophe.getNodeFromJid(this.myroomjid), this.password,
  736. this.focusMucJid);
  737. };
  738. /**
  739. * Hangup an existing call
  740. */
  741. ChatRoom.prototype.hangup = function () {
  742. return this.connection.rayo.hangup();
  743. };
  744. /**
  745. * Returns the phone number for joining the conference.
  746. */
  747. ChatRoom.prototype.getPhoneNumber = function () {
  748. return this.phoneNumber;
  749. };
  750. /**
  751. * Returns the pin for joining the conference with phone.
  752. */
  753. ChatRoom.prototype.getPhonePin = function () {
  754. return this.phonePin;
  755. };
  756. /**
  757. * Returns the connection state for the current session.
  758. */
  759. ChatRoom.prototype.getConnectionState = function () {
  760. if(!this.session)
  761. return null;
  762. return this.session.getIceConnectionState();
  763. };
  764. /**
  765. * Mutes remote participant.
  766. * @param jid of the participant
  767. * @param mute
  768. */
  769. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  770. logger.info("set mute", mute);
  771. var iqToFocus = $iq(
  772. {to: this.focusMucJid, type: 'set'})
  773. .c('mute', {
  774. xmlns: 'http://jitsi.org/jitmeet/audio',
  775. jid: jid
  776. })
  777. .t(mute.toString())
  778. .up();
  779. this.connection.sendIQ(
  780. iqToFocus,
  781. function (result) {
  782. logger.log('set mute', result);
  783. },
  784. function (error) {
  785. logger.log('set mute error', error);
  786. });
  787. };
  788. ChatRoom.prototype.onMute = function (iq) {
  789. var from = iq.getAttribute('from');
  790. if (from !== this.focusMucJid) {
  791. logger.warn("Ignored mute from non focus peer");
  792. return false;
  793. }
  794. var mute = $(iq).find('mute');
  795. if (mute.length) {
  796. var doMuteAudio = mute.text() === "true";
  797. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  798. }
  799. return true;
  800. };
  801. /**
  802. * Leaves the room. Closes the jingle session.
  803. */
  804. ChatRoom.prototype.leave = function () {
  805. if (this.session) {
  806. this.session.close();
  807. }
  808. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  809. this.doLeave();
  810. this.connection.emuc.doLeave(this.roomjid);
  811. };
  812. module.exports = ChatRoom;