You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.6 KiB

  1. function Uploader(url, cb) {
  2. this.ws = new WebSocket(url);
  3. if (cb) this.ws.onopen = cb;
  4. this.sendQueue = [];
  5. this.sending = null;
  6. this.sendCallback = null;
  7. this.ondone = null;
  8. var self = this;
  9. this.ws.onmessage = function(event) {
  10. var data = JSON.parse(event.data);
  11. if (data.event == 'complete') {
  12. if (data.path != self.sending.path) {
  13. self.sendQueue = [];
  14. self.sending = null;
  15. self.sendCallback = null;
  16. throw new Error('Got message for wrong file!');
  17. }
  18. self.sending = null;
  19. var callback = self.sendCallback;
  20. self.sendCallback = null;
  21. if (callback) callback();
  22. if (self.sendQueue.length === 0 && self.ondone) self.ondone(null);
  23. if (self.sendQueue.length > 0) {
  24. var args = self.sendQueue.pop();
  25. setTimeout(function() { self.sendFile.apply(self, args); }, 0);
  26. }
  27. }
  28. else if (data.event == 'error') {
  29. self.sendQueue = [];
  30. self.sending = null;
  31. var callback = self.sendCallback;
  32. self.sendCallback = null;
  33. var error = new Error('Server reported send error for file ' + data.path);
  34. if (callback) callback(error);
  35. if (self.ondone) self.ondone(error);
  36. }
  37. }
  38. }
  39. Uploader.prototype.sendFile = function(file, cb) {
  40. if (this.ws.readyState != WebSocket.OPEN) throw new Error('Not connected');
  41. if (this.sending) {
  42. this.sendQueue.push(arguments);
  43. return;
  44. }
  45. var fileData = { name: file.name, path: file.webkitRelativePath };
  46. this.sending = fileData;
  47. this.sendCallback = cb;
  48. this.ws.send(JSON.stringify(fileData));
  49. this.ws.send(file);
  50. }
  51. Uploader.prototype.close = function() {
  52. this.ws.close();
  53. }