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

ChatRoom.js 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. /**
  383. * Makes the underlying JingleSession generate new SSRC for the recvonly
  384. * video stream.
  385. * @deprecated
  386. */
  387. generateRecvonlySsrc() {
  388. if (this.session) {
  389. this.session.generateRecvonlySsrc();
  390. } else {
  391. logger.warn("Unable to generate recvonly SSRC - no session");
  392. }
  393. }
  394. processNode (node, from) {
  395. // make sure we catch all errors coming from any handler
  396. // otherwise we can remove the presence handler from strophe
  397. try {
  398. var tagHandler = this.presHandlers[node.tagName];
  399. if (node.tagName.startsWith("jitsi_participant_")) {
  400. tagHandler = this.participantPropertyListener;
  401. }
  402. if(tagHandler) {
  403. tagHandler(node, Strophe.getResourceFromJid(from), from);
  404. }
  405. } catch (e) {
  406. GlobalOnErrorHandler.callErrorHandler(e);
  407. logger.error('Error processing:' + node.tagName + ' node.', e);
  408. }
  409. }
  410. sendMessage (body, nickname) {
  411. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  412. msg.c('body', body).up();
  413. if (nickname) {
  414. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  415. }
  416. this.connection.send(msg);
  417. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  418. }
  419. setSubject (subject) {
  420. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  421. msg.c('subject', subject);
  422. this.connection.send(msg);
  423. }
  424. /**
  425. * Called when participant leaves.
  426. * @param jid the jid of the participant that leaves
  427. * @param skipEvents optional params to skip any events, including check
  428. * whether this is the focus that left
  429. */
  430. onParticipantLeft (jid, skipEvents) {
  431. delete this.lastPresences[jid];
  432. if(skipEvents)
  433. return;
  434. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  435. this.moderator.onMucMemberLeft(jid);
  436. }
  437. onPresenceUnavailable (pres, from) {
  438. // room destroyed ?
  439. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  440. '>destroy').length) {
  441. var reason;
  442. var reasonSelect = $(pres).find(
  443. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  444. '>destroy>reason');
  445. if (reasonSelect.length) {
  446. reason = reasonSelect.text();
  447. }
  448. this._dispose();
  449. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  450. this.connection.emuc.doLeave(this.roomjid);
  451. return true;
  452. }
  453. // Status code 110 indicates that this notification is "self-presence".
  454. var isSelfPresence = $(pres).find(
  455. '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]'
  456. ).length !== 0;
  457. var isKick = $(pres).find(
  458. '>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]'
  459. ).length !== 0;
  460. if (!isSelfPresence) {
  461. delete this.members[from];
  462. this.onParticipantLeft(from, false);
  463. }
  464. // If the status code is 110 this means we're leaving and we would like
  465. // to remove everyone else from our view, so we trigger the event.
  466. else if (Object.keys(this.members).length > 0) {
  467. for (const i in this.members) {
  468. const member = this.members[i];
  469. delete this.members[i];
  470. this.onParticipantLeft(i, member.isFocus);
  471. }
  472. this.connection.emuc.doLeave(this.roomjid);
  473. // we fire muc_left only if this is not a kick,
  474. // kick has both statuses 110 and 307.
  475. if (!isKick)
  476. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  477. }
  478. if (isKick && this.myroomjid === from) {
  479. this._dispose();
  480. this.eventEmitter.emit(XMPPEvents.KICKED);
  481. }
  482. }
  483. onMessage (msg, from) {
  484. var nick =
  485. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  486. .text() ||
  487. Strophe.getResourceFromJid(from);
  488. var txt = $(msg).find('>body').text();
  489. var type = msg.getAttribute("type");
  490. if (type == "error") {
  491. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  492. $(msg).find('>text').text(), txt);
  493. return true;
  494. }
  495. var subject = $(msg).find('>subject');
  496. if (subject.length) {
  497. var subjectText = subject.text();
  498. if (subjectText || subjectText === "") {
  499. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  500. logger.log("Subject is changed to " + subjectText);
  501. }
  502. }
  503. // xep-0203 delay
  504. var stamp = $(msg).find('>delay').attr('stamp');
  505. if (!stamp) {
  506. // or xep-0091 delay, UTC timestamp
  507. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  508. if (stamp) {
  509. // the format is CCYYMMDDThh:mm:ss
  510. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  511. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  512. }
  513. }
  514. if (from==this.roomjid && $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  515. this.discoRoomInfo();
  516. }
  517. if (txt) {
  518. logger.log('chat', nick, txt);
  519. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  520. from, nick, txt, this.myroomjid, stamp);
  521. }
  522. }
  523. onPresenceError (pres, from) {
  524. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  525. logger.log('on password required', from);
  526. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  527. } else if ($(pres).find(
  528. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  529. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  530. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  531. // enter the room by replying with 'not-authorized'. This would
  532. // result in reconnection from authorized domain.
  533. // We're either missing Jicofo/Prosody config for anonymous
  534. // domains or something is wrong.
  535. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  536. } else {
  537. logger.warn('onPresError ', pres);
  538. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  539. }
  540. } else if($(pres).find('>error>service-unavailable').length) {
  541. logger.warn('Maximum users limit for the room has been reached',
  542. pres);
  543. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  544. } else {
  545. logger.warn('onPresError ', pres);
  546. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  547. }
  548. }
  549. kick (jid) {
  550. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  551. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  552. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  553. .c('reason').t('You have been kicked.').up().up().up();
  554. this.connection.sendIQ(
  555. kickIQ,
  556. function (result) {
  557. logger.log('Kick participant with jid: ', jid, result);
  558. },
  559. function (error) {
  560. logger.log('Kick participant error: ', error);
  561. });
  562. }
  563. lockRoom (key, onSuccess, onError, onNotSupported) {
  564. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  565. var ob = this;
  566. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  567. function (res) {
  568. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  569. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  570. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  571. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  572. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  573. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  574. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  575. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  576. ob.connection.sendIQ(formsubmit,
  577. onSuccess,
  578. onError);
  579. } else {
  580. onNotSupported();
  581. }
  582. }, onError);
  583. }
  584. addToPresence (key, values) {
  585. values.tagName = key;
  586. this.removeFromPresence(key);
  587. this.presMap.nodes.push(values);
  588. }
  589. removeFromPresence (key) {
  590. var nodes = this.presMap.nodes.filter(function(node) {
  591. return key !== node.tagName;});
  592. this.presMap.nodes = nodes;
  593. }
  594. addPresenceListener (name, handler) {
  595. this.presHandlers[name] = handler;
  596. }
  597. removePresenceListener (name) {
  598. delete this.presHandlers[name];
  599. }
  600. /**
  601. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  602. * focus.
  603. * @param mucJid the full MUC address of the user to be checked.
  604. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus or
  605. * <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  606. * the MUC then <tt>null</tt> is returned.
  607. */
  608. isFocus (mucJid) {
  609. var member = this.members[mucJid];
  610. if (member) {
  611. return member.isFocus;
  612. } else {
  613. return null;
  614. }
  615. }
  616. isModerator () {
  617. return this.role === 'moderator';
  618. }
  619. getMemberRole (peerJid) {
  620. if (this.members[peerJid]) {
  621. return this.members[peerJid].role;
  622. }
  623. return null;
  624. }
  625. setJingleSession (session){
  626. this.session = session;
  627. }
  628. /**
  629. * Replaces oldStream with newStream and performs a single offer/answer
  630. * cycle after both operations are done. Either oldStream or newStream
  631. * can be null; replacing a valid 'oldStream' with a null 'newStream'
  632. * effectively just removes 'oldStream'
  633. * @param oldStream the current stream in use to be replaced
  634. * @param newStream the new stream to use
  635. * @returns {Promise}
  636. */
  637. replaceStream (oldStream, newStream) {
  638. if (this.session) {
  639. return this.session.replaceStream(oldStream, newStream);
  640. }
  641. return Promise.resolve();
  642. }
  643. /**
  644. * Remove stream.
  645. * @param stream stream that will be removed.
  646. * @param callback callback executed after successful stream removal.
  647. * @param errorCallback callback executed if stream removal fail.
  648. * @param ssrcInfo object with information about the SSRCs associated with the
  649. * stream.
  650. */
  651. removeStream (stream, callback, errorCallback, ssrcInfo) {
  652. if(!this.session) {
  653. callback();
  654. return;
  655. }
  656. this.session.removeStream(stream, callback, errorCallback, ssrcInfo);
  657. }
  658. /**
  659. * Adds stream.
  660. * @param stream new stream that will be added.
  661. * @param callback callback executed after successful stream addition.
  662. * @param errorCallback callback executed if stream addition fail.
  663. * @param ssrcInfo object with information about the SSRCs associated with the
  664. * stream.
  665. * @param dontModifySources {boolean} if true _modifySources won't be called.
  666. * Used for streams added before the call start.
  667. */
  668. addStream (stream, callback, errorCallback, ssrcInfo, dontModifySources) {
  669. if(this.session) {
  670. // FIXME: will block switchInProgress on true value in case of exception
  671. this.session.addStream(stream, callback, errorCallback, ssrcInfo,
  672. dontModifySources);
  673. } else {
  674. // We are done immediately
  675. logger.warn("No conference handler or conference not started yet");
  676. callback();
  677. }
  678. }
  679. /**
  680. * Generate ssrc info object for a stream with the following properties:
  681. * - ssrcs - Array of the ssrcs associated with the stream.
  682. * - groups - Array of the groups associated with the stream.
  683. */
  684. generateNewStreamSSRCInfo () {
  685. if(!this.session) {
  686. logger.warn("The call haven't been started. " +
  687. "Cannot generate ssrc info at the moment!");
  688. return null;
  689. }
  690. return this.session.generateNewStreamSSRCInfo();
  691. }
  692. setVideoMute (mute, callback) {
  693. this.sendVideoInfoPresence(mute);
  694. if(callback)
  695. callback(mute);
  696. }
  697. setAudioMute (mute, callback) {
  698. return this.sendAudioInfoPresence(mute, callback);
  699. }
  700. addAudioInfoToPresence (mute) {
  701. this.removeFromPresence("audiomuted");
  702. this.addToPresence("audiomuted",
  703. {attributes:
  704. {"xmlns": "http://jitsi.org/jitmeet/audio"},
  705. value: mute.toString()});
  706. }
  707. sendAudioInfoPresence (mute, callback) {
  708. this.addAudioInfoToPresence(mute);
  709. if(this.connection) {
  710. this.sendPresence();
  711. }
  712. if(callback)
  713. callback();
  714. }
  715. addVideoInfoToPresence (mute) {
  716. this.removeFromPresence("videomuted");
  717. this.addToPresence("videomuted",
  718. {attributes:
  719. {"xmlns": "http://jitsi.org/jitmeet/video"},
  720. value: mute.toString()});
  721. }
  722. sendVideoInfoPresence (mute) {
  723. this.addVideoInfoToPresence(mute);
  724. if(!this.connection)
  725. return;
  726. this.sendPresence();
  727. }
  728. remoteTrackAdded (data) {
  729. // Will figure out current muted status by looking up owner's presence
  730. var pres = this.lastPresences[data.owner];
  731. if(pres) {
  732. var mediaType = data.mediaType;
  733. var mutedNode = null;
  734. if (mediaType === MediaType.AUDIO) {
  735. mutedNode = filterNodeFromPresenceJSON(pres, "audiomuted");
  736. } else if (mediaType === MediaType.VIDEO) {
  737. mutedNode = filterNodeFromPresenceJSON(pres, "videomuted");
  738. var videoTypeNode = filterNodeFromPresenceJSON(pres, "videoType");
  739. if(videoTypeNode
  740. && videoTypeNode.length > 0
  741. && videoTypeNode[0])
  742. data.videoType = videoTypeNode[0]["value"];
  743. } else {
  744. logger.warn("Unsupported media type: " + mediaType);
  745. data.muted = null;
  746. }
  747. if (mutedNode) {
  748. data.muted = mutedNode.length > 0 &&
  749. mutedNode[0] &&
  750. mutedNode[0]["value"] === "true";
  751. }
  752. }
  753. this.eventEmitter.emit(XMPPEvents.REMOTE_TRACK_ADDED, data);
  754. }
  755. /**
  756. * Returns true if the recording is supproted and false if not.
  757. */
  758. isRecordingSupported () {
  759. if(this.recording)
  760. return this.recording.isSupported();
  761. return false;
  762. }
  763. /**
  764. * Returns null if the recording is not supported, "on" if the recording started
  765. * and "off" if the recording is not started.
  766. */
  767. getRecordingState () {
  768. return (this.recording) ? this.recording.getState() : undefined;
  769. }
  770. /**
  771. * Returns the url of the recorded video.
  772. */
  773. getRecordingURL () {
  774. return (this.recording) ? this.recording.getURL() : null;
  775. }
  776. /**
  777. * Starts/stops the recording
  778. * @param token token for authentication
  779. * @param statusChangeHandler {function} receives the new status as argument.
  780. */
  781. toggleRecording (options, statusChangeHandler) {
  782. if(this.recording)
  783. return this.recording.toggleRecording(options, statusChangeHandler);
  784. return statusChangeHandler("error",
  785. new Error("The conference is not created yet!"));
  786. }
  787. /**
  788. * Returns true if the SIP calls are supported and false otherwise
  789. */
  790. isSIPCallingSupported () {
  791. if(this.moderator)
  792. return this.moderator.isSipGatewayEnabled();
  793. return false;
  794. }
  795. /**
  796. * Dials a number.
  797. * @param number the number
  798. */
  799. dial (number) {
  800. return this.connection.rayo.dial(number, "fromnumber",
  801. Strophe.getNodeFromJid(this.myroomjid), this.password,
  802. this.focusMucJid);
  803. }
  804. /**
  805. * Hangup an existing call
  806. */
  807. hangup () {
  808. return this.connection.rayo.hangup();
  809. }
  810. /**
  811. * Returns the phone number for joining the conference.
  812. */
  813. getPhoneNumber () {
  814. return this.phoneNumber;
  815. }
  816. /**
  817. * Returns the pin for joining the conference with phone.
  818. */
  819. getPhonePin () {
  820. return this.phonePin;
  821. }
  822. /**
  823. * Returns the connection state for the current session.
  824. */
  825. getConnectionState () {
  826. if(!this.session)
  827. return null;
  828. return this.session.getIceConnectionState();
  829. }
  830. /**
  831. * Mutes remote participant.
  832. * @param jid of the participant
  833. * @param mute
  834. */
  835. muteParticipant (jid, mute) {
  836. logger.info("set mute", mute);
  837. var iqToFocus = $iq(
  838. {to: this.focusMucJid, type: 'set'})
  839. .c('mute', {
  840. xmlns: 'http://jitsi.org/jitmeet/audio',
  841. jid: jid
  842. })
  843. .t(mute.toString())
  844. .up();
  845. this.connection.sendIQ(
  846. iqToFocus,
  847. function (result) {
  848. logger.log('set mute', result);
  849. },
  850. function (error) {
  851. logger.log('set mute error', error);
  852. });
  853. }
  854. onMute (iq) {
  855. var from = iq.getAttribute('from');
  856. if (from !== this.focusMucJid) {
  857. logger.warn("Ignored mute from non focus peer");
  858. return false;
  859. }
  860. var mute = $(iq).find('mute');
  861. if (mute.length) {
  862. var doMuteAudio = mute.text() === "true";
  863. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  864. }
  865. return true;
  866. }
  867. /**
  868. * Leaves the room. Closes the jingle session.
  869. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received less
  870. * than 5s after sending presence unavailable. Otherwise the promise is
  871. * rejected.
  872. */
  873. leave () {
  874. this._dispose();
  875. return new Promise((resolve, reject) => {
  876. let timeout = setTimeout(() => onMucLeft(true), 5000);
  877. let eventEmitter = this.eventEmitter;
  878. function onMucLeft(doReject = false) {
  879. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  880. clearTimeout(timeout);
  881. if(doReject) {
  882. // the timeout expired
  883. reject(new Error("The timeout for the confirmation about " +
  884. "leaving the room expired."));
  885. } else {
  886. resolve();
  887. }
  888. }
  889. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  890. this.doLeave();
  891. });
  892. }
  893. /**
  894. * Disposes the conference, closes the jingle session.
  895. */
  896. _dispose () {
  897. if (this.session) {
  898. this.session.close();
  899. }
  900. }
  901. }