web-socket.html 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <link rel="import" href="binaryjs.html">
  2. <dom-module id="web-socket">
  3. <template>
  4. <style>
  5. :host {
  6. display: block;
  7. }
  8. </style>
  9. </template>
  10. <script>
  11. 'use strict';
  12. window.isActive = true;
  13. window.onfocus = function() {
  14. window.isActive = true;
  15. };
  16. window.onblur = function() {
  17. window.isActive = false;
  18. };
  19. Polymer({
  20. is: 'web-socket',
  21. attached: function() {
  22. this.init();
  23. },
  24. init: function() {
  25. if (window.isActive) {
  26. clearInterval(this.reconnectTimer);
  27. this.reconnectTimer = undefined;
  28. var websocketUrl = (window.debug ? 'ws://' + window.location.hostname + ':3002' : 'wss://snapdrop.net') + '/binary';
  29. this.client = new BinaryClient(websocketUrl);
  30. this.client.on('stream', function(stream, meta) {
  31. // collect stream data
  32. var parts = [];
  33. stream.on('data', function(data) {
  34. //console.log('part received', meta, data);
  35. if (data.isSystemEvent) {
  36. if (meta) {
  37. data.from = meta.from;
  38. }
  39. this.fire('system-event', data);
  40. } else {
  41. parts.push(data);
  42. }
  43. }.bind(this));
  44. // when finished, set it as the background image
  45. stream.on('end', function() {
  46. var blob = new Blob(parts, {
  47. type: meta.type
  48. });
  49. console.log('file received', blob, meta);
  50. this.fire('file-received', {
  51. blob: blob,
  52. name: meta.name,
  53. from: meta.from
  54. });
  55. }.bind(this));
  56. }.bind(this));
  57. this.client.on('open', function(e) {
  58. console.log(e);
  59. this.client.send({}, {
  60. serverMsg: 'rtc-support',
  61. rtc: window.webRTCSupported
  62. });
  63. }.bind(this));
  64. this.client.on('error', function(e) {
  65. this._reconnect(e);
  66. }.bind(this));
  67. this.client.on('close', function(e) {
  68. this._reconnect(e);
  69. }.bind(this));
  70. }
  71. },
  72. _sendFile: function(toPeer, file) {
  73. console.log('send file via WebSocket', file);
  74. this.client.send(file.file, {
  75. name: file.file.name,
  76. type: file.file.type,
  77. toPeer: toPeer
  78. });
  79. },
  80. connectToPeer: function(peer, callback) {
  81. callback();
  82. },
  83. _sendSystemEvent: function(toPeer, event) {
  84. console.log('system event', toPeer, event);
  85. event.isSystemEvent = true;
  86. this.client.send(event, {
  87. toPeer: toPeer
  88. });
  89. },
  90. _reconnect: function(e) {
  91. console.log('disconnected', e);
  92. //try to reconnect after 3s
  93. if (!this.reconnectTimer) {
  94. this.reconnectTimer = setInterval(this.init.bind(this), 3000);
  95. }
  96. }
  97. });
  98. </script>
  99. </dom-module>