Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ProxyConnectionService.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /* globals $ */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { $iq } from 'strophe.js';
  4. import * as MediaType from '../../service/RTC/MediaType';
  5. import VideoType from '../../service/RTC/VideoType';
  6. import RTC from '../RTC/RTC';
  7. import ProxyConnectionPC from './ProxyConnectionPC';
  8. import { ACTIONS } from './constants';
  9. const logger = getLogger(__filename);
  10. /**
  11. * Instantiates a new ProxyConnectionPC and ensures only one exists at a given
  12. * time. Currently it assumes ProxyConnectionPC is used only for screensharing
  13. * and assumes IQs to be used for communication.
  14. */
  15. export default class ProxyConnectionService {
  16. /**
  17. * Initializes a new {@code ProxyConnectionService} instance.
  18. *
  19. * @param {Object} options - Values to initialize the instance with.
  20. * @param {boolean} [options.convertVideoToDesktop] - Whether or not proxied
  21. * video should be returned as a desktop stream. Defaults to false.
  22. * @param {Object} [options.iceConfig] - The {@code RTCConfiguration} to use
  23. * for the peer connection.
  24. * @param {JitsiConnection} [options.jitsiConnection] - The
  25. * {@code JitsiConnection} which will be used to fetch TURN credentials for
  26. * the P2P connection.
  27. * @param {Function} options.onRemoteStream - Callback to invoke when a
  28. * remote video stream has been received and converted to a
  29. * {@code JitsiLocakTrack}. The {@code JitsiLocakTrack} will be passed in.
  30. * @param {Function} options.onSendMessage - Callback to invoke when a
  31. * message has to be sent (signaled) out. The arguments passed in are the
  32. * jid to send the message to and the message
  33. */
  34. constructor(options = {}) {
  35. const {
  36. jitsiConnection,
  37. ...otherOptions
  38. } = options;
  39. /**
  40. * Holds a reference to the collection of all callbacks.
  41. *
  42. * @type {Object}
  43. */
  44. this._options = {
  45. iceConfig: jitsiConnection
  46. && jitsiConnection.xmpp.connection.jingle.p2pIceConfig,
  47. ...otherOptions
  48. };
  49. /**
  50. * The active instance of {@code ProxyConnectionService}.
  51. *
  52. * @type {ProxyConnectionPC|null}
  53. */
  54. this._peerConnection = null;
  55. // Bind event handlers so they are only bound once for every instance.
  56. this._onFatalError = this._onFatalError.bind(this);
  57. this._onSendMessage = this._onSendMessage.bind(this);
  58. this._onRemoteStream = this._onRemoteStream.bind(this);
  59. }
  60. /**
  61. * Parses a message object regarding a proxy connection to create a new
  62. * proxy connection or update and existing connection.
  63. *
  64. * @param {Object} message - A message object regarding establishing or
  65. * updating a proxy connection.
  66. * @param {Object} message.data - An object containing additional message
  67. * details.
  68. * @param {string} message.data.iq - The stringified iq which explains how
  69. * and what to update regarding the proxy connection.
  70. * @param {string} message.from - The message sender's full jid. Used for
  71. * sending replies.
  72. * @returns {void}
  73. */
  74. processMessage(message) {
  75. const peerJid = message.from;
  76. if (!peerJid) {
  77. return;
  78. }
  79. // If a proxy connection has already been established and messages come
  80. // from another peer jid then those messages should be replied to with
  81. // a rejection.
  82. if (this._peerConnection
  83. && this._peerConnection.getPeerJid() !== peerJid) {
  84. this._onFatalError(
  85. peerJid,
  86. ACTIONS.CONNECTION_ERROR,
  87. 'rejected'
  88. );
  89. return;
  90. }
  91. const iq = this._convertStringToXML(message.data.iq);
  92. const $jingle = iq && iq.find('jingle');
  93. const action = $jingle && $jingle.attr('action');
  94. if (action === ACTIONS.INITIATE) {
  95. this._peerConnection = this._createPeerConnection(peerJid, {
  96. isInitiator: false,
  97. receiveVideo: true
  98. });
  99. }
  100. // Truthy check for peer connection added to protect against possibly
  101. // receiving actions before an ACTIONS.INITIATE.
  102. if (this._peerConnection) {
  103. this._peerConnection.processMessage($jingle);
  104. }
  105. // Take additional steps to ensure the peer connection is cleaned up
  106. // if it is to be closed.
  107. if (action === ACTIONS.CONNECTION_ERROR
  108. || action === ACTIONS.UNAVAILABLE
  109. || action === ACTIONS.TERMINATE) {
  110. this._selfCloseConnection();
  111. }
  112. return;
  113. }
  114. /**
  115. * Instantiates and initiates a proxy peer connection.
  116. *
  117. * @param {string} peerJid - The jid of the remote client that should
  118. * receive messages.
  119. * @param {Array<JitsiLocalTrack>} localTracks - Initial media tracks to
  120. * send through to the peer.
  121. * @returns {void}
  122. */
  123. start(peerJid, localTracks = []) {
  124. this._peerConnection = this._createPeerConnection(peerJid, {
  125. isInitiator: true,
  126. receiveVideo: false
  127. });
  128. this._peerConnection.start(localTracks);
  129. }
  130. /**
  131. * Terminates any active proxy peer connection.
  132. *
  133. * @returns {void}
  134. */
  135. stop() {
  136. if (this._peerConnection) {
  137. this._peerConnection.stop();
  138. }
  139. this._peerConnection = null;
  140. }
  141. /**
  142. * Transforms a stringified xML into a XML wrapped in jQuery.
  143. *
  144. * @param {string} xml - The XML in string form.
  145. * @private
  146. * @returns {Object|null} A jQuery version of the xml. Null will be returned
  147. * if an error is encountered during transformation.
  148. */
  149. _convertStringToXML(xml) {
  150. try {
  151. const xmlDom = new DOMParser().parseFromString(xml, 'text/xml');
  152. return $(xmlDom);
  153. } catch (e) {
  154. logger.error('Attempted to convert incorrectly formatted xml');
  155. return null;
  156. }
  157. }
  158. /**
  159. * Helper for creating an instance of {@code ProxyConnectionPC}.
  160. *
  161. * @param {string} peerJid - The jid of the remote peer with which the
  162. * {@code ProxyConnectionPC} will be established with.
  163. * @param {Object} options - Additional defaults to instantiate the
  164. * {@code ProxyConnectionPC} with. See the constructor of ProxyConnectionPC
  165. * for more details.
  166. * @private
  167. * @returns {ProxyConnectionPC}
  168. */
  169. _createPeerConnection(peerJid, options = {}) {
  170. if (!peerJid) {
  171. throw new Error('Cannot create ProxyConnectionPC without a peer.');
  172. }
  173. const pcOptions = {
  174. iceConfig: this._options.iceConfig,
  175. onError: this._onFatalError,
  176. onRemoteStream: this._onRemoteStream,
  177. onSendMessage: this._onSendMessage,
  178. peerJid,
  179. ...options
  180. };
  181. return new ProxyConnectionPC(pcOptions);
  182. }
  183. /**
  184. * Callback invoked when an error occurs that should cause
  185. * {@code ProxyConnectionPC} to be closed if the peer is currently
  186. * connected. Sends an error message/reply back to the peer.
  187. *
  188. * @param {string} peerJid - The peer jid with which the connection was
  189. * attempted or started, and to which an iq with error details should be
  190. * sent.
  191. * @param {string} errorType - The constant indicating the type of the error
  192. * that occured.
  193. * @param {string} details - Optional additional data about the error.
  194. * @private
  195. * @returns {void}
  196. */
  197. _onFatalError(peerJid, errorType, details = '') {
  198. logger.error(
  199. 'Received a proxy connection error', peerJid, errorType, details);
  200. const iq = $iq({
  201. to: peerJid,
  202. type: 'set'
  203. })
  204. .c('jingle', {
  205. xmlns: 'urn:xmpp:jingle:1',
  206. action: errorType
  207. })
  208. .c('details')
  209. .t(details)
  210. .up();
  211. this._onSendMessage(peerJid, iq);
  212. if (this._peerConnection
  213. && this._peerConnection.getPeerJid() === peerJid) {
  214. this._selfCloseConnection();
  215. }
  216. }
  217. /**
  218. * Callback invoked when the remote peer of the {@code ProxyConnectionPC}
  219. * has offered a media stream. The stream is converted into a
  220. * {@code JitsiLocalTrack} for local usage if the {@code onRemoteStream}
  221. * callback is defined.
  222. *
  223. * @param {JitsiRemoteTrack} jitsiRemoteTrack - The {@code JitsiRemoteTrack}
  224. * for the peer's media stream.
  225. * @private
  226. * @returns {void}
  227. */
  228. _onRemoteStream(jitsiRemoteTrack) {
  229. if (!this._options.onRemoteStream) {
  230. logger.error('Remote track received without callback.');
  231. jitsiRemoteTrack.dispose();
  232. return;
  233. }
  234. const isVideo = jitsiRemoteTrack.isVideoTrack();
  235. let videoType;
  236. if (isVideo) {
  237. videoType = this._options.convertVideoToDesktop
  238. ? VideoType.DESKTOP : VideoType.CAMERA;
  239. }
  240. // Grab the webrtc media stream and pipe it through the same processing
  241. // that would occur for a locally obtained media stream.
  242. const mediaStream = jitsiRemoteTrack.getOriginalStream();
  243. const jitsiLocalTracks = RTC.newCreateLocalTracks(
  244. [
  245. {
  246. deviceId:
  247. `proxy:${this._peerConnection.getPeerJid()}`,
  248. mediaType: isVideo ? MediaType.VIDEO : MediaType.AUDIO,
  249. sourceType: 'proxy',
  250. stream: mediaStream,
  251. track: mediaStream.getVideoTracks()[0],
  252. videoType
  253. }
  254. ]);
  255. this._options.onRemoteStream(jitsiLocalTracks[0]);
  256. }
  257. /**
  258. * Formats and forwards a message an iq to be sent to a peer jid.
  259. *
  260. * @param {string} peerJid - The jid the iq should be sent to.
  261. * @param {Object} iq - The iq which would be sent to the peer jid.
  262. * @private
  263. * @returns {void}
  264. */
  265. _onSendMessage(peerJid, iq) {
  266. if (!this._options.onSendMessage) {
  267. return;
  268. }
  269. try {
  270. const stringifiedIq
  271. = new XMLSerializer().serializeToString(iq.nodeTree || iq);
  272. this._options.onSendMessage(peerJid, { iq: stringifiedIq });
  273. } catch (e) {
  274. logger.error('Attempted to send an incorrectly formatted iq.');
  275. }
  276. }
  277. /**
  278. * Invoked when preemptively closing the {@code ProxyConnectionPC}.
  279. *
  280. * @private
  281. * @returns {void}
  282. */
  283. _selfCloseConnection() {
  284. this.stop();
  285. this._options.onConnectionClosed
  286. && this._options.onConnectionClosed();
  287. }
  288. }