Debian Codegraph @

resources/src/mediawiki.ForeignStructuredUpload.BookletLayout/BookletLayout.js

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