This repository has been archived by the owner on Mar 14, 2019. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 237
/
upload-http-client.js
260 lines (223 loc) · 7.56 KB
/
upload-http-client.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
/*
* HTTP Upload Transfer Queue
*/
// 2MB default upload chunk size
// Can be overridden by user with FS.config.uploadChunkSize or per FS.Collection in collection options
var defaultChunkSize = 2 * 1024 * 1024;
/**
* @private
* @param {Object} task
* @param {Function} next
* @return {undefined}
*/
var _taskHandler = function(task, next) {
FS.debug && console.log("uploading chunk " + task.chunk + ", bytes " + task.start + " to " + Math.min(task.end, task.fileObj.size()) + " of " + task.fileObj.size());
task.fileObj.data.getBinary(task.start, task.end, function gotBinaryCallback(err, data) {
if (err) {
next(new Meteor.Error(err.error, err.message));
} else {
FS.debug && console.log('PUT to URL', task.url, task.urlParams);
HTTP.call("PUT", task.url, {
params: FS.Utility.extend({chunk: task.chunk}, task.urlParams),
content: data,
headers: {
'Content-Type': task.fileObj.type()
}
}, function(error, result) {
task = null;
if (error) {
next(new Meteor.Error(error.error, error.message));
} else {
next();
}
});
}
});
};
/**
* @private
* @param {Object} data
* @param {Function} addTask
* @return {undefined}
*/
var _errorHandler = function(data, addTask, failures) {
// If file upload fails
// TODO We should retry a few times and then emit error?
// data.fileObj.emit("error", error);
};
/** @method UploadTransferQueue
* @namespace UploadTransferQueue
* @constructor
* @param {Object} [options]
*/
UploadTransferQueue = function(options) {
// Rig options
options = options || {};
// Init the power queue
var self = new PowerQueue({
name: 'HTTPUploadTransferQueue',
// spinalQueue: ReactiveList,
maxProcessing: 1,
maxFailures: 5,
jumpOnFailure: true,
autostart: true,
isPaused: false,
filo: false,
debug: FS.debug
});
// Keep track of uploaded files via this queue
self.files = {};
// cancel maps onto queue reset
self.cancel = self.reset;
/**
* @method UploadTransferQueue.isUploadingFile
* @param {FS.File} fileObj File to check if uploading
* @returns {Boolean} True if the file is uploading
*
* @todo Maybe have a similar function for accessing the file upload queue?
*/
self.isUploadingFile = function(fileObj) {
// Check if file is already in queue
return !!(fileObj && fileObj._id && fileObj.collectionName && (self.files[fileObj.collectionName] || {})[fileObj._id]);
};
/** @method UploadTransferQueue.resumeUploadingFile
* @param {FS.File} File to resume uploading
* @todo Not sure if this is the best way to handle resumes
*/
self.resumeUploadingFile = function(fileObj) {
// Make sure we are handed a FS.File
if (!(fileObj instanceof FS.File)) {
throw new Error('Transfer queue expects a FS.File');
}
if (fileObj.isMounted()) {
// This might still be true, preventing upload, if
// there was a server restart without client restart.
self.files[fileObj.collectionName] = self.files[fileObj.collectionName] || {};
self.files[fileObj.collectionName][fileObj._id] = false;
// Kick off normal upload
self.uploadFile(fileObj);
}
};
/** @method UploadTransferQueue.uploadFile
* @param {FS.File} File to upload
* @todo Check that a file can only be added once - maybe a visual helper on the FS.File?
* @todo Have an initial request to the server getting uploaded chunks for resume
*/
self.uploadFile = function(fileObj) {
FS.debug && console.log("HTTP uploadFile");
// Make sure we are handed a FS.File
if (!(fileObj instanceof FS.File)) {
throw new Error('Transfer queue expects a FS.File');
}
// Make sure that we have size as number
if (typeof fileObj.size() !== 'number') {
throw new Error('TransferQueue upload failed: fileObj size not set');
}
// We don't add the file if it's already in transfer or if already uploaded
if (self.isUploadingFile(fileObj) || fileObj.isUploaded()) {
return;
}
// Make sure the file object is mounted on a collection
if (fileObj.isMounted()) {
var collectionName = fileObj.collectionName;
var id = fileObj._id;
// Set the chunkSize to match the collection options, or global config, or default
fileObj.chunkSize = fileObj.collection.options.chunkSize || FS.config.uploadChunkSize || defaultChunkSize;
// Set counter for uploaded chunks
fileObj.chunkCount = 0;
// Calc the number of chunks
fileObj.chunkSum = Math.ceil(fileObj.size() / fileObj.chunkSize);
if (fileObj.chunkSum === 0)
return;
// Update the filerecord
// TODO eventually we should be able to do this without storing any chunk info in the filerecord
fileObj.update({$set: {chunkSize: fileObj.chunkSize, chunkCount: fileObj.chunkCount, chunkSum: fileObj.chunkSum}});
// Create a sub queue
var chunkQueue = new PowerQueue({
onEnded: function oneChunkQueueEnded() {
// Remove from list of files being uploaded
self.files[collectionName][id] = false;
// XXX It might be possible for this to be called even though there were errors uploading?
fileObj.emit("uploaded");
},
spinalQueue: ReactiveList,
maxProcessing: 1,
maxFailures: 5,
jumpOnFailure: true,
autostart: false,
isPaused: false,
filo: false
});
// Rig the custom task handler
chunkQueue.taskHandler = _taskHandler;
// Rig the error handler
chunkQueue.errorHandler = _errorHandler;
// Set flag that this file is being transfered
self.files[collectionName] = self.files[collectionName] || {};
self.files[collectionName][id] = true;
// Construct URL
var url = FS.HTTP.uploadUrl + '/' + collectionName;
if (id) {
url += '/' + id;
}
// TODO: Could we somehow figure out if the collection requires login?
var authToken = '';
if (typeof Accounts !== "undefined") {
var authObject = {
authToken: Accounts._storedLoginToken() || '',
};
// Set the authToken
var authString = JSON.stringify(authObject);
authToken = FS.Utility.btoa(authString);
}
// Construct query string
var urlParams = {
filename: fileObj.name()
};
if (authToken !== '') {
urlParams.token = authToken;
}
// Add chunk upload tasks
for (var chunk = 0, start; chunk < fileObj.chunkSum; chunk++) {
start = chunk * fileObj.chunkSize;
// Create and add the task
// XXX should we somehow make sure we haven't uploaded this chunk already, in
// case we are resuming?
chunkQueue.add({
chunk: chunk,
name: fileObj.name(),
url: url,
urlParams: urlParams,
fileObj: fileObj,
start: start,
end: (chunk + 1) * fileObj.chunkSize
});
}
// Add the queue to the main upload queue
self.add(chunkQueue);
}
};
return self;
};
/**
* @namespace FS
* @type UploadTransferQueue
*
* There is a single uploads transfer queue per client (not per CFS)
*/
FS.HTTP.uploadQueue = new UploadTransferQueue();
/*
* FS.File extensions
*/
/**
* @method FS.File.prototype.resume
* @public
* @param {File|Blob|Buffer} ref
* @todo WIP, Not yet implemented for server
*
* > This function is not yet implemented for server
*/
FS.File.prototype.resume = function(ref) {
var self = this;
FS.uploadQueue.resumeUploadingFile(self);
};