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

Caps.js 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. const emuc = connection.emuc;
  70. emuc.addListener(XMPPEvents.EMUC_ROOM_ADDED,
  71. room => this._addChatRoom(room));
  72. emuc.addListener(XMPPEvents.EMUC_ROOM_REMOVED,
  73. room => this._removeChatRoom(room));
  74. Object.keys(emuc.rooms).forEach(jid => {
  75. this._addChatRoom(emuc.rooms[jid]);
  76. });
  77. Strophe.addNamespace('CAPS', 'http://jabber.org/protocol/caps');
  78. this.disco.addFeature(Strophe.NS.CAPS);
  79. connection.addHandler(this._handleCaps.bind(this), Strophe.NS.CAPS);
  80. this._onMucMemberLeft = this._removeJidToVersionEntry.bind(this);
  81. }
  82. /**
  83. * Adds new feature to the list of supported features for the local
  84. * participant
  85. * @param {String} feature the name of the feature.
  86. * @param {boolean} submit if true - new presence with updated "c" node
  87. * will be sent.
  88. */
  89. addFeature(feature, submit = false) {
  90. this.disco.addFeature(feature);
  91. this._generateVersion();
  92. if (submit) {
  93. this.submit();
  94. }
  95. }
  96. /**
  97. * Removes a feature from the list of supported features for the local
  98. * participant
  99. * @param {String} feature the name of the feature.
  100. * @param {boolean} submit if true - new presence with updated "c" node
  101. * will be sent.
  102. */
  103. removeFeature(feature, submit = false) {
  104. this.disco.removeFeature(feature);
  105. this._generateVersion();
  106. if (submit) {
  107. this.submit();
  108. }
  109. }
  110. /**
  111. * Sends new presence stanza for every room from the list of rooms.
  112. */
  113. submit() {
  114. this.rooms.forEach(room => room.sendPresence());
  115. }
  116. /**
  117. * Returns a set with the features for a participant.
  118. * @param {String} jid the jid of the participant
  119. * @param {int} timeout the timeout in ms for reply from the participant.
  120. * @returns {Promise<Set<String>, Error>}
  121. */
  122. getFeatures(jid, timeout = 5000) {
  123. const user
  124. = jid in this.jidToVersion ? this.jidToVersion[jid] : null;
  125. if (!user || !(user.version in this.versionToCapabilities)) {
  126. const node = user ? `${user.node}#${user.version}` : null;
  127. return this._getDiscoInfo(jid, node, timeout)
  128. .then(({ features, identities }) => {
  129. if (user) {
  130. const sha = generateSha(
  131. Array.from(identities),
  132. Array.from(features)
  133. );
  134. const receivedNode = `${user.node}#${sha}`;
  135. if (receivedNode === node) {
  136. this.versionToCapabilities[receivedNode] = features;
  137. return features;
  138. }
  139. // Check once if it has been cached asynchronously.
  140. if (this.versionToCapabilities[receivedNode]) {
  141. return this.versionToCapabilities[receivedNode];
  142. }
  143. logger.error(`Expected node ${node} but received ${
  144. receivedNode}`);
  145. return Promise.reject(ERROR_FEATURE_VERSION_MISMATCH);
  146. }
  147. });
  148. }
  149. return Promise.resolve(this.versionToCapabilities[user.version]);
  150. }
  151. /**
  152. * Returns a set with the features for a host.
  153. * @param {String} jid the jid of the host
  154. * @param {int} timeout the timeout in ms for reply from the host.
  155. * @returns {Promise<Set<String>, Error>}
  156. */
  157. getFeaturesAndIdentities(jid, node, timeout = 5000) {
  158. return this._getDiscoInfo(jid, node, timeout);
  159. }
  160. /**
  161. * Returns a set with the features and identities for a host.
  162. * @param {String} jid the jid of the host
  163. * @param {String|null} node the node to query
  164. * @param {int} timeout the timeout in ms for reply from the host.
  165. * @returns {Promise<Object>}
  166. * @private
  167. */
  168. _getDiscoInfo(jid, node, timeout) {
  169. return new Promise((resolve, reject) =>
  170. this.disco.info(jid, node, response => {
  171. const features = new Set();
  172. const identities = new Set();
  173. $(response)
  174. .find('>query>feature')
  175. .each(
  176. (_, el) => features.add(el.getAttribute('var')));
  177. $(response)
  178. .find('>query>identity')
  179. .each(
  180. (_, el) => identities.add({
  181. type: el.getAttribute('type'),
  182. name: el.getAttribute('name'),
  183. category: el.getAttribute('category')
  184. }));
  185. resolve({
  186. features,
  187. identities });
  188. }, reject, timeout)
  189. );
  190. }
  191. /**
  192. * Adds ChatRoom instance to the list of rooms. Adds listeners to the room
  193. * and adds "c" element to the presences of the room.
  194. * @param {ChatRoom} room the room.
  195. */
  196. _addChatRoom(room) {
  197. this.rooms.add(room);
  198. room.addListener(XMPPEvents.MUC_MEMBER_LEFT, this._onMucMemberLeft);
  199. this._fixChatRoomPresenceMap(room);
  200. }
  201. /**
  202. * Removes ChatRoom instance from the list of rooms. Removes listeners
  203. * added from the Caps class.
  204. * @param {ChatRoom} room the room.
  205. */
  206. _removeChatRoom(room) {
  207. this.rooms.delete(room);
  208. room.removeListener(XMPPEvents.MUC_MEMBER_LEFT, this._onMucMemberLeft);
  209. }
  210. /**
  211. * Creates/updates the "c" xml node into the presence of the passed room.
  212. * @param {ChatRoom} room the room.
  213. */
  214. _fixChatRoomPresenceMap(room) {
  215. room.addToPresence('c', {
  216. attributes: {
  217. xmlns: Strophe.NS.CAPS,
  218. hash: HASH,
  219. node: this.node,
  220. ver: this.version
  221. }
  222. });
  223. }
  224. /**
  225. * Handles this.version changes.
  226. */
  227. _notifyVersionChanged() {
  228. // update the version for all rooms
  229. this.rooms.forEach(room => this._fixChatRoomPresenceMap(room));
  230. }
  231. /**
  232. * Generates the value for the "ver" attribute.
  233. */
  234. _generateVersion() {
  235. this.version
  236. = generateSha(this.disco._identities, this.disco._features);
  237. this._notifyVersionChanged();
  238. }
  239. /**
  240. * Parses the "c" xml node from presence.
  241. * @param {DOMElement} stanza the presence packet
  242. */
  243. _handleCaps(stanza) {
  244. const from = stanza.getAttribute('from');
  245. const caps = stanza.querySelector('c');
  246. const version = caps.getAttribute('ver');
  247. const node = caps.getAttribute('node');
  248. const oldVersion = this.jidToVersion[from];
  249. this.jidToVersion[from] = { version,
  250. node };
  251. if (oldVersion && oldVersion.version !== version) {
  252. this.eventEmitter.emit(XMPPEvents.PARTCIPANT_FEATURES_CHANGED,
  253. from);
  254. }
  255. // return true to not remove the handler from Strophe
  256. return true;
  257. }
  258. /**
  259. * Removes entry from this.jidToVersion map.
  260. * @param {String} jid the jid to be removed.
  261. */
  262. _removeJidToVersionEntry(jid) {
  263. if (jid in this.jidToVersion) {
  264. delete this.jidToVersion[jid];
  265. }
  266. }
  267. }