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ů.

DataChannels.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // cache datachannels to avoid garbage collection
  2. // https://code.google.com/p/chromium/issues/detail?id=405545
  3. const logger = require('jitsi-meet-logger').getLogger(__filename);
  4. const RTCEvents = require('../../service/RTC/RTCEvents');
  5. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  6. /**
  7. * Binds "ondatachannel" event listener to given PeerConnection instance.
  8. * @param peerConnection WebRTC peer connection instance.
  9. */
  10. function DataChannels(peerConnection, emitter) {
  11. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  12. this.eventEmitter = emitter;
  13. this._dataChannels = [];
  14. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  15. // Although it's not a requirement to open separate channels from both
  16. // bridge and peer as single channel can be used for sending and receiving
  17. // data. So either channel opened by the bridge or the one opened here is
  18. // enough for communication with the bridge.
  19. /* var dataChannelOptions =
  20. {
  21. reliable: true
  22. };
  23. var dataChannel
  24. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  25. // Can be used only when is in open state
  26. dataChannel.onopen = function ()
  27. {
  28. dataChannel.send("My channel !!!");
  29. };
  30. dataChannel.onmessage = function (event)
  31. {
  32. var msgData = event.data;
  33. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  34. };*/
  35. }
  36. /**
  37. * Callback triggered by PeerConnection when new data channel is opened
  38. * on the bridge.
  39. * @param event the event info object.
  40. */
  41. DataChannels.prototype.onDataChannel = function(event) {
  42. const dataChannel = event.channel;
  43. const self = this;
  44. dataChannel.onopen = function() {
  45. logger.info('Data channel opened by the Videobridge!', dataChannel);
  46. // Code sample for sending string and/or binary data
  47. // Sends String message to the bridge
  48. // dataChannel.send("Hello bridge!");
  49. // Sends 12 bytes binary message to the bridge
  50. // dataChannel.send(new ArrayBuffer(12));
  51. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  52. };
  53. dataChannel.onerror = function(error) {
  54. // FIXME: this one seems to be generated a bit too often right now
  55. // so we are temporarily commenting it before we have more clarity
  56. // on which of the errors we absolutely need to report
  57. // GlobalOnErrorHandler.callErrorHandler(
  58. // new Error("Data Channel Error:" + error));
  59. logger.error('Data Channel Error:', error, dataChannel);
  60. };
  61. dataChannel.onmessage = function({ data }) {
  62. // JSON
  63. let obj;
  64. try {
  65. obj = JSON.parse(data);
  66. } catch (e) {
  67. GlobalOnErrorHandler.callErrorHandler(e);
  68. logger.error(
  69. 'Failed to parse data channel message as JSON: ',
  70. data,
  71. dataChannel,
  72. e);
  73. }
  74. if ((typeof obj !== 'undefined') && (obj !== null)) {
  75. const colibriClass = obj.colibriClass;
  76. if (colibriClass === 'DominantSpeakerEndpointChangeEvent') {
  77. // Endpoint ID from the Videobridge.
  78. const dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  79. logger.info(
  80. 'Data channel new dominant speaker event: ',
  81. dominantSpeakerEndpoint);
  82. self.eventEmitter.emit(RTCEvents.DOMINANT_SPEAKER_CHANGED,
  83. dominantSpeakerEndpoint);
  84. } else if (colibriClass === 'LastNEndpointsChangeEvent') {
  85. // The new/latest list of last-n endpoint IDs.
  86. const lastNEndpoints = obj.lastNEndpoints;
  87. // The list of endpoint IDs which are entering the list of
  88. // last-n at this time i.e. were not in the old list of last-n
  89. // endpoint IDs.
  90. const endpointsEnteringLastN = obj.endpointsEnteringLastN;
  91. logger.info('Data channel new last-n event: ',
  92. lastNEndpoints, endpointsEnteringLastN, obj);
  93. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  94. lastNEndpoints, endpointsEnteringLastN, obj);
  95. } else if (colibriClass === 'EndpointMessage') {
  96. self.eventEmitter.emit(
  97. RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from,
  98. obj.msgPayload);
  99. } else if (colibriClass
  100. === 'EndpointConnectivityStatusChangeEvent') {
  101. const endpoint = obj.endpoint;
  102. const isActive = obj.active === 'true';
  103. logger.info(
  104. `Endpoint connection status changed: ${endpoint} active ? ${
  105. isActive}`);
  106. self.eventEmitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED,
  107. endpoint, isActive);
  108. } else {
  109. logger.debug('Data channel JSON-formatted message: ', obj);
  110. // The received message appears to be appropriately formatted
  111. // (i.e. is a JSON object which assigns a value to the mandatory
  112. // property colibriClass) so don't just swallow it, expose it to
  113. // public consumption.
  114. self.eventEmitter.emit(`rtc.datachannel.${colibriClass}`, obj);
  115. }
  116. }
  117. };
  118. dataChannel.onclose = function() {
  119. logger.info('The Data Channel closed', dataChannel);
  120. const idx = self._dataChannels.indexOf(dataChannel);
  121. if (idx > -1) {
  122. self._dataChannels = self._dataChannels.splice(idx, 1);
  123. }
  124. };
  125. this._dataChannels.push(dataChannel);
  126. };
  127. /**
  128. * Closes all currently opened data channels.
  129. */
  130. DataChannels.prototype.closeAllChannels = function() {
  131. this._dataChannels.forEach(dc => {
  132. // the DC will be removed from the array on 'onclose' event
  133. dc.close();
  134. });
  135. };
  136. /**
  137. * Sends a "selected endpoint changed" message via the data channel.
  138. * @param endpointId {string} the id of the selected endpoint
  139. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  140. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  141. * or Error with "No opened data channels found!" message.
  142. */
  143. DataChannels.prototype.sendSelectedEndpointMessage = function(endpointId) {
  144. this._onXXXEndpointChanged('selected', endpointId);
  145. };
  146. /**
  147. * Sends a "pinned endpoint changed" message via the data channel.
  148. * @param endpointId {string} the id of the pinned endpoint
  149. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  150. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  151. * or Error with "No opened data channels found!" message.
  152. */
  153. DataChannels.prototype.sendPinnedEndpointMessage = function(endpointId) {
  154. this._onXXXEndpointChanged('pinned', endpointId);
  155. };
  156. /**
  157. * Notifies Videobridge about a change in the value of a specific
  158. * endpoint-related property such as selected endpoint and pinned endpoint.
  159. *
  160. * @param xxx the name of the endpoint-related property whose value changed
  161. * @param userResource the new value of the endpoint-related property after the
  162. * change
  163. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  164. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  165. * or Error with "No opened data channels found!" message.
  166. */
  167. DataChannels.prototype._onXXXEndpointChanged = function(xxx, userResource) {
  168. // Derive the correct words from xxx such as selected and Selected, pinned
  169. // and Pinned.
  170. const head = xxx.charAt(0);
  171. const tail = xxx.substring(1);
  172. const lower = head.toLowerCase() + tail;
  173. const upper = head.toUpperCase() + tail;
  174. logger.log(
  175. `sending ${lower} endpoint changed notification to the bridge: `,
  176. userResource);
  177. const jsonObject = {};
  178. jsonObject.colibriClass = `${upper}EndpointChangedEvent`;
  179. jsonObject[`${lower}Endpoint`]
  180. = userResource ? userResource : null;
  181. this.send(jsonObject);
  182. // Notify Videobridge about the specified endpoint change.
  183. logger.log(`${lower} endpoint changed: `, userResource);
  184. };
  185. DataChannels.prototype._some = function(callback, thisArg) {
  186. const dataChannels = this._dataChannels;
  187. if (dataChannels && dataChannels.length !== 0) {
  188. if (thisArg) {
  189. return dataChannels.some(callback, thisArg);
  190. }
  191. return dataChannels.some(callback);
  192. }
  193. return false;
  194. };
  195. /**
  196. * Sends passed object via the first found open datachannel
  197. * @param jsonObject {object} the object that will be sent
  198. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  199. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  200. * or Error with "No opened data channels found!" message.
  201. */
  202. DataChannels.prototype.send = function(jsonObject) {
  203. if (!this._some(dataChannel => {
  204. if (dataChannel.readyState === 'open') {
  205. dataChannel.send(JSON.stringify(jsonObject));
  206. return true;
  207. }
  208. })) {
  209. throw new Error('No opened data channels found!');
  210. }
  211. };
  212. /**
  213. * Sends message via the datachannels.
  214. * @param to {string} the id of the endpoint that should receive the message.
  215. * If "" the message will be sent to all participants.
  216. * @param payload {object} the payload of the message.
  217. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  218. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  219. * or Error with "No opened data channels found!" message.
  220. */
  221. DataChannels.prototype.sendDataChannelMessage = function(to, payload) {
  222. this.send({
  223. colibriClass: 'EndpointMessage',
  224. to,
  225. msgPayload: payload
  226. });
  227. };
  228. /**
  229. * Sends a "lastN value changed" message via the data channel.
  230. * @param value {int} The new value for lastN. -1 means unlimited.
  231. */
  232. DataChannels.prototype.sendSetLastNMessage = function(value) {
  233. const jsonObject = {
  234. colibriClass: 'LastNChangedEvent',
  235. lastN: value
  236. };
  237. this.send(jsonObject);
  238. logger.log(`Channel lastN set to: ${value}`);
  239. };
  240. module.exports = DataChannels;