2 ( function ( $, mw
, moment
) {
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.
14 * The {@link OO.ui.BookletLayout booklet layout} has three steps:
16 * - **Upload**: Has a {@link OO.ui.SelectFileWidget field} to get the file object.
18 * - **Information**: Has a {@link OO.ui.FormLayout form} to collect metadata. This can be
21 * - **Insert**: Has details on how to use the file that was uploaded.
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}.
35 * See the {@link mw.Upload.Dialog upload dialog}.
37 * The {@link #event-fileUploaded fileUploaded},
38 * and {@link #event-fileSaved fileSaved} events can
39 * be used to get details of the upload.
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.
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.
59 * @extends OO.ui.BookletLayout
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.
66 mw
.Upload
.BookletLayout = function ( config
) {
68 mw
.Upload
.BookletLayout
.parent
.call( this, config
);
70 this.$overlay
= config
.$overlay
;
72 this.filekey
= config
.filekey
;
74 this.renderUploadForm();
75 this.renderInfoForm();
76 this.renderInsertForm();
79 new OO
.ui
.PageLayout( 'upload', {
82 content
: [ this.uploadForm
]
84 new OO
.ui
.PageLayout( 'info', {
87 content
: [ this.infoForm
]
89 new OO
.ui
.PageLayout( 'insert', {
92 content
: [ this.insertForm
]
99 OO
.inheritClass( mw
.Upload
.BookletLayout
, OO
.ui
.BookletLayout
);
104 * Progress events for the uploaded file
106 * @event fileUploadProgress
107 * @param {number} progress In percentage
108 * @param {Object} duration Duration object from `moment.duration()`
112 * The file has finished uploading
114 * @event fileUploaded
118 * The file has been saved to the database
121 * @param {Object} imageInfo See mw.Upload#getImageInfo
125 * The upload form has changed
128 * @param {boolean} isValid The form is valid
132 * The info form has changed
135 * @param {boolean} isValid The form is valid
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}.
147 * @property {OO.ui.FormLayout} infoForm
148 * The form rendered in the second step to get metadata.
149 * Rendered in {@link #renderInfoForm renderInfoForm}
153 * @property {OO.ui.FormLayout} insertForm
154 * The form rendered in the third step to show usage
155 * Rendered in {@link #renderInsertForm renderInsertForm}
161 * Initialize for a new upload
163 * @return {jQuery.Promise} Promise resolved when everything is initialized
165 mw
.Upload
.BookletLayout
.prototype.initialize = function () {
169 this.upload
= this.createUpload();
171 this.setPage( 'upload' );
173 if ( this.filekey
) {
174 this.setFilekey( this.filekey
);
177 return this.upload
.getApi().then(
180 booklet
.upload
.loadConfig().then(
182 function ( errorMsg
) {
183 booklet
.getPage( 'upload' ).$element
.msg( errorMsg
);
184 return $.Deferred().resolve();
187 // If the user can't upload anything, don't give them the option to.
188 api
.getUserInfo().then( function ( userInfo
) {
189 if ( userInfo
.rights
.indexOf( 'upload' ) === -1 ) {
190 // TODO Use a better error message when not all logged-in users can upload
191 booklet
.getPage( 'upload' ).$element
.msg( 'api-error-mustbeloggedin' );
193 return $.Deferred().resolve();
197 // Always resolve, never reject
198 function () { return $.Deferred().resolve(); }
201 function ( errorMsg
) {
202 booklet
.getPage( 'upload' ).$element
.msg( errorMsg
);
203 return $.Deferred().resolve();
209 * Create a new upload model
212 * @return {mw.Upload} Upload model
214 mw
.Upload
.BookletLayout
.prototype.createUpload = function () {
215 return new mw
.Upload();
221 * Uploads the file that was added in the upload form. Uses
222 * {@link #getFile getFile} to get the HTML5
226 * @fires fileUploadProgress
227 * @fires fileUploaded
228 * @return {jQuery.Promise}
230 mw
.Upload
.BookletLayout
.prototype.uploadFile = function () {
231 var deferred
= $.Deferred(),
232 startTime
= new Date(),
234 file
= this.getFile();
236 this.setPage( 'info' );
238 if ( this.filekey
) {
239 if ( file
=== null ) {
240 // Someone gonna get-a hurt real bad
241 throw new Error( 'filekey not passed into file select widget, which is impossible. Quitting while we\'re behind.' );
244 // Stashed file already uploaded.
246 this.uploadPromise
= deferred
;
247 this.emit( 'fileUploaded' );
251 this.setFilename( file
.name
);
253 this.upload
.setFile( file
);
254 // The original file name might contain invalid characters, so use our sanitized one
255 this.upload
.setFilename( this.getFilename() );
257 this.uploadPromise
= this.upload
.uploadToStash();
258 this.uploadPromise
.then( function () {
260 layout
.emit( 'fileUploaded' );
262 // These errors will be thrown while the user is on the info page.
263 layout
.getErrorMessageForStateDetails().then( function ( errorMessage
) {
264 deferred
.reject( errorMessage
);
266 }, function ( progress
) {
267 var elapsedTime
= new Date() - startTime
,
268 estimatedTotalTime
= ( 1 / progress
) * elapsedTime
,
269 estimatedRemainingTime
= moment
.duration( estimatedTotalTime
- elapsedTime
);
270 layout
.emit( 'fileUploadProgress', progress
, estimatedRemainingTime
);
273 // If there is an error in uploading, come back to the upload page
274 deferred
.fail( function () {
275 layout
.setPage( 'upload' );
282 * Saves the stash finalizes upload. Uses
283 * {@link #getFilename getFilename}, and
284 * {@link #getText getText} to get details from
289 * @return {jQuery.Promise} Rejects the promise with an
290 * {@link OO.ui.Error error}, or resolves if the upload was successful.
292 mw
.Upload
.BookletLayout
.prototype.saveFile = function () {
294 deferred
= $.Deferred();
296 this.upload
.setFilename( this.getFilename() );
297 this.upload
.setText( this.getText() );
299 this.uploadPromise
.then( function () {
300 layout
.upload
.finishStashUpload().then( function () {
303 // Normalize page name and localise the 'File:' prefix
304 name
= new mw
.Title( 'File:' + layout
.upload
.getFilename() ).toString();
305 layout
.filenameUsageWidget
.setValue( '[[' + name
+ ']]' );
306 layout
.setPage( 'insert' );
309 layout
.emit( 'fileSaved', layout
.upload
.getImageInfo() );
311 layout
.getErrorMessageForStateDetails().then( function ( errorMessage
) {
312 deferred
.reject( errorMessage
);
317 return deferred
.promise();
321 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
322 * state and state details.
325 * @return {jQuery.Promise} A Promise that will be resolved with an OO.ui.Error.
327 mw
.Upload
.BookletLayout
.prototype.getErrorMessageForStateDetails = function () {
329 state
= this.upload
.getState(),
330 stateDetails
= this.upload
.getStateDetails(),
331 error
= stateDetails
.error
,
332 warnings
= stateDetails
.upload
&& stateDetails
.upload
.warnings
;
334 if ( state
=== mw
.Upload
.State
.ERROR
) {
336 // If there's an 'exception' key, this might be a timeout, or other connection problem
337 return $.Deferred().resolve( new OO
.ui
.Error(
338 $( '<p>' ).msg( 'api-error-unknownerror', JSON
.stringify( stateDetails
) ),
339 { recoverable
: false }
343 // Errors in this format are produced by TitleBlacklist and AbuseFilter. Perhaps other
344 // extensions will follow this format in the future.
345 if ( error
.message
) {
346 return this.upload
.getApi()
347 .then( function ( api
) {
348 return api
.loadMessagesIfMissing( [ error
.message
.key
] ).then( function () {
349 if ( !mw
.message( error
.message
.key
).exists() ) {
350 return $.Deferred().reject();
352 return new OO
.ui
.Error(
353 $( '<p>' ).msg( error
.message
.key
, error
.message
.params
|| [] ),
354 { recoverable
: false }
358 .then( null, function () {
359 // We failed when loading the error message, or it doesn't actually exist, fall back
360 return $.Deferred().resolve( new OO
.ui
.Error(
361 $( '<p>' ).msg( 'api-error-unknownerror', JSON
.stringify( stateDetails
) ),
362 { recoverable
: false }
367 if ( error
.code
=== 'protectedpage' ) {
368 message
= mw
.message( 'protectedpagetext' );
370 message
= mw
.message( 'api-error-' + error
.code
);
371 if ( !message
.exists() ) {
372 message
= mw
.message( 'api-error-unknownerror', JSON
.stringify( stateDetails
) );
375 return $.Deferred().resolve( new OO
.ui
.Error(
376 $( '<p>' ).append( message
.parseDom() ),
377 { recoverable
: false }
381 if ( state
=== mw
.Upload
.State
.WARNING
) {
382 // We could get more than one of these errors, these are in order
383 // of importance. For example fixing the thumbnail like file name
384 // won't help the fact that the file already exists.
385 if ( warnings
.stashfailed
!== undefined ) {
386 return $.Deferred().resolve( new OO
.ui
.Error(
387 $( '<p>' ).msg( 'api-error-stashfailed' ),
388 { recoverable
: false }
390 } else if ( warnings
.exists
!== undefined ) {
391 return $.Deferred().resolve( new OO
.ui
.Error(
392 $( '<p>' ).msg( 'fileexists', 'File:' + warnings
.exists
),
393 { recoverable
: false }
395 } else if ( warnings
[ 'exists-normalized' ] !== undefined ) {
396 return $.Deferred().resolve( new OO
.ui
.Error(
397 $( '<p>' ).msg( 'fileexists', 'File:' + warnings
[ 'exists-normalized' ] ),
398 { recoverable
: false }
400 } else if ( warnings
[ 'page-exists' ] !== undefined ) {
401 return $.Deferred().resolve( new OO
.ui
.Error(
402 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings
[ 'page-exists' ] ),
403 { recoverable
: false }
405 } else if ( warnings
.duplicate
!== undefined ) {
406 return $.Deferred().resolve( new OO
.ui
.Error(
407 $( '<p>' ).msg( 'api-error-duplicate', warnings
.duplicate
.length
),
408 { recoverable
: false }
410 } else if ( warnings
[ 'thumb-name' ] !== undefined ) {
411 return $.Deferred().resolve( new OO
.ui
.Error(
412 $( '<p>' ).msg( 'filename-thumb-name' ),
413 { recoverable
: false }
415 } else if ( warnings
[ 'bad-prefix' ] !== undefined ) {
416 return $.Deferred().resolve( new OO
.ui
.Error(
417 $( '<p>' ).msg( 'filename-bad-prefix', warnings
[ 'bad-prefix' ] ),
418 { recoverable
: false }
420 } else if ( warnings
[ 'duplicate-archive' ] !== undefined ) {
421 return $.Deferred().resolve( new OO
.ui
.Error(
422 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
423 { recoverable
: false }
425 } else if ( warnings
[ 'was-deleted' ] !== undefined ) {
426 return $.Deferred().resolve( new OO
.ui
.Error(
427 $( '<p>' ).msg( 'api-error-was-deleted' ),
428 { recoverable
: false }
430 } else if ( warnings
.badfilename
!== undefined ) {
431 // Change the name if the current name isn't acceptable
432 // TODO This might not really be the best place to do this
433 this.setFilename( warnings
.badfilename
);
434 return $.Deferred().resolve( new OO
.ui
.Error(
435 $( '<p>' ).msg( 'badfilename', warnings
.badfilename
)
438 return $.Deferred().resolve( new OO
.ui
.Error(
439 // Let's get all the help we can if we can't pin point the error
440 $( '<p>' ).msg( 'api-error-unknown-warning', JSON
.stringify( stateDetails
) ),
441 { recoverable
: false }
450 * Renders and returns the upload form and sets the
451 * {@link #uploadForm uploadForm} property.
455 * @return {OO.ui.FormLayout}
457 mw
.Upload
.BookletLayout
.prototype.renderUploadForm = function () {
461 this.selectFileWidget
= this.getFileWidget();
462 fieldset
= new OO
.ui
.FieldsetLayout();
463 fieldset
.addItems( [ this.selectFileWidget
] );
464 this.uploadForm
= new OO
.ui
.FormLayout( { items
: [ fieldset
] } );
466 // Validation (if the SFW is for a stashed file, this never fires)
467 this.selectFileWidget
.on( 'change', this.onUploadFormChange
.bind( this ) );
469 this.selectFileWidget
.on( 'change', function () {
470 layout
.updateFilePreview();
473 return this.uploadForm
;
477 * Gets the widget for displaying or inputting the file to upload.
479 * @return {OO.ui.SelectFileWidget|mw.widgets.StashedFileWidget}
481 mw
.Upload
.BookletLayout
.prototype.getFileWidget = function () {
482 if ( this.filekey
) {
483 return new mw
.widgets
.StashedFileWidget( {
484 filekey
: this.filekey
488 return new OO
.ui
.SelectFileWidget( {
494 * Updates the file preview on the info form when a file is added.
498 mw
.Upload
.BookletLayout
.prototype.updateFilePreview = function () {
499 this.selectFileWidget
.loadAndGetImageUrl().done( function ( url
) {
500 this.filePreview
.$element
.find( 'p' ).remove();
501 this.filePreview
.$element
.css( 'background-image', 'url(' + url
+ ')' );
502 this.infoForm
.$element
.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
503 }.bind( this ) ).fail( function () {
504 this.filePreview
.$element
.find( 'p' ).remove();
505 if ( this.selectFileWidget
.getValue() ) {
506 this.filePreview
.$element
.append(
507 $( '<p>' ).text( this.selectFileWidget
.getValue().name
)
510 this.filePreview
.$element
.css( 'background-image', '' );
511 this.infoForm
.$element
.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
516 * Handle change events to the upload form
521 mw
.Upload
.BookletLayout
.prototype.onUploadFormChange = function () {
522 this.emit( 'uploadValid', !!this.selectFileWidget
.getValue() );
526 * Renders and returns the information form for collecting
527 * metadata and sets the {@link #infoForm infoForm}
531 * @return {OO.ui.FormLayout}
533 mw
.Upload
.BookletLayout
.prototype.renderInfoForm = function () {
536 this.filePreview
= new OO
.ui
.Widget( {
537 classes
: [ 'mw-upload-bookletLayout-filePreview' ]
539 this.progressBarWidget
= new OO
.ui
.ProgressBarWidget( {
542 this.filePreview
.$element
.append( this.progressBarWidget
.$element
);
544 this.filenameWidget
= new OO
.ui
.TextInputWidget( {
545 indicator
: 'required',
549 this.descriptionWidget
= new OO
.ui
.TextInputWidget( {
550 indicator
: 'required',
557 fieldset
= new OO
.ui
.FieldsetLayout( {
558 label
: mw
.msg( 'upload-form-label-infoform-title' )
561 new OO
.ui
.FieldLayout( this.filenameWidget
, {
562 label
: mw
.msg( 'upload-form-label-infoform-name' ),
564 help
: mw
.msg( 'upload-form-label-infoform-name-tooltip' )
566 new OO
.ui
.FieldLayout( this.descriptionWidget
, {
567 label
: mw
.msg( 'upload-form-label-infoform-description' ),
569 help
: mw
.msg( 'upload-form-label-infoform-description-tooltip' )
572 this.infoForm
= new OO
.ui
.FormLayout( {
573 classes
: [ 'mw-upload-bookletLayout-infoForm' ],
574 items
: [ this.filePreview
, fieldset
]
577 this.on( 'fileUploadProgress', function ( progress
) {
578 this.progressBarWidget
.setProgress( progress
* 100 );
581 this.filenameWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
582 this.descriptionWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
584 return this.infoForm
;
588 * Handle change events to the info form
593 mw
.Upload
.BookletLayout
.prototype.onInfoFormChange = function () {
596 this.filenameWidget
.getValidity(),
597 this.descriptionWidget
.getValidity()
598 ).done( function () {
599 layout
.emit( 'infoValid', true );
600 } ).fail( function () {
601 layout
.emit( 'infoValid', false );
606 * Renders and returns the insert form to show file usage and
607 * sets the {@link #insertForm insertForm} property.
610 * @return {OO.ui.FormLayout}
612 mw
.Upload
.BookletLayout
.prototype.renderInsertForm = function () {
615 this.filenameUsageWidget
= new OO
.ui
.TextInputWidget();
616 fieldset
= new OO
.ui
.FieldsetLayout( {
617 label
: mw
.msg( 'upload-form-label-usage-title' )
620 new OO
.ui
.FieldLayout( this.filenameUsageWidget
, {
621 label
: mw
.msg( 'upload-form-label-usage-filename' ),
625 this.insertForm
= new OO
.ui
.FormLayout( { items
: [ fieldset
] } );
627 return this.insertForm
;
633 * Gets the file object from the
634 * {@link #uploadForm upload form}.
637 * @return {File|null}
639 mw
.Upload
.BookletLayout
.prototype.getFile = function () {
640 return this.selectFileWidget
.getValue();
644 * Gets the file name from the
645 * {@link #infoForm information form}.
650 mw
.Upload
.BookletLayout
.prototype.getFilename = function () {
651 var filename
= this.filenameWidget
.getValue();
652 if ( this.filenameExtension
) {
653 filename
+= '.' + this.filenameExtension
;
659 * Prefills the {@link #infoForm information form} with the given filename.
662 * @param {string} filename
664 mw
.Upload
.BookletLayout
.prototype.setFilename = function ( filename
) {
665 var title
= mw
.Title
.newFromFileName( filename
);
668 this.filenameWidget
.setValue( title
.getNameText() );
669 this.filenameExtension
= mw
.Title
.normalizeExtension( title
.getExtension() );
671 // Seems to happen for files with no extension, which should fail some checks anyway...
672 this.filenameWidget
.setValue( filename
);
673 this.filenameExtension
= null;
678 * Gets the page text from the
679 * {@link #infoForm information form}.
684 mw
.Upload
.BookletLayout
.prototype.getText = function () {
685 return this.descriptionWidget
.getValue();
691 * Sets the file object
694 * @param {File|null} file File to select
696 mw
.Upload
.BookletLayout
.prototype.setFile = function ( file
) {
697 this.selectFileWidget
.setValue( file
);
701 * Sets the filekey of a file already stashed on the server
702 * as the target of this upload operation.
705 * @param {string} filekey
707 mw
.Upload
.BookletLayout
.prototype.setFilekey = function ( filekey
) {
708 this.upload
.setFilekey( this.filekey
);
709 this.selectFileWidget
.setValue( filekey
);
711 this.onUploadFormChange();
715 * Clear the values of all fields
719 mw
.Upload
.BookletLayout
.prototype.clear = function () {
720 this.selectFileWidget
.setValue( null );
721 this.progressBarWidget
.setProgress( 0 );
722 this.filenameWidget
.setValue( null ).setValidityFlag( true );
723 this.descriptionWidget
.setValue( null ).setValidityFlag( true );
724 this.filenameUsageWidget
.setValue( null );
727 }( jQuery
, mediaWiki
, moment
) );