util.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. // Lists which features are supported
  58. // Temporarily set everything to true
  59. supports: (function(){
  60. return {
  61. audioVideo: true,
  62. data: true,
  63. binary: false,
  64. reliable: (function() {
  65. // Reliable (not RTP).
  66. var pc = new RTCPeerConnection(defaultConfig, {});
  67. try {
  68. pc.createDataChannel('PEERJSRELIABLETEST');
  69. } catch (e) {
  70. if (e.name === 'NotSupportedError') {
  71. return false
  72. }
  73. }
  74. })(),
  75. onnegotiationneeded: true,
  76. interop: false
  77. };
  78. }()),
  79. //
  80. // Ensure alphanumeric ids
  81. validateId: function(id) {
  82. // Allow empty ids
  83. return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id);
  84. },
  85. validateKey: function(key) {
  86. // Allow empty keys
  87. return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key);
  88. },
  89. // OLD
  90. chromeCompatible: true,
  91. firefoxCompatible: true,
  92. chromeVersion: 26,
  93. firefoxVersion: 22,
  94. debug: false,
  95. browserisms: '',
  96. inherits: function(ctor, superCtor) {
  97. ctor.super_ = superCtor;
  98. ctor.prototype = Object.create(superCtor.prototype, {
  99. constructor: {
  100. value: ctor,
  101. enumerable: false,
  102. writable: true,
  103. configurable: true
  104. }
  105. });
  106. },
  107. extend: function(dest, source) {
  108. for(var key in source) {
  109. if(source.hasOwnProperty(key)) {
  110. dest[key] = source[key];
  111. }
  112. }
  113. return dest;
  114. },
  115. pack: BinaryPack.pack,
  116. unpack: BinaryPack.unpack,
  117. log: function () {
  118. if (util.debug) {
  119. var err = false;
  120. var copy = Array.prototype.slice.call(arguments);
  121. copy.unshift('PeerJS: ');
  122. for (var i = 0, l = copy.length; i < l; i++){
  123. if (copy[i] instanceof Error) {
  124. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  125. err = true;
  126. }
  127. }
  128. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  129. }
  130. },
  131. setZeroTimeout: (function(global) {
  132. var timeouts = [];
  133. var messageName = 'zero-timeout-message';
  134. // Like setTimeout, but only takes a function argument. There's
  135. // no time argument (always zero) and no arguments (you have to
  136. // use a closure).
  137. function setZeroTimeoutPostMessage(fn) {
  138. timeouts.push(fn);
  139. global.postMessage(messageName, '*');
  140. }
  141. function handleMessage(event) {
  142. if (event.source == global && event.data == messageName) {
  143. if (event.stopPropagation) {
  144. event.stopPropagation();
  145. }
  146. if (timeouts.length) {
  147. timeouts.shift()();
  148. }
  149. }
  150. }
  151. if (global.addEventListener) {
  152. global.addEventListener('message', handleMessage, true);
  153. } else if (global.attachEvent) {
  154. global.attachEvent('onmessage', handleMessage);
  155. }
  156. return setZeroTimeoutPostMessage;
  157. }(this)),
  158. // Binary stuff
  159. blobToArrayBuffer: function(blob, cb){
  160. var fr = new FileReader();
  161. fr.onload = function(evt) {
  162. cb(evt.target.result);
  163. };
  164. fr.readAsArrayBuffer(blob);
  165. },
  166. blobToBinaryString: function(blob, cb){
  167. var fr = new FileReader();
  168. fr.onload = function(evt) {
  169. cb(evt.target.result);
  170. };
  171. fr.readAsBinaryString(blob);
  172. },
  173. binaryStringToArrayBuffer: function(binary) {
  174. var byteArray = new Uint8Array(binary.length);
  175. for (var i = 0; i < binary.length; i++) {
  176. byteArray[i] = binary.charCodeAt(i) & 0xff;
  177. }
  178. return byteArray.buffer;
  179. },
  180. randomToken: function () {
  181. return Math.random().toString(36).substr(2);
  182. },
  183. //
  184. // When we have proper version/feature mappings we can remove this
  185. isBrowserCompatible: function() {
  186. var c, f;
  187. if (this.chromeCompatible) {
  188. if ((c = navigator.userAgent.split('Chrome/')) && c.length > 1) {
  189. // Get version #.
  190. var v = c[1].split('.')[0];
  191. return parseInt(v) >= this.chromeVersion;
  192. }
  193. }
  194. if (this.firefoxCompatible) {
  195. if ((f = navigator.userAgent.split('Firefox/')) && f.length > 1) {
  196. // Get version #.
  197. var v = f[1].split('.')[0];
  198. return parseInt(v) >= this.firefoxVersion;
  199. }
  200. }
  201. return false;
  202. },
  203. isSecure: function() {
  204. return location.protocol === 'https:';
  205. }
  206. };
  207. exports.util = util;