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

ChatRoom.js 32KB

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