web-socket.html 3.1 KB

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