fetch.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. JSMpeg.Source.Fetch = (function(){ "use strict";
  2. var FetchSource = function(url, options) {
  3. this.url = url;
  4. this.destination = null;
  5. this.request = null;
  6. this.streaming = true;
  7. this.completed = false;
  8. this.established = false;
  9. this.progress = 0;
  10. this.aborted = false;
  11. this.onEstablishedCallback = options.onSourceEstablished;
  12. this.onCompletedCallback = options.onSourceCompleted;
  13. };
  14. FetchSource.prototype.connect = function(destination) {
  15. this.destination = destination;
  16. };
  17. FetchSource.prototype.start = function() {
  18. var params = {
  19. method: 'GET',
  20. headers: new Headers(),
  21. cache: 'default'
  22. };
  23. self.fetch(this.url, params).then(function(res) {
  24. if (res.ok && (res.status >= 200 && res.status <= 299)) {
  25. this.progress = 1;
  26. this.established = true;
  27. return this.pump(res.body.getReader());
  28. }
  29. else {
  30. //error
  31. }
  32. }.bind(this)).catch(function(err) {
  33. throw(err);
  34. });
  35. };
  36. FetchSource.prototype.pump = function(reader) {
  37. return reader.read().then(function(result) {
  38. if (result.done) {
  39. this.completed = true;
  40. }
  41. else {
  42. if (this.aborted) {
  43. return reader.cancel();
  44. }
  45. if (this.destination) {
  46. this.destination.write(result.value.buffer);
  47. }
  48. return this.pump(reader);
  49. }
  50. }.bind(this)).catch(function(err) {
  51. throw(err);
  52. });
  53. };
  54. FetchSource.prototype.resume = function(secondsHeadroom) {
  55. // Nothing to do here
  56. };
  57. FetchSource.prototype.abort = function() {
  58. this.aborted = true;
  59. };
  60. return FetchSource;
  61. })();