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

ChatRoom.js 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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. * Remove stream.
  618. * @param stream stream that will be removed.
  619. * @param callback callback executed after successful stream removal.
  620. * @param errorCallback callback executed if stream removal fail.
  621. * @param ssrcInfo object with information about the SSRCs associated with the
  622. * stream.
  623. */
  624. removeStream (stream, callback, errorCallback, ssrcInfo) {
  625. if(!this.session) {
  626. callback();
  627. return;
  628. }
  629. this.session.removeStream(stream, callback, errorCallback, ssrcInfo);
  630. }
  631. /**
  632. * Adds stream.
  633. * @param stream new stream that will be added.
  634. * @param callback callback executed after successful stream addition.
  635. * @param errorCallback callback executed if stream addition fail.
  636. * @param ssrcInfo object with information about the SSRCs associated with the
  637. * stream.
  638. * @param dontModifySources {boolean} if true _modifySources won't be called.
  639. * Used for streams added before the call start.
  640. */
  641. addStream (stream, callback, errorCallback, ssrcInfo, dontModifySources) {
  642. if(this.session) {
  643. // FIXME: will block switchInProgress on true value in case of exception
  644. this.session.addStream(stream, callback, errorCallback, ssrcInfo,
  645. dontModifySources);
  646. } else {
  647. // We are done immediately
  648. logger.warn("No conference handler or conference not started yet");
  649. callback();
  650. }
  651. }
  652. /**
  653. * Generate ssrc info object for a stream with the following properties:
  654. * - ssrcs - Array of the ssrcs associated with the stream.
  655. * - groups - Array of the groups associated with the stream.
  656. */
  657. generateNewStreamSSRCInfo () {
  658. if(!this.session) {
  659. logger.warn("The call haven't been started. " +
  660. "Cannot generate ssrc info at the moment!");
  661. return null;
  662. }
  663. return this.session.generateNewStreamSSRCInfo();
  664. }
  665. setVideoMute (mute, callback) {
  666. this.sendVideoInfoPresence(mute);
  667. if(callback)
  668. callback(mute);
  669. }
  670. setAudioMute (mute, callback) {
  671. return this.sendAudioInfoPresence(mute, callback);
  672. }
  673. addAudioInfoToPresence (mute) {
  674. this.removeFromPresence("audiomuted");
  675. this.addToPresence("audiomuted",
  676. {attributes:
  677. {"xmlns": "http://jitsi.org/jitmeet/audio"},
  678. value: mute.toString()});
  679. }
  680. sendAudioInfoPresence (mute, callback) {
  681. this.addAudioInfoToPresence(mute);
  682. if(this.connection) {
  683. this.sendPresence();
  684. }
  685. if(callback)
  686. callback();
  687. }
  688. addVideoInfoToPresence (mute) {
  689. this.removeFromPresence("videomuted");
  690. this.addToPresence("videomuted",
  691. {attributes:
  692. {"xmlns": "http://jitsi.org/jitmeet/video"},
  693. value: mute.toString()});
  694. }
  695. sendVideoInfoPresence (mute) {
  696. this.addVideoInfoToPresence(mute);
  697. if(!this.connection)
  698. return;
  699. this.sendPresence();
  700. }
  701. remoteTrackAdded (data) {
  702. // Will figure out current muted status by looking up owner's presence
  703. var pres = this.lastPresences[data.owner];
  704. if(pres) {
  705. var mediaType = data.mediaType;
  706. var mutedNode = null;
  707. if (mediaType === MediaType.AUDIO) {
  708. mutedNode = filterNodeFromPresenceJSON(pres, "audiomuted");
  709. } else if (mediaType === MediaType.VIDEO) {
  710. mutedNode = filterNodeFromPresenceJSON(pres, "videomuted");
  711. var videoTypeNode = filterNodeFromPresenceJSON(pres, "videoType");
  712. if(videoTypeNode
  713. && videoTypeNode.length > 0
  714. && videoTypeNode[0])
  715. data.videoType = videoTypeNode[0]["value"];
  716. } else {
  717. logger.warn("Unsupported media type: " + mediaType);
  718. data.muted = null;
  719. }
  720. if (mutedNode) {
  721. data.muted = mutedNode.length > 0 &&
  722. mutedNode[0] &&
  723. mutedNode[0]["value"] === "true";
  724. }
  725. }
  726. this.eventEmitter.emit(XMPPEvents.REMOTE_TRACK_ADDED, data);
  727. }
  728. /**
  729. * Returns true if the recording is supproted and false if not.
  730. */
  731. isRecordingSupported () {
  732. if(this.recording)
  733. return this.recording.isSupported();
  734. return false;
  735. }
  736. /**
  737. * Returns null if the recording is not supported, "on" if the recording started
  738. * and "off" if the recording is not started.
  739. */
  740. getRecordingState () {
  741. return (this.recording) ? this.recording.getState() : undefined;
  742. }
  743. /**
  744. * Returns the url of the recorded video.
  745. */
  746. getRecordingURL () {
  747. return (this.recording) ? this.recording.getURL() : null;
  748. }
  749. /**
  750. * Starts/stops the recording
  751. * @param token token for authentication
  752. * @param statusChangeHandler {function} receives the new status as argument.
  753. */
  754. toggleRecording (options, statusChangeHandler) {
  755. if(this.recording)
  756. return this.recording.toggleRecording(options, statusChangeHandler);
  757. return statusChangeHandler("error",
  758. new Error("The conference is not created yet!"));
  759. }
  760. /**
  761. * Returns true if the SIP calls are supported and false otherwise
  762. */
  763. isSIPCallingSupported () {
  764. if(this.moderator)
  765. return this.moderator.isSipGatewayEnabled();
  766. return false;
  767. }
  768. /**
  769. * Dials a number.
  770. * @param number the number
  771. */
  772. dial (number) {
  773. return this.connection.rayo.dial(number, "fromnumber",
  774. Strophe.getNodeFromJid(this.myroomjid), this.password,
  775. this.focusMucJid);
  776. }
  777. /**
  778. * Hangup an existing call
  779. */
  780. hangup () {
  781. return this.connection.rayo.hangup();
  782. }
  783. /**
  784. * Returns the phone number for joining the conference.
  785. */
  786. getPhoneNumber () {
  787. return this.phoneNumber;
  788. }
  789. /**
  790. * Returns the pin for joining the conference with phone.
  791. */
  792. getPhonePin () {
  793. return this.phonePin;
  794. }
  795. /**
  796. * Returns the connection state for the current session.
  797. */
  798. getConnectionState () {
  799. if(!this.session)
  800. return null;
  801. return this.session.getIceConnectionState();
  802. }
  803. /**
  804. * Mutes remote participant.
  805. * @param jid of the participant
  806. * @param mute
  807. */
  808. muteParticipant (jid, mute) {
  809. logger.info("set mute", mute);
  810. var iqToFocus = $iq(
  811. {to: this.focusMucJid, type: 'set'})
  812. .c('mute', {
  813. xmlns: 'http://jitsi.org/jitmeet/audio',
  814. jid: jid
  815. })
  816. .t(mute.toString())
  817. .up();
  818. this.connection.sendIQ(
  819. iqToFocus,
  820. function (result) {
  821. logger.log('set mute', result);
  822. },
  823. function (error) {
  824. logger.log('set mute error', error);
  825. });
  826. }
  827. onMute (iq) {
  828. var from = iq.getAttribute('from');
  829. if (from !== this.focusMucJid) {
  830. logger.warn("Ignored mute from non focus peer");
  831. return false;
  832. }
  833. var mute = $(iq).find('mute');
  834. if (mute.length) {
  835. var doMuteAudio = mute.text() === "true";
  836. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  837. }
  838. return true;
  839. }
  840. /**
  841. * Leaves the room. Closes the jingle session.
  842. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received less
  843. * than 5s after sending presence unavailable. Otherwise the promise is
  844. * rejected.
  845. */
  846. leave () {
  847. this._dispose();
  848. return new Promise((resolve, reject) => {
  849. let timeout = setTimeout(() => onMucLeft(true), 5000);
  850. let eventEmitter = this.eventEmitter;
  851. function onMucLeft(doReject = false) {
  852. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  853. clearTimeout(timeout);
  854. if(doReject) {
  855. // the timeout expired
  856. reject(new Error("The timeout for the confirmation about " +
  857. "leaving the room expired."));
  858. } else {
  859. resolve();
  860. }
  861. }
  862. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  863. this.doLeave();
  864. });
  865. }
  866. /**
  867. * Disposes the conference, closes the jingle session.
  868. */
  869. _dispose () {
  870. if (this.session) {
  871. this.session.close();
  872. }
  873. }
  874. }