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

ChatRoom.js 31KB

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