util.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. var defaultConfig = {'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]};
  2. var util = {
  3. noop: function() {},
  4. CLOUD_HOST: '0.peerjs.com',
  5. CLOUD_PORT: 9000,
  6. // Logging logic
  7. logLevel: 0,
  8. setLogLevel: function(level) {
  9. var debugLevel = parseInt(level, 10);
  10. if (!isNaN(parseInt(level, 10))) {
  11. util.logLevel = debugLevel;
  12. } else {
  13. // If they are using truthy/falsy values for debug
  14. util.logLevel = level ? 3 : 0;
  15. }
  16. util.log = util.warn = util.error = util.noop;
  17. if (util.logLevel > 0) {
  18. util.error = util._printWith('ERROR');
  19. }
  20. if (util.logLevel > 1) {
  21. util.warn = util._printWith('WARNING');
  22. }
  23. if (util.logLevel > 2) {
  24. util.log = util._print;
  25. }
  26. },
  27. setLogFunction: function(fn) {
  28. if (fn.constructor !== Function) {
  29. util.warn('The log function you passed in is not a function. Defaulting to regular logs.');
  30. } else {
  31. util._print = fn;
  32. }
  33. },
  34. _printWith: function(prefix) {
  35. return function() {
  36. var copy = Array.prototype.slice.call(arguments);
  37. copy.unshift(prefix);
  38. util._print.apply(util, copy);
  39. };
  40. },
  41. _print: function () {
  42. var err = false;
  43. var copy = Array.prototype.slice.call(arguments);
  44. copy.unshift('PeerJS: ');
  45. for (var i = 0, l = copy.length; i < l; i++){
  46. if (copy[i] instanceof Error) {
  47. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  48. err = true;
  49. }
  50. }
  51. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  52. },
  53. //
  54. // Returns browser-agnostic default config
  55. defaultConfig: defaultConfig,
  56. //
  57. // Returns the current browser.
  58. browser: (function() {
  59. if (window.mozRTCPeerConnection) {
  60. return 'Firefox';
  61. } else if (window.webkitRTCPeerConnection) {
  62. return 'Chrome';
  63. } else if (window.RTCPeerConnection) {
  64. return 'Supported';
  65. } else {
  66. return 'Unsupported';
  67. }
  68. })(),
  69. //
  70. // Lists which features are supported
  71. supports: (function() {
  72. if (typeof RTCPeerConnection === 'undefined') {
  73. return {};
  74. }
  75. var data = true;
  76. var audioVideo = true;
  77. var binaryBlob = false;
  78. var sctp = false;
  79. var onnegotiationneeded = !!window.webkitRTCPeerConnection;
  80. var pc, dc;
  81. try {
  82. pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  83. } catch (e) {
  84. data = false;
  85. audioVideo = false;
  86. }
  87. if (data) {
  88. try {
  89. dc = pc.createDataChannel('_PEERJSTEST');
  90. } catch (e) {
  91. data = false;
  92. }
  93. }
  94. if (data) {
  95. // Binary test
  96. try {
  97. dc.binaryType = 'blob';
  98. binaryBlob = true;
  99. } catch (e) {
  100. }
  101. // Reliable test.
  102. // Unfortunately Chrome is a bit unreliable about whether or not they
  103. // support reliable.
  104. var reliablePC = new RTCPeerConnection(defaultConfig, {});
  105. try {
  106. var reliableDC = reliablePC.createDataChannel('_PEERJSRELIABLETEST', {});
  107. sctp = reliableDC.reliable;
  108. } catch (e) {
  109. }
  110. reliablePC.close();
  111. }
  112. // FIXME: not really the best check...
  113. if (audioVideo) {
  114. audioVideo = !!pc.addStream;
  115. }
  116. // FIXME: this is not great because in theory it doesn't work for
  117. // av-only browsers (?).
  118. if (!onnegotiationneeded && data) {
  119. // sync default check.
  120. var negotiationPC = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  121. negotiationPC.onnegotiationneeded = function() {
  122. onnegotiationneeded = true;
  123. // async check.
  124. if (util && util.supports) {
  125. util.supports.onnegotiationneeded = true;
  126. }
  127. };
  128. var negotiationDC = negotiationPC.createDataChannel('_PEERJSNEGOTIATIONTEST');
  129. setTimeout(function() {
  130. negotiationPC.close();
  131. }, 1000);
  132. }
  133. if (pc) {
  134. pc.close();
  135. }
  136. return {
  137. audioVideo: audioVideo,
  138. data: data,
  139. binaryBlob: binaryBlob,
  140. binary: sctp, // deprecated; sctp implies binary support.
  141. reliable: sctp, // deprecated; sctp implies reliable data.
  142. sctp: sctp,
  143. onnegotiationneeded: onnegotiationneeded
  144. };
  145. }()),
  146. //
  147. // Ensure alphanumeric ids
  148. validateId: function(id) {
  149. // Allow empty ids
  150. return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id);
  151. },
  152. validateKey: function(key) {
  153. // Allow empty keys
  154. return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key);
  155. },
  156. debug: false,
  157. inherits: function(ctor, superCtor) {
  158. ctor.super_ = superCtor;
  159. ctor.prototype = Object.create(superCtor.prototype, {
  160. constructor: {
  161. value: ctor,
  162. enumerable: false,
  163. writable: true,
  164. configurable: true
  165. }
  166. });
  167. },
  168. extend: function(dest, source) {
  169. for(var key in source) {
  170. if(source.hasOwnProperty(key)) {
  171. dest[key] = source[key];
  172. }
  173. }
  174. return dest;
  175. },
  176. pack: BinaryPack.pack,
  177. unpack: BinaryPack.unpack,
  178. log: function () {
  179. if (util.debug) {
  180. var err = false;
  181. var copy = Array.prototype.slice.call(arguments);
  182. copy.unshift('PeerJS: ');
  183. for (var i = 0, l = copy.length; i < l; i++){
  184. if (copy[i] instanceof Error) {
  185. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  186. err = true;
  187. }
  188. }
  189. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  190. }
  191. },
  192. setZeroTimeout: (function(global) {
  193. var timeouts = [];
  194. var messageName = 'zero-timeout-message';
  195. // Like setTimeout, but only takes a function argument. There's
  196. // no time argument (always zero) and no arguments (you have to
  197. // use a closure).
  198. function setZeroTimeoutPostMessage(fn) {
  199. timeouts.push(fn);
  200. global.postMessage(messageName, '*');
  201. }
  202. function handleMessage(event) {
  203. if (event.source == global && event.data == messageName) {
  204. if (event.stopPropagation) {
  205. event.stopPropagation();
  206. }
  207. if (timeouts.length) {
  208. timeouts.shift()();
  209. }
  210. }
  211. }
  212. if (global.addEventListener) {
  213. global.addEventListener('message', handleMessage, true);
  214. } else if (global.attachEvent) {
  215. global.attachEvent('onmessage', handleMessage);
  216. }
  217. return setZeroTimeoutPostMessage;
  218. }(this)),
  219. // Binary stuff
  220. blobToArrayBuffer: function(blob, cb){
  221. var fr = new FileReader();
  222. fr.onload = function(evt) {
  223. cb(evt.target.result);
  224. };
  225. fr.readAsArrayBuffer(blob);
  226. },
  227. blobToBinaryString: function(blob, cb){
  228. var fr = new FileReader();
  229. fr.onload = function(evt) {
  230. cb(evt.target.result);
  231. };
  232. fr.readAsBinaryString(blob);
  233. },
  234. binaryStringToArrayBuffer: function(binary) {
  235. var byteArray = new Uint8Array(binary.length);
  236. for (var i = 0; i < binary.length; i++) {
  237. byteArray[i] = binary.charCodeAt(i) & 0xff;
  238. }
  239. return byteArray.buffer;
  240. },
  241. randomToken: function () {
  242. return Math.random().toString(36).substr(2);
  243. },
  244. //
  245. isSecure: function() {
  246. return location.protocol === 'https:';
  247. }
  248. };
  249. exports.util = util;