util.js 7.6 KB

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