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