You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 32KB

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