NGL@1.0.0-beta.7 Home Manual Reference Source Gallery

src/streamer/network-streamer.js

  1. /**
  2. * @file Network Streamer
  3. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  4. * @private
  5. */
  6.  
  7. import Streamer from './streamer.js'
  8.  
  9. class NetworkStreamer extends Streamer {
  10. get type () { return 'network' }
  11.  
  12. get __srcName () { return 'url' }
  13.  
  14. _read (callback) {
  15. let url = this.src
  16.  
  17. if (typeof importScripts === 'function') {
  18. // FIXME
  19. // adjust relative path when inside a web worker
  20. if (url.substr(0, 3) === '../') url = '../' + url
  21. }
  22.  
  23. const xhr = new window.XMLHttpRequest()
  24. xhr.open('GET', url, true)
  25.  
  26. //
  27.  
  28. xhr.addEventListener('load', function () {
  29. if (xhr.status === 200 || xhr.status === 304 ||
  30. // when requesting from local file system
  31. // the status in Google Chrome/Chromium is 0
  32. xhr.status === 0
  33. ) {
  34. try {
  35. callback(xhr.response)
  36. } catch (e) {
  37. this.onerror(e)
  38. }
  39. } else {
  40. if (typeof this.onerror === 'function') {
  41. this.onerror(xhr.status)
  42. }
  43.  
  44. throw new Error('NetworkStreamer._read: status code ' + xhr.status)
  45. }
  46. }.bind(this), false)
  47.  
  48. //
  49.  
  50. // if( typeof this.onprogress === "function" ){
  51.  
  52. // xhr.addEventListener( 'progress', function ( event ) {
  53.  
  54. // this.onprogress( event );
  55.  
  56. // }.bind( this ), false );
  57.  
  58. // }
  59.  
  60. //
  61.  
  62. if (typeof this.onerror === 'function') {
  63. xhr.addEventListener('error', function (event) {
  64. this.onerror(event)
  65. }.bind(this), false)
  66. }
  67.  
  68. //
  69.  
  70. if (this.isBinary()) {
  71. xhr.responseType = 'arraybuffer'
  72. } else if (this.json) {
  73. xhr.responseType = 'json'
  74. } else if (this.xml) {
  75. xhr.responseType = 'document'
  76. } else {
  77. xhr.responseType = 'text'
  78. }
  79. // xhr.crossOrigin = true;
  80.  
  81. xhr.send(null)
  82.  
  83. // try {
  84. // xhr.send( null );
  85. // }catch( e ){
  86. // if( typeof this.onerror === "function" ){
  87. // this.onerror( e.message );
  88. // }
  89. // }
  90. }
  91. }
  92.  
  93. export default NetworkStreamer