peer.js 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407
  1. /*! peerjs.js build:0.2.8, development. Copyright(c) 2013 Michelle Bu <michelle@michellebu.com> */
  2. (function(exports){
  3. var binaryFeatures = {};
  4. binaryFeatures.useBlobBuilder = (function(){
  5. try {
  6. new Blob([]);
  7. return false;
  8. } catch (e) {
  9. return true;
  10. }
  11. })();
  12. binaryFeatures.useArrayBufferView = !binaryFeatures.useBlobBuilder && (function(){
  13. try {
  14. return (new Blob([new Uint8Array([])])).size === 0;
  15. } catch (e) {
  16. return true;
  17. }
  18. })();
  19. exports.binaryFeatures = binaryFeatures;
  20. exports.BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
  21. function BufferBuilder(){
  22. this._pieces = [];
  23. this._parts = [];
  24. }
  25. BufferBuilder.prototype.append = function(data) {
  26. if(typeof data === 'number') {
  27. this._pieces.push(data);
  28. } else {
  29. this._flush();
  30. this._parts.push(data);
  31. }
  32. };
  33. BufferBuilder.prototype._flush = function() {
  34. if (this._pieces.length > 0) {
  35. var buf = new Uint8Array(this._pieces);
  36. if(!binaryFeatures.useArrayBufferView) {
  37. buf = buf.buffer;
  38. }
  39. this._parts.push(buf);
  40. this._pieces = [];
  41. }
  42. };
  43. BufferBuilder.prototype.getBuffer = function() {
  44. this._flush();
  45. if(binaryFeatures.useBlobBuilder) {
  46. var builder = new BlobBuilder();
  47. for(var i = 0, ii = this._parts.length; i < ii; i++) {
  48. builder.append(this._parts[i]);
  49. }
  50. return builder.getBlob();
  51. } else {
  52. return new Blob(this._parts);
  53. }
  54. };
  55. exports.BinaryPack = {
  56. unpack: function(data){
  57. var unpacker = new Unpacker(data);
  58. return unpacker.unpack();
  59. },
  60. pack: function(data, utf8){
  61. var packer = new Packer(utf8);
  62. var buffer = packer.pack(data);
  63. return buffer;
  64. }
  65. };
  66. function Unpacker (data){
  67. // Data is ArrayBuffer
  68. this.index = 0;
  69. this.dataBuffer = data;
  70. this.dataView = new Uint8Array(this.dataBuffer);
  71. this.length = this.dataBuffer.byteLength;
  72. }
  73. Unpacker.prototype.unpack = function(){
  74. var type = this.unpack_uint8();
  75. if (type < 0x80){
  76. var positive_fixnum = type;
  77. return positive_fixnum;
  78. } else if ((type ^ 0xe0) < 0x20){
  79. var negative_fixnum = (type ^ 0xe0) - 0x20;
  80. return negative_fixnum;
  81. }
  82. var size;
  83. if ((size = type ^ 0xa0) <= 0x0f){
  84. return this.unpack_raw(size);
  85. } else if ((size = type ^ 0xb0) <= 0x0f){
  86. return this.unpack_string(size);
  87. } else if ((size = type ^ 0x90) <= 0x0f){
  88. return this.unpack_array(size);
  89. } else if ((size = type ^ 0x80) <= 0x0f){
  90. return this.unpack_map(size);
  91. }
  92. switch(type){
  93. case 0xc0:
  94. return null;
  95. case 0xc1:
  96. return undefined;
  97. case 0xc2:
  98. return false;
  99. case 0xc3:
  100. return true;
  101. case 0xca:
  102. return this.unpack_float();
  103. case 0xcb:
  104. return this.unpack_double();
  105. case 0xcc:
  106. return this.unpack_uint8();
  107. case 0xcd:
  108. return this.unpack_uint16();
  109. case 0xce:
  110. return this.unpack_uint32();
  111. case 0xcf:
  112. return this.unpack_uint64();
  113. case 0xd0:
  114. return this.unpack_int8();
  115. case 0xd1:
  116. return this.unpack_int16();
  117. case 0xd2:
  118. return this.unpack_int32();
  119. case 0xd3:
  120. return this.unpack_int64();
  121. case 0xd4:
  122. return undefined;
  123. case 0xd5:
  124. return undefined;
  125. case 0xd6:
  126. return undefined;
  127. case 0xd7:
  128. return undefined;
  129. case 0xd8:
  130. size = this.unpack_uint16();
  131. return this.unpack_string(size);
  132. case 0xd9:
  133. size = this.unpack_uint32();
  134. return this.unpack_string(size);
  135. case 0xda:
  136. size = this.unpack_uint16();
  137. return this.unpack_raw(size);
  138. case 0xdb:
  139. size = this.unpack_uint32();
  140. return this.unpack_raw(size);
  141. case 0xdc:
  142. size = this.unpack_uint16();
  143. return this.unpack_array(size);
  144. case 0xdd:
  145. size = this.unpack_uint32();
  146. return this.unpack_array(size);
  147. case 0xde:
  148. size = this.unpack_uint16();
  149. return this.unpack_map(size);
  150. case 0xdf:
  151. size = this.unpack_uint32();
  152. return this.unpack_map(size);
  153. }
  154. }
  155. Unpacker.prototype.unpack_uint8 = function(){
  156. var byte = this.dataView[this.index] & 0xff;
  157. this.index++;
  158. return byte;
  159. };
  160. Unpacker.prototype.unpack_uint16 = function(){
  161. var bytes = this.read(2);
  162. var uint16 =
  163. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  164. this.index += 2;
  165. return uint16;
  166. }
  167. Unpacker.prototype.unpack_uint32 = function(){
  168. var bytes = this.read(4);
  169. var uint32 =
  170. ((bytes[0] * 256 +
  171. bytes[1]) * 256 +
  172. bytes[2]) * 256 +
  173. bytes[3];
  174. this.index += 4;
  175. return uint32;
  176. }
  177. Unpacker.prototype.unpack_uint64 = function(){
  178. var bytes = this.read(8);
  179. var uint64 =
  180. ((((((bytes[0] * 256 +
  181. bytes[1]) * 256 +
  182. bytes[2]) * 256 +
  183. bytes[3]) * 256 +
  184. bytes[4]) * 256 +
  185. bytes[5]) * 256 +
  186. bytes[6]) * 256 +
  187. bytes[7];
  188. this.index += 8;
  189. return uint64;
  190. }
  191. Unpacker.prototype.unpack_int8 = function(){
  192. var uint8 = this.unpack_uint8();
  193. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  194. };
  195. Unpacker.prototype.unpack_int16 = function(){
  196. var uint16 = this.unpack_uint16();
  197. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  198. }
  199. Unpacker.prototype.unpack_int32 = function(){
  200. var uint32 = this.unpack_uint32();
  201. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  202. uint32 - Math.pow(2, 32);
  203. }
  204. Unpacker.prototype.unpack_int64 = function(){
  205. var uint64 = this.unpack_uint64();
  206. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  207. uint64 - Math.pow(2, 64);
  208. }
  209. Unpacker.prototype.unpack_raw = function(size){
  210. if ( this.length < this.index + size){
  211. throw new Error('BinaryPackFailure: index is out of range'
  212. + ' ' + this.index + ' ' + size + ' ' + this.length);
  213. }
  214. var buf = this.dataBuffer.slice(this.index, this.index + size);
  215. this.index += size;
  216. //buf = util.bufferToString(buf);
  217. return buf;
  218. }
  219. Unpacker.prototype.unpack_string = function(size){
  220. var bytes = this.read(size);
  221. var i = 0, str = '', c, code;
  222. while(i < size){
  223. c = bytes[i];
  224. if ( c < 128){
  225. str += String.fromCharCode(c);
  226. i++;
  227. } else if ((c ^ 0xc0) < 32){
  228. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  229. str += String.fromCharCode(code);
  230. i += 2;
  231. } else {
  232. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  233. (bytes[i+2] & 63);
  234. str += String.fromCharCode(code);
  235. i += 3;
  236. }
  237. }
  238. this.index += size;
  239. return str;
  240. }
  241. Unpacker.prototype.unpack_array = function(size){
  242. var objects = new Array(size);
  243. for(var i = 0; i < size ; i++){
  244. objects[i] = this.unpack();
  245. }
  246. return objects;
  247. }
  248. Unpacker.prototype.unpack_map = function(size){
  249. var map = {};
  250. for(var i = 0; i < size ; i++){
  251. var key = this.unpack();
  252. var value = this.unpack();
  253. map[key] = value;
  254. }
  255. return map;
  256. }
  257. Unpacker.prototype.unpack_float = function(){
  258. var uint32 = this.unpack_uint32();
  259. var sign = uint32 >> 31;
  260. var exp = ((uint32 >> 23) & 0xff) - 127;
  261. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  262. return (sign == 0 ? 1 : -1) *
  263. fraction * Math.pow(2, exp - 23);
  264. }
  265. Unpacker.prototype.unpack_double = function(){
  266. var h32 = this.unpack_uint32();
  267. var l32 = this.unpack_uint32();
  268. var sign = h32 >> 31;
  269. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  270. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  271. var frac = hfrac * Math.pow(2, exp - 20) +
  272. l32 * Math.pow(2, exp - 52);
  273. return (sign == 0 ? 1 : -1) * frac;
  274. }
  275. Unpacker.prototype.read = function(length){
  276. var j = this.index;
  277. if (j + length <= this.length) {
  278. return this.dataView.subarray(j, j + length);
  279. } else {
  280. throw new Error('BinaryPackFailure: read index out of range');
  281. }
  282. }
  283. function Packer(utf8){
  284. this.utf8 = utf8;
  285. this.bufferBuilder = new BufferBuilder();
  286. }
  287. Packer.prototype.pack = function(value){
  288. var type = typeof(value);
  289. if (type == 'string'){
  290. this.pack_string(value);
  291. } else if (type == 'number'){
  292. if (Math.floor(value) === value){
  293. this.pack_integer(value);
  294. } else{
  295. this.pack_double(value);
  296. }
  297. } else if (type == 'boolean'){
  298. if (value === true){
  299. this.bufferBuilder.append(0xc3);
  300. } else if (value === false){
  301. this.bufferBuilder.append(0xc2);
  302. }
  303. } else if (type == 'undefined'){
  304. this.bufferBuilder.append(0xc0);
  305. } else if (type == 'object'){
  306. if (value === null){
  307. this.bufferBuilder.append(0xc0);
  308. } else {
  309. var constructor = value.constructor;
  310. if (constructor == Array){
  311. this.pack_array(value);
  312. } else if (constructor == Blob || constructor == File) {
  313. this.pack_bin(value);
  314. } else if (constructor == ArrayBuffer) {
  315. if(binaryFeatures.useArrayBufferView) {
  316. this.pack_bin(new Uint8Array(value));
  317. } else {
  318. this.pack_bin(value);
  319. }
  320. } else if ('BYTES_PER_ELEMENT' in value){
  321. if(binaryFeatures.useArrayBufferView) {
  322. this.pack_bin(value);
  323. } else {
  324. this.pack_bin(value.buffer);
  325. }
  326. } else if (constructor == Object){
  327. this.pack_object(value);
  328. } else if (constructor == Date){
  329. this.pack_string(value.toString());
  330. } else if (typeof value.toBinaryPack == 'function'){
  331. this.bufferBuilder.append(value.toBinaryPack());
  332. } else {
  333. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  334. }
  335. }
  336. } else {
  337. throw new Error('Type "' + type + '" not yet supported');
  338. }
  339. return this.bufferBuilder.getBuffer();
  340. }
  341. Packer.prototype.pack_bin = function(blob){
  342. var length = blob.length || blob.byteLength || blob.size;
  343. if (length <= 0x0f){
  344. this.pack_uint8(0xa0 + length);
  345. } else if (length <= 0xffff){
  346. this.bufferBuilder.append(0xda) ;
  347. this.pack_uint16(length);
  348. } else if (length <= 0xffffffff){
  349. this.bufferBuilder.append(0xdb);
  350. this.pack_uint32(length);
  351. } else{
  352. throw new Error('Invalid length');
  353. return;
  354. }
  355. this.bufferBuilder.append(blob);
  356. }
  357. Packer.prototype.pack_string = function(str){
  358. var length;
  359. if (this.utf8) {
  360. var blob = new Blob([str]);
  361. length = blob.size;
  362. } else {
  363. length = str.length;
  364. }
  365. if (length <= 0x0f){
  366. this.pack_uint8(0xb0 + length);
  367. } else if (length <= 0xffff){
  368. this.bufferBuilder.append(0xd8) ;
  369. this.pack_uint16(length);
  370. } else if (length <= 0xffffffff){
  371. this.bufferBuilder.append(0xd9);
  372. this.pack_uint32(length);
  373. } else{
  374. throw new Error('Invalid length');
  375. return;
  376. }
  377. this.bufferBuilder.append(str);
  378. }
  379. Packer.prototype.pack_array = function(ary){
  380. var length = ary.length;
  381. if (length <= 0x0f){
  382. this.pack_uint8(0x90 + length);
  383. } else if (length <= 0xffff){
  384. this.bufferBuilder.append(0xdc)
  385. this.pack_uint16(length);
  386. } else if (length <= 0xffffffff){
  387. this.bufferBuilder.append(0xdd);
  388. this.pack_uint32(length);
  389. } else{
  390. throw new Error('Invalid length');
  391. }
  392. for(var i = 0; i < length ; i++){
  393. this.pack(ary[i]);
  394. }
  395. }
  396. Packer.prototype.pack_integer = function(num){
  397. if ( -0x20 <= num && num <= 0x7f){
  398. this.bufferBuilder.append(num & 0xff);
  399. } else if (0x00 <= num && num <= 0xff){
  400. this.bufferBuilder.append(0xcc);
  401. this.pack_uint8(num);
  402. } else if (-0x80 <= num && num <= 0x7f){
  403. this.bufferBuilder.append(0xd0);
  404. this.pack_int8(num);
  405. } else if ( 0x0000 <= num && num <= 0xffff){
  406. this.bufferBuilder.append(0xcd);
  407. this.pack_uint16(num);
  408. } else if (-0x8000 <= num && num <= 0x7fff){
  409. this.bufferBuilder.append(0xd1);
  410. this.pack_int16(num);
  411. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  412. this.bufferBuilder.append(0xce);
  413. this.pack_uint32(num);
  414. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  415. this.bufferBuilder.append(0xd2);
  416. this.pack_int32(num);
  417. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  418. this.bufferBuilder.append(0xd3);
  419. this.pack_int64(num);
  420. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  421. this.bufferBuilder.append(0xcf);
  422. this.pack_uint64(num);
  423. } else{
  424. throw new Error('Invalid integer');
  425. }
  426. }
  427. Packer.prototype.pack_double = function(num){
  428. var sign = 0;
  429. if (num < 0){
  430. sign = 1;
  431. num = -num;
  432. }
  433. var exp = Math.floor(Math.log(num) / Math.LN2);
  434. var frac0 = num / Math.pow(2, exp) - 1;
  435. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  436. var b32 = Math.pow(2, 32);
  437. var h32 = (sign << 31) | ((exp+1023) << 20) |
  438. (frac1 / b32) & 0x0fffff;
  439. var l32 = frac1 % b32;
  440. this.bufferBuilder.append(0xcb);
  441. this.pack_int32(h32);
  442. this.pack_int32(l32);
  443. }
  444. Packer.prototype.pack_object = function(obj){
  445. var keys = Object.keys(obj);
  446. var length = keys.length;
  447. if (length <= 0x0f){
  448. this.pack_uint8(0x80 + length);
  449. } else if (length <= 0xffff){
  450. this.bufferBuilder.append(0xde);
  451. this.pack_uint16(length);
  452. } else if (length <= 0xffffffff){
  453. this.bufferBuilder.append(0xdf);
  454. this.pack_uint32(length);
  455. } else{
  456. throw new Error('Invalid length');
  457. }
  458. for(var prop in obj){
  459. if (obj.hasOwnProperty(prop)){
  460. this.pack(prop);
  461. this.pack(obj[prop]);
  462. }
  463. }
  464. }
  465. Packer.prototype.pack_uint8 = function(num){
  466. this.bufferBuilder.append(num);
  467. }
  468. Packer.prototype.pack_uint16 = function(num){
  469. this.bufferBuilder.append(num >> 8);
  470. this.bufferBuilder.append(num & 0xff);
  471. }
  472. Packer.prototype.pack_uint32 = function(num){
  473. var n = num & 0xffffffff;
  474. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  475. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  476. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  477. this.bufferBuilder.append((n & 0x000000ff));
  478. }
  479. Packer.prototype.pack_uint64 = function(num){
  480. var high = num / Math.pow(2, 32);
  481. var low = num % Math.pow(2, 32);
  482. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  483. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  484. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  485. this.bufferBuilder.append((high & 0x000000ff));
  486. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  487. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  488. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  489. this.bufferBuilder.append((low & 0x000000ff));
  490. }
  491. Packer.prototype.pack_int8 = function(num){
  492. this.bufferBuilder.append(num & 0xff);
  493. }
  494. Packer.prototype.pack_int16 = function(num){
  495. this.bufferBuilder.append((num & 0xff00) >> 8);
  496. this.bufferBuilder.append(num & 0xff);
  497. }
  498. Packer.prototype.pack_int32 = function(num){
  499. this.bufferBuilder.append((num >>> 24) & 0xff);
  500. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  501. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  502. this.bufferBuilder.append((num & 0x000000ff));
  503. }
  504. Packer.prototype.pack_int64 = function(num){
  505. var high = Math.floor(num / Math.pow(2, 32));
  506. var low = num % Math.pow(2, 32);
  507. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  508. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  509. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  510. this.bufferBuilder.append((high & 0x000000ff));
  511. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  512. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  513. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  514. this.bufferBuilder.append((low & 0x000000ff));
  515. }
  516. /**
  517. * Light EventEmitter. Ported from Node.js/events.js
  518. * Eric Zhang
  519. */
  520. /**
  521. * EventEmitter class
  522. * Creates an object with event registering and firing methods
  523. */
  524. function EventEmitter() {
  525. // Initialise required storage variables
  526. this._events = {};
  527. }
  528. var isArray = Array.isArray;
  529. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  530. if ('function' !== typeof listener) {
  531. throw new Error('addListener only takes instances of Function');
  532. }
  533. // To avoid recursion in the case that type == "newListeners"! Before
  534. // adding it to the listeners, first emit "newListeners".
  535. this.emit('newListener', type, typeof listener.listener === 'function' ?
  536. listener.listener : listener);
  537. if (!this._events[type]) {
  538. // Optimize the case of one listener. Don't need the extra array object.
  539. this._events[type] = listener;
  540. } else if (isArray(this._events[type])) {
  541. // If we've already got an array, just append.
  542. this._events[type].push(listener);
  543. } else {
  544. // Adding the second element, need to change to array.
  545. this._events[type] = [this._events[type], listener];
  546. }
  547. return this;
  548. };
  549. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  550. EventEmitter.prototype.once = function(type, listener, scope) {
  551. if ('function' !== typeof listener) {
  552. throw new Error('.once only takes instances of Function');
  553. }
  554. var self = this;
  555. function g() {
  556. self.removeListener(type, g);
  557. listener.apply(this, arguments);
  558. };
  559. g.listener = listener;
  560. self.on(type, g);
  561. return this;
  562. };
  563. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  564. if ('function' !== typeof listener) {
  565. throw new Error('removeListener only takes instances of Function');
  566. }
  567. // does not use listeners(), so no side effect of creating _events[type]
  568. if (!this._events[type]) return this;
  569. var list = this._events[type];
  570. if (isArray(list)) {
  571. var position = -1;
  572. for (var i = 0, length = list.length; i < length; i++) {
  573. if (list[i] === listener ||
  574. (list[i].listener && list[i].listener === listener))
  575. {
  576. position = i;
  577. break;
  578. }
  579. }
  580. if (position < 0) return this;
  581. list.splice(position, 1);
  582. if (list.length == 0)
  583. delete this._events[type];
  584. } else if (list === listener ||
  585. (list.listener && list.listener === listener))
  586. {
  587. delete this._events[type];
  588. }
  589. return this;
  590. };
  591. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  592. EventEmitter.prototype.removeAllListeners = function(type) {
  593. if (arguments.length === 0) {
  594. this._events = {};
  595. return this;
  596. }
  597. // does not use listeners(), so no side effect of creating _events[type]
  598. if (type && this._events && this._events[type]) this._events[type] = null;
  599. return this;
  600. };
  601. EventEmitter.prototype.listeners = function(type) {
  602. if (!this._events[type]) this._events[type] = [];
  603. if (!isArray(this._events[type])) {
  604. this._events[type] = [this._events[type]];
  605. }
  606. return this._events[type];
  607. };
  608. EventEmitter.prototype.emit = function(type) {
  609. var type = arguments[0];
  610. var handler = this._events[type];
  611. if (!handler) return false;
  612. if (typeof handler == 'function') {
  613. switch (arguments.length) {
  614. // fast cases
  615. case 1:
  616. handler.call(this);
  617. break;
  618. case 2:
  619. handler.call(this, arguments[1]);
  620. break;
  621. case 3:
  622. handler.call(this, arguments[1], arguments[2]);
  623. break;
  624. // slower
  625. default:
  626. var l = arguments.length;
  627. var args = new Array(l - 1);
  628. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  629. handler.apply(this, args);
  630. }
  631. return true;
  632. } else if (isArray(handler)) {
  633. var l = arguments.length;
  634. var args = new Array(l - 1);
  635. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  636. var listeners = handler.slice();
  637. for (var i = 0, l = listeners.length; i < l; i++) {
  638. listeners[i].apply(this, args);
  639. }
  640. return true;
  641. } else {
  642. return false;
  643. }
  644. };
  645. /**
  646. * Reliable transfer for Chrome Canary DataChannel impl.
  647. * Author: @michellebu
  648. */
  649. function Reliable(dc, debug) {
  650. if (!(this instanceof Reliable)) return new Reliable(dc);
  651. this._dc = dc;
  652. util.debug = debug;
  653. // Messages sent/received so far.
  654. // id: { ack: n, chunks: [...] }
  655. this._outgoing = {};
  656. // id: { ack: ['ack', id, n], chunks: [...] }
  657. this._incoming = {};
  658. this._received = {};
  659. // Window size.
  660. this._window = 1000;
  661. // MTU.
  662. this._mtu = 500;
  663. // Interval for setInterval. In ms.
  664. this._interval = 0;
  665. // Messages sent.
  666. this._count = 0;
  667. // Outgoing message queue.
  668. this._queue = [];
  669. this._setupDC();
  670. };
  671. // Send a message reliably.
  672. Reliable.prototype.send = function(msg) {
  673. // Determine if chunking is necessary.
  674. var bl = util.pack(msg);
  675. if (bl.size < this._mtu) {
  676. this._handleSend(['no', bl]);
  677. return;
  678. }
  679. this._outgoing[this._count] = {
  680. ack: 0,
  681. chunks: this._chunk(bl)
  682. };
  683. if (util.debug) {
  684. this._outgoing[this._count].timer = new Date();
  685. }
  686. // Send prelim window.
  687. this._sendWindowedChunks(this._count);
  688. this._count += 1;
  689. };
  690. // Set up interval for processing queue.
  691. Reliable.prototype._setupInterval = function() {
  692. // TODO: fail gracefully.
  693. var self = this;
  694. this._timeout = setInterval(function() {
  695. // FIXME: String stuff makes things terribly async.
  696. var msg = self._queue.shift();
  697. if (msg._multiple) {
  698. for (var i = 0, ii = msg.length; i < ii; i += 1) {
  699. self._intervalSend(msg[i]);
  700. }
  701. } else {
  702. self._intervalSend(msg);
  703. }
  704. }, this._interval);
  705. };
  706. Reliable.prototype._intervalSend = function(msg) {
  707. var self = this;
  708. msg = util.pack(msg);
  709. util.blobToBinaryString(msg, function(str) {
  710. self._dc.send(str);
  711. });
  712. if (self._queue.length === 0) {
  713. clearTimeout(self._timeout);
  714. self._timeout = null;
  715. //self._processAcks();
  716. }
  717. };
  718. // Go through ACKs to send missing pieces.
  719. Reliable.prototype._processAcks = function() {
  720. for (var id in this._outgoing) {
  721. if (this._outgoing.hasOwnProperty(id)) {
  722. this._sendWindowedChunks(id);
  723. }
  724. }
  725. };
  726. // Handle sending a message.
  727. // FIXME: Don't wait for interval time for all messages...
  728. Reliable.prototype._handleSend = function(msg) {
  729. var push = true;
  730. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  731. var item = this._queue[i];
  732. if (item === msg) {
  733. push = false;
  734. } else if (item._multiple && item.indexOf(msg) !== -1) {
  735. push = false;
  736. }
  737. }
  738. if (push) {
  739. this._queue.push(msg);
  740. if (!this._timeout) {
  741. this._setupInterval();
  742. }
  743. }
  744. };
  745. // Set up DataChannel handlers.
  746. Reliable.prototype._setupDC = function() {
  747. // Handle various message types.
  748. var self = this;
  749. this._dc.onmessage = function(e) {
  750. var msg = e.data;
  751. var datatype = msg.constructor;
  752. // FIXME: msg is String until binary is supported.
  753. // Once that happens, this will have to be smarter.
  754. if (datatype === String) {
  755. var ab = util.binaryStringToArrayBuffer(msg);
  756. msg = util.unpack(ab);
  757. self._handleMessage(msg);
  758. }
  759. };
  760. };
  761. // Handles an incoming message.
  762. Reliable.prototype._handleMessage = function(msg) {
  763. var id = msg[1];
  764. var idata = this._incoming[id];
  765. var odata = this._outgoing[id];
  766. var data;
  767. switch (msg[0]) {
  768. // No chunking was done.
  769. case 'no':
  770. var message = id;
  771. if (!!message) {
  772. this.onmessage(util.unpack(message));
  773. }
  774. break;
  775. // Reached the end of the message.
  776. case 'end':
  777. data = idata;
  778. // In case end comes first.
  779. this._received[id] = msg[2];
  780. if (!data) {
  781. break;
  782. }
  783. this._ack(id);
  784. break;
  785. case 'ack':
  786. data = odata;
  787. if (!!data) {
  788. var ack = msg[2];
  789. // Take the larger ACK, for out of order messages.
  790. data.ack = Math.max(ack, data.ack);
  791. // Clean up when all chunks are ACKed.
  792. if (data.ack >= data.chunks.length) {
  793. util.log('Time: ', new Date() - data.timer);
  794. delete this._outgoing[id];
  795. } else {
  796. this._processAcks();
  797. }
  798. }
  799. // If !data, just ignore.
  800. break;
  801. // Received a chunk of data.
  802. case 'chunk':
  803. // Create a new entry if none exists.
  804. data = idata;
  805. if (!data) {
  806. var end = this._received[id];
  807. if (end === true) {
  808. break;
  809. }
  810. data = {
  811. ack: ['ack', id, 0],
  812. chunks: []
  813. };
  814. this._incoming[id] = data;
  815. }
  816. var n = msg[2];
  817. var chunk = msg[3];
  818. data.chunks[n] = new Uint8Array(chunk);
  819. // If we get the chunk we're looking for, ACK for next missing.
  820. // Otherwise, ACK the same N again.
  821. if (n === data.ack[2]) {
  822. this._calculateNextAck(id);
  823. }
  824. this._ack(id);
  825. break;
  826. default:
  827. // Shouldn't happen, but would make sense for message to just go
  828. // through as is.
  829. this._handleSend(msg);
  830. break;
  831. }
  832. };
  833. // Chunks BL into smaller messages.
  834. Reliable.prototype._chunk = function(bl) {
  835. var chunks = [];
  836. var size = bl.size;
  837. var start = 0;
  838. while (start < size) {
  839. var end = Math.min(size, start + this._mtu);
  840. var b = bl.slice(start, end);
  841. var chunk = {
  842. payload: b
  843. }
  844. chunks.push(chunk);
  845. start = end;
  846. }
  847. util.log('Created', chunks.length, 'chunks.');
  848. return chunks;
  849. };
  850. // Sends ACK N, expecting Nth blob chunk for message ID.
  851. Reliable.prototype._ack = function(id) {
  852. var ack = this._incoming[id].ack;
  853. // if ack is the end value, then call _complete.
  854. if (this._received[id] === ack[2]) {
  855. this._complete(id);
  856. this._received[id] = true;
  857. }
  858. this._handleSend(ack);
  859. };
  860. // Calculates the next ACK number, given chunks.
  861. Reliable.prototype._calculateNextAck = function(id) {
  862. var data = this._incoming[id];
  863. var chunks = data.chunks;
  864. for (var i = 0, ii = chunks.length; i < ii; i += 1) {
  865. // This chunk is missing!!! Better ACK for it.
  866. if (chunks[i] === undefined) {
  867. data.ack[2] = i;
  868. return;
  869. }
  870. }
  871. data.ack[2] = chunks.length;
  872. };
  873. // Sends the next window of chunks.
  874. Reliable.prototype._sendWindowedChunks = function(id) {
  875. util.log('sendWindowedChunks for: ', id);
  876. var data = this._outgoing[id];
  877. var ch = data.chunks;
  878. var chunks = [];
  879. var limit = Math.min(data.ack + this._window, ch.length);
  880. for (var i = data.ack; i < limit; i += 1) {
  881. if (!ch[i].sent || i === data.ack) {
  882. ch[i].sent = true;
  883. chunks.push(['chunk', id, i, ch[i].payload]);
  884. }
  885. }
  886. if (data.ack + this._window >= ch.length) {
  887. chunks.push(['end', id, ch.length])
  888. }
  889. chunks._multiple = true;
  890. this._handleSend(chunks);
  891. };
  892. // Puts together a message from chunks.
  893. Reliable.prototype._complete = function(id) {
  894. util.log('Completed called for', id);
  895. var self = this;
  896. var chunks = this._incoming[id].chunks;
  897. var bl = new Blob(chunks);
  898. util.blobToArrayBuffer(bl, function(ab) {
  899. self.onmessage(util.unpack(ab));
  900. });
  901. delete this._incoming[id];
  902. };
  903. // Ups bandwidth limit on SDP. Meant to be called during offer/answer.
  904. Reliable.higherBandwidthSDP = function(sdp) {
  905. // AS stands for Application-Specific Maximum.
  906. // Bandwidth number is in kilobits / sec.
  907. // See RFC for more info: http://www.ietf.org/rfc/rfc2327.txt
  908. var parts = sdp.split('b=AS:30');
  909. var replace = 'b=AS:102400'; // 100 Mbps
  910. return parts[0] + replace + parts[1];
  911. };
  912. // Overwritten, typically.
  913. Reliable.prototype.onmessage = function(msg) {};
  914. exports.Reliable = Reliable;
  915. exports.RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
  916. exports.RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
  917. var defaultConfig = {'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]};
  918. var util = {
  919. noop: function() {},
  920. CLOUD_HOST: '0.peerjs.com',
  921. CLOUD_PORT: 9000,
  922. // Logging logic
  923. logLevel: 0,
  924. setLogLevel: function(level) {
  925. var debugLevel = parseInt(level, 10);
  926. if (!isNaN(parseInt(level, 10))) {
  927. util.logLevel = debugLevel;
  928. } else {
  929. // If they are using truthy/falsy values for debug
  930. util.logLevel = level ? 3 : 0;
  931. }
  932. util.log = util.warn = util.error = util.noop;
  933. if (util.logLevel > 0) {
  934. util.error = util._printWith('ERROR');
  935. }
  936. if (util.logLevel > 1) {
  937. util.warn = util._printWith('WARNING');
  938. }
  939. if (util.logLevel > 2) {
  940. util.log = util._print;
  941. }
  942. },
  943. setLogFunction: function(fn) {
  944. if (fn.constructor !== Function) {
  945. util.warn('The log function you passed in is not a function. Defaulting to regular logs.');
  946. } else {
  947. util._print = fn;
  948. }
  949. },
  950. _printWith: function(prefix) {
  951. return function() {
  952. var copy = Array.prototype.slice.call(arguments);
  953. copy.unshift(prefix);
  954. util._print.apply(util, copy);
  955. };
  956. },
  957. _print: function () {
  958. var err = false;
  959. var copy = Array.prototype.slice.call(arguments);
  960. copy.unshift('PeerJS: ');
  961. for (var i = 0, l = copy.length; i < l; i++){
  962. if (copy[i] instanceof Error) {
  963. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  964. err = true;
  965. }
  966. }
  967. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  968. },
  969. //
  970. // Returns browser-agnostic default config
  971. defaultConfig: defaultConfig,
  972. //
  973. // Returns the current browser.
  974. browser: (function() {
  975. if (window.mozRTCPeerConnection) {
  976. return 'Firefox';
  977. } else if (window.webkitRTCPeerConnection) {
  978. return 'Chrome';
  979. } else if (window.RTCPeerConnection) {
  980. return 'Supported';
  981. } else {
  982. return 'Unsupported';
  983. }
  984. })(),
  985. //
  986. // Lists which features are supported
  987. supports: (function() {
  988. var data = true;
  989. var audioVideo = true;
  990. var pc, dc;
  991. try {
  992. pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  993. } catch (e) {
  994. data = false;
  995. audioVideo = false;
  996. }
  997. if (data) {
  998. try {
  999. dc = pc.createDataChannel('_PEERJSDATATEST');
  1000. } catch (e) {
  1001. data = false;
  1002. }
  1003. }
  1004. // FIXME: not really the best check...
  1005. if (audioVideo) {
  1006. audioVideo = !!pc.addStream;
  1007. }
  1008. pc.close();
  1009. dc.close();
  1010. return {
  1011. audioVideo: audioVideo,
  1012. data: data,
  1013. binary: data && (function() {
  1014. var pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1015. var dc = pc.createDataChannel('_PEERJSBINARYTEST');
  1016. try {
  1017. dc.binaryType = 'blob';
  1018. } catch (e) {
  1019. pc.close();
  1020. if (e.name === 'NotSupportedError') {
  1021. return false
  1022. }
  1023. }
  1024. pc.close();
  1025. dc.close();
  1026. return true;
  1027. })(),
  1028. reliable: data && (function() {
  1029. // Reliable (not RTP).
  1030. var pc = new RTCPeerConnection(defaultConfig, {});
  1031. var dc;
  1032. try {
  1033. dc = pc.createDataChannel('_PEERJSRELIABLETEST');
  1034. } catch (e) {
  1035. pc.close();
  1036. if (e.name === 'NotSupportedError') {
  1037. return false
  1038. }
  1039. }
  1040. pc.close();
  1041. dc.close();
  1042. return true;
  1043. })(),
  1044. onnegotiationneeded: (data || audioVideo) && (function() {
  1045. var pc = new RTCPeerConnection(defaultConfig, {});
  1046. // sync default check.
  1047. var called = false;
  1048. var pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1049. pc.onnegotiationneeded = function() {
  1050. called = true;
  1051. // async check.
  1052. if (util && util.supports) {
  1053. util.supports.onnegotiationneeded = true;
  1054. }
  1055. };
  1056. // FIXME: this is not great because in theory it doesn't work for
  1057. // av-only browsers (?).
  1058. var dc = pc.createDataChannel('_PEERJSRELIABLETEST');
  1059. pc.close();
  1060. dc.close();
  1061. return called;
  1062. })(),
  1063. // TODO(michelle): whether this browser can interop with a different
  1064. // browser. But the two browsers both have to support interop.
  1065. interop: false
  1066. };
  1067. }()),
  1068. //
  1069. // Ensure alphanumeric ids
  1070. validateId: function(id) {
  1071. // Allow empty ids
  1072. return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id);
  1073. },
  1074. validateKey: function(key) {
  1075. // Allow empty keys
  1076. return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key);
  1077. },
  1078. debug: false,
  1079. inherits: function(ctor, superCtor) {
  1080. ctor.super_ = superCtor;
  1081. ctor.prototype = Object.create(superCtor.prototype, {
  1082. constructor: {
  1083. value: ctor,
  1084. enumerable: false,
  1085. writable: true,
  1086. configurable: true
  1087. }
  1088. });
  1089. },
  1090. extend: function(dest, source) {
  1091. for(var key in source) {
  1092. if(source.hasOwnProperty(key)) {
  1093. dest[key] = source[key];
  1094. }
  1095. }
  1096. return dest;
  1097. },
  1098. pack: BinaryPack.pack,
  1099. unpack: BinaryPack.unpack,
  1100. log: function () {
  1101. if (util.debug) {
  1102. var err = false;
  1103. var copy = Array.prototype.slice.call(arguments);
  1104. copy.unshift('PeerJS: ');
  1105. for (var i = 0, l = copy.length; i < l; i++){
  1106. if (copy[i] instanceof Error) {
  1107. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  1108. err = true;
  1109. }
  1110. }
  1111. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  1112. }
  1113. },
  1114. setZeroTimeout: (function(global) {
  1115. var timeouts = [];
  1116. var messageName = 'zero-timeout-message';
  1117. // Like setTimeout, but only takes a function argument. There's
  1118. // no time argument (always zero) and no arguments (you have to
  1119. // use a closure).
  1120. function setZeroTimeoutPostMessage(fn) {
  1121. timeouts.push(fn);
  1122. global.postMessage(messageName, '*');
  1123. }
  1124. function handleMessage(event) {
  1125. if (event.source == global && event.data == messageName) {
  1126. if (event.stopPropagation) {
  1127. event.stopPropagation();
  1128. }
  1129. if (timeouts.length) {
  1130. timeouts.shift()();
  1131. }
  1132. }
  1133. }
  1134. if (global.addEventListener) {
  1135. global.addEventListener('message', handleMessage, true);
  1136. } else if (global.attachEvent) {
  1137. global.attachEvent('onmessage', handleMessage);
  1138. }
  1139. return setZeroTimeoutPostMessage;
  1140. }(this)),
  1141. // Binary stuff
  1142. blobToArrayBuffer: function(blob, cb){
  1143. var fr = new FileReader();
  1144. fr.onload = function(evt) {
  1145. cb(evt.target.result);
  1146. };
  1147. fr.readAsArrayBuffer(blob);
  1148. },
  1149. blobToBinaryString: function(blob, cb){
  1150. var fr = new FileReader();
  1151. fr.onload = function(evt) {
  1152. cb(evt.target.result);
  1153. };
  1154. fr.readAsBinaryString(blob);
  1155. },
  1156. binaryStringToArrayBuffer: function(binary) {
  1157. var byteArray = new Uint8Array(binary.length);
  1158. for (var i = 0; i < binary.length; i++) {
  1159. byteArray[i] = binary.charCodeAt(i) & 0xff;
  1160. }
  1161. return byteArray.buffer;
  1162. },
  1163. randomToken: function () {
  1164. return Math.random().toString(36).substr(2);
  1165. },
  1166. //
  1167. isSecure: function() {
  1168. return location.protocol === 'https:';
  1169. }
  1170. };
  1171. exports.util = util;
  1172. /**
  1173. * A peer who can initiate connections with other peers.
  1174. */
  1175. function Peer(id, options) {
  1176. if (!(this instanceof Peer)) return new Peer(id, options);
  1177. EventEmitter.call(this);
  1178. // Deal with overloading
  1179. if (id && id.constructor == Object) {
  1180. options = id;
  1181. id = undefined;
  1182. } else if (id) {
  1183. // Ensure id is a string
  1184. id = id.toString();
  1185. }
  1186. //
  1187. // Configurize options
  1188. options = util.extend({
  1189. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  1190. host: util.CLOUD_HOST,
  1191. port: util.CLOUD_PORT,
  1192. key: 'peerjs',
  1193. config: util.defaultConfig
  1194. }, options);
  1195. this.options = options;
  1196. // Detect relative URL host.
  1197. if (options.host === '/') {
  1198. options.host = window.location.hostname;
  1199. }
  1200. // Set whether we use SSL to same as current host
  1201. if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
  1202. options.secure = util.isSecure();
  1203. }
  1204. // Set a custom log function if present
  1205. if (options.logFunction) {
  1206. util.setLogFunction(options.logFunction);
  1207. }
  1208. util.setLogLevel(options.debug);
  1209. //
  1210. // Sanity checks
  1211. // Ensure WebRTC supported
  1212. if (!util.supports.audioVideo && !util.supports.data ) {
  1213. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  1214. return;
  1215. }
  1216. // Ensure alphanumeric id
  1217. if (!util.validateId(id)) {
  1218. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  1219. return;
  1220. }
  1221. // Ensure valid key
  1222. if (!util.validateKey(options.key)) {
  1223. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1224. return;
  1225. }
  1226. // Ensure not using unsecure cloud server on SSL page
  1227. if (options.secure && options.host === '0.peerjs.com') {
  1228. this._delayedAbort('ssl-unavailable',
  1229. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  1230. return;
  1231. }
  1232. //
  1233. // States.
  1234. this.destroyed = false; // Connections have been killed
  1235. this.disconnected = false; // Connection to PeerServer killed manually but P2P connections still active
  1236. this.open = false; // Sockets and such are not yet open.
  1237. //
  1238. // References
  1239. this.connections = {}; // DataConnections for this peer.
  1240. this._lostMessages = {}; // src => [list of messages]
  1241. //
  1242. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  1243. // websockets.)
  1244. var self = this;
  1245. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.key);
  1246. this.socket.on('message', function(data) {
  1247. self._handleMessage(data);
  1248. });
  1249. this.socket.on('error', function(error) {
  1250. self._abort('socket-error', error);
  1251. });
  1252. this.socket.on('close', function() {
  1253. if (!self.disconnected) { // If we haven't explicitly disconnected, emit error.
  1254. self._abort('socket-closed', 'Underlying socket is already closed.');
  1255. }
  1256. });
  1257. //
  1258. // Start the connections
  1259. if (id) {
  1260. this._initialize(id);
  1261. } else {
  1262. this._retrieveId();
  1263. }
  1264. //
  1265. };
  1266. util.inherits(Peer, EventEmitter);
  1267. /** Get a unique ID from the server via XHR. */
  1268. Peer.prototype._retrieveId = function(cb) {
  1269. var self = this;
  1270. var http = new XMLHttpRequest();
  1271. var protocol = this.options.secure ? 'https://' : 'http://';
  1272. var url = protocol + this.options.host + ':' + this.options.port + '/' + this.options.key + '/id';
  1273. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1274. url += queryString;
  1275. // If there's no ID we need to wait for one before trying to init socket.
  1276. http.open('get', url, true);
  1277. http.onerror = function(e) {
  1278. util.error('Error retrieving ID', e);
  1279. self._abort('server-error', 'Could not get an ID from the server');
  1280. }
  1281. http.onreadystatechange = function() {
  1282. if (http.readyState !== 4) {
  1283. return;
  1284. }
  1285. if (http.status !== 200) {
  1286. http.onerror();
  1287. return;
  1288. }
  1289. self._initialize(http.responseText);
  1290. };
  1291. http.send(null);
  1292. };
  1293. /** Initialize a connection with the server. */
  1294. Peer.prototype._initialize = function(id) {
  1295. var self = this;
  1296. this.id = id;
  1297. this.socket.start(this.id);
  1298. }
  1299. /** Handles messages from the server. */
  1300. Peer.prototype._handleMessage = function(message) {
  1301. var type = message.type;
  1302. var payload = message.payload;
  1303. var peer = message.src;
  1304. switch (type) {
  1305. case 'OPEN': // The connection to the server is open.
  1306. this.emit('open', this.id);
  1307. this.open = true;
  1308. break;
  1309. case 'ERROR': // Server error.
  1310. this._abort('server-error', payload.msg);
  1311. break;
  1312. case 'ID-TAKEN': // The selected ID is taken.
  1313. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  1314. break;
  1315. case 'INVALID-KEY': // The given API key cannot be found.
  1316. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  1317. break;
  1318. //
  1319. case 'LEAVE': // Another peer has closed its connection to this peer.
  1320. util.log('Received leave message from', peer);
  1321. this._cleanupPeer(peer);
  1322. break;
  1323. case 'EXPIRE': // The offer sent to a peer has expired without response.
  1324. this.emit('error', new Error('Could not connect to peer ' + peer));
  1325. break;
  1326. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  1327. var connectionId = payload.connectionId;
  1328. var connection = this.getConnection(peer, connectionId);
  1329. if (connection) {
  1330. util.warn('Offer received for existing Connection ID:', connectionId);
  1331. //connection.handleMessage(message);
  1332. } else {
  1333. // Create a new connection.
  1334. if (payload.type === 'media') {
  1335. var connection = new MediaConnection(peer, this, {
  1336. connectionId: connectionId,
  1337. _payload: payload,
  1338. metadata: payload.metadata,
  1339. });
  1340. this._addConnection(peer, connection);
  1341. this.emit('call', connection);
  1342. } else if (payload.type === 'data') {
  1343. connection = new DataConnection(peer, this, {
  1344. connectionId: connectionId,
  1345. _payload: payload,
  1346. metadata: payload.metadata,
  1347. label: payload.label,
  1348. serialization: payload.serialization,
  1349. reliable: payload.reliable
  1350. });
  1351. this._addConnection(peer, connection);
  1352. this.emit('connection', connection);
  1353. } else {
  1354. util.warn('Received malformed connection type:', payload.type);
  1355. return;
  1356. }
  1357. // Find messages.
  1358. var messages = this._lostMessages[connection.id];
  1359. if (messages) {
  1360. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1361. connection.handleMessage(messages[i]);
  1362. }
  1363. delete this._lostMessages[connection.id];
  1364. }
  1365. }
  1366. break;
  1367. default:
  1368. if (!payload) {
  1369. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  1370. return;
  1371. }
  1372. var id = payload.connectionId;
  1373. var connection = this.getConnection(peer, id);
  1374. if (connection) {
  1375. // Pass it on.
  1376. connection.handleMessage(message);
  1377. } else if (id) {
  1378. // Store for possible later use
  1379. this._storeMessage(id, message);
  1380. } else {
  1381. util.warn('You received an unrecognized message:', message);
  1382. }
  1383. break;
  1384. }
  1385. }
  1386. /** Stores messages without a connection, to be claimed later. */
  1387. Peer.prototype._storeMessage = function(connectionId, message) {
  1388. if (!this._lostMessages[connectionId]) {
  1389. this._lostMessages[connectionId] = [];
  1390. }
  1391. this._lostMessages[connectionId].push(message);
  1392. }
  1393. /**
  1394. * Returns a DataConnection to the specified peer. See documentation for a
  1395. * complete list of options.
  1396. */
  1397. Peer.prototype.connect = function(peer, options) {
  1398. if (this.disconnected) {
  1399. util.warn('You cannot connect to a new Peer because you called '
  1400. + '.disconnect() on this Peer and ended your connection with the'
  1401. + ' server. You can create a new Peer to reconnect.');
  1402. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1403. return;
  1404. }
  1405. var connection = new DataConnection(peer, this, options);
  1406. this._addConnection(peer, connection);
  1407. return connection;
  1408. }
  1409. /**
  1410. * Returns a MediaConnection to the specified peer. See documentation for a
  1411. * complete list of options.
  1412. */
  1413. Peer.prototype.call = function(peer, stream, options) {
  1414. if (this.disconnected) {
  1415. util.warn('You cannot connect to a new Peer because you called '
  1416. + '.disconnect() on this Peer and ended your connection with the'
  1417. + ' server. You can create a new Peer to reconnect.');
  1418. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1419. return;
  1420. }
  1421. if (!stream) {
  1422. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  1423. return;
  1424. }
  1425. options = options || {};
  1426. options._stream = stream;
  1427. var call = new MediaConnection(peer, this, options);
  1428. this._addConnection(peer, call);
  1429. return call;
  1430. }
  1431. /** Add a data/media connection to this peer. */
  1432. Peer.prototype._addConnection = function(peer, connection) {
  1433. if (!this.connections[peer]) {
  1434. this.connections[peer] = [];
  1435. }
  1436. this.connections[peer].push(connection);
  1437. }
  1438. /** Retrieve a data/media connection for this peer. */
  1439. Peer.prototype.getConnection = function(peer, id) {
  1440. var connections = this.connections[peer];
  1441. if (!connections) {
  1442. return null;
  1443. }
  1444. for (var i = 0, ii = connections.length; i < ii; i++) {
  1445. if (connections[i].id === id) {
  1446. return connections[i];
  1447. }
  1448. }
  1449. return null;
  1450. }
  1451. Peer.prototype._delayedAbort = function(type, message) {
  1452. var self = this;
  1453. util.setZeroTimeout(function(){
  1454. self._abort(type, message);
  1455. });
  1456. }
  1457. /** Destroys the Peer and emits an error message. */
  1458. Peer.prototype._abort = function(type, message) {
  1459. util.error('Aborting. Error:', message);
  1460. var err = new Error(message);
  1461. err.type = type;
  1462. this.destroy();
  1463. this.emit('error', err);
  1464. };
  1465. /**
  1466. * Destroys the Peer: closes all active connections as well as the connection
  1467. * to the server.
  1468. * Warning: The peer can no longer create or accept connections after being
  1469. * destroyed.
  1470. */
  1471. Peer.prototype.destroy = function() {
  1472. if (!this.destroyed) {
  1473. this._cleanup();
  1474. this.disconnect();
  1475. this.destroyed = true;
  1476. }
  1477. }
  1478. /** Disconnects every connection on this peer. */
  1479. Peer.prototype._cleanup = function() {
  1480. var peers = Object.keys(this.connections);
  1481. for (var i = 0, ii = peers.length; i < ii; i++) {
  1482. this._cleanupPeer(peers[i]);
  1483. }
  1484. this.emit('close');
  1485. }
  1486. /** Closes all connections to this peer. */
  1487. Peer.prototype._cleanupPeer = function(peer) {
  1488. var connections = this.connections[peer];
  1489. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  1490. connections[j].close();
  1491. }
  1492. }
  1493. /**
  1494. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1495. * active connections.
  1496. * Warning: The peer can no longer create or accept connections after being
  1497. * disconnected. It also cannot reconnect to the server.
  1498. */
  1499. Peer.prototype.disconnect = function() {
  1500. var self = this;
  1501. util.setZeroTimeout(function(){
  1502. if (!self.disconnected) {
  1503. self.disconnected = true;
  1504. self.open = false;
  1505. if (self.socket) {
  1506. self.socket.close();
  1507. }
  1508. self.id = null;
  1509. }
  1510. });
  1511. }
  1512. exports.Peer = Peer;
  1513. /**
  1514. * Wraps a DataChannel between two Peers.
  1515. */
  1516. function DataConnection(peer, provider, options) {
  1517. if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options);
  1518. EventEmitter.call(this);
  1519. // TODO: perhaps default serialization should be binary-utf8?
  1520. this.options = util.extend({
  1521. serialization: 'binary'
  1522. }, options);
  1523. // Connection is not open yet.
  1524. this.open = false;
  1525. this.type = 'data';
  1526. this.peer = peer;
  1527. this.provider = provider;
  1528. this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
  1529. this.label = this.options.label || this.id;
  1530. this.metadata = this.options.metadata;
  1531. this.serialization = this.options.serialization;
  1532. this.reliable = this.options.reliable;
  1533. Negotiator.startConnection(
  1534. this,
  1535. this.options._payload || {
  1536. originator: true
  1537. }
  1538. );
  1539. }
  1540. util.inherits(DataConnection, EventEmitter);
  1541. DataConnection._idPrefix = 'dc_';
  1542. /** Called by the Negotiator when the DataChannel is ready. */
  1543. DataConnection.prototype.initialize = function(dc) {
  1544. this._dc = dc;
  1545. this._configureDataChannel();
  1546. }
  1547. DataConnection.prototype._configureDataChannel = function() {
  1548. var self = this;
  1549. if (util.supports.binary) {
  1550. // Webkit doesn't support binary yet
  1551. this._dc.binaryType = 'arraybuffer';
  1552. }
  1553. this._dc.onopen = function() {
  1554. util.log('Data channel connection success');
  1555. self.open = true;
  1556. self.emit('open');
  1557. }
  1558. // Use the Reliable shim for non Firefox browsers
  1559. if (!util.supports.reliable) {
  1560. this._reliable = new Reliable(this._dc, util.debug);
  1561. }
  1562. if (this._reliable) {
  1563. this._reliable.onmessage = function(msg) {
  1564. self.emit('data', msg);
  1565. };
  1566. } else {
  1567. this._dc.onmessage = function(e) {
  1568. self._handleDataMessage(e);
  1569. };
  1570. }
  1571. this._dc.onclose = function(e) {
  1572. util.log('DataChannel closed for:', self.peer);
  1573. self.close();
  1574. };
  1575. }
  1576. // Handles a DataChannel message.
  1577. DataConnection.prototype._handleDataMessage = function(e) {
  1578. var self = this;
  1579. var data = e.data;
  1580. var datatype = data.constructor;
  1581. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1582. if (datatype === Blob) {
  1583. // Datatype should never be blob
  1584. util.blobToArrayBuffer(data, function(ab) {
  1585. data = util.unpack(ab);
  1586. self.emit('data', data);
  1587. });
  1588. return;
  1589. } else if (datatype === ArrayBuffer) {
  1590. data = util.unpack(data);
  1591. } else if (datatype === String) {
  1592. // String fallback for binary data for browsers that don't support binary yet
  1593. var ab = util.binaryStringToArrayBuffer(data);
  1594. data = util.unpack(ab);
  1595. }
  1596. } else if (this.serialization === 'json') {
  1597. data = JSON.parse(data);
  1598. }
  1599. this.emit('data', data);
  1600. }
  1601. /**
  1602. * Exposed functionality for users.
  1603. */
  1604. /** Allows user to close connection. */
  1605. DataConnection.prototype.close = function() {
  1606. if (!this.open) {
  1607. return;
  1608. }
  1609. this.open = false;
  1610. Negotiator.cleanup(this);
  1611. this.emit('close');
  1612. }
  1613. /** Allows user to send data. */
  1614. DataConnection.prototype.send = function(data) {
  1615. if (!this.open) {
  1616. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  1617. }
  1618. if (this._reliable) {
  1619. // Note: reliable shim sending will make it so that you cannot customize
  1620. // serialization.
  1621. this._reliable.send(data);
  1622. return;
  1623. }
  1624. var self = this;
  1625. if (this.serialization === 'none') {
  1626. this._dc.send(data);
  1627. } else if (this.serialization === 'json') {
  1628. this._dc.send(JSON.stringify(data));
  1629. } else {
  1630. var utf8 = (this.serialization === 'binary-utf8');
  1631. var blob = util.pack(data, utf8);
  1632. // DataChannel currently only supports strings.
  1633. if (!util.supports.binary) {
  1634. util.blobToBinaryString(blob, function(str){
  1635. self._dc.send(str);
  1636. });
  1637. } else {
  1638. this._dc.send(blob);
  1639. }
  1640. }
  1641. }
  1642. DataConnection.prototype.handleMessage = function(message) {
  1643. var payload = message.payload;
  1644. switch (message.type) {
  1645. case 'ANSWER':
  1646. // Forward to negotiator
  1647. Negotiator.handleSDP(message.type, this, payload.sdp);
  1648. break;
  1649. case 'CANDIDATE':
  1650. Negotiator.handleCandidate(this, payload.candidate);
  1651. break;
  1652. default:
  1653. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1654. break;
  1655. }
  1656. }
  1657. /**
  1658. * Wraps the streaming interface between two Peers.
  1659. */
  1660. function MediaConnection(peer, provider, options) {
  1661. if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
  1662. EventEmitter.call(this);
  1663. this.options = util.extend({}, options);
  1664. this.open = false;
  1665. this.type = 'media';
  1666. this.peer = peer;
  1667. this.provider = provider;
  1668. this.metadata = this.options.metadata;
  1669. this.localStream = this.options._stream;
  1670. this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
  1671. if (this.localStream) {
  1672. Negotiator.startConnection(
  1673. this,
  1674. {_stream: this.localStream, originator: true}
  1675. );
  1676. }
  1677. };
  1678. util.inherits(MediaConnection, EventEmitter);
  1679. MediaConnection._idPrefix = 'mc_';
  1680. MediaConnection.prototype.addStream = function(remoteStream) {
  1681. util.log('Receiving stream', remoteStream);
  1682. this.remoteStream = remoteStream;
  1683. this.emit('stream', remoteStream); // Should we call this `open`?
  1684. this.open = true;
  1685. };
  1686. MediaConnection.prototype.handleMessage = function(message) {
  1687. var payload = message.payload;
  1688. switch (message.type) {
  1689. case 'ANSWER':
  1690. // Forward to negotiator
  1691. Negotiator.handleSDP(message.type, this, payload.sdp);
  1692. break;
  1693. case 'CANDIDATE':
  1694. Negotiator.handleCandidate(this, payload.candidate);
  1695. break;
  1696. default:
  1697. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1698. break;
  1699. }
  1700. }
  1701. MediaConnection.prototype.answer = function(stream) {
  1702. if (this.localStream) {
  1703. // Throw some error.
  1704. return;
  1705. }
  1706. this.options._payload._stream = stream;
  1707. this.localStream = stream;
  1708. Negotiator.startConnection(
  1709. this,
  1710. this.options._payload
  1711. )
  1712. };
  1713. /**
  1714. * Exposed functionality for users.
  1715. */
  1716. /** Allows user to close connection. */
  1717. MediaConnection.prototype.close = function() {
  1718. if (!this.open) {
  1719. return;
  1720. }
  1721. this.open = false;
  1722. Negotiator.cleanup(this);
  1723. this.emit('close')
  1724. };
  1725. /**
  1726. * Manages all negotiations between Peers.
  1727. */
  1728. var Negotiator = {
  1729. pcs: {
  1730. data: {},
  1731. media: {}
  1732. }, // type => {peerId: {pc_id: pc}}.
  1733. //providers: {}, // provider's id => providers (there may be multiple providers/client.
  1734. queue: [] // connections that are delayed due to a PC being in use.
  1735. }
  1736. Negotiator._idPrefix = 'pc_';
  1737. /** Returns a PeerConnection object set up correctly (for data, media). */
  1738. Negotiator.startConnection = function(connection, options) {
  1739. var pc = Negotiator._getPeerConnection(connection, options);
  1740. if (connection.type === 'media' && options._stream) {
  1741. // Add the stream.
  1742. pc.addStream(options._stream);
  1743. }
  1744. // Set the connection's PC.
  1745. connection.pc = pc;
  1746. // What do we need to do now?
  1747. if (options.originator) {
  1748. if (connection.type === 'data') {
  1749. // Create the datachannel.
  1750. var dc = pc.createDataChannel(connection.label, {reliable: options.reliable});
  1751. connection.initialize(dc);
  1752. }
  1753. if (!util.supports.onnegotiationneeded) {
  1754. Negotiator._makeOffer(connection);
  1755. }
  1756. } else {
  1757. Negotiator.handleSDP('OFFER', connection, options.sdp);
  1758. }
  1759. }
  1760. Negotiator._getPeerConnection = function(connection, options) {
  1761. if (!Negotiator.pcs[connection.type]) {
  1762. util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.');
  1763. }
  1764. if (!Negotiator.pcs[connection.type][connection.peer]) {
  1765. Negotiator.pcs[connection.type][connection.peer] = {};
  1766. }
  1767. var peerConnections = Negotiator.pcs[connection.type][connection.peer];
  1768. var pc;
  1769. // Not multiplexing while FF and Chrome have not-great support for it.
  1770. /*if (options.multiplex) {
  1771. ids = Object.keys(peerConnections);
  1772. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  1773. pc = peerConnections[ids[i]];
  1774. if (pc.signalingState === 'stable') {
  1775. break; // We can go ahead and use this PC.
  1776. }
  1777. }
  1778. } else */
  1779. if (options.pc) { // Simplest case: PC id already provided for us.
  1780. pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
  1781. }
  1782. if (!pc || pc.signalingState !== 'stable') {
  1783. pc = Negotiator._startPeerConnection(connection);
  1784. }
  1785. return pc;
  1786. }
  1787. /*
  1788. Negotiator._addProvider = function(provider) {
  1789. if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
  1790. // Wait for provider to obtain an ID.
  1791. provider.on('open', function(id) {
  1792. Negotiator._addProvider(provider);
  1793. });
  1794. } else {
  1795. Negotiator.providers[provider.id] = provider;
  1796. }
  1797. }*/
  1798. /** Start a PC. */
  1799. Negotiator._startPeerConnection = function(connection) {
  1800. util.log('Creating RTCPeerConnection.');
  1801. var id = Negotiator._idPrefix + util.randomToken();
  1802. var optional = {};
  1803. if (connection.type === 'data' && !util.supports.reliable) {
  1804. optional = {optional: [{RtpDataChannels: true}]};
  1805. } else if (connection.type === 'media') {
  1806. // Interop req for chrome.
  1807. optional = {optional: [{DtlsSrtpKeyAgreement: true}]};
  1808. }
  1809. pc = new RTCPeerConnection(connection.provider.options.config, optional);
  1810. Negotiator.pcs[connection.type][connection.peer][id] = pc;
  1811. Negotiator._setupListeners(connection, pc, id);
  1812. return pc;
  1813. }
  1814. /** Set up various WebRTC listeners. */
  1815. Negotiator._setupListeners = function(connection, pc, pc_id) {
  1816. var peerId = connection.peer;
  1817. var connectionId = connection.id;
  1818. var provider = connection.provider;
  1819. // ICE CANDIDATES.
  1820. util.log('Listening for ICE candidates.');
  1821. pc.onicecandidate = function(evt) {
  1822. if (evt.candidate) {
  1823. util.log('Received ICE candidates for:', connection.peer);
  1824. provider.socket.send({
  1825. type: 'CANDIDATE',
  1826. payload: {
  1827. candidate: evt.candidate,
  1828. type: connection.type,
  1829. connectionId: connection.id
  1830. },
  1831. dst: peerId,
  1832. });
  1833. }
  1834. };
  1835. pc.oniceconnectionstatechange = function() {
  1836. switch (pc.iceConnectionState) {
  1837. case 'disconnected':
  1838. case 'failed':
  1839. util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
  1840. connection.close();
  1841. break;
  1842. case 'completed':
  1843. pc.onicecandidate = util.noop;
  1844. break;
  1845. }
  1846. };
  1847. // Fallback for older Chrome impls.
  1848. pc.onicechange = pc.oniceconnectionstatechange;
  1849. // ONNEGOTIATIONNEEDED (Chrome)
  1850. util.log('Listening for `negotiationneeded`');
  1851. pc.onnegotiationneeded = function() {
  1852. util.log('`negotiationneeded` triggered');
  1853. if (pc.signalingState == 'stable') {
  1854. Negotiator._makeOffer(connection);
  1855. } else {
  1856. util.log('onnegotiationneeded triggered when not stable. Is another connection being established?');
  1857. }
  1858. };
  1859. // DATACONNECTION.
  1860. util.log('Listening for data channel');
  1861. // Fired between offer and answer, so options should already be saved
  1862. // in the options hash.
  1863. pc.ondatachannel = function(evt) {
  1864. util.log('Received data channel');
  1865. var dc = evt.channel;
  1866. var connection = provider.getConnection(peerId, connectionId);
  1867. connection.initialize(dc);
  1868. };
  1869. // MEDIACONNECTION.
  1870. util.log('Listening for remote stream');
  1871. pc.onaddstream = function(evt) {
  1872. util.log('Received remote stream');
  1873. var stream = evt.stream;
  1874. provider.getConnection(peerId, connectionId).addStream(stream);
  1875. };
  1876. }
  1877. Negotiator.cleanup = function(connection) {
  1878. util.log('Cleaning up PeerConnection to ' + connection.peer);
  1879. var pc = connection.pc;
  1880. if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) {
  1881. pc.close();
  1882. connection.pc = null;
  1883. }
  1884. }
  1885. Negotiator._makeOffer = function(connection) {
  1886. var pc = connection.pc;
  1887. console.log('using constraints', connection.options.constraints);
  1888. pc.createOffer(function(offer) {
  1889. util.log('Created offer.');
  1890. if (!util.supports.reliable && connection.type === 'data') {
  1891. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  1892. }
  1893. pc.setLocalDescription(offer, function() {
  1894. util.log('Set localDescription: offer', 'for:', connection.peer);
  1895. connection.provider.socket.send({
  1896. type: 'OFFER',
  1897. payload: {
  1898. sdp: offer,
  1899. type: connection.type,
  1900. label: connection.label,
  1901. reliable: connection.reliable,
  1902. serialization: connection.serialization,
  1903. metadata: connection.metadata,
  1904. connectionId: connection.id
  1905. },
  1906. dst: connection.peer,
  1907. });
  1908. }, function(err) {
  1909. connection.provider.emit('error', err);
  1910. util.log('Failed to setLocalDescription, ', err);
  1911. });
  1912. }, function(err) {
  1913. connection.provider.emit('error', err);
  1914. util.log('Failed to createOffer, ', err);
  1915. }, connection.options.constraints);
  1916. }
  1917. Negotiator._makeAnswer = function(connection) {
  1918. var pc = connection.pc;
  1919. pc.createAnswer(function(answer) {
  1920. util.log('Created answer.');
  1921. if (!util.supports.reliable && connection.type === 'data') {
  1922. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  1923. }
  1924. pc.setLocalDescription(answer, function() {
  1925. util.log('Set localDescription: answer', 'for:', connection.peer);
  1926. connection.provider.socket.send({
  1927. type: 'ANSWER',
  1928. payload: {
  1929. sdp: answer,
  1930. type: connection.type,
  1931. connectionId: connection.id
  1932. },
  1933. dst: connection.peer
  1934. });
  1935. }, function(err) {
  1936. connection.provider.emit('error', err);
  1937. util.log('Failed to setLocalDescription, ', err);
  1938. });
  1939. }, function(err) {
  1940. connection.provider.emit('error', err);
  1941. util.log('Failed to create answer, ', err);
  1942. });
  1943. }
  1944. /** Handle an SDP. */
  1945. Negotiator.handleSDP = function(type, connection, sdp) {
  1946. sdp = new RTCSessionDescription(sdp);
  1947. var pc = connection.pc;
  1948. util.log('Setting remote description', sdp);
  1949. pc.setRemoteDescription(sdp, function() {
  1950. util.log('Set remoteDescription:', type, 'for:', connection.peer);
  1951. if (type === 'OFFER') {
  1952. Negotiator._makeAnswer(connection);
  1953. }
  1954. }, function(err) {
  1955. connection.provider.emit('error', err);
  1956. util.log('Failed to setRemoteDescription, ', err);
  1957. });
  1958. }
  1959. /** Handle a candidate. */
  1960. Negotiator.handleCandidate = function(connection, candidate) {
  1961. var candidate = new RTCIceCandidate(candidate);
  1962. connection.pc.addIceCandidate(candidate);
  1963. util.log('Added ICE candidate for:', connection.peer);
  1964. }
  1965. /**
  1966. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  1967. * possible connection for peers.
  1968. */
  1969. function Socket(secure, host, port, key) {
  1970. if (!(this instanceof Socket)) return new Socket(secure, host, port, key);
  1971. EventEmitter.call(this);
  1972. // Disconnected manually.
  1973. this.disconnected = false;
  1974. this._queue = [];
  1975. var httpProtocol = secure ? 'https://' : 'http://';
  1976. var wsProtocol = secure ? 'wss://' : 'ws://';
  1977. this._httpUrl = httpProtocol + host + ':' + port + '/' + key;
  1978. this._wsUrl = wsProtocol + host + ':' + port + '/peerjs?key=' + key;
  1979. }
  1980. util.inherits(Socket, EventEmitter);
  1981. /** Check in with ID or get one from server. */
  1982. Socket.prototype.start = function(id) {
  1983. this.id = id;
  1984. var token = util.randomToken();
  1985. this._httpUrl += '/' + id + '/' + token;
  1986. this._wsUrl += '&id='+id+'&token='+token;
  1987. this._startXhrStream();
  1988. this._startWebSocket();
  1989. }
  1990. /** Start up websocket communications. */
  1991. Socket.prototype._startWebSocket = function(id) {
  1992. var self = this;
  1993. if (this._socket) {
  1994. return;
  1995. }
  1996. this._socket = new WebSocket(this._wsUrl);
  1997. this._socket.onmessage = function(event) {
  1998. var data;
  1999. try {
  2000. data = JSON.parse(event.data);
  2001. } catch(e) {
  2002. util.log('Invalid server message', event.data);
  2003. return;
  2004. }
  2005. self.emit('message', data);
  2006. };
  2007. // Take care of the queue of connections if necessary and make sure Peer knows
  2008. // socket is open.
  2009. this._socket.onopen = function() {
  2010. if (self._timeout) {
  2011. clearTimeout(self._timeout);
  2012. setTimeout(function(){
  2013. self._http.abort();
  2014. self._http = null;
  2015. }, 5000);
  2016. }
  2017. self._sendQueuedMessages();
  2018. util.log('Socket open');
  2019. };
  2020. }
  2021. /** Start XHR streaming. */
  2022. Socket.prototype._startXhrStream = function(n) {
  2023. try {
  2024. var self = this;
  2025. this._http = new XMLHttpRequest();
  2026. this._http._index = 1;
  2027. this._http._streamIndex = n || 0;
  2028. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  2029. this._http.onreadystatechange = function() {
  2030. if (this.readyState == 2 && this.old) {
  2031. this.old.abort();
  2032. delete this.old;
  2033. }
  2034. if (this.readyState > 2 && this.status == 200 && this.responseText) {
  2035. self._handleStream(this);
  2036. }
  2037. };
  2038. this._http.send(null);
  2039. this._setHTTPTimeout();
  2040. } catch(e) {
  2041. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  2042. }
  2043. }
  2044. /** Handles onreadystatechange response as a stream. */
  2045. Socket.prototype._handleStream = function(http) {
  2046. // 3 and 4 are loading/done state. All others are not relevant.
  2047. var messages = http.responseText.split('\n');
  2048. // Check to see if anything needs to be processed on buffer.
  2049. if (http._buffer) {
  2050. while (http._buffer.length > 0) {
  2051. var index = http._buffer.shift();
  2052. var bufferedMessage = messages[index];
  2053. try {
  2054. bufferedMessage = JSON.parse(bufferedMessage);
  2055. } catch(e) {
  2056. http._buffer.shift(index);
  2057. break;
  2058. }
  2059. this.emit('message', bufferedMessage);
  2060. }
  2061. }
  2062. var message = messages[http._index];
  2063. if (message) {
  2064. http._index += 1;
  2065. // Buffering--this message is incomplete and we'll get to it next time.
  2066. // This checks if the httpResponse ended in a `\n`, in which case the last
  2067. // element of messages should be the empty string.
  2068. if (http._index === messages.length) {
  2069. if (!http._buffer) {
  2070. http._buffer = [];
  2071. }
  2072. http._buffer.push(http._index - 1);
  2073. } else {
  2074. try {
  2075. message = JSON.parse(message);
  2076. } catch(e) {
  2077. util.log('Invalid server message', message);
  2078. return;
  2079. }
  2080. this.emit('message', message);
  2081. }
  2082. }
  2083. }
  2084. Socket.prototype._setHTTPTimeout = function() {
  2085. var self = this;
  2086. this._timeout = setTimeout(function() {
  2087. var old = self._http;
  2088. if (!self._wsOpen()) {
  2089. self._startXhrStream(old._streamIndex + 1);
  2090. self._http.old = old;
  2091. } else {
  2092. old.abort();
  2093. }
  2094. }, 25000);
  2095. }
  2096. /** Is the websocket currently open? */
  2097. Socket.prototype._wsOpen = function() {
  2098. return this._socket && this._socket.readyState == 1;
  2099. }
  2100. /** Send queued messages. */
  2101. Socket.prototype._sendQueuedMessages = function() {
  2102. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  2103. this.send(this._queue[i]);
  2104. }
  2105. }
  2106. /** Exposed send for DC & Peer. */
  2107. Socket.prototype.send = function(data) {
  2108. if (this.disconnected) {
  2109. return;
  2110. }
  2111. // If we didn't get an ID yet, we can't yet send anything so we should queue
  2112. // up these messages.
  2113. if (!this.id) {
  2114. this._queue.push(data);
  2115. return;
  2116. }
  2117. if (!data.type) {
  2118. this.emit('error', 'Invalid message');
  2119. return;
  2120. }
  2121. var message = JSON.stringify(data);
  2122. if (this._wsOpen()) {
  2123. this._socket.send(message);
  2124. } else {
  2125. var http = new XMLHttpRequest();
  2126. var url = this._httpUrl + '/' + data.type.toLowerCase();
  2127. http.open('post', url, true);
  2128. http.setRequestHeader('Content-Type', 'application/json');
  2129. http.send(message);
  2130. }
  2131. }
  2132. Socket.prototype.close = function() {
  2133. if (!this.disconnected && this._wsOpen()) {
  2134. this._socket.close();
  2135. this.disconnected = true;
  2136. }
  2137. }
  2138. })(this);