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

ChatRoom.js 32KB

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