Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ChatRoom.js 35KB

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