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

Caps.js 9.6KB

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