You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DataChannels.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // cache datachannels to avoid garbage collection
  2. // https://code.google.com/p/chromium/issues/detail?id=405545
  3. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var RTCEvents = require("../../service/RTC/RTCEvents");
  5. var 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 bridge
  16. // and peer as single channel can be used for sending and receiving data.
  17. // So either channel opened by the bridge or the one opened here is enough
  18. // 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. var dataChannel = event.channel;
  43. var 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 (event) {
  62. var data = event.data;
  63. // JSON
  64. var obj;
  65. try {
  66. obj = JSON.parse(data);
  67. } catch (e) {
  68. GlobalOnErrorHandler.callErrorHandler(e);
  69. logger.error(
  70. "Failed to parse data channel message as JSON: ",
  71. data,
  72. dataChannel,
  73. e);
  74. }
  75. if (('undefined' !== typeof obj) && (null !== obj)) {
  76. var colibriClass = obj.colibriClass;
  77. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  78. // Endpoint ID from the Videobridge.
  79. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  80. logger.info(
  81. "Data channel new dominant speaker event: ",
  82. dominantSpeakerEndpoint);
  83. self.eventEmitter.emit(RTCEvents.DOMINANT_SPEAKER_CHANGED,
  84. dominantSpeakerEndpoint);
  85. } else if ("InLastNChangeEvent" === colibriClass) {
  86. var oldValue = obj.oldValue;
  87. var newValue = obj.newValue;
  88. // Make sure that oldValue and newValue are of type boolean.
  89. var type;
  90. if ((type = typeof oldValue) !== 'boolean') {
  91. if (type === 'string') {
  92. oldValue = oldValue == "true";
  93. } else {
  94. oldValue = new Boolean(oldValue).valueOf();
  95. }
  96. }
  97. if ((type = typeof newValue) !== 'boolean') {
  98. if (type === 'string') {
  99. newValue = newValue == "true";
  100. } else {
  101. newValue = new Boolean(newValue).valueOf();
  102. }
  103. }
  104. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  105. } else if ("LastNEndpointsChangeEvent" === colibriClass) {
  106. // The new/latest list of last-n endpoint IDs.
  107. var lastNEndpoints = obj.lastNEndpoints;
  108. // The list of endpoint IDs which are entering the list of
  109. // last-n at this time i.e. were not in the old list of last-n
  110. // endpoint IDs.
  111. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  112. logger.info(
  113. "Data channel new last-n event: ",
  114. lastNEndpoints, endpointsEnteringLastN, obj);
  115. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  116. lastNEndpoints, endpointsEnteringLastN, obj);
  117. } else if("EndpointMessage" === colibriClass) {
  118. self.eventEmitter.emit(
  119. RTCEvents.ENDPOINT_MESSAGE_RECEIVED, obj.from,
  120. obj.msgPayload);
  121. } else if ("EndpointConnectivityStatusChangeEvent" === colibriClass) {
  122. var endpoint = obj.endpoint;
  123. var isActive = obj.active === "true";
  124. logger.info("Endpoint connection status changed: " + endpoint
  125. + " active ? " + isActive);
  126. self.eventEmitter.emit(RTCEvents.ENDPOINT_CONN_STATUS_CHANGED,
  127. endpoint, isActive);
  128. } else {
  129. logger.debug("Data channel JSON-formatted message: ", obj);
  130. // The received message appears to be appropriately formatted
  131. // (i.e. is a JSON object which assigns a value to the mandatory
  132. // property colibriClass) so don't just swallow it, expose it to
  133. // public consumption.
  134. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  135. }
  136. }
  137. };
  138. dataChannel.onclose = function () {
  139. logger.info("The Data Channel closed", dataChannel);
  140. var idx = self._dataChannels.indexOf(dataChannel);
  141. if (idx > -1) {
  142. self._dataChannels = self._dataChannels.splice(idx, 1);
  143. }
  144. };
  145. this._dataChannels.push(dataChannel);
  146. };
  147. /**
  148. * Closes all currently opened data channels.
  149. */
  150. DataChannels.prototype.closeAllChannels = function () {
  151. this._dataChannels.forEach(function (dc){
  152. // the DC will be removed from the array on 'onclose' event
  153. dc.close();
  154. });
  155. };
  156. /**
  157. * Sends a "selected endpoint changed" message via the data channel.
  158. * @param endpointId {string} the id of the selected endpoint
  159. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  160. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  161. * or Error with "No opened data channels found!" message.
  162. */
  163. DataChannels.prototype.sendSelectedEndpointMessage = function (endpointId) {
  164. this._onXXXEndpointChanged("selected", endpointId);
  165. };
  166. /**
  167. * Sends a "pinned endpoint changed" message via the data channel.
  168. * @param endpointId {string} the id of the pinned endpoint
  169. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  170. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  171. * or Error with "No opened data channels found!" message.
  172. */
  173. DataChannels.prototype.sendPinnedEndpointMessage = function (endpointId) {
  174. this._onXXXEndpointChanged("pinned", endpointId);
  175. };
  176. /**
  177. * Notifies Videobridge about a change in the value of a specific
  178. * endpoint-related property such as selected endpoint and pinned endpoint.
  179. *
  180. * @param xxx the name of the endpoint-related property whose value changed
  181. * @param userResource the new value of the endpoint-related property after the
  182. * change
  183. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  184. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  185. * or Error with "No opened data channels found!" message.
  186. */
  187. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  188. // Derive the correct words from xxx such as selected and Selected, pinned
  189. // and Pinned.
  190. var head = xxx.charAt(0);
  191. var tail = xxx.substring(1);
  192. var lower = head.toLowerCase() + tail;
  193. var upper = head.toUpperCase() + tail;
  194. logger.log(
  195. 'sending ' + lower
  196. + ' endpoint changed notification to the bridge: ',
  197. userResource);
  198. var jsonObject = {};
  199. jsonObject.colibriClass = upper + 'EndpointChangedEvent';
  200. jsonObject[lower + "Endpoint"]
  201. = userResource ? userResource : null;
  202. this.send(jsonObject);
  203. // Notify Videobridge about the specified endpoint change.
  204. logger.log(lower + ' endpoint changed: ', userResource);
  205. };
  206. DataChannels.prototype._some = function (callback, thisArg) {
  207. var dataChannels = this._dataChannels;
  208. if (dataChannels && dataChannels.length !== 0) {
  209. if (thisArg) {
  210. return dataChannels.some(callback, thisArg);
  211. } else {
  212. return dataChannels.some(callback);
  213. }
  214. } else {
  215. return false;
  216. }
  217. };
  218. /**
  219. * Sends passed object via the first found open datachannel
  220. * @param jsonObject {object} the object that will be sent
  221. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  222. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  223. * or Error with "No opened data channels found!" message.
  224. */
  225. DataChannels.prototype.send = function (jsonObject) {
  226. if(!this._some(function (dataChannel) {
  227. if (dataChannel.readyState == 'open') {
  228. dataChannel.send(JSON.stringify(jsonObject));
  229. return true;
  230. }
  231. })) {
  232. throw new Error("No opened data channels found!");
  233. }
  234. };
  235. /**
  236. * Sends message via the datachannels.
  237. * @param to {string} the id of the endpoint that should receive the message.
  238. * If "" the message will be sent to all participants.
  239. * @param payload {object} the payload of the message.
  240. * @throws NetworkError or InvalidStateError from RTCDataChannel#send (@see
  241. * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/send})
  242. * or Error with "No opened data channels found!" message.
  243. */
  244. DataChannels.prototype.sendDataChannelMessage = function (to, payload) {
  245. this.send({
  246. colibriClass: "EndpointMessage",
  247. to: to,
  248. msgPayload: payload
  249. });
  250. };
  251. /**
  252. * Sends a "lastN value changed" message via the data channel.
  253. * @param value {int} The new value for lastN. -1 means unlimited.
  254. */
  255. DataChannels.prototype.sendSetLastNMessage = function (value) {
  256. const jsonObject = {
  257. colibriClass : 'LastNChangedEvent',
  258. lastN : value
  259. };
  260. this.send(jsonObject);
  261. logger.log('Channel lastN set to: ' + value);
  262. };
  263. module.exports = DataChannels;