1 /* global moment, Uint8Array */
5 * mw.ForeignStructuredUpload.BookletLayout encapsulates the process
6 * of uploading a file to MediaWiki using the mw.ForeignStructuredUpload model.
8 * var uploadDialog = new mw.Upload.Dialog( {
9 * bookletClass: mw.ForeignStructuredUpload.BookletLayout,
14 * var windowManager = new OO.ui.WindowManager();
15 * $( 'body' ).append( windowManager.$element );
16 * windowManager.addWindows( [ uploadDialog ] );
18 * @class mw.ForeignStructuredUpload.BookletLayout
19 * @uses mw.ForeignStructuredUpload
20 * @extends mw.Upload.BookletLayout
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.
27 mw
.ForeignStructuredUpload
.BookletLayout = function ( config
) {
28 config
= config
|| {};
30 mw
.ForeignStructuredUpload
.BookletLayout
.parent
.call( this, config
);
32 this.target
= config
.target
;
37 OO
.inheritClass( mw
.ForeignStructuredUpload
.BookletLayout
, mw
.Upload
.BookletLayout
);
44 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.initialize = function () {
46 return mw
.ForeignStructuredUpload
.BookletLayout
.parent
.prototype.initialize
.call( this ).then(
49 // Point the CategorySelector 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
53 // Can't reuse the same object, CategorySelector calls #abort on its mw.Api instance
54 booklet
.categoriesWidget
.api
= new mw
.ForeignApi( api
.apiUrl
);
56 return $.Deferred().resolve();
58 // Set up booklet fields and license messages to match configuration
59 booklet
.upload
.loadConfig().then( function ( config
) {
62 isLocal
= booklet
.upload
.target
=== 'local',
63 fields
= config
.fields
,
64 msgs
= config
.licensemessages
[ isLocal
? 'local' : 'foreign' ];
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();
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();
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
87 // Update license messages
88 return msgPromise
.then( function () {
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
);
95 booklet
.$ownWorkMessage
[ 0 ],
96 booklet
.$notOwnWorkMessage
[ 0 ],
97 booklet
.$notOwnWorkLocal
[ 0 ]
100 // Improve the behavior of links inside these labels, which may point to important
101 // things like licensing requirements or terms of use
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.
110 }, function ( errorMsg
) {
111 booklet
.getPage( 'upload' ).$element
.msg( errorMsg
);
112 return $.Deferred().resolve();
118 // Always resolve, never reject
119 function () { return $.Deferred().resolve(); }
124 * Returns a {@link mw.ForeignStructuredUpload mw.ForeignStructuredUpload}
125 * with the {@link #cfg-target target} specified in config.
128 * @return {mw.Upload}
130 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.createUpload = function () {
131 return new mw
.ForeignStructuredUpload( this.target
, {
134 errorlang
: mw
.config
.get( 'wgUserLanguage' ),
146 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.renderUploadForm = function () {
150 // These elements are filled with text in #initialize
151 // TODO Refactor this to be in one place
152 this.$ownWorkMessage
= $( '<p>' )
153 .addClass( 'mw-foreignStructuredUpload-bookletLayout-license' );
154 this.$notOwnWorkMessage
= $( '<p>' );
155 this.$notOwnWorkLocal
= $( '<p>' );
157 this.selectFileWidget
= new OO
.ui
.SelectFileWidget( {
160 this.messageLabel
= new OO
.ui
.LabelWidget( {
161 label
: $( '<div>' ).append(
162 this.$notOwnWorkMessage
,
163 this.$notOwnWorkLocal
166 this.ownWorkCheckbox
= new OO
.ui
.CheckboxInputWidget().on( 'change', function ( on
) {
167 layout
.messageLabel
.toggle( !on
);
170 fieldset
= new OO
.ui
.FieldsetLayout();
172 new OO
.ui
.FieldLayout( this.selectFileWidget
, {
175 new OO
.ui
.FieldLayout( this.ownWorkCheckbox
, {
177 label
: $( '<div>' ).append(
178 $( '<p>' ).text( mw
.msg( 'upload-form-label-own-work' ) ),
182 new OO
.ui
.FieldLayout( this.messageLabel
, {
186 this.uploadForm
= new OO
.ui
.FormLayout( { items
: [ fieldset
] } );
189 this.selectFileWidget
.on( 'change', this.onUploadFormChange
.bind( this ) );
190 this.ownWorkCheckbox
.on( 'change', this.onUploadFormChange
.bind( this ) );
192 this.selectFileWidget
.on( 'change', function () {
193 var file
= layout
.getFile();
195 // Set the date to lastModified once we have the file
196 if ( layout
.getDateFromLastModified( file
) !== undefined ) {
197 layout
.dateWidget
.setValue( layout
.getDateFromLastModified( file
) );
200 // Check if we have EXIF data and set to that where available
201 layout
.getDateFromExif( file
).done( function ( date
) {
202 layout
.dateWidget
.setValue( date
);
205 layout
.updateFilePreview();
208 return this.uploadForm
;
214 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.onUploadFormChange = function () {
215 var file
= this.selectFileWidget
.getValue(),
216 ownWork
= this.ownWorkCheckbox
.isSelected(),
217 valid
= !!file
&& ownWork
;
218 this.emit( 'uploadValid', valid
);
224 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.renderInfoForm = function () {
227 this.filePreview
= new OO
.ui
.Widget( {
228 classes
: [ 'mw-upload-bookletLayout-filePreview' ]
230 this.progressBarWidget
= new OO
.ui
.ProgressBarWidget( {
233 this.filePreview
.$element
.append( this.progressBarWidget
.$element
);
235 this.filenameWidget
= new OO
.ui
.TextInputWidget( {
239 this.descriptionWidget
= new OO
.ui
.TextInputWidget( {
245 this.categoriesWidget
= new mw
.widgets
.CategorySelector( {
246 // Can't be done here because we don't know the target wiki yet... done in #initialize.
247 // api: new mw.ForeignApi( ... ),
248 $overlay
: this.$overlay
250 this.dateWidget
= new mw
.widgets
.DateInputWidget( {
251 $overlay
: this.$overlay
,
253 mustBeBefore
: moment().add( 1, 'day' ).locale( 'en' ).format( 'YYYY-MM-DD' ) // Tomorrow
256 this.filenameField
= new OO
.ui
.FieldLayout( this.filenameWidget
, {
257 label
: mw
.msg( 'upload-form-label-infoform-name' ),
259 classes
: [ 'mw-foreignStructuredUploa-bookletLayout-small-notice' ],
260 notices
: [ mw
.msg( 'upload-form-label-infoform-name-tooltip' ) ]
262 this.descriptionField
= new OO
.ui
.FieldLayout( this.descriptionWidget
, {
263 label
: mw
.msg( 'upload-form-label-infoform-description' ),
265 classes
: [ 'mw-foreignStructuredUploa-bookletLayout-small-notice' ],
266 notices
: [ mw
.msg( 'upload-form-label-infoform-description-tooltip' ) ]
268 this.categoriesField
= new OO
.ui
.FieldLayout( this.categoriesWidget
, {
269 label
: mw
.msg( 'upload-form-label-infoform-categories' ),
272 this.dateField
= new OO
.ui
.FieldLayout( this.dateWidget
, {
273 label
: mw
.msg( 'upload-form-label-infoform-date' ),
277 fieldset
= new OO
.ui
.FieldsetLayout( {
278 label
: mw
.msg( 'upload-form-label-infoform-title' )
282 this.descriptionField
,
283 this.categoriesField
,
286 this.infoForm
= new OO
.ui
.FormLayout( {
287 classes
: [ 'mw-upload-bookletLayout-infoForm' ],
288 items
: [ this.filePreview
, fieldset
]
292 this.filenameWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
293 this.descriptionWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
294 this.dateWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
296 this.on( 'fileUploadProgress', function ( progress
) {
297 this.progressBarWidget
.setProgress( progress
* 100 );
300 return this.infoForm
;
306 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.onInfoFormChange = function () {
308 validityPromises
= [];
310 validityPromises
.push( this.filenameWidget
.getValidity() );
311 if ( this.descriptionField
.isVisible() ) {
312 validityPromises
.push( this.descriptionWidget
.getValidity() );
314 if ( this.dateField
.isVisible() ) {
315 validityPromises
.push( this.dateWidget
.getValidity() );
318 $.when
.apply( $, validityPromises
).done( function () {
319 layout
.emit( 'infoValid', true );
320 } ).fail( function () {
321 layout
.emit( 'infoValid', false );
326 * @param {mw.Title} filename
327 * @return {jQuery.Promise} Resolves (on success) or rejects with OO.ui.Error
329 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.validateFilename = function ( filename
) {
330 return ( new mw
.Api() ).get( {
333 titles
: filename
.getPrefixedDb(),
336 function ( result
) {
337 // if the file already exists, reject right away, before
338 // ever firing finishStashUpload()
339 if ( !result
.query
.pages
[ 0 ].missing
) {
340 return $.Deferred().reject( new OO
.ui
.Error(
341 $( '<p>' ).msg( 'fileexists', filename
.getPrefixedDb() ),
342 { recoverable
: false }
347 // API call failed - this could be a connection hiccup...
348 // Let's just ignore this validation step and turn this
349 // failure into a successful resolve ;)
350 return $.Deferred().resolve();
358 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.saveFile = function () {
359 var title
= mw
.Title
.newFromText(
361 mw
.config
.get( 'wgNamespaceIds' ).file
364 return this.uploadPromise
365 .then( this.validateFilename
.bind( this, title
) )
366 .then( mw
.ForeignStructuredUpload
.BookletLayout
.parent
.prototype.saveFile
.bind( this ) );
374 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.getText = function () {
375 var language
= mw
.config
.get( 'wgContentLanguage' );
376 this.upload
.clearDescriptions();
377 this.upload
.addDescription( language
, this.descriptionWidget
.getValue() );
378 this.upload
.setDate( this.dateWidget
.getValue() );
379 this.upload
.clearCategories();
380 this.upload
.addCategories( this.categoriesWidget
.getItemsData() );
381 return this.upload
.getText();
385 * Get original date from EXIF data
387 * @param {Object} file
388 * @return {jQuery.Promise} Promise resolved with the EXIF date
390 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.getDateFromExif = function ( file
) {
392 deferred
= $.Deferred();
394 if ( file
&& file
.type
=== 'image/jpeg' ) {
395 fileReader
= new FileReader();
396 fileReader
.onload = function () {
397 var fileStr
, arr
, i
, metadata
;
399 if ( typeof fileReader
.result
=== 'string' ) {
400 fileStr
= fileReader
.result
;
402 // Array buffer; convert to binary string for the library.
403 arr
= new Uint8Array( fileReader
.result
);
405 for ( i
= 0; i
< arr
.byteLength
; i
++ ) {
406 fileStr
+= String
.fromCharCode( arr
[ i
] );
411 metadata
= mw
.libs
.jpegmeta( fileStr
, file
.name
);
416 if ( metadata
!== null && metadata
.exif
!== undefined && metadata
.exif
.DateTimeOriginal
) {
417 deferred
.resolve( moment( metadata
.exif
.DateTimeOriginal
, 'YYYY:MM:DD' ).format( 'YYYY-MM-DD' ) );
423 if ( 'readAsBinaryString' in fileReader
) {
424 fileReader
.readAsBinaryString( file
);
425 } else if ( 'readAsArrayBuffer' in fileReader
) {
426 fileReader
.readAsArrayBuffer( file
);
428 // We should never get here
430 throw new Error( 'Cannot read thumbnail as binary string or array buffer.' );
434 return deferred
.promise();
438 * Get last modified date from file
440 * @param {Object} file
441 * @return {Object} Last modified date from file
443 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.getDateFromLastModified = function ( file
) {
444 if ( file
&& file
.lastModified
) {
445 return moment( file
.lastModified
).format( 'YYYY-MM-DD' );
454 mw
.ForeignStructuredUpload
.BookletLayout
.prototype.clear = function () {
455 mw
.ForeignStructuredUpload
.BookletLayout
.parent
.prototype.clear
.call( this );
457 this.ownWorkCheckbox
.setSelected( false );
458 this.categoriesWidget
.setItemsFromData( [] );
459 this.dateWidget
.setValue( '' ).setValidityFlag( true );
462 }( jQuery
, mediaWiki
) );