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
65 mw
.Upload
.BookletLayout = function ( config
) {
67 mw
.Upload
.BookletLayout
.parent
.call( this, config
);
69 this.$overlay
= config
.$overlay
;
71 this.renderUploadForm();
72 this.renderInfoForm();
73 this.renderInsertForm();
76 new OO
.ui
.PageLayout( 'upload', {
79 content
: [ this.uploadForm
]
81 new OO
.ui
.PageLayout( 'info', {
84 content
: [ this.infoForm
]
86 new OO
.ui
.PageLayout( 'insert', {
89 content
: [ this.insertForm
]
96 OO
.inheritClass( mw
.Upload
.BookletLayout
, OO
.ui
.BookletLayout
);
101 * Progress events for the uploaded file
103 * @event fileUploadProgress
104 * @param {number} progress In percentage
105 * @param {Object} duration Duration object from `moment.duration()`
109 * The file has finished uploading
111 * @event fileUploaded
115 * The file has been saved to the database
118 * @param {Object} imageInfo See mw.Upload#getImageInfo
122 * The upload form has changed
125 * @param {boolean} isValid The form is valid
129 * The info form has changed
132 * @param {boolean} isValid The form is valid
138 * @property {OO.ui.FormLayout} uploadForm
139 * The form rendered in the first step to get the file object.
140 * Rendered in {@link #renderUploadForm renderUploadForm}.
144 * @property {OO.ui.FormLayout} infoForm
145 * The form rendered in the second step to get metadata.
146 * Rendered in {@link #renderInfoForm renderInfoForm}
150 * @property {OO.ui.FormLayout} insertForm
151 * The form rendered in the third step to show usage
152 * Rendered in {@link #renderInsertForm renderInsertForm}
158 * Initialize for a new upload
160 * @return {jQuery.Promise} Promise resolved when everything is initialized
162 mw
.Upload
.BookletLayout
.prototype.initialize = function () {
166 this.upload
= this.createUpload();
167 this.setPage( 'upload' );
169 return this.upload
.getApi().then(
171 // If the user can't upload anything, don't give them the option to.
172 return api
.getUserInfo().then(
173 function ( userInfo
) {
174 if ( userInfo
.rights
.indexOf( 'upload' ) === -1 ) {
175 // TODO Use a better error message when not all logged-in users can upload
176 booklet
.getPage( 'upload' ).$element
.msg( 'api-error-mustbeloggedin' );
178 return $.Deferred().resolve();
181 return $.Deferred().resolve();
185 function ( errorMsg
) {
186 booklet
.getPage( 'upload' ).$element
.msg( errorMsg
);
187 return $.Deferred().resolve();
193 * Create a new upload model
196 * @return {mw.Upload} Upload model
198 mw
.Upload
.BookletLayout
.prototype.createUpload = function () {
199 return new mw
.Upload();
205 * Uploads the file that was added in the upload form. Uses
206 * {@link #getFile getFile} to get the HTML5
210 * @fires fileUploadProgress
211 * @fires fileUploaded
212 * @return {jQuery.Promise}
214 mw
.Upload
.BookletLayout
.prototype.uploadFile = function () {
215 var deferred
= $.Deferred(),
216 startTime
= new Date(),
218 file
= this.getFile();
220 this.setFilename( file
.name
);
222 this.setPage( 'info' );
224 this.upload
.setFile( file
);
225 // The original file name might contain invalid characters, so use our sanitized one
226 this.upload
.setFilename( this.getFilename() );
228 this.uploadPromise
= this.upload
.uploadToStash();
229 this.uploadPromise
.then( function () {
231 layout
.emit( 'fileUploaded' );
233 // These errors will be thrown while the user is on the info page.
234 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
235 // really be an error...
236 var errorMessage
= layout
.getErrorMessageForStateDetails();
237 deferred
.reject( errorMessage
);
238 }, function ( progress
) {
239 var elapsedTime
= new Date() - startTime
,
240 estimatedTotalTime
= ( 1 / progress
) * elapsedTime
,
241 estimatedRemainingTime
= moment
.duration( estimatedTotalTime
- elapsedTime
);
242 layout
.emit( 'fileUploadProgress', progress
, estimatedRemainingTime
);
245 // If there is an error in uploading, come back to the upload page
246 deferred
.fail( function () {
247 layout
.setPage( 'upload' );
254 * Saves the stash finalizes upload. Uses
255 * {@link #getFilename getFilename}, and
256 * {@link #getText getText} to get details from
261 * @return {jQuery.Promise} Rejects the promise with an
262 * {@link OO.ui.Error error}, or resolves if the upload was successful.
264 mw
.Upload
.BookletLayout
.prototype.saveFile = function () {
266 deferred
= $.Deferred();
268 this.upload
.setFilename( this.getFilename() );
269 this.upload
.setText( this.getText() );
271 this.uploadPromise
.then( function () {
272 layout
.upload
.finishStashUpload().then( function () {
275 // Normalize page name and localise the 'File:' prefix
276 name
= new mw
.Title( 'File:' + layout
.upload
.getFilename() ).toString();
277 layout
.filenameUsageWidget
.setValue( '[[' + name
+ ']]' );
278 layout
.setPage( 'insert' );
281 layout
.emit( 'fileSaved', layout
.upload
.getImageInfo() );
283 var errorMessage
= layout
.getErrorMessageForStateDetails();
284 deferred
.reject( errorMessage
);
288 return deferred
.promise();
292 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
293 * state and state details.
296 * @return {OO.ui.Error} Error to display for given state and details.
298 mw
.Upload
.BookletLayout
.prototype.getErrorMessageForStateDetails = function () {
300 state
= this.upload
.getState(),
301 stateDetails
= this.upload
.getStateDetails(),
302 error
= stateDetails
.error
,
303 warnings
= stateDetails
.upload
&& stateDetails
.upload
.warnings
;
305 if ( state
=== mw
.Upload
.State
.ERROR
) {
307 // If there's an 'exception' key, this might be a timeout, or other connection problem
308 return new OO
.ui
.Error(
309 $( '<p>' ).msg( 'api-error-unknownerror', JSON
.stringify( stateDetails
) ),
310 { recoverable
: false }
314 // HACK We should either have a hook here to allow TitleBlacklist to handle this, or just have
315 // TitleBlacklist produce sane error messages that can be displayed without arcane knowledge
316 if ( error
.info
=== 'TitleBlacklist prevents this title from being created' ) {
317 // HACK Apparently the only reliable way to determine whether TitleBlacklist was involved
318 return new OO
.ui
.Error(
319 // HACK TitleBlacklist doesn't have a sensible message, this one is from UploadWizard
320 $( '<p>' ).msg( 'api-error-blacklisted' ),
321 { recoverable
: false }
325 if ( error
.code
=== 'protectedpage' ) {
326 message
= mw
.message( 'protectedpagetext' );
328 message
= mw
.message( 'api-error-' + error
.code
);
329 if ( !message
.exists() ) {
330 message
= mw
.message( 'api-error-unknownerror', JSON
.stringify( stateDetails
) );
333 return new OO
.ui
.Error(
334 $( '<p>' ).append( message
.parseDom() ),
335 { recoverable
: false }
339 if ( state
=== mw
.Upload
.State
.WARNING
) {
340 // We could get more than one of these errors, these are in order
341 // of importance. For example fixing the thumbnail like file name
342 // won't help the fact that the file already exists.
343 if ( warnings
.stashfailed
!== undefined ) {
344 return new OO
.ui
.Error(
345 $( '<p>' ).msg( 'api-error-stashfailed' ),
346 { recoverable
: false }
348 } else if ( warnings
.exists
!== undefined ) {
349 return new OO
.ui
.Error(
350 $( '<p>' ).msg( 'fileexists', 'File:' + warnings
.exists
),
351 { recoverable
: false }
353 } else if ( warnings
[ 'exists-normalized' ] !== undefined ) {
354 return new OO
.ui
.Error(
355 $( '<p>' ).msg( 'fileexists', 'File:' + warnings
[ 'exists-normalized' ] ),
356 { recoverable
: false }
358 } else if ( warnings
[ 'page-exists' ] !== undefined ) {
359 return new OO
.ui
.Error(
360 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings
[ 'page-exists' ] ),
361 { recoverable
: false }
363 } else if ( warnings
.duplicate
!== undefined ) {
364 return new OO
.ui
.Error(
365 $( '<p>' ).msg( 'api-error-duplicate', warnings
.duplicate
.length
),
366 { recoverable
: false }
368 } else if ( warnings
[ 'thumb-name' ] !== undefined ) {
369 return new OO
.ui
.Error(
370 $( '<p>' ).msg( 'filename-thumb-name' ),
371 { recoverable
: false }
373 } else if ( warnings
[ 'bad-prefix' ] !== undefined ) {
374 return new OO
.ui
.Error(
375 $( '<p>' ).msg( 'filename-bad-prefix', warnings
[ 'bad-prefix' ] ),
376 { recoverable
: false }
378 } else if ( warnings
[ 'duplicate-archive' ] !== undefined ) {
379 return new OO
.ui
.Error(
380 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
381 { recoverable
: false }
383 } else if ( warnings
[ 'was-deleted' ] !== undefined ) {
384 return new OO
.ui
.Error(
385 $( '<p>' ).msg( 'api-error-was-deleted' ),
386 { recoverable
: false }
388 } else if ( warnings
.badfilename
!== undefined ) {
389 // Change the name if the current name isn't acceptable
390 // TODO This might not really be the best place to do this
391 this.setFilename( warnings
.badfilename
);
392 return new OO
.ui
.Error(
393 $( '<p>' ).msg( 'badfilename', warnings
.badfilename
)
396 return new OO
.ui
.Error(
397 // Let's get all the help we can if we can't pin point the error
398 $( '<p>' ).msg( 'api-error-unknown-warning', JSON
.stringify( stateDetails
) ),
399 { recoverable
: false }
408 * Renders and returns the upload form and sets the
409 * {@link #uploadForm uploadForm} property.
413 * @return {OO.ui.FormLayout}
415 mw
.Upload
.BookletLayout
.prototype.renderUploadForm = function () {
419 this.selectFileWidget
= new OO
.ui
.SelectFileWidget( {
422 fieldset
= new OO
.ui
.FieldsetLayout();
423 fieldset
.addItems( [ this.selectFileWidget
] );
424 this.uploadForm
= new OO
.ui
.FormLayout( { items
: [ fieldset
] } );
427 this.selectFileWidget
.on( 'change', this.onUploadFormChange
.bind( this ) );
429 this.selectFileWidget
.on( 'change', function () {
430 layout
.updateFilePreview();
433 return this.uploadForm
;
437 * Updates the file preview on the info form when a file is added.
441 mw
.Upload
.BookletLayout
.prototype.updateFilePreview = function () {
442 this.selectFileWidget
.loadAndGetImageUrl().done( function ( url
) {
443 this.filePreview
.$element
.find( 'p' ).remove();
444 this.filePreview
.$element
.css( 'background-image', 'url(' + url
+ ')' );
445 this.infoForm
.$element
.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
446 }.bind( this ) ).fail( function () {
447 this.filePreview
.$element
.find( 'p' ).remove();
448 if ( this.selectFileWidget
.getValue() ) {
449 this.filePreview
.$element
.append(
450 $( '<p>' ).text( this.selectFileWidget
.getValue().name
)
453 this.filePreview
.$element
.css( 'background-image', '' );
454 this.infoForm
.$element
.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
459 * Handle change events to the upload form
464 mw
.Upload
.BookletLayout
.prototype.onUploadFormChange = function () {
465 this.emit( 'uploadValid', !!this.selectFileWidget
.getValue() );
469 * Renders and returns the information form for collecting
470 * metadata and sets the {@link #infoForm infoForm}
474 * @return {OO.ui.FormLayout}
476 mw
.Upload
.BookletLayout
.prototype.renderInfoForm = function () {
479 this.filePreview
= new OO
.ui
.Widget( {
480 classes
: [ 'mw-upload-bookletLayout-filePreview' ]
482 this.progressBarWidget
= new OO
.ui
.ProgressBarWidget( {
485 this.filePreview
.$element
.append( this.progressBarWidget
.$element
);
487 this.filenameWidget
= new OO
.ui
.TextInputWidget( {
488 indicator
: 'required',
492 this.descriptionWidget
= new OO
.ui
.TextInputWidget( {
493 indicator
: 'required',
500 fieldset
= new OO
.ui
.FieldsetLayout( {
501 label
: mw
.msg( 'upload-form-label-infoform-title' )
504 new OO
.ui
.FieldLayout( this.filenameWidget
, {
505 label
: mw
.msg( 'upload-form-label-infoform-name' ),
507 help
: mw
.msg( 'upload-form-label-infoform-name-tooltip' )
509 new OO
.ui
.FieldLayout( this.descriptionWidget
, {
510 label
: mw
.msg( 'upload-form-label-infoform-description' ),
512 help
: mw
.msg( 'upload-form-label-infoform-description-tooltip' )
515 this.infoForm
= new OO
.ui
.FormLayout( {
516 classes
: [ 'mw-upload-bookletLayout-infoForm' ],
517 items
: [ this.filePreview
, fieldset
]
520 this.on( 'fileUploadProgress', function ( progress
) {
521 this.progressBarWidget
.setProgress( progress
* 100 );
524 this.filenameWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
525 this.descriptionWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
527 return this.infoForm
;
531 * Handle change events to the info form
536 mw
.Upload
.BookletLayout
.prototype.onInfoFormChange = function () {
539 this.filenameWidget
.getValidity(),
540 this.descriptionWidget
.getValidity()
541 ).done( function () {
542 layout
.emit( 'infoValid', true );
543 } ).fail( function () {
544 layout
.emit( 'infoValid', false );
549 * Renders and returns the insert form to show file usage and
550 * sets the {@link #insertForm insertForm} property.
553 * @return {OO.ui.FormLayout}
555 mw
.Upload
.BookletLayout
.prototype.renderInsertForm = function () {
558 this.filenameUsageWidget
= new OO
.ui
.TextInputWidget();
559 fieldset
= new OO
.ui
.FieldsetLayout( {
560 label
: mw
.msg( 'upload-form-label-usage-title' )
563 new OO
.ui
.FieldLayout( this.filenameUsageWidget
, {
564 label
: mw
.msg( 'upload-form-label-usage-filename' ),
568 this.insertForm
= new OO
.ui
.FormLayout( { items
: [ fieldset
] } );
570 return this.insertForm
;
576 * Gets the file object from the
577 * {@link #uploadForm upload form}.
580 * @return {File|null}
582 mw
.Upload
.BookletLayout
.prototype.getFile = function () {
583 return this.selectFileWidget
.getValue();
587 * Gets the file name from the
588 * {@link #infoForm information form}.
593 mw
.Upload
.BookletLayout
.prototype.getFilename = function () {
594 var filename
= this.filenameWidget
.getValue();
595 if ( this.filenameExtension
) {
596 filename
+= '.' + this.filenameExtension
;
602 * Prefills the {@link #infoForm information form} with the given filename.
605 * @param {string} filename
607 mw
.Upload
.BookletLayout
.prototype.setFilename = function ( filename
) {
608 var title
= mw
.Title
.newFromFileName( filename
);
611 this.filenameWidget
.setValue( title
.getNameText() );
612 this.filenameExtension
= mw
.Title
.normalizeExtension( title
.getExtension() );
614 // Seems to happen for files with no extension, which should fail some checks anyway...
615 this.filenameWidget
.setValue( filename
);
616 this.filenameExtension
= null;
621 * Gets the page text from the
622 * {@link #infoForm information form}.
627 mw
.Upload
.BookletLayout
.prototype.getText = function () {
628 return this.descriptionWidget
.getValue();
634 * Sets the file object
637 * @param {File|null} file File to select
639 mw
.Upload
.BookletLayout
.prototype.setFile = function ( file
) {
640 this.selectFileWidget
.setValue( file
);
644 * Clear the values of all fields
648 mw
.Upload
.BookletLayout
.prototype.clear = function () {
649 this.selectFileWidget
.setValue( null );
650 this.progressBarWidget
.setProgress( 0 );
651 this.filenameWidget
.setValue( null ).setValidityFlag( true );
652 this.descriptionWidget
.setValue( null ).setValidityFlag( true );
653 this.filenameUsageWidget
.setValue( null );
656 }( jQuery
, mediaWiki
, moment
) );