You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Caps.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /* global $ */
  2. import { b64_sha1, Strophe } from 'strophe.js'; // eslint-disable-line camelcase
  3. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  4. import Listenable from '../util/Listenable';
  5. const logger = require('jitsi-meet-logger').getLogger(__filename);
  6. /**
  7. * The property
  8. */
  9. const IDENTITY_PROPERTIES = [ 'category', 'type', 'lang', 'name' ];
  10. const IDENTITY_PROPERTIES_FOR_COMPARE = [ 'category', 'type', 'lang' ];
  11. const HASH = 'sha-1';
  12. export const ERROR_FEATURE_VERSION_MISMATCH = 'Feature version mismatch';
  13. /**
  14. *
  15. * @param a
  16. * @param b
  17. */
  18. function compareIdentities(a, b) {
  19. let res = 0;
  20. IDENTITY_PROPERTIES_FOR_COMPARE.some(key =>
  21. (res = ((a[key] > b[key]) && 1) || ((a[key] < b[key]) && -1)) !== 0
  22. );
  23. return res;
  24. }
  25. /**
  26. * Produces a sha-1 from provided identity and features values.
  27. *
  28. * @param {Array<Object>} identities - The identity objects.
  29. * @param {Array<string>} features - The features.
  30. * @returns {string}
  31. */
  32. function generateSha(identities, features) {
  33. const sortedIdentities = identities.sort(compareIdentities).reduce(
  34. (accumulatedValue, identity) => `${
  35. IDENTITY_PROPERTIES.reduce(
  36. (tmp, key, idx) =>
  37. tmp
  38. + (idx === 0 ? '' : '/')
  39. + (identity[key] ? identity[key] : ''),
  40. '')
  41. }<`, '');
  42. const sortedFeatures = features.sort().reduce(
  43. (tmp, feature) => `${tmp + feature}<`, '');
  44. return b64_sha1(sortedIdentities + sortedFeatures);
  45. }
  46. /**
  47. * Implements xep-0115 ( http://xmpp.org/extensions/xep-0115.html )
  48. */
  49. export default class Caps extends Listenable {
  50. /**
  51. * Constructs new Caps instance.
  52. * @param {Strophe.Connection} connection the strophe connection object
  53. * @param {String} node the value of the node attribute of the "c" xml node
  54. * that will be sent to the other participants
  55. */
  56. constructor(connection = {}, node = 'http://jitsi.org/jitsimeet') {
  57. super();
  58. this.node = node;
  59. this.disco = connection.disco;
  60. if (!this.disco) {
  61. throw new Error(
  62. 'Missing strophe-plugins '
  63. + '(disco plugin is required)!');
  64. }
  65. this.versionToCapabilities = Object.create(null);
  66. this.jidToVersion = Object.create(null);
  67. this.version = '';
  68. this.rooms = new Set();
  69. // We keep track of features added outside the library and we publish them
  70. // in the presence of the participant for simplicity, avoiding the disco info request-response.
  71. this.externalFeatures = new Set();
  72. const emuc = connection.emuc;
  73. emuc.addListener(XMPPEvents.EMUC_ROOM_ADDED,
  74. room => this._addChatRoom(room));
  75. emuc.addListener(XMPPEvents.EMUC_ROOM_REMOVED,
  76. room => this._removeChatRoom(room));
  77. Object.keys(emuc.rooms).forEach(jid => {
  78. this._addChatRoom(emuc.rooms[jid]);
  79. });
  80. Strophe.addNamespace('CAPS', 'http://jabber.org/protocol/caps');
  81. this.disco.addFeature(Strophe.NS.CAPS);
  82. connection.addHandler(this._handleCaps.bind(this), Strophe.NS.CAPS);
  83. this._onMucMemberLeft = this._removeJidToVersionEntry.bind(this);
  84. }
  85. /**
  86. * Adds new feature to the list of supported features for the local
  87. * participant
  88. * @param {String} feature the name of the feature.
  89. * @param {boolean} submit if true - new presence with updated "c" node
  90. * will be sent.
  91. * @param {boolean} external whether this feature was added externally to the library.
  92. * We put features used directly by the clients (is jibri, remote-control enabled etc.) in the presence
  93. * to avoid additional disco-info queries by those clients.
  94. */
  95. addFeature(feature, submit = false, external = false) {
  96. this.disco.addFeature(feature);
  97. this._generateVersion();
  98. if (external && !this.externalFeatures.has(feature)) {
  99. this.externalFeatures.add(feature);
  100. this.rooms.forEach(room => this._updateRoomWithExternalFeatures(room));
  101. }
  102. if (submit) {
  103. this.submit();
  104. }
  105. }
  106. /**
  107. * Removes a feature from the list of supported features for the local
  108. * participant
  109. * @param {String} feature the name of the feature.
  110. * @param {boolean} submit if true - new presence with updated "c" node
  111. * will be sent.
  112. * @param {boolean} external whether this feature was added externally to the library.
  113. */
  114. removeFeature(feature, submit = false, external = false) {
  115. this.disco.removeFeature(feature);
  116. this._generateVersion();
  117. if (external && this.externalFeatures.has(feature)) {
  118. this.externalFeatures.delete(feature);
  119. this.rooms.forEach(room => this._updateRoomWithExternalFeatures(room));
  120. }
  121. if (submit) {
  122. this.submit();
  123. }
  124. }
  125. /**
  126. * Sends new presence stanza for every room from the list of rooms.
  127. */
  128. submit() {
  129. this.rooms.forEach(room => room.sendPresence());
  130. }
  131. /**
  132. * Updates the presences in the room based on the current values in externalFeatures.
  133. * @param {ChatRoom} room the room to update.
  134. * @private
  135. */
  136. _updateRoomWithExternalFeatures(room) {
  137. if (this.externalFeatures.size === 0) {
  138. room.removeFromPresence('features');
  139. } else {
  140. const children = [];
  141. this.externalFeatures.forEach(f => {
  142. children.push({
  143. 'tagName': 'feature',
  144. attributes: { 'var': f }
  145. });
  146. });
  147. room.addToPresence('features', { children });
  148. }
  149. }
  150. /**
  151. * Returns a set with the features for a participant.
  152. * @param {String} jid the jid of the participant
  153. * @param {int} timeout the timeout in ms for reply from the participant.
  154. * @returns {Promise<Set<String>, Error>}
  155. */
  156. getFeatures(jid, timeout = 5000) {
  157. const user
  158. = jid in this.jidToVersion ? this.jidToVersion[jid] : null;
  159. if (!user || !(user.version in this.versionToCapabilities)) {
  160. const node = user ? `${user.node}#${user.version}` : null;
  161. return this._getDiscoInfo(jid, node, timeout)
  162. .then(({ features, identities }) => {
  163. if (user) {
  164. const sha = generateSha(
  165. Array.from(identities),
  166. Array.from(features)
  167. );
  168. const receivedNode = `${user.node}#${sha}`;
  169. if (receivedNode === node) {
  170. this.versionToCapabilities[receivedNode] = features;
  171. return features;
  172. }
  173. // Check once if it has been cached asynchronously.
  174. if (this.versionToCapabilities[receivedNode]) {
  175. return this.versionToCapabilities[receivedNode];
  176. }
  177. logger.error(`Expected node ${node} but received ${
  178. receivedNode}`);
  179. return Promise.reject(ERROR_FEATURE_VERSION_MISMATCH);
  180. }
  181. return features;
  182. });
  183. }
  184. return Promise.resolve(this.versionToCapabilities[user.version]);
  185. }
  186. /**
  187. * Returns a set with the features for a host.
  188. * @param {String} jid the jid of the host
  189. * @param {int} timeout the timeout in ms for reply from the host.
  190. * @returns {Promise<Set<String>, Error>}
  191. */
  192. getFeaturesAndIdentities(jid, node, timeout = 5000) {
  193. return this._getDiscoInfo(jid, node, timeout);
  194. }
  195. /**
  196. * Returns a set with the features and identities for a host.
  197. * @param {String} jid the jid of the host
  198. * @param {String|null} node the node to query
  199. * @param {int} timeout the timeout in ms for reply from the host.
  200. * @returns {Promise<Object>}
  201. * @private
  202. */
  203. _getDiscoInfo(jid, node, timeout) {
  204. return new Promise((resolve, reject) =>
  205. this.disco.info(jid, node, response => {
  206. const features = new Set();
  207. const identities = new Set();
  208. $(response)
  209. .find('>query>feature')
  210. .each(
  211. (_, el) => features.add(el.getAttribute('var')));
  212. $(response)
  213. .find('>query>identity')
  214. .each(
  215. (_, el) => identities.add({
  216. type: el.getAttribute('type'),
  217. name: el.getAttribute('name'),
  218. category: el.getAttribute('category')
  219. }));
  220. resolve({
  221. features,
  222. identities });
  223. }, reject, timeout)
  224. );
  225. }
  226. /**
  227. * Adds ChatRoom instance to the list of rooms. Adds listeners to the room
  228. * and adds "c" element to the presences of the room.
  229. * @param {ChatRoom} room the room.
  230. */
  231. _addChatRoom(room) {
  232. this.rooms.add(room);
  233. room.addListener(XMPPEvents.MUC_MEMBER_LEFT, this._onMucMemberLeft);
  234. this._fixChatRoomPresenceMap(room);
  235. this._updateRoomWithExternalFeatures(room);
  236. }
  237. /**
  238. * Removes ChatRoom instance from the list of rooms. Removes listeners
  239. * added from the Caps class.
  240. * @param {ChatRoom} room the room.
  241. */
  242. _removeChatRoom(room) {
  243. this.rooms.delete(room);
  244. room.removeListener(XMPPEvents.MUC_MEMBER_LEFT, this._onMucMemberLeft);
  245. }
  246. /**
  247. * Creates/updates the "c" xml node into the presence of the passed room.
  248. * @param {ChatRoom} room the room.
  249. */
  250. _fixChatRoomPresenceMap(room) {
  251. room.addToPresence('c', {
  252. attributes: {
  253. xmlns: Strophe.NS.CAPS,
  254. hash: HASH,
  255. node: this.node,
  256. ver: this.version
  257. }
  258. });
  259. }
  260. /**
  261. * Handles this.version changes.
  262. */
  263. _notifyVersionChanged() {
  264. // update the version for all rooms
  265. this.rooms.forEach(room => this._fixChatRoomPresenceMap(room));
  266. }
  267. /**
  268. * Generates the value for the "ver" attribute.
  269. */
  270. _generateVersion() {
  271. this.version
  272. = generateSha(this.disco._identities, this.disco._features);
  273. this._notifyVersionChanged();
  274. }
  275. /**
  276. * Parses the "c" xml node from presence.
  277. * @param {DOMElement} stanza the presence packet
  278. */
  279. _handleCaps(stanza) {
  280. const from = stanza.getAttribute('from');
  281. const caps = stanza.querySelector('c');
  282. const version = caps.getAttribute('ver');
  283. const node = caps.getAttribute('node');
  284. const oldVersion = this.jidToVersion[from];
  285. this.jidToVersion[from] = { version,
  286. node };
  287. if (oldVersion && oldVersion.version !== version) {
  288. this.eventEmitter.emit(XMPPEvents.PARTICIPANT_FEATURES_CHANGED, from);
  289. }
  290. // return true to not remove the handler from Strophe
  291. return true;
  292. }
  293. /**
  294. * Removes entry from this.jidToVersion map.
  295. * @param {String} jid the jid to be removed.
  296. */
  297. _removeJidToVersionEntry(jid) {
  298. if (jid in this.jidToVersion) {
  299. delete this.jidToVersion[jid];
  300. }
  301. }
  302. }