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

ProxyConnectionService.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import { $iq } from 'strophe.js';
  4. import { MediaType } from '../../service/RTC/MediaType';
  5. import { getSourceNameForJitsiTrack } from '../../service/RTC/SignalingLayer';
  6. import { VideoType } from '../../service/RTC/VideoType';
  7. import RTC from '../RTC/RTC';
  8. import ProxyConnectionPC from './ProxyConnectionPC';
  9. import { ACTIONS } from './constants';
  10. const logger = getLogger(__filename);
  11. /**
  12. * Instantiates a new ProxyConnectionPC and ensures only one exists at a given
  13. * time. Currently it assumes ProxyConnectionPC is used only for screensharing
  14. * and assumes IQs to be used for communication.
  15. */
  16. export default class ProxyConnectionService {
  17. /**
  18. * Initializes a new {@code ProxyConnectionService} instance.
  19. *
  20. * @param {Object} options - Values to initialize the instance with.
  21. * @param {boolean} [options.convertVideoToDesktop] - Whether or not proxied video should be returned as a desktop
  22. * stream. Defaults to false.
  23. * @param {Object} [options.pcConfig] - The {@code RTCConfiguration} to use for the WebRTC peer connection.
  24. * @param {JitsiConnection} [options.jitsiConnection] - The {@code JitsiConnection} which will be used to fetch
  25. * TURN credentials for the P2P connection.
  26. * @param {Function} options.onRemoteStream - Callback to invoke when a remote video stream has been received and
  27. * converted to a {@code JitsiLocakTrack}. The {@code JitsiLocakTrack} will be passed in.
  28. * @param {Function} options.onSendMessage - Callback to invoke when a message has to be sent (signaled) out. The
  29. * arguments passed in are the jid to send the message to and the message.
  30. */
  31. constructor(options = {}) {
  32. const {
  33. jitsiConnection,
  34. ...otherOptions
  35. } = options;
  36. /**
  37. * Holds a reference to the collection of all callbacks.
  38. *
  39. * @type {Object}
  40. */
  41. this._options = {
  42. pcConfig: jitsiConnection && jitsiConnection.xmpp.connection.jingle.p2pIceConfig,
  43. ...otherOptions
  44. };
  45. /**
  46. * The active instance of {@code ProxyConnectionService}.
  47. *
  48. * @type {ProxyConnectionPC|null}
  49. */
  50. this._peerConnection = null;
  51. // Bind event handlers so they are only bound once for every instance.
  52. this._onFatalError = this._onFatalError.bind(this);
  53. this._onSendMessage = this._onSendMessage.bind(this);
  54. this._onRemoteStream = this._onRemoteStream.bind(this);
  55. }
  56. /**
  57. * Parses a message object regarding a proxy connection to create a new
  58. * proxy connection or update and existing connection.
  59. *
  60. * @param {Object} message - A message object regarding establishing or
  61. * updating a proxy connection.
  62. * @param {Object} message.data - An object containing additional message
  63. * details.
  64. * @param {string} message.data.iq - The stringified iq which explains how
  65. * and what to update regarding the proxy connection.
  66. * @param {string} message.from - The message sender's full jid. Used for
  67. * sending replies.
  68. * @returns {void}
  69. */
  70. processMessage(message) {
  71. const peerJid = message.from;
  72. if (!peerJid) {
  73. return;
  74. }
  75. // If a proxy connection has already been established and messages come
  76. // from another peer jid then those messages should be replied to with
  77. // a rejection.
  78. if (this._peerConnection
  79. && this._peerConnection.getPeerJid() !== peerJid) {
  80. this._onFatalError(
  81. peerJid,
  82. ACTIONS.CONNECTION_ERROR,
  83. 'rejected'
  84. );
  85. return;
  86. }
  87. const iq = this._convertStringToXML(message.data.iq);
  88. const $jingle = iq && iq.find('jingle');
  89. const action = $jingle && $jingle.attr('action');
  90. if (action === ACTIONS.INITIATE) {
  91. this._peerConnection = this._createPeerConnection(peerJid, {
  92. isInitiator: false,
  93. receiveVideo: true
  94. });
  95. }
  96. // Truthy check for peer connection added to protect against possibly
  97. // receiving actions before an ACTIONS.INITIATE.
  98. if (this._peerConnection) {
  99. this._peerConnection.processMessage($jingle);
  100. }
  101. // Take additional steps to ensure the peer connection is cleaned up
  102. // if it is to be closed.
  103. if (action === ACTIONS.CONNECTION_ERROR
  104. || action === ACTIONS.UNAVAILABLE
  105. || action === ACTIONS.TERMINATE) {
  106. this._selfCloseConnection();
  107. }
  108. return;
  109. }
  110. /**
  111. * Instantiates and initiates a proxy peer connection.
  112. *
  113. * @param {string} peerJid - The jid of the remote client that should
  114. * receive messages.
  115. * @param {Array<JitsiLocalTrack>} localTracks - Initial media tracks to
  116. * send through to the peer.
  117. * @returns {void}
  118. */
  119. start(peerJid, localTracks = []) {
  120. this._peerConnection = this._createPeerConnection(peerJid, {
  121. isInitiator: true,
  122. receiveVideo: false
  123. });
  124. localTracks.forEach((localTrack, localTrackIndex) => {
  125. const localSourceNameTrack = getSourceNameForJitsiTrack('peer', localTrack.getType(), localTrackIndex);
  126. localTrack.setSourceName(localSourceNameTrack);
  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. pcConfig: this._options.pcConfig,
  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.createLocalTracks(
  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. }