summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/UploadWizard/resources/transports/mw.FormDataTransport.js
blob: 51d0772d8cb17b9fd5d5f534d0f2a8af18a6e637 (plain)
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
( function ( mw, $, OO ) {
	/**
	 * Represents a "transport" for files to upload; using HTML5 FormData.
	 *
	 * @constructor
	 * @class mw.FormDataTransport
	 * @mixins OO.EventEmitter
	 * @param {mw.Api} api
	 * @param {Object} formData Additional form fields required for upload api call
	 * @param {Object} [config]
	 * @param {Object} [config.chunkSize]
	 * @param {Object} [config.maxPhpUploadSize]
	 * @param {Object} [config.useRetryTimeout]
	 */
	mw.FormDataTransport = function ( api, formData, config ) {
		this.config = config || mw.UploadWizard.config;

		OO.EventEmitter.call( this );

		this.formData = formData;
		this.aborted = false;
		this.api = api;

		// Set chunk size to configured chunk size or max php size,
		// whichever is smaller.
		this.chunkSize = Math.min( this.config.chunkSize, this.config.maxPhpUploadSize );
		this.maxRetries = 2;
		this.retries = 0;
		this.firstPoll = false;

		// running API request
		this.request = null;
	};

	OO.mixinClass( mw.FormDataTransport, OO.EventEmitter );

	mw.FormDataTransport.prototype.abort = function () {
		this.aborted = true;

		if ( this.request ) {
			this.request.abort();
		}
	};

	/**
	 * Submits an upload to the API.
	 *
	 * @param {Object} params Request params
	 * @return {jQuery.Promise}
	 */
	mw.FormDataTransport.prototype.post = function ( params ) {
		var deferred = $.Deferred();

		this.request = this.api.post( params, {
			/*
			 * $.ajax is not quite equiped to handle File uploads with params.
			 * The most convenient way would be to submit it with a FormData
			 * object, but mw.Api will already do that for us: it'll transform
			 * params if it encounters a multipart/form-data POST request, and
			 * submit it accordingly!
			 *
			 * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
			 */
			contentType: 'multipart/form-data',
			/*
			 * $.ajax also has no progress event that will allow us to figure
			 * out how much of the upload has already gone out, so let's add it!
			 */
			xhr: function () {
				var xhr = $.ajaxSettings.xhr();
				xhr.upload.addEventListener( 'progress', function ( evt ) {
					var fraction = null;
					if ( evt.lengthComputable ) {
						fraction = parseFloat( evt.loaded / evt.total );
					}
					deferred.notify( fraction );
				}, false );
				return xhr;
			}
		} );

		// just pass on success & failures
		this.request.then( deferred.resolve, deferred.reject );

		return deferred.promise();
	};

	/**
	 * Creates the upload API params.
	 *
	 * @param {string} filename
	 * @param {number} [offset] For chunked uploads
	 * @return {Object}
	 */
	mw.FormDataTransport.prototype.createParams = function ( filename, offset ) {
		var params = OO.cloneObject( this.formData );

		$.extend( params, {
			filename: filename,

			// ignorewarnings is turned on, since warnings are presented in a
			// later step and this transport doesn't know how to deal with them.
			// Also, it's important to allow people to upload files with (for
			// example) blacklisted names, and then rename them later in the
			// wizard.
			ignorewarnings: true,

			offset: offset || 0
		} );

		return params;
	};

	/**
	 * Start the upload with the provided file.
	 *
	 * @param {File} file
	 * @param {string} tempFileName
	 * @return {jQuery.Promise}
	 */
	mw.FormDataTransport.prototype.upload = function ( file, tempFileName ) {
		var params, ext;

		this.tempname = tempFileName;
		// Limit length to 240 bytes (limit hardcoded in UploadBase.php).
		if ( this.tempname.length > 240 ) {
			ext = this.tempname.split( '.' ).pop();
			this.tempname = this.tempname.substr( 0, 240 - ext.length - 1 ) + '.' + ext;
		}

		if ( file.size > this.chunkSize ) {
			return this.chunkedUpload( file );
		} else {
			params = this.createParams( this.tempname );
			params.file = file;
			return this.post( params );
		}
	};

	/**
	 * This function exists to safely chain several hundred promises without using .then() or nested
	 * promises. We might divide a 4 GB file into 800 chunks of 5 MB each.
	 *
	 * In jQuery 2.x, nested promises result in nested call stacks when resolving/rejecting/notifying
	 * the last promise in the chain and listening on the first one, and browsers have call stack
	 * limits low enough that we previously ran into them for files around a couple hundred megabytes
	 * (the worst is Firefox 47 with a limit of 1024 calls).
	 *
	 * @param {File} file
	 * @return {jQuery.Promise} Promise which behaves identically to a regular non-chunked upload
	 *   promise from #upload
	 */
	mw.FormDataTransport.prototype.chunkedUpload = function ( file ) {
		var
			offset,
			prevPromise = $.Deferred().resolve(),
			deferred = $.Deferred(),
			fileSize = file.size,
			chunkSize = this.chunkSize,
			transport = this;

		for ( offset = 0; offset < fileSize; offset += chunkSize ) {
			// Capture offset in a closure
			// eslint-disable-next-line no-loop-func
			( function ( offset ) {
				var
					newPromise = $.Deferred(),
					isLastChunk = offset + chunkSize >= fileSize,
					thisChunkSize = isLastChunk ? ( fileSize % chunkSize ) : chunkSize;
				prevPromise.done( function () {
					transport.uploadChunk( file, offset )
						.done( isLastChunk ? deferred.resolve : newPromise.resolve )
						.fail( deferred.reject )
						.progress( function ( fraction ) {
							// The progress notifications give us per-chunk progress.
							// Calculate progress for the whole file.
							deferred.notify( ( offset + fraction * thisChunkSize ) / fileSize );
						} );
				} );
				prevPromise = newPromise;
			}( offset ) );
		}

		return deferred.promise();
	};

	/**
	 * Upload a single chunk.
	 *
	 * @param {File} file
	 * @param {number} offset Offset in bytes.
	 * @return {jQuery.Promise}
	 */
	mw.FormDataTransport.prototype.uploadChunk = function ( file, offset ) {
		var params = this.createParams( this.tempname, offset ),
			transport = this,
			bytesAvailable = file.size,
			chunk;

		if ( this.aborted ) {
			return $.Deferred().reject( 'aborted', {
				errors: [ {
					code: 'aborted',
					html: mw.message( 'api-error-aborted' ).parse()
				} ]
			} );
		}

		// Slice API was changed and has vendor prefix for now
		// new version now require start/end and not start/length
		if ( file.mozSlice ) {
			chunk = file.mozSlice( offset, offset + this.chunkSize, file.type );
		} else if ( file.webkitSlice ) {
			chunk = file.webkitSlice( offset, offset + this.chunkSize, file.type );
		} else {
			chunk = file.slice( offset, offset + this.chunkSize, file.type );
		}

		// only enable async if file is larger 10Mb
		if ( bytesAvailable > 10 * 1024 * 1024 ) {
			params.async = true;
		}

		// If offset is 0, we're uploading the file from scratch. filekey may be set if we're retrying
		// the first chunk. The API errors out if a filekey is given with zero offset (as it's
		// nonsensical). TODO Why do we need to retry in this case, if we managed to upload something?
		if ( this.filekey && offset !== 0 ) {
			params.filekey = this.filekey;
		}
		params.filesize = bytesAvailable;
		params.chunk = chunk;

		return this.post( params ).then( function ( response ) {
			if ( response.upload && response.upload.filekey ) {
				transport.filekey = response.upload.filekey;
			}

			if ( response.upload && response.upload.result ) {
				switch ( response.upload.result ) {
					case 'Continue':
						// Reset retry counter
						transport.retries = 0;
						/* falls through */
					case 'Success':
						// Just pass the response through.
						return response;
					case 'Poll':
						// Need to retry with checkStatus.
						return transport.retryWithMethod( 'checkStatus' );
				}
			} else {
				return transport.maybeRetry(
					'on unknown response',
					response.error ? response.error.code : 'unknown-error',
					response,
					'uploadChunk',
					file, offset
				);
			}
		}, function ( code, result ) {
			// Ain't this some great machine readable output eh
			if (
				result.errors &&
				result.errors[ 0 ].code === 'stashfailed' &&
				result.errors[ 0 ].html === mw.message( 'apierror-stashfailed-complete' ).parse()
			) {
				return transport.retryWithMethod( 'checkStatus' );
			}

			// Failed to upload, try again in 3 seconds
			// This is really dumb, we should only do this for cases where retrying has a chance to work
			// (so basically, network failures). If your upload was blocked by AbuseFilter you're
			// shafted anyway. But some server-side errors really are temporary...
			return transport.maybeRetry(
				'on error event',
				code,
				result,
				'uploadChunk',
				file, offset
			);
		} );
	};

	/**
	 * Handle possible retry event - rejected if maximum retries already fired.
	 *
	 * @param {string} contextMsg
	 * @param {string} code
	 * @param {Object} response
	 * @param {string} retryMethod
	 * @param {File} [file]
	 * @param {number} [offset]
	 * @return {jQuery.Promise}
	 */
	mw.FormDataTransport.prototype.maybeRetry = function ( contextMsg, code, response, retryMethod, file, offset ) {
		this.retries++;

		if ( this.tooManyRetries() ) {
			mw.log.warn( 'Max retries exceeded ' + contextMsg );
			return $.Deferred().reject( code, response );
		} else if ( this.aborted ) {
			return $.Deferred().reject( code, response );
		} else {
			mw.log( 'Retry #' + this.retries + ' ' + contextMsg );
			return this.retryWithMethod( retryMethod, file, offset );
		}
	};

	/**
	 * Have we retried too many times already?
	 *
	 * @return {boolean}
	 */
	mw.FormDataTransport.prototype.tooManyRetries = function () {
		return this.maxRetries > 0 && this.retries >= this.maxRetries;
	};

	/**
	 * Either retry uploading or checking the status.
	 *
	 * @param {'uploadChunk'|'checkStatus'} methodName
	 * @param {File} [file]
	 * @param {number} [offset]
	 * @return {jQuery.Promise}
	 */
	mw.FormDataTransport.prototype.retryWithMethod = function ( methodName, file, offset ) {
		var
			transport = this,
			retryDeferred = $.Deferred(),
			retry = function () {
				transport[ methodName ]( file, offset ).then( retryDeferred.resolve, retryDeferred.reject );
			};

		if ( this.config.useRetryTimeout !== false ) {
			setTimeout( retry, 3000 );
		} else {
			retry();
		}

		return retryDeferred.promise();
	};

	/**
	 * Check the status of the upload.
	 *
	 * @return {jQuery.Promise}
	 */
	mw.FormDataTransport.prototype.checkStatus = function () {
		var transport = this,
			params = OO.cloneObject( this.formData );

		if ( this.aborted ) {
			return $.Deferred().reject( 'aborted', {
				errors: [ {
					code: 'aborted',
					html: mw.message( 'api-error-aborted' ).parse()
				} ]
			} );
		}

		if ( !this.firstPoll ) {
			this.firstPoll = ( new Date() ).getTime();
		}
		params.checkstatus = true;
		params.filekey = this.filekey;
		this.request = this.api.post( params )
			.then( function ( response ) {
				if ( response.upload && response.upload.result === 'Poll' ) {
					// If concatenation takes longer than 10 minutes give up
					if ( ( ( new Date() ).getTime() - transport.firstPoll ) > 10 * 60 * 1000 ) {
						return $.Deferred().reject( 'server-error', { errors: [ {
							code: 'server-error',
							html: mw.message( 'apierror-unknownerror' ).parse()
						} ] } );
					} else {
						if ( response.upload.stage === undefined ) {
							mw.log.warn( 'Unable to check file\'s status' );
							return $.Deferred().reject( 'server-error', { errors: [ {
								code: 'server-error',
								html: mw.message( 'apierror-unknownerror' ).parse()
							} ] } );
						} else {
							// Statuses that can be returned:
							// * queued
							// * publish
							// * assembling
							transport.emit( 'update-stage', response.upload.stage );
							return transport.retryWithMethod( 'checkStatus' );
						}
					}
				}

				return response;
			}, function ( code, result ) {
				return $.Deferred().reject( code, result );
			} );

		return this.request;
	};
}( mediaWiki, jQuery, OO ) );