Merge "Speed up password-handling in the unit tests"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.Upload.BookletLayout.js
1 /*global moment*/
2 ( function ( $, mw, moment ) {
3
4 /**
5 * mw.Upload.BookletLayout encapsulates the process of uploading a file
6 * to MediaWiki using the {@link mw.Upload upload model}.
7 * The booklet emits events that can be used to get the stashed
8 * upload and the final file. It can be extended to accept
9 * additional fields from the user for specific scenarios like
10 * for Commons, or campaigns.
11 *
12 * ## Structure
13 *
14 * The {@link OO.ui.BookletLayout booklet layout} has three steps:
15 *
16 * - **Upload**: Has a {@link OO.ui.SelectFileWidget field} to get the file object.
17 *
18 * - **Information**: Has a {@link OO.ui.FormLayout form} to collect metadata. This can be
19 * extended.
20 *
21 * - **Insert**: Has details on how to use the file that was uploaded.
22 *
23 * Each step has a form associated with it defined in
24 * {@link #renderUploadForm renderUploadForm},
25 * {@link #renderInfoForm renderInfoForm}, and
26 * {@link #renderInsertForm renderInfoForm}. The
27 * {@link #getFile getFile},
28 * {@link #getFilename getFilename}, and
29 * {@link #getText getText} methods are used to get
30 * the information filled in these forms, required to call
31 * {@link mw.Upload mw.Upload}.
32 *
33 * ## Usage
34 *
35 * See the {@link mw.Upload.Dialog upload dialog}.
36 *
37 * The {@link #event-fileUploaded fileUploaded},
38 * and {@link #event-fileSaved fileSaved} events can
39 * be used to get details of the upload.
40 *
41 * ## Extending
42 *
43 * To extend using {@link mw.Upload mw.Upload}, override
44 * {@link #renderInfoForm renderInfoForm} to render
45 * the form required for the specific use-case. Update the
46 * {@link #getFilename getFilename}, and
47 * {@link #getText getText} methods to return data
48 * from your newly created form. If you added new fields you'll also have
49 * to update the {@link #clear} method.
50 *
51 * If you plan to use a different upload model, apart from what is mentioned
52 * above, you'll also have to override the
53 * {@link #createUpload createUpload} method to
54 * return the new model. The {@link #saveFile saveFile}, and
55 * the {@link #uploadFile uploadFile} methods need to be
56 * overridden to use the new model and data returned from the forms.
57 *
58 * @class
59 * @extends OO.ui.BookletLayout
60 *
61 * @constructor
62 * @param {Object} config Configuration options
63 * @cfg {jQuery} [$overlay] Overlay to use for widgets in the booklet
64 * @cfg {string} [filekey] Sets the stashed file to finish uploading. Overrides most of the file selection process, and fetches a thumbnail from the server.
65 */
66 mw.Upload.BookletLayout = function ( config ) {
67 // Parent constructor
68 mw.Upload.BookletLayout.parent.call( this, config );
69
70 this.$overlay = config.$overlay;
71
72 this.filekey = config.filekey;
73
74 this.renderUploadForm();
75 this.renderInfoForm();
76 this.renderInsertForm();
77
78 this.addPages( [
79 new OO.ui.PageLayout( 'upload', {
80 scrollable: true,
81 padded: true,
82 content: [ this.uploadForm ]
83 } ),
84 new OO.ui.PageLayout( 'info', {
85 scrollable: true,
86 padded: true,
87 content: [ this.infoForm ]
88 } ),
89 new OO.ui.PageLayout( 'insert', {
90 scrollable: true,
91 padded: true,
92 content: [ this.insertForm ]
93 } )
94 ] );
95 };
96
97 /* Setup */
98
99 OO.inheritClass( mw.Upload.BookletLayout, OO.ui.BookletLayout );
100
101 /* Events */
102
103 /**
104 * Progress events for the uploaded file
105 *
106 * @event fileUploadProgress
107 * @param {number} progress In percentage
108 * @param {Object} duration Duration object from `moment.duration()`
109 */
110
111 /**
112 * The file has finished uploading
113 *
114 * @event fileUploaded
115 */
116
117 /**
118 * The file has been saved to the database
119 *
120 * @event fileSaved
121 * @param {Object} imageInfo See mw.Upload#getImageInfo
122 */
123
124 /**
125 * The upload form has changed
126 *
127 * @event uploadValid
128 * @param {boolean} isValid The form is valid
129 */
130
131 /**
132 * The info form has changed
133 *
134 * @event infoValid
135 * @param {boolean} isValid The form is valid
136 */
137
138 /* Properties */
139
140 /**
141 * @property {OO.ui.FormLayout} uploadForm
142 * The form rendered in the first step to get the file object.
143 * Rendered in {@link #renderUploadForm renderUploadForm}.
144 */
145
146 /**
147 * @property {OO.ui.FormLayout} infoForm
148 * The form rendered in the second step to get metadata.
149 * Rendered in {@link #renderInfoForm renderInfoForm}
150 */
151
152 /**
153 * @property {OO.ui.FormLayout} insertForm
154 * The form rendered in the third step to show usage
155 * Rendered in {@link #renderInsertForm renderInsertForm}
156 */
157
158 /* Methods */
159
160 /**
161 * Initialize for a new upload
162 *
163 * @return {jQuery.Promise} Promise resolved when everything is initialized
164 */
165 mw.Upload.BookletLayout.prototype.initialize = function () {
166 var booklet = this;
167
168 this.clear();
169 this.upload = this.createUpload();
170
171 this.setPage( 'upload' );
172
173 if ( this.filekey ) {
174 this.setFilekey( this.filekey );
175 }
176
177 return this.upload.getApi().then(
178 function ( api ) {
179 return $.when(
180 booklet.upload.loadConfig(),
181 // If the user can't upload anything, don't give them the option to.
182 api.getUserInfo().then( function ( userInfo ) {
183 if ( userInfo.rights.indexOf( 'upload' ) === -1 ) {
184 // TODO Use a better error message when not all logged-in users can upload
185 booklet.getPage( 'upload' ).$element.msg( 'api-error-mustbeloggedin' );
186 }
187 return $.Deferred().resolve();
188 } )
189 ).then(
190 null,
191 // Always resolve, never reject
192 function () { return $.Deferred().resolve(); }
193 );
194 },
195 function ( errorMsg ) {
196 booklet.getPage( 'upload' ).$element.msg( errorMsg );
197 return $.Deferred().resolve();
198 }
199 );
200 };
201
202 /**
203 * Create a new upload model
204 *
205 * @protected
206 * @return {mw.Upload} Upload model
207 */
208 mw.Upload.BookletLayout.prototype.createUpload = function () {
209 return new mw.Upload();
210 };
211
212 /* Uploading */
213
214 /**
215 * Uploads the file that was added in the upload form. Uses
216 * {@link #getFile getFile} to get the HTML5
217 * file object.
218 *
219 * @protected
220 * @fires fileUploadProgress
221 * @fires fileUploaded
222 * @return {jQuery.Promise}
223 */
224 mw.Upload.BookletLayout.prototype.uploadFile = function () {
225 var deferred = $.Deferred(),
226 startTime = new Date(),
227 layout = this,
228 file = this.getFile();
229
230 this.setPage( 'info' );
231
232 if ( this.filekey ) {
233 if ( file === null ) {
234 // Someone gonna get-a hurt real bad
235 throw new Error( 'filekey not passed into file select widget, which is impossible. Quitting while we\'re behind.' );
236 }
237
238 // Stashed file already uploaded.
239 deferred.resolve();
240 this.uploadPromise = deferred;
241 this.emit( 'fileUploaded' );
242 return deferred;
243 }
244
245 this.setFilename( file.name );
246
247 this.upload.setFile( file );
248 // The original file name might contain invalid characters, so use our sanitized one
249 this.upload.setFilename( this.getFilename() );
250
251 this.uploadPromise = this.upload.uploadToStash();
252 this.uploadPromise.then( function () {
253 deferred.resolve();
254 layout.emit( 'fileUploaded' );
255 }, function () {
256 // These errors will be thrown while the user is on the info page.
257 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
258 // really be an error...
259 var errorMessage = layout.getErrorMessageForStateDetails();
260 deferred.reject( errorMessage );
261 }, function ( progress ) {
262 var elapsedTime = new Date() - startTime,
263 estimatedTotalTime = ( 1 / progress ) * elapsedTime,
264 estimatedRemainingTime = moment.duration( estimatedTotalTime - elapsedTime );
265 layout.emit( 'fileUploadProgress', progress, estimatedRemainingTime );
266 } );
267
268 // If there is an error in uploading, come back to the upload page
269 deferred.fail( function () {
270 layout.setPage( 'upload' );
271 } );
272
273 return deferred;
274 };
275
276 /**
277 * Saves the stash finalizes upload. Uses
278 * {@link #getFilename getFilename}, and
279 * {@link #getText getText} to get details from
280 * the form.
281 *
282 * @protected
283 * @fires fileSaved
284 * @return {jQuery.Promise} Rejects the promise with an
285 * {@link OO.ui.Error error}, or resolves if the upload was successful.
286 */
287 mw.Upload.BookletLayout.prototype.saveFile = function () {
288 var layout = this,
289 deferred = $.Deferred();
290
291 this.upload.setFilename( this.getFilename() );
292 this.upload.setText( this.getText() );
293
294 this.uploadPromise.then( function () {
295 layout.upload.finishStashUpload().then( function () {
296 var name;
297
298 // Normalize page name and localise the 'File:' prefix
299 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
300 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
301 layout.setPage( 'insert' );
302
303 deferred.resolve();
304 layout.emit( 'fileSaved', layout.upload.getImageInfo() );
305 }, function () {
306 var errorMessage = layout.getErrorMessageForStateDetails();
307 deferred.reject( errorMessage );
308 } );
309 } );
310
311 return deferred.promise();
312 };
313
314 /**
315 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
316 * state and state details.
317 *
318 * @protected
319 * @return {OO.ui.Error} Error to display for given state and details.
320 */
321 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
322 var message,
323 state = this.upload.getState(),
324 stateDetails = this.upload.getStateDetails(),
325 error = stateDetails.error,
326 warnings = stateDetails.upload && stateDetails.upload.warnings;
327
328 if ( state === mw.Upload.State.ERROR ) {
329 if ( !error ) {
330 // If there's an 'exception' key, this might be a timeout, or other connection problem
331 return new OO.ui.Error(
332 $( '<p>' ).msg( 'api-error-unknownerror', JSON.stringify( stateDetails ) ),
333 { recoverable: false }
334 );
335 }
336
337 // HACK We should either have a hook here to allow TitleBlacklist to handle this, or just have
338 // TitleBlacklist produce sane error messages that can be displayed without arcane knowledge
339 if ( error.info === 'TitleBlacklist prevents this title from being created' ) {
340 // HACK Apparently the only reliable way to determine whether TitleBlacklist was involved
341 return new OO.ui.Error(
342 // HACK TitleBlacklist doesn't have a sensible message, this one is from UploadWizard
343 $( '<p>' ).msg( 'api-error-blacklisted' ),
344 { recoverable: false }
345 );
346 }
347
348 if ( error.code === 'protectedpage' ) {
349 message = mw.message( 'protectedpagetext' );
350 } else {
351 message = mw.message( 'api-error-' + error.code );
352 if ( !message.exists() ) {
353 message = mw.message( 'api-error-unknownerror', JSON.stringify( stateDetails ) );
354 }
355 }
356 return new OO.ui.Error(
357 $( '<p>' ).append( message.parseDom() ),
358 { recoverable: false }
359 );
360 }
361
362 if ( state === mw.Upload.State.WARNING ) {
363 // We could get more than one of these errors, these are in order
364 // of importance. For example fixing the thumbnail like file name
365 // won't help the fact that the file already exists.
366 if ( warnings.stashfailed !== undefined ) {
367 return new OO.ui.Error(
368 $( '<p>' ).msg( 'api-error-stashfailed' ),
369 { recoverable: false }
370 );
371 } else if ( warnings.exists !== undefined ) {
372 return new OO.ui.Error(
373 $( '<p>' ).msg( 'fileexists', 'File:' + warnings.exists ),
374 { recoverable: false }
375 );
376 } else if ( warnings[ 'exists-normalized' ] !== undefined ) {
377 return new OO.ui.Error(
378 $( '<p>' ).msg( 'fileexists', 'File:' + warnings[ 'exists-normalized' ] ),
379 { recoverable: false }
380 );
381 } else if ( warnings[ 'page-exists' ] !== undefined ) {
382 return new OO.ui.Error(
383 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings[ 'page-exists' ] ),
384 { recoverable: false }
385 );
386 } else if ( warnings.duplicate !== undefined ) {
387 return new OO.ui.Error(
388 $( '<p>' ).msg( 'api-error-duplicate', warnings.duplicate.length ),
389 { recoverable: false }
390 );
391 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
392 return new OO.ui.Error(
393 $( '<p>' ).msg( 'filename-thumb-name' ),
394 { recoverable: false }
395 );
396 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
397 return new OO.ui.Error(
398 $( '<p>' ).msg( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ),
399 { recoverable: false }
400 );
401 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
402 return new OO.ui.Error(
403 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
404 { recoverable: false }
405 );
406 } else if ( warnings[ 'was-deleted' ] !== undefined ) {
407 return new OO.ui.Error(
408 $( '<p>' ).msg( 'api-error-was-deleted' ),
409 { recoverable: false }
410 );
411 } else if ( warnings.badfilename !== undefined ) {
412 // Change the name if the current name isn't acceptable
413 // TODO This might not really be the best place to do this
414 this.setFilename( warnings.badfilename );
415 return new OO.ui.Error(
416 $( '<p>' ).msg( 'badfilename', warnings.badfilename )
417 );
418 } else {
419 return new OO.ui.Error(
420 // Let's get all the help we can if we can't pin point the error
421 $( '<p>' ).msg( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ),
422 { recoverable: false }
423 );
424 }
425 }
426 };
427
428 /* Form renderers */
429
430 /**
431 * Renders and returns the upload form and sets the
432 * {@link #uploadForm uploadForm} property.
433 *
434 * @protected
435 * @fires selectFile
436 * @return {OO.ui.FormLayout}
437 */
438 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
439 var fieldset,
440 layout = this;
441
442 this.selectFileWidget = this.getFileWidget();
443 fieldset = new OO.ui.FieldsetLayout();
444 fieldset.addItems( [ this.selectFileWidget ] );
445 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
446
447 // Validation (if the SFW is for a stashed file, this never fires)
448 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
449
450 this.selectFileWidget.on( 'change', function () {
451 layout.updateFilePreview();
452 } );
453
454 return this.uploadForm;
455 };
456
457 /**
458 * Gets the widget for displaying or inputting the file to upload.
459 *
460 * @return {OO.ui.SelectFileWidget|mw.widgets.StashedFileWidget}
461 */
462 mw.Upload.BookletLayout.prototype.getFileWidget = function () {
463 if ( this.filekey ) {
464 return new mw.widgets.StashedFileWidget( {
465 filekey: this.filekey
466 } );
467 }
468
469 return new OO.ui.SelectFileWidget( {
470 showDropTarget: true
471 } );
472 };
473
474 /**
475 * Updates the file preview on the info form when a file is added.
476 *
477 * @protected
478 */
479 mw.Upload.BookletLayout.prototype.updateFilePreview = function () {
480 this.selectFileWidget.loadAndGetImageUrl().done( function ( url ) {
481 this.filePreview.$element.find( 'p' ).remove();
482 this.filePreview.$element.css( 'background-image', 'url(' + url + ')' );
483 this.infoForm.$element.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
484 }.bind( this ) ).fail( function () {
485 this.filePreview.$element.find( 'p' ).remove();
486 if ( this.selectFileWidget.getValue() ) {
487 this.filePreview.$element.append(
488 $( '<p>' ).text( this.selectFileWidget.getValue().name )
489 );
490 }
491 this.filePreview.$element.css( 'background-image', '' );
492 this.infoForm.$element.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
493 }.bind( this ) );
494 };
495
496 /**
497 * Handle change events to the upload form
498 *
499 * @protected
500 * @fires uploadValid
501 */
502 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
503 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
504 };
505
506 /**
507 * Renders and returns the information form for collecting
508 * metadata and sets the {@link #infoForm infoForm}
509 * property.
510 *
511 * @protected
512 * @return {OO.ui.FormLayout}
513 */
514 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
515 var fieldset;
516
517 this.filePreview = new OO.ui.Widget( {
518 classes: [ 'mw-upload-bookletLayout-filePreview' ]
519 } );
520 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
521 progress: 0
522 } );
523 this.filePreview.$element.append( this.progressBarWidget.$element );
524
525 this.filenameWidget = new OO.ui.TextInputWidget( {
526 indicator: 'required',
527 required: true,
528 validate: /.+/
529 } );
530 this.descriptionWidget = new OO.ui.TextInputWidget( {
531 indicator: 'required',
532 required: true,
533 validate: /\S+/,
534 multiline: true,
535 autosize: true
536 } );
537
538 fieldset = new OO.ui.FieldsetLayout( {
539 label: mw.msg( 'upload-form-label-infoform-title' )
540 } );
541 fieldset.addItems( [
542 new OO.ui.FieldLayout( this.filenameWidget, {
543 label: mw.msg( 'upload-form-label-infoform-name' ),
544 align: 'top',
545 help: mw.msg( 'upload-form-label-infoform-name-tooltip' )
546 } ),
547 new OO.ui.FieldLayout( this.descriptionWidget, {
548 label: mw.msg( 'upload-form-label-infoform-description' ),
549 align: 'top',
550 help: mw.msg( 'upload-form-label-infoform-description-tooltip' )
551 } )
552 ] );
553 this.infoForm = new OO.ui.FormLayout( {
554 classes: [ 'mw-upload-bookletLayout-infoForm' ],
555 items: [ this.filePreview, fieldset ]
556 } );
557
558 this.on( 'fileUploadProgress', function ( progress ) {
559 this.progressBarWidget.setProgress( progress * 100 );
560 }.bind( this ) );
561
562 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
563 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
564
565 return this.infoForm;
566 };
567
568 /**
569 * Handle change events to the info form
570 *
571 * @protected
572 * @fires infoValid
573 */
574 mw.Upload.BookletLayout.prototype.onInfoFormChange = function () {
575 var layout = this;
576 $.when(
577 this.filenameWidget.getValidity(),
578 this.descriptionWidget.getValidity()
579 ).done( function () {
580 layout.emit( 'infoValid', true );
581 } ).fail( function () {
582 layout.emit( 'infoValid', false );
583 } );
584 };
585
586 /**
587 * Renders and returns the insert form to show file usage and
588 * sets the {@link #insertForm insertForm} property.
589 *
590 * @protected
591 * @return {OO.ui.FormLayout}
592 */
593 mw.Upload.BookletLayout.prototype.renderInsertForm = function () {
594 var fieldset;
595
596 this.filenameUsageWidget = new OO.ui.TextInputWidget();
597 fieldset = new OO.ui.FieldsetLayout( {
598 label: mw.msg( 'upload-form-label-usage-title' )
599 } );
600 fieldset.addItems( [
601 new OO.ui.FieldLayout( this.filenameUsageWidget, {
602 label: mw.msg( 'upload-form-label-usage-filename' ),
603 align: 'top'
604 } )
605 ] );
606 this.insertForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
607
608 return this.insertForm;
609 };
610
611 /* Getters */
612
613 /**
614 * Gets the file object from the
615 * {@link #uploadForm upload form}.
616 *
617 * @protected
618 * @return {File|null}
619 */
620 mw.Upload.BookletLayout.prototype.getFile = function () {
621 return this.selectFileWidget.getValue();
622 };
623
624 /**
625 * Gets the file name from the
626 * {@link #infoForm information form}.
627 *
628 * @protected
629 * @return {string}
630 */
631 mw.Upload.BookletLayout.prototype.getFilename = function () {
632 var filename = this.filenameWidget.getValue();
633 if ( this.filenameExtension ) {
634 filename += '.' + this.filenameExtension;
635 }
636 return filename;
637 };
638
639 /**
640 * Prefills the {@link #infoForm information form} with the given filename.
641 *
642 * @protected
643 * @param {string} filename
644 */
645 mw.Upload.BookletLayout.prototype.setFilename = function ( filename ) {
646 var title = mw.Title.newFromFileName( filename );
647
648 if ( title ) {
649 this.filenameWidget.setValue( title.getNameText() );
650 this.filenameExtension = mw.Title.normalizeExtension( title.getExtension() );
651 } else {
652 // Seems to happen for files with no extension, which should fail some checks anyway...
653 this.filenameWidget.setValue( filename );
654 this.filenameExtension = null;
655 }
656 };
657
658 /**
659 * Gets the page text from the
660 * {@link #infoForm information form}.
661 *
662 * @protected
663 * @return {string}
664 */
665 mw.Upload.BookletLayout.prototype.getText = function () {
666 return this.descriptionWidget.getValue();
667 };
668
669 /* Setters */
670
671 /**
672 * Sets the file object
673 *
674 * @protected
675 * @param {File|null} file File to select
676 */
677 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
678 this.selectFileWidget.setValue( file );
679 };
680
681 /**
682 * Sets the filekey of a file already stashed on the server
683 * as the target of this upload operation.
684 *
685 * @protected
686 * @param {string} filekey
687 */
688 mw.Upload.BookletLayout.prototype.setFilekey = function ( filekey ) {
689 this.upload.setFilekey( this.filekey );
690 this.selectFileWidget.setValue( filekey );
691
692 this.onUploadFormChange();
693 };
694
695 /**
696 * Clear the values of all fields
697 *
698 * @protected
699 */
700 mw.Upload.BookletLayout.prototype.clear = function () {
701 this.selectFileWidget.setValue( null );
702 this.progressBarWidget.setProgress( 0 );
703 this.filenameWidget.setValue( null ).setValidityFlag( true );
704 this.descriptionWidget.setValue( null ).setValidityFlag( true );
705 this.filenameUsageWidget.setValue( null );
706 };
707
708 }( jQuery, mediaWiki, moment ) );