Merge "ApiQueryInfo: fix query limits for testactions"
[lhc/web/wiklou.git] / resources / src / mediawiki.ForeignStructuredUpload.BookletLayout / BookletLayout.js
1 /* global moment, Uint8Array */
2 ( function ( $, mw ) {
3
4 /**
5 * mw.ForeignStructuredUpload.BookletLayout encapsulates the process
6 * of uploading a file to MediaWiki using the mw.ForeignStructuredUpload model.
7 *
8 * var uploadDialog = new mw.Upload.Dialog( {
9 * bookletClass: mw.ForeignStructuredUpload.BookletLayout,
10 * booklet: {
11 * target: 'local'
12 * }
13 * } );
14 * var windowManager = new OO.ui.WindowManager();
15 * $( 'body' ).append( windowManager.$element );
16 * windowManager.addWindows( [ uploadDialog ] );
17 *
18 * @class mw.ForeignStructuredUpload.BookletLayout
19 * @uses mw.ForeignStructuredUpload
20 * @extends mw.Upload.BookletLayout
21 *
22 * @constructor
23 * @param {Object} config Configuration options
24 * @cfg {string} [target] Used to choose the target repository.
25 * If nothing is passed, the {@link mw.ForeignUpload#property-target default} is used.
26 */
27 mw.ForeignStructuredUpload.BookletLayout = function ( config ) {
28 config = config || {};
29 // Parent constructor
30 mw.ForeignStructuredUpload.BookletLayout.parent.call( this, config );
31
32 this.target = config.target;
33 };
34
35 /* Setup */
36
37 OO.inheritClass( mw.ForeignStructuredUpload.BookletLayout, mw.Upload.BookletLayout );
38
39 /* Uploading */
40
41 /**
42 * @inheritdoc
43 */
44 mw.ForeignStructuredUpload.BookletLayout.prototype.initialize = function () {
45 var booklet = this;
46 return mw.ForeignStructuredUpload.BookletLayout.parent.prototype.initialize.call( this ).then(
47 function () {
48 return $.when(
49 // Point the CategoryMultiselectWidget to the right wiki
50 booklet.upload.getApi().then( function ( api ) {
51 // If this is a ForeignApi, it will have a apiUrl, otherwise we don't need to do anything
52 if ( api.apiUrl ) {
53 // Can't reuse the same object, CategoryMultiselectWidget calls #abort on its mw.Api instance
54 booklet.categoriesWidget.api = new mw.ForeignApi( api.apiUrl );
55 }
56 return $.Deferred().resolve();
57 } ),
58 // Set up booklet fields and license messages to match configuration
59 booklet.upload.loadConfig().then( function ( config ) {
60 var
61 msgPromise,
62 isLocal = booklet.upload.target === 'local',
63 fields = config.fields,
64 msgs = config.licensemessages[ isLocal ? 'local' : 'foreign' ];
65
66 // Hide disabled fields
67 booklet.descriptionField.toggle( !!fields.description );
68 booklet.categoriesField.toggle( !!fields.categories );
69 booklet.dateField.toggle( !!fields.date );
70 // Update form validity
71 booklet.onInfoFormChange();
72
73 // Load license messages from the remote wiki if we don't have these messages locally
74 // (this means that we only load messages from the foreign wiki for custom config)
75 if ( mw.message( 'upload-form-label-own-work-message-' + msgs ).exists() ) {
76 msgPromise = $.Deferred().resolve();
77 } else {
78 msgPromise = booklet.upload.apiPromise.then( function ( api ) {
79 return api.loadMessages( [
80 'upload-form-label-own-work-message-' + msgs,
81 'upload-form-label-not-own-work-message-' + msgs,
82 'upload-form-label-not-own-work-local-' + msgs
83 ] );
84 } );
85 }
86
87 // Update license messages
88 return msgPromise.then( function () {
89 var $labels;
90 booklet.$ownWorkMessage.msg( 'upload-form-label-own-work-message-' + msgs );
91 booklet.$notOwnWorkMessage.msg( 'upload-form-label-not-own-work-message-' + msgs );
92 booklet.$notOwnWorkLocal.msg( 'upload-form-label-not-own-work-local-' + msgs );
93
94 $labels = $( [
95 booklet.$ownWorkMessage[ 0 ],
96 booklet.$notOwnWorkMessage[ 0 ],
97 booklet.$notOwnWorkLocal[ 0 ]
98 ] );
99
100 // Improve the behavior of links inside these labels, which may point to important
101 // things like licensing requirements or terms of use
102 $labels.find( 'a' )
103 .attr( 'target', '_blank' )
104 .on( 'click', function ( e ) {
105 // OO.ui.FieldLayout#onLabelClick is trying to prevent default on all clicks,
106 // which causes the links to not be openable. Don't let it do that.
107 e.stopPropagation();
108 } );
109 } );
110 }, function ( errorMsg ) {
111 booklet.getPage( 'upload' ).$element.msg( errorMsg );
112 return $.Deferred().resolve();
113 } )
114 );
115 }
116 ).catch(
117 // Always resolve, never reject
118 function () { return $.Deferred().resolve(); }
119 );
120 };
121
122 /**
123 * Returns a {@link mw.ForeignStructuredUpload mw.ForeignStructuredUpload}
124 * with the {@link #cfg-target target} specified in config.
125 *
126 * @protected
127 * @return {mw.Upload}
128 */
129 mw.ForeignStructuredUpload.BookletLayout.prototype.createUpload = function () {
130 return new mw.ForeignStructuredUpload( this.target, {
131 parameters: {
132 errorformat: 'html',
133 errorlang: mw.config.get( 'wgUserLanguage' ),
134 errorsuselocal: 1,
135 formatversion: 2
136 }
137 } );
138 };
139
140 /* Form renderers */
141
142 /**
143 * @inheritdoc
144 */
145 mw.ForeignStructuredUpload.BookletLayout.prototype.renderUploadForm = function () {
146 var fieldset,
147 layout = this;
148
149 // These elements are filled with text in #initialize
150 // TODO Refactor this to be in one place
151 this.$ownWorkMessage = $( '<p>' );
152 this.$notOwnWorkMessage = $( '<p>' );
153 this.$notOwnWorkLocal = $( '<p>' );
154
155 this.selectFileWidget = new OO.ui.SelectFileWidget( {
156 showDropTarget: true
157 } );
158 this.messageLabel = new OO.ui.LabelWidget( {
159 label: $( '<div>' ).append(
160 this.$notOwnWorkMessage,
161 this.$notOwnWorkLocal
162 )
163 } );
164 this.ownWorkCheckbox = new OO.ui.CheckboxInputWidget().on( 'change', function ( on ) {
165 layout.messageLabel.toggle( !on );
166 } );
167
168 fieldset = new OO.ui.FieldsetLayout();
169 fieldset.addItems( [
170 new OO.ui.FieldLayout( this.selectFileWidget, {
171 align: 'top'
172 } ),
173 new OO.ui.FieldLayout( this.ownWorkCheckbox, {
174 align: 'inline',
175 label: mw.msg( 'upload-form-label-own-work' ),
176 help: this.$ownWorkMessage,
177 helpInline: true
178 } ),
179 new OO.ui.FieldLayout( this.messageLabel, {
180 align: 'top'
181 } )
182 ] );
183 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
184
185 // Validation
186 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
187 this.ownWorkCheckbox.on( 'change', this.onUploadFormChange.bind( this ) );
188
189 this.selectFileWidget.on( 'change', function () {
190 var file = layout.getFile();
191
192 // Set the date to lastModified once we have the file
193 if ( layout.getDateFromLastModified( file ) !== undefined ) {
194 layout.dateWidget.setValue( layout.getDateFromLastModified( file ) );
195 }
196
197 // Check if we have EXIF data and set to that where available
198 layout.getDateFromExif( file ).done( function ( date ) {
199 layout.dateWidget.setValue( date );
200 } );
201
202 layout.updateFilePreview();
203 } );
204
205 return this.uploadForm;
206 };
207
208 /**
209 * @inheritdoc
210 */
211 mw.ForeignStructuredUpload.BookletLayout.prototype.onUploadFormChange = function () {
212 var file = this.selectFileWidget.getValue(),
213 ownWork = this.ownWorkCheckbox.isSelected(),
214 valid = !!file && ownWork;
215 this.emit( 'uploadValid', valid );
216 };
217
218 /**
219 * @inheritdoc
220 */
221 mw.ForeignStructuredUpload.BookletLayout.prototype.renderInfoForm = function () {
222 var fieldset;
223
224 this.filePreview = new OO.ui.Widget( {
225 classes: [ 'mw-upload-bookletLayout-filePreview' ]
226 } );
227 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
228 progress: 0
229 } );
230 this.filePreview.$element.append( this.progressBarWidget.$element );
231
232 this.filenameWidget = new OO.ui.TextInputWidget( {
233 required: true,
234 validate: /.+/
235 } );
236 this.descriptionWidget = new OO.ui.MultilineTextInputWidget( {
237 required: true,
238 validate: /\S+/,
239 autosize: true
240 } );
241 this.categoriesWidget = new mw.widgets.CategoryMultiselectWidget( {
242 // Can't be done here because we don't know the target wiki yet... done in #initialize.
243 // api: new mw.ForeignApi( ... ),
244 $overlay: this.$overlay
245 } );
246 this.dateWidget = new mw.widgets.DateInputWidget( {
247 $overlay: this.$overlay,
248 required: true,
249 mustBeBefore: moment().add( 1, 'day' ).locale( 'en' ).format( 'YYYY-MM-DD' ) // Tomorrow
250 } );
251
252 this.filenameField = new OO.ui.FieldLayout( this.filenameWidget, {
253 label: mw.msg( 'upload-form-label-infoform-name' ),
254 align: 'top',
255 help: mw.msg( 'upload-form-label-infoform-name-tooltip' ),
256 helpInline: true
257 } );
258 this.descriptionField = new OO.ui.FieldLayout( this.descriptionWidget, {
259 label: mw.msg( 'upload-form-label-infoform-description' ),
260 align: 'top',
261 help: mw.msg( 'upload-form-label-infoform-description-tooltip' ),
262 helpInline: true
263 } );
264 this.categoriesField = new OO.ui.FieldLayout( this.categoriesWidget, {
265 label: mw.msg( 'upload-form-label-infoform-categories' ),
266 align: 'top'
267 } );
268 this.dateField = new OO.ui.FieldLayout( this.dateWidget, {
269 label: mw.msg( 'upload-form-label-infoform-date' ),
270 align: 'top'
271 } );
272
273 fieldset = new OO.ui.FieldsetLayout( {
274 label: mw.msg( 'upload-form-label-infoform-title' )
275 } );
276 fieldset.addItems( [
277 this.filenameField,
278 this.descriptionField,
279 this.categoriesField,
280 this.dateField
281 ] );
282 this.infoForm = new OO.ui.FormLayout( {
283 classes: [ 'mw-upload-bookletLayout-infoForm' ],
284 items: [ this.filePreview, fieldset ]
285 } );
286
287 // Validation
288 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
289 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
290 this.dateWidget.on( 'change', this.onInfoFormChange.bind( this ) );
291
292 this.on( 'fileUploadProgress', function ( progress ) {
293 this.progressBarWidget.setProgress( progress * 100 );
294 }.bind( this ) );
295
296 return this.infoForm;
297 };
298
299 /**
300 * @inheritdoc
301 */
302 mw.ForeignStructuredUpload.BookletLayout.prototype.onInfoFormChange = function () {
303 var layout = this,
304 validityPromises = [];
305
306 validityPromises.push( this.filenameWidget.getValidity() );
307 if ( this.descriptionField.isVisible() ) {
308 validityPromises.push( this.descriptionWidget.getValidity() );
309 }
310 if ( this.dateField.isVisible() ) {
311 validityPromises.push( this.dateWidget.getValidity() );
312 }
313
314 $.when.apply( $, validityPromises ).done( function () {
315 layout.emit( 'infoValid', true );
316 } ).fail( function () {
317 layout.emit( 'infoValid', false );
318 } );
319 };
320
321 /**
322 * @param {mw.Title} filename
323 * @return {jQuery.Promise} Resolves (on success) or rejects with OO.ui.Error
324 */
325 mw.ForeignStructuredUpload.BookletLayout.prototype.validateFilename = function ( filename ) {
326 return ( new mw.Api() ).get( {
327 action: 'query',
328 prop: 'info',
329 titles: filename.getPrefixedDb(),
330 formatversion: 2
331 } ).then(
332 function ( result ) {
333 // if the file already exists, reject right away, before
334 // ever firing finishStashUpload()
335 if ( !result.query.pages[ 0 ].missing ) {
336 return $.Deferred().reject( new OO.ui.Error(
337 $( '<p>' ).msg( 'fileexists', filename.getPrefixedDb() ),
338 { recoverable: false }
339 ) );
340 }
341 },
342 function () {
343 // API call failed - this could be a connection hiccup...
344 // Let's just ignore this validation step and turn this
345 // failure into a successful resolve ;)
346 return $.Deferred().resolve();
347 }
348 );
349 };
350
351 /**
352 * @inheritdoc
353 */
354 mw.ForeignStructuredUpload.BookletLayout.prototype.saveFile = function () {
355 var title = mw.Title.newFromText(
356 this.getFilename(),
357 mw.config.get( 'wgNamespaceIds' ).file
358 );
359
360 return this.uploadPromise
361 .then( this.validateFilename.bind( this, title ) )
362 .then( mw.ForeignStructuredUpload.BookletLayout.parent.prototype.saveFile.bind( this ) );
363 };
364
365 /* Getters */
366
367 /**
368 * @inheritdoc
369 */
370 mw.ForeignStructuredUpload.BookletLayout.prototype.getText = function () {
371 var language = mw.config.get( 'wgContentLanguage' ),
372 categories = this.categoriesWidget.getItems().map( function ( item ) {
373 return item.data;
374 } );
375 this.upload.clearDescriptions();
376 this.upload.addDescription( language, this.descriptionWidget.getValue() );
377 this.upload.setDate( this.dateWidget.getValue() );
378 this.upload.clearCategories();
379 this.upload.addCategories( categories );
380 return this.upload.getText();
381 };
382
383 /**
384 * Get original date from EXIF data
385 *
386 * @param {Object} file
387 * @return {jQuery.Promise} Promise resolved with the EXIF date
388 */
389 mw.ForeignStructuredUpload.BookletLayout.prototype.getDateFromExif = function ( file ) {
390 var fileReader,
391 deferred = $.Deferred();
392
393 if ( file && file.type === 'image/jpeg' ) {
394 fileReader = new FileReader();
395 fileReader.onload = function () {
396 var fileStr, arr, i, metadata,
397 jpegmeta = mw.loader.require( 'mediawiki.libs.jpegmeta' );
398
399 if ( typeof fileReader.result === 'string' ) {
400 fileStr = fileReader.result;
401 } else {
402 // Array buffer; convert to binary string for the library.
403 arr = new Uint8Array( fileReader.result );
404 fileStr = '';
405 for ( i = 0; i < arr.byteLength; i++ ) {
406 fileStr += String.fromCharCode( arr[ i ] );
407 }
408 }
409
410 try {
411 metadata = jpegmeta( fileStr, file.name );
412 } catch ( e ) {
413 metadata = null;
414 }
415
416 if ( metadata !== null && metadata.exif !== undefined && metadata.exif.DateTimeOriginal ) {
417 deferred.resolve( moment( metadata.exif.DateTimeOriginal, 'YYYY:MM:DD' ).format( 'YYYY-MM-DD' ) );
418 } else {
419 deferred.reject();
420 }
421 };
422
423 if ( 'readAsBinaryString' in fileReader ) {
424 fileReader.readAsBinaryString( file );
425 } else if ( 'readAsArrayBuffer' in fileReader ) {
426 fileReader.readAsArrayBuffer( file );
427 } else {
428 // We should never get here
429 deferred.reject();
430 throw new Error( 'Cannot read thumbnail as binary string or array buffer.' );
431 }
432 }
433
434 return deferred.promise();
435 };
436
437 /**
438 * Get last modified date from file
439 *
440 * @param {Object} file
441 * @return {Object} Last modified date from file
442 */
443 mw.ForeignStructuredUpload.BookletLayout.prototype.getDateFromLastModified = function ( file ) {
444 if ( file && file.lastModified ) {
445 return moment( file.lastModified ).format( 'YYYY-MM-DD' );
446 }
447 };
448
449 /* Setters */
450
451 /**
452 * @inheritdoc
453 */
454 mw.ForeignStructuredUpload.BookletLayout.prototype.clear = function () {
455 mw.ForeignStructuredUpload.BookletLayout.parent.prototype.clear.call( this );
456
457 this.ownWorkCheckbox.setSelected( false );
458 this.categoriesWidget.setValue( [] );
459 this.dateWidget.setValue( '' ).setValidityFlag( true );
460 };
461
462 }( jQuery, mediaWiki ) );