Debian Codegraph @

resources/src/mediawiki.api/upload.js

raw symbols SCIP
1 ( function () {
2 const
3 fieldsAllowed = {
4 stash: true,
5 filekey: true,
6 filename: true,
7 comment: true,
8 text: true,
9 watchlist: true,
10 ignorewarnings: true,
11 chunk: true,
12 offset: true,
13 filesize: true,
14 async: true
15 };
16
17 /**
18 * Given a non-empty object, return one of its keys.
19 *
20 * @private
21 * @param {Object} obj
22 * @return {string}
23 */
24 function getFirstKey( obj ) {
25 return obj[ Object.keys( obj )[ 0 ] ];
26 }
27
28 Object.assign( mw.Api.prototype, /** @lends mw.Api.prototype */ {
29 /**
30 * Upload a file to MediaWiki.
31 *
32 * The file will be uploaded using AJAX and FormData.
33 *
34 * @param {HTMLInputElement|File|Blob} file HTML input type=file element with a file already inside
35 * of it, or a File object.
36 * @param {Object} data Other upload options, see action=upload API docs for more
37 * @return {jQuery.Promise}
38 */
39 upload: function ( file, data ) {
40 if ( file && file.nodeType === Node.ELEMENT_NODE && file.files ) {
41 file = file.files[ 0 ];
42 }
43
44 if ( !file ) {
45 throw new Error( 'No file' );
46 }
47
48 // Blobs are allowed in formdata uploads, it turns out
49 if ( !( file instanceof window.File || file instanceof window.Blob ) ) {
50 throw new Error( 'Unsupported argument type passed to mw.Api.upload' );
51 }
52
53 return this.uploadWithFormData( file, data );
54 },
55
56 /**
57 * Uploads a file using the FormData API.
58 *
59 * @private
60 * @param {File} file
61 * @param {Object} data Other upload options, see action=upload API docs for more
62 * @return {jQuery.Promise}
63 */
64 uploadWithFormData: function ( file, data ) {
65 const deferred = $.Deferred();
66
67 for ( const key in data ) {
68 if ( !fieldsAllowed[ key ] ) {
69 delete data[ key ];
70 }
71 }
72
73 data = Object.assign( {}, this.defaults.parameters, { action: 'upload' }, data );
74 if ( !data.chunk ) {
75 data.file = file;
76 }
77
78 if ( !data.filename && !data.stash ) {
79 throw new Error( 'Filename not included in file data.' );
80 }
81
82 // Use this.postWithEditToken() or this.post()
83 const request = this[ this.needToken() ? 'postWithEditToken' : 'post' ]( data, {
84 // Use FormData (if we got here, we know that it's available)
85 contentType: 'multipart/form-data',
86 // No timeout (default from mw.Api is 30 seconds)
87 timeout: 0,
88 // Provide upload progress notifications
89 xhr: function () {
90 const xhr = $.ajaxSettings.xhr();
91 if ( xhr.upload ) {
92 // need to bind this event before we open the connection (see note at
93 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress)
94 xhr.upload.addEventListener( 'progress', ( ev ) => {
95 if ( ev.lengthComputable ) {
96 deferred.notify( ev.loaded / ev.total );
97 }
98 } );
99 }
100 return xhr;
101 }
102 } )
103 .done( ( result ) => {
104 deferred.notify( 1 );
105 if ( result.upload && result.upload.warnings ) {
106 deferred.reject( getFirstKey( result.upload.warnings ), result );
107 } else {
108 deferred.resolve( result );
109 }
110 } )
111 .fail( ( errorCode, result ) => {
112 deferred.notify( 1 );
113 deferred.reject( errorCode, result );
114 } );
115
116 return deferred.promise( { abort: request.abort } );
117 },
118
119 /**
120 * Upload a file in several chunks.
121 *
122 * @param {File} file
123 * @param {Object} data Other upload options, see action=upload API docs for more
124 * @param {number} [chunkSize] Size (in bytes) per chunk (default: 5 MiB)
125 * @param {number} [chunkRetries] Amount of times to retry a failed chunk (default: 1)
126 * @return {jQuery.Promise}
127 */
128 chunkedUpload: function ( file, data, chunkSize, chunkRetries ) {
129 const deferred = $.Deferred();
130
131 chunkSize = chunkSize === undefined ? 5 * 1024 * 1024 : chunkSize;
132 chunkRetries = chunkRetries === undefined ? 1 : chunkRetries;
133
134 if ( !data.filename ) {
135 throw new Error( 'Filename not included in file data.' );
136 }
137
138 let promise;
139 // Submit first chunk to get the filekey
140 let active = promise = this.uploadChunk( file, data, 0, chunkSize, '', chunkRetries )
141 .done( chunkSize >= file.size ? deferred.resolve : null )
142 .fail( deferred.reject )
143 .progress( deferred.notify );
144
145 // Now iteratively submit the rest of the chunks
146 for ( let start = chunkSize; start < file.size; start += chunkSize ) {
147 const end = Math.min( start + chunkSize, file.size );
148 const next = $.Deferred();
149
150 // We could simply chain one this.uploadChunk after another with
151 // .then(), but then we'd hit an `Uncaught RangeError: Maximum
152 // call stack size exceeded` at as low as 1024 calls in Firefox
153 // 47. This'll work around it, but comes with the drawback of
154 // having to properly relay the results to the returned promise.
155 // eslint-disable-next-line no-loop-func
156 promise.done( function ( s, e, n, result ) {
157 const filekey = result.upload.filekey;
158 active = this.uploadChunk( file, data, s, e, filekey, chunkRetries )
159 .done( e === file.size ? deferred.resolve : n.resolve )
160 .fail( deferred.reject )
161 .progress( deferred.notify );
162 // start, end & next must be bound to closure, or they'd have
163 // changed by the time the promises are resolved
164 }.bind( this, start, end, next ) );
165
166 promise = next;
167 }
168
169 return deferred.promise( { abort: active.abort } );
170 },
171
172 /**
173 * Uploads 1 chunk.
174 *
175 * @private
176 * @param {File} file
177 * @param {Object} data Other upload options, see action=upload API docs for more
178 * @param {number} start Chunk start position
179 * @param {number} end Chunk end position
180 * @param {string} [filekey] File key, for follow-up chunks
181 * @param {number} [retries] Amount of times to retry request
182 * @return {jQuery.Promise}
183 */
184 uploadChunk: function ( file, data, start, end, filekey, retries ) {
185 const api = this,
186 chunk = this.slice( file, start, end );
187
188 // When uploading in chunks, we're going to be issuing a lot more
189 // requests and there's always a chance of 1 getting dropped.
190 // In such case, it could be useful to try again: a network hickup
191 // doesn't necessarily have to result in upload failure...
192 retries = retries === undefined ? 1 : retries;
193
194 data.filesize = file.size;
195 data.chunk = chunk;
196 data.offset = start;
197
198 // filekey must only be added when uploading follow-up chunks; the
199 // first chunk should never have a filekey (it'll be generated)
200 if ( filekey && start !== 0 ) {
201 data.filekey = filekey;
202 }
203
204 const upload = this.uploadWithFormData( file, data );
205 return upload.then(
206 null,
207 ( code, result ) => {
208 // uploadWithFormData will reject uploads with warnings, but
209 // these warnings could be "harmless" or recovered from
210 // (e.g. exists-normalized, when it'll be renamed later)
211 // In the case of (only) a warning, we still want to
212 // continue the chunked upload until it completes: then
213 // reject it - at least it's been fully uploaded by then and
214 // failure handlers have a complete result object (including
215 // possibly more warnings, e.g. duplicate)
216 // This matches .upload, which also completes the upload.
217 if ( result.upload && result.upload.warnings ) {
218 if ( end === file.size ) {
219 // uploaded last chunk = reject with result data
220 return $.Deferred().reject( result.upload.warnings.code || 'unknown', result );
221 } else {
222 // still uploading chunks = resolve to keep going
223 return $.Deferred().resolve( result );
224 }
225 }
226
227 if ( retries === 0 ) {
228 return $.Deferred().reject( code, result );
229 }
230
231 // If the call flat out failed, we may want to try again...
232 const retry = api.uploadChunk.bind( api, file, data, start, end, filekey, retries - 1 );
233 return api.retry( code, result, retry );
234 },
235 // Since we're only uploading small parts of a file, we
236 // need to adjust the reported progress to reflect where
237 // we actually are in the combined upload
238 ( fraction ) => ( start + fraction * ( end - start ) ) / file.size
239 ).promise( { abort: upload.abort } );
240 },
241
242 /**
243 * Launch the upload anew if it failed because of network issues.
244 *
245 * @private
246 * @param {string} code Error code
247 * @param {Object} result API result
248 * @param {Function} callable
249 * @return {jQuery.Promise}
250 */
251 retry: function ( code, result, callable ) {
252 let uploadPromise;
253 const deferred = $.Deferred(),
254 // Wrap around the callable, so that once it completes, it'll
255 // resolve/reject the promise we'll return
256 retry = function () {
257 uploadPromise = callable();
258 uploadPromise.then( deferred.resolve, deferred.reject );
259 };
260
261 // Don't retry if the request failed because we aborted it (or if
262 // it's another kind of request failure)
263 if ( code !== 'http' || result.textStatus === 'abort' ) {
264 return deferred.reject( code, result );
265 }
266
267 const retryTimer = setTimeout( retry, 1000 );
268 return deferred.promise( { abort: function () {
269 // Clear the scheduled upload, or abort if already in flight
270 if ( retryTimer ) {
271 clearTimeout( retryTimer );
272 }
273 if ( uploadPromise.abort ) {
274 uploadPromise.abort();
275 }
276 } } );
277 },
278
279 /**
280 * Slice a chunk out of a File object.
281 *
282 * @private
283 * @param {File} file
284 * @param {number} start
285 * @param {number} stop
286 * @return {Blob}
287 */
288 slice: function ( file, start, stop ) {
289 if ( file.mozSlice ) {
290 // FF <= 12
291 return file.mozSlice( start, stop, file.type );
292 } else if ( file.webkitSlice ) {
293 // Chrome <= 20
294 return file.webkitSlice( start, stop, file.type );
295 } else {
296 // On really old browser versions (before slice was prefixed),
297 // slice() would take (start, length) instead of (start, end)
298 // We'll ignore that here...
299 return file.slice( start, stop, file.type );
300 }
301 },
302
303 /**
304 * This function will handle how uploads to stash (via uploadToStash or
305 * chunkedUploadToStash) are resolved/rejected.
306 *
307 * After a successful stash, it'll resolve with a callback which, when
308 * called, will finalize the upload in stash (with the given data, or
309 * with additional/conflicting data)
310 *
311 * A failed stash can still be recovered from as long as 'filekey' is
312 * present. In that case, it'll also resolve with the callback to
313 * finalize the upload (all warnings are then ignored.)
314 * Otherwise, it'll just reject as you'd expect, with code & result.
315 *
316 * @private
317 * @param {jQuery.Promise} uploadPromise
318 * @param {Object} data
319 * @return {jQuery.Promise<function(Object): jQuery.Promise>} Promise that resolves with a
320 * function that should be called to finish the upload.
321 */
322 finishUploadToStash: function ( uploadPromise, data ) {
323 const api = this;
324 let filekey;
325
326 function finishUpload( moreData ) {
327 return api.uploadFromStash( filekey, Object.assign( {}, data, moreData ) );
328 }
329
330 return uploadPromise.then(
331 ( result ) => {
332 filekey = result.upload.filekey;
333 return finishUpload;
334 },
335 ( errorCode, result ) => {
336 if ( result && result.upload && result.upload.result === 'Success' && result.upload.filekey ) {
337 // When a file is uploaded with `ignorewarnings` and there are warnings,
338 // the promise will be rejected (because of those warnings, e.g. 'duplicate')
339 // but the result is actually a success
340 // We don't really care about those warnings, as long as the upload got stashed...
341 // Turn this back into a successful promise and allow the upload to complete
342 filekey = result.upload.filekey;
343 return $.Deferred().resolve( finishUpload );
344 }
345 return $.Deferred().reject( errorCode, result );
346 }
347 );
348 },
349
350 /**
351 * Upload a file to the stash.
352 *
353 * This function will return a promise, which when resolved, will pass back a function
354 * to finish the stash upload. You can call that function with an argument containing
355 * more, or conflicting, data to pass to the server.
356 *
357 * @example
358 * // upload a file to the stash with a placeholder filename
359 * api.uploadToStash( file, { filename: 'testing.png' } ).done( function ( finish ) {
360 * // finish is now the function we can use to finalize the upload
361 * // pass it a new filename from user input to override the initial value
362 * finish( { filename: getFilenameFromUser() } ).done( function ( data ) {
363 * // the upload is complete, data holds the API response
364 * } );
365 * } );
366 *
367 * @param {File|HTMLInputElement} file
368 * @param {Object} [data]
369 * @return {jQuery.Promise<function(Object): jQuery.Promise>} Promise that resolves with a
370 * function that should be called to finish the upload.
371 */
372 uploadToStash: function ( file, data ) {
373 if ( !data.filename ) {
374 throw new Error( 'Filename not included in file data.' );
375 }
376
377 const promise = this.upload( file, { stash: true, filename: data.filename, ignorewarnings: data.ignorewarnings } );
378
379 return this.finishUploadToStash( promise, data );
380 },
381
382 /**
383 * Upload a file to the stash, in chunks.
384 *
385 * This function will return a promise, which when resolved, will pass back a function
386 * to finish the stash upload.
387 *
388 * @see mw.Api#uploadToStash
389 * @param {File|HTMLInputElement} file
390 * @param {Object} [data]
391 * @param {number} [chunkSize] Size (in bytes) per chunk (default: 5 MiB)
392 * @param {number} [chunkRetries] Amount of times to retry a failed chunk (default: 1)
393 * @return {jQuery.Promise<function(Object): jQuery.Promise>} Promise that resolves with a
394 * function that should be called to finish the upload.
395 */
396 chunkedUploadToStash: function ( file, data, chunkSize, chunkRetries ) {
397 if ( !data.filename ) {
398 throw new Error( 'Filename not included in file data.' );
399 }
400
401 const promise = this.chunkedUpload(
402 file,
403 { stash: true, filename: data.filename, ignorewarnings: data.ignorewarnings },
404 chunkSize,
405 chunkRetries
406 );
407
408 return this.finishUploadToStash( promise, data );
409 },
410
411 /**
412 * Finish an upload in the stash.
413 *
414 * @param {string} filekey
415 * @param {Object} data
416 * @return {jQuery.Promise}
417 */
418 uploadFromStash: function ( filekey, data ) {
419 data.filekey = filekey;
420 data.action = 'upload';
421 data.format = 'json';
422
423 if ( !data.filename ) {
424 throw new Error( 'Filename not included in file data.' );
425 }
426
427 return this.postWithEditToken( data ).then( ( result ) => {
428 if ( result.upload && result.upload.warnings ) {
429 return $.Deferred().reject( getFirstKey( result.upload.warnings ), result ).promise();
430 }
431 return result;
432 } );
433 },
434
435 /**
436 * @private
437 * @return {boolean}
438 */
439 needToken: function () {
440 return true;
441 }
442 } );
443
444 }() );