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

ChatRoom.js 30KB

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