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 Strophe, $, $pres, $iq, $msg */
  2. import {getLogger} from "jitsi-meet-logger";
  3. const logger = getLogger(__filename);
  4. import Listenable from "../util/Listenable";
  5. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6. var MediaType = require("../../service/RTC/MediaType");
  7. var Moderator = require("./moderator");
  8. var Recorder = require("./recording");
  9. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  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. /**
  382. * Makes the underlying JingleSession generate new SSRC for the recvonly
  383. * video stream.
  384. * @deprecated
  385. */
  386. generateRecvonlySsrc() {
  387. if (this.session) {
  388. this.session.generateRecvonlySsrc();
  389. } else {
  390. logger.warn("Unable to generate recvonly SSRC - no session");
  391. }
  392. }
  393. processNode (node, from) {
  394. // make sure we catch all errors coming from any handler
  395. // otherwise we can remove the presence handler from strophe
  396. try {
  397. var tagHandler = this.presHandlers[node.tagName];
  398. if (node.tagName.startsWith("jitsi_participant_")) {
  399. tagHandler = this.participantPropertyListener;
  400. }
  401. if(tagHandler) {
  402. tagHandler(node, Strophe.getResourceFromJid(from), from);
  403. }
  404. } catch (e) {
  405. GlobalOnErrorHandler.callErrorHandler(e);
  406. logger.error('Error processing:' + node.tagName + ' node.', e);
  407. }
  408. }
  409. sendMessage (body, nickname) {
  410. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  411. msg.c('body', body).up();
  412. if (nickname) {
  413. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  414. }
  415. this.connection.send(msg);
  416. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  417. }
  418. setSubject (subject) {
  419. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  420. msg.c('subject', subject);
  421. this.connection.send(msg);
  422. }
  423. /**
  424. * Called when participant leaves.
  425. * @param jid the jid of the participant that leaves
  426. * @param skipEvents optional params to skip any events, including check
  427. * whether this is the focus that left
  428. */
  429. onParticipantLeft (jid, skipEvents) {
  430. delete this.lastPresences[jid];
  431. if(skipEvents)
  432. return;
  433. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  434. this.moderator.onMucMemberLeft(jid);
  435. }
  436. onPresenceUnavailable (pres, from) {
  437. // room destroyed ?
  438. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  439. '>destroy').length) {
  440. var reason;
  441. var reasonSelect = $(pres).find(
  442. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  443. '>destroy>reason');
  444. if (reasonSelect.length) {
  445. reason = reasonSelect.text();
  446. }
  447. this._dispose();
  448. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  449. this.connection.emuc.doLeave(this.roomjid);
  450. return true;
  451. }
  452. // Status code 110 indicates that this notification is "self-presence".
  453. var isSelfPresence = $(pres).find(
  454. '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]'
  455. ).length !== 0;
  456. var isKick = $(pres).find(
  457. '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]'
  458. ).length !== 0;
  459. if (!isSelfPresence) {
  460. delete this.members[from];
  461. this.onParticipantLeft(from, false);
  462. }
  463. // If the status code is 110 this means we're leaving and we would like
  464. // to remove everyone else from our view, so we trigger the event.
  465. else if (Object.keys(this.members).length > 0) {
  466. for (const i in this.members) {
  467. const member = this.members[i];
  468. delete this.members[i];
  469. this.onParticipantLeft(i, member.isFocus);
  470. }
  471. this.connection.emuc.doLeave(this.roomjid);
  472. // we fire muc_left only if this is not a kick,
  473. // kick has both statuses 110 and 307.
  474. if (!isKick)
  475. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  476. }
  477. if (isKick && this.myroomjid === from) {
  478. this._dispose();
  479. this.eventEmitter.emit(XMPPEvents.KICKED);
  480. }
  481. }
  482. onMessage (msg, from) {
  483. var nick =
  484. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  485. .text() ||
  486. Strophe.getResourceFromJid(from);
  487. var txt = $(msg).find('>body').text();
  488. var type = msg.getAttribute("type");
  489. if (type == "error") {
  490. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  491. $(msg).find('>text').text(), txt);
  492. return true;
  493. }
  494. var subject = $(msg).find('>subject');
  495. if (subject.length) {
  496. var subjectText = subject.text();
  497. if (subjectText || subjectText === "") {
  498. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  499. logger.log("Subject is changed to " + subjectText);
  500. }
  501. }
  502. // xep-0203 delay
  503. var stamp = $(msg).find('>delay').attr('stamp');
  504. if (!stamp) {
  505. // or xep-0091 delay, UTC timestamp
  506. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  507. if (stamp) {
  508. // the format is CCYYMMDDThh:mm:ss
  509. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  510. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  511. }
  512. }
  513. if (from==this.roomjid && $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  514. this.discoRoomInfo();
  515. }
  516. if (txt) {
  517. logger.log('chat', nick, txt);
  518. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  519. from, nick, txt, this.myroomjid, stamp);
  520. }
  521. }
  522. onPresenceError (pres, from) {
  523. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  524. logger.log('on password required', from);
  525. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  526. } else if ($(pres).find(
  527. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  528. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  529. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  530. // enter the room by replying with 'not-authorized'. This would
  531. // result in reconnection from authorized domain.
  532. // We're either missing Jicofo/Prosody config for anonymous
  533. // domains or something is wrong.
  534. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  535. } else {
  536. logger.warn('onPresError ', pres);
  537. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  538. }
  539. } else if($(pres).find('>error>service-unavailable').length) {
  540. logger.warn('Maximum users limit for the room has been reached',
  541. pres);
  542. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  543. } else {
  544. logger.warn('onPresError ', pres);
  545. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  546. }
  547. }
  548. kick (jid) {
  549. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  550. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  551. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  552. .c('reason').t('You have been kicked.').up().up().up();
  553. this.connection.sendIQ(
  554. kickIQ,
  555. function (result) {
  556. logger.log('Kick participant with jid: ', jid, result);
  557. },
  558. function (error) {
  559. logger.log('Kick participant error: ', error);
  560. });
  561. }
  562. lockRoom (key, onSuccess, onError, onNotSupported) {
  563. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  564. var ob = this;
  565. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  566. function (res) {
  567. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  568. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  569. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  570. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  571. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  572. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  573. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  574. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  575. ob.connection.sendIQ(formsubmit,
  576. onSuccess,
  577. onError);
  578. } else {
  579. onNotSupported();
  580. }
  581. }, onError);
  582. }
  583. addToPresence (key, values) {
  584. values.tagName = key;
  585. this.removeFromPresence(key);
  586. this.presMap.nodes.push(values);
  587. }
  588. removeFromPresence (key) {
  589. var nodes = this.presMap.nodes.filter(function(node) {
  590. return key !== node.tagName;});
  591. this.presMap.nodes = nodes;
  592. }
  593. addPresenceListener (name, handler) {
  594. this.presHandlers[name] = handler;
  595. }
  596. removePresenceListener (name) {
  597. delete this.presHandlers[name];
  598. }
  599. /**
  600. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  601. * focus.
  602. * @param mucJid the full MUC address of the user to be checked.
  603. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus or
  604. * <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  605. * the MUC then <tt>null</tt> is returned.
  606. */
  607. isFocus (mucJid) {
  608. var member = this.members[mucJid];
  609. if (member) {
  610. return member.isFocus;
  611. } else {
  612. return null;
  613. }
  614. }
  615. isModerator () {
  616. return this.role === 'moderator';
  617. }
  618. getMemberRole (peerJid) {
  619. if (this.members[peerJid]) {
  620. return this.members[peerJid].role;
  621. }
  622. return null;
  623. }
  624. setVideoMute (mute, callback) {
  625. this.sendVideoInfoPresence(mute);
  626. if(callback)
  627. callback(mute);
  628. }
  629. setAudioMute (mute, callback) {
  630. return this.sendAudioInfoPresence(mute, callback);
  631. }
  632. addAudioInfoToPresence (mute) {
  633. this.removeFromPresence("audiomuted");
  634. this.addToPresence("audiomuted",
  635. {attributes:
  636. {"xmlns": "http://jitsi.org/jitmeet/audio"},
  637. value: mute.toString()});
  638. }
  639. sendAudioInfoPresence (mute, callback) {
  640. this.addAudioInfoToPresence(mute);
  641. if(this.connection) {
  642. this.sendPresence();
  643. }
  644. if(callback)
  645. callback();
  646. }
  647. addVideoInfoToPresence (mute) {
  648. this.removeFromPresence("videomuted");
  649. this.addToPresence("videomuted",
  650. {attributes:
  651. {"xmlns": "http://jitsi.org/jitmeet/video"},
  652. value: mute.toString()});
  653. }
  654. sendVideoInfoPresence (mute) {
  655. this.addVideoInfoToPresence(mute);
  656. if(!this.connection)
  657. return;
  658. this.sendPresence();
  659. }
  660. remoteTrackAdded (data) {
  661. // Will figure out current muted status by looking up owner's presence
  662. var pres = this.lastPresences[data.owner];
  663. if(pres) {
  664. var mediaType = data.mediaType;
  665. var mutedNode = null;
  666. if (mediaType === MediaType.AUDIO) {
  667. mutedNode = filterNodeFromPresenceJSON(pres, "audiomuted");
  668. } else if (mediaType === MediaType.VIDEO) {
  669. mutedNode = filterNodeFromPresenceJSON(pres, "videomuted");
  670. var videoTypeNode = filterNodeFromPresenceJSON(pres, "videoType");
  671. if(videoTypeNode
  672. && videoTypeNode.length > 0
  673. && videoTypeNode[0])
  674. data.videoType = videoTypeNode[0]["value"];
  675. } else {
  676. logger.warn("Unsupported media type: " + mediaType);
  677. data.muted = null;
  678. }
  679. if (mutedNode) {
  680. data.muted = mutedNode.length > 0 &&
  681. mutedNode[0] &&
  682. mutedNode[0]["value"] === "true";
  683. }
  684. }
  685. this.eventEmitter.emit(XMPPEvents.REMOTE_TRACK_ADDED, data);
  686. }
  687. /**
  688. * Returns true if the recording is supproted and false if not.
  689. */
  690. isRecordingSupported () {
  691. if(this.recording)
  692. return this.recording.isSupported();
  693. return false;
  694. }
  695. /**
  696. * Returns null if the recording is not supported, "on" if the recording started
  697. * and "off" if the recording is not started.
  698. */
  699. getRecordingState () {
  700. return (this.recording) ? this.recording.getState() : undefined;
  701. }
  702. /**
  703. * Returns the url of the recorded video.
  704. */
  705. getRecordingURL () {
  706. return (this.recording) ? this.recording.getURL() : null;
  707. }
  708. /**
  709. * Starts/stops the recording
  710. * @param token token for authentication
  711. * @param statusChangeHandler {function} receives the new status as argument.
  712. */
  713. toggleRecording (options, statusChangeHandler) {
  714. if(this.recording)
  715. return this.recording.toggleRecording(options, statusChangeHandler);
  716. return statusChangeHandler("error",
  717. new Error("The conference is not created yet!"));
  718. }
  719. /**
  720. * Returns true if the SIP calls are supported and false otherwise
  721. */
  722. isSIPCallingSupported () {
  723. if(this.moderator)
  724. return this.moderator.isSipGatewayEnabled();
  725. return false;
  726. }
  727. /**
  728. * Dials a number.
  729. * @param number the number
  730. */
  731. dial (number) {
  732. return this.connection.rayo.dial(number, "fromnumber",
  733. Strophe.getNodeFromJid(this.myroomjid), this.password,
  734. this.focusMucJid);
  735. }
  736. /**
  737. * Hangup an existing call
  738. */
  739. hangup () {
  740. return this.connection.rayo.hangup();
  741. }
  742. /**
  743. * Returns the phone number for joining the conference.
  744. */
  745. getPhoneNumber () {
  746. return this.phoneNumber;
  747. }
  748. /**
  749. * Returns the pin for joining the conference with phone.
  750. */
  751. getPhonePin () {
  752. return this.phonePin;
  753. }
  754. /**
  755. * Mutes remote participant.
  756. * @param jid of the participant
  757. * @param mute
  758. */
  759. muteParticipant (jid, mute) {
  760. logger.info("set mute", mute);
  761. var iqToFocus = $iq(
  762. {to: this.focusMucJid, type: 'set'})
  763. .c('mute', {
  764. xmlns: 'http://jitsi.org/jitmeet/audio',
  765. jid: jid
  766. })
  767. .t(mute.toString())
  768. .up();
  769. this.connection.sendIQ(
  770. iqToFocus,
  771. function (result) {
  772. logger.log('set mute', result);
  773. },
  774. function (error) {
  775. logger.log('set mute error', error);
  776. });
  777. }
  778. onMute (iq) {
  779. var from = iq.getAttribute('from');
  780. if (from !== this.focusMucJid) {
  781. logger.warn("Ignored mute from non focus peer");
  782. return false;
  783. }
  784. var mute = $(iq).find('mute');
  785. if (mute.length) {
  786. var doMuteAudio = mute.text() === "true";
  787. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  788. }
  789. return true;
  790. }
  791. /**
  792. * Leaves the room. Closes the jingle session.
  793. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received less
  794. * than 5s after sending presence unavailable. Otherwise the promise is
  795. * rejected.
  796. */
  797. leave () {
  798. return new Promise((resolve, reject) => {
  799. let timeout = setTimeout(() => onMucLeft(true), 5000);
  800. let eventEmitter = this.eventEmitter;
  801. function onMucLeft(doReject = false) {
  802. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  803. clearTimeout(timeout);
  804. if(doReject) {
  805. // the timeout expired
  806. reject(new Error("The timeout for the confirmation about " +
  807. "leaving the room expired."));
  808. } else {
  809. resolve();
  810. }
  811. }
  812. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  813. this.doLeave();
  814. });
  815. }
  816. }