-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStreamFile.js
267 lines (240 loc) · 6.47 KB
/
StreamFile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/**
* Quickie wrapper around XHR to fetch a file as array buffer chunks.
*
* Call streamFile.readBytes() after an onread event's data has been
* processed to trigger the next read.
*
* IE 10: uses MSStream / MSStreamReader for true streaming
* Firefox: uses moz-chunked-arraybuffer to buffer & deliver during download
* Safari, Chrome: uses binary string to buffer & deliver during download
*/
function StreamFile(options) {
var self = this,
url = options.url,
onstart = options.onstart || function(){},
onbuffer = options.onbuffer || function(){},
onread = options.onread || function(){},
ondone = options.ondone || function(){},
onerror = options.onerror || function(){},
bufferSize = options.bufferSize || 4096;
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
var foundMethod = false;
function tryMethod(rt) {
if (foundMethod) {
return false;
}
try {
// Set the response type and see if it explodes!
xhr.responseType = rt;
} catch (e) {
// Safari 6 throws a DOM Exception on invalid setting
return false;
}
// Other browsers just don't accept the setting, so check
// whether it made it through.
if (xhr.responseType == rt) {
foundMethod = true;
return true;
}
return false;
}
var waitingForInput = false,
doneBuffering = false;
if (tryMethod('moz-chunked-arraybuffer')) {
console.log("Streaming input using moz-chunked-arraybuffer");
var buffers = [];
function popBuffer() {
var buffer = buffers.shift();
if (!bufferSize || bufferSize >= buffer.byteLength) {
self.bytesRead += buffer.byteLength;
return buffer;
} else {
// Split the buffer and requeue the rest
var thisBuffer = buffer.slice(0, bufferSize),
nextBuffer = buffer.slice(bufferSize);
buffers.unshift(nextBuffer);
self.bytesRead += thisBuffer.byteLength;
return thisBuffer;
}
}
function handleInput(buffer) {
self.bytesBuffered += buffer.byteLength;
onbuffer();
buffers.push(buffer);
if (waitingForInput) {
waitingForInput = false;
onread(popBuffer());
if (doneBuffering && buffers.length == 0) {
// We're out of data!
ondone();
}
}
}
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 2) {
if (xhr.status >= 400) {
// errrorrrrrrr
callback(null, "HTTP " + xhr.status + ": " +xhr.statusText);
onerror();
xhr.abort();
} else {
onstart();
}
} else if (xhr.readyState == 4) {
// Complete.
doneBuffering = true;
}
};
xhr.onprogress = function(event) {
// xhr.response is a per-chunk ArrayBuffer
handleInput(xhr.response);
};
self.readBytes = function() {
if (buffers.length > 0) {
var buffer = popBuffer();
setTimeout(function() {
onread(buffer);
}, 0);
} else if (doneBuffering) {
// We're out of data!
setTimeout(function() {
ondone();
}, 0);
} else {
// Nothing queued...
waitingForInput = true;
}
};
}
if (tryMethod('ms-stream')) {
// IE 10 supports returning a Stream from XHR.
console.log("Streaming input using MSStreamReader");
var stream, streamReader;
xhr.onreadystatechange = function() {
if (xhr.readyState == 2) {
if (xhr.status >= 400) {
// errrorrrrrrr
callback(null, "HTTP " + xhr.status + ": " +xhr.statusText);
onerror();
xhr.abort();
}
} else if (xhr.readyState == xhr.LOADING) {
// Transfer us over to the StreamReader...
stream = xhr.response;
xhr.onreadystatechange = null;
onstart();
}
}
self.readBytes = function() {
if (stream) {
streamReader = new MSStreamReader();
streamReader.onload = function(event) {
var buffer = event.target.result,
len = buffer.byteLength;
if (len > 0) {
self.bytesBuffered += len;
self.bytesRead += len;
onread(buffer);
} else {
// Zero length means end of stream.
ondone();
}
}
streamReader.onerror = function(event) {
onerror('mystery error streaming');
}
streamReader.readAsArrayBuffer(stream, bufferSize);
} else {
waitingForInput = true;
}
};
}
if (!foundMethod && xhr.overrideMimeType !== undefined) {
foundMethod = true;
// Use old binary string method since we can read reponseText
// progressively and extract ArrayBuffers from that.
console.log("Streaming input using XHR progressive binary string");
xhr.responseType = "text";
xhr.overrideMimeType('text/plain; charset=x-user-defined');
var lastPosition = 0,
doneBuffering = false;
// Is there a better way to do this conversion? :(
function stringToArrayBuffer(chunk) {
var len = chunk.length,
buffer = new ArrayBuffer(len),
bytes = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
bytes[i] = chunk.charCodeAt(i);
}
return buffer;
}
// Return a buffer with up to bufferSize from the next data
function popBuffer() {
var chunk = xhr.responseText.slice(lastPosition, lastPosition + bufferSize);
lastPosition += chunk.length;
self.bytesRead += chunk.length;
return stringToArrayBuffer(chunk);
}
// Is there data available to read?
function dataToRead() {
return lastPosition < xhr.responseText.length;
}
// Read the next binary buffer out of the input string
function readNextChunk() {
if (waitingForInput) {
waitingForInput = false;
onread(popBuffer());
if (doneBuffering && !dataToRead()) {
// We're out of data!
ondone();
}
}
}
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 2) {
if (xhr.status >= 400) {
// errrorrrrrrr
callback(null, "HTTP " + xhr.status + ": " +xhr.statusText);
onerror();
xhr.abort();
} else {
onstart();
}
} else if (xhr.readyState == 3) {
// xhr.responseText is a binary string of entire file so far
self.bytesBuffered = xhr.responseText.length;
onbuffer();
readNextChunk();
} else if (xhr.readyState == 4) {
// Complete.
doneBuffering = true;
}
};
self.readBytes = function() {
if (dataToRead()) {
var buffer = popBuffer();
setTimeout(function() {
onread(buffer);
}, 0);
} else if (doneBuffering) {
// We're out of data!
setTimeout(function() {
ondone();
}, 0);
} else {
// Nothing queued...
waitingForInput = true;
}
};
}
if (!foundMethod) {
throw new Error("No streaming HTTP input method found.");
}
xhr.send();
self.bytesBuffered = 0;
self.bytesRead = 0;
self.abort = function() {
xhr.abort();
};
}