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

ChatRoom.js 32KB

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