-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathutils.js
589 lines (504 loc) · 15 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/**
* External dependencies
*
* @format
*/
import url from 'url';
import path from 'path';
import photon from 'photon';
import { includes, omitBy, startsWith } from 'lodash';
import { isUri } from 'valid-url';
/**
* Internal dependencies
*/
import resize from 'lib/resize-image-url';
import {
MimeTypes,
VideoPressFileTypes,
ThumbnailSizeDimensions,
GalleryColumnedTypes,
GallerySizeableTypes,
GalleryDefaultAttrs,
} from './constants';
import Shortcode from 'lib/shortcode';
import { uniqueId } from 'lib/impure-lodash';
/**
* Module variables
*/
const REGEXP_VIDEOPRESS_GUID = /^[a-z\d]+$/i;
const MediaUtils = {
/**
* Given a media object, returns a URL string to that media. Accepts
* optional options to specify photon usage or a maximum image width.
*
* @param {Object} media Media object
* @param {Object} options Optional options, accepting a `photon` boolean,
* `maxWidth` pixel value, or `size`.
* @return {string} URL to the media
*/
url: function( media, options ) {
if ( ! media ) {
return;
}
if ( media.transient ) {
return media.URL;
}
// We've found that some media can be corrupt with an unusable URL.
// Return early so attempts to parse the URL don't result in an error.
if ( ! media.URL ) {
return;
}
options = options || {};
if ( options.photon ) {
if ( options.maxWidth ) {
return photon( media.URL, { width: options.maxWidth } );
}
return photon( media.URL );
}
if ( media.thumbnails && options.size in media.thumbnails ) {
return media.thumbnails[ options.size ];
}
if ( options.maxWidth ) {
return resize( media.URL, {
w: options.maxWidth,
} );
}
return media.URL;
},
/**
* Given a media string, File, or object, returns the file extension.
*
* @example
* getFileExtension( 'example.gif' );
* getFileExtension( { URL: 'https://wordpress.com/example.gif' } );
* getFileExtension( new window.File( [''], 'example.gif' ) );
* // All examples return 'gif'
*
* @param {(string|File|Object)} media Media object or string
* @return {string} File extension
*/
getFileExtension: function( media ) {
let extension;
if ( ! media ) {
return;
}
const isString = 'string' === typeof media;
const isFileObject = 'File' in window && media instanceof window.File;
if ( isString ) {
let filePath;
if ( isUri( media ) ) {
filePath = url.parse( media ).pathname;
} else {
filePath = media;
}
extension = path.extname( filePath ).slice( 1 );
} else if ( isFileObject ) {
extension = path.extname( media.name ).slice( 1 );
} else if ( media.extension ) {
extension = media.extension;
} else {
const pathname = url.parse( media.URL || media.file || media.guid || '' ).pathname || '';
extension = path.extname( pathname ).slice( 1 );
}
return extension;
},
/**
* Given a media string or object, returns the MIME type prefix.
*
* @example
* getMimeType( 'example.gif' );
* getMimeType( { URL: 'https://wordpress.com/example.gif' } );
* getMimeType( { mime_type: 'image/gif' } );
* // All examples return 'image'
*
* @param {string} media Media object or mime type string
* @return {string} The MIME type prefix
*/
getMimePrefix: function( media ) {
var mimeType = MediaUtils.getMimeType( media ),
mimePrefixMatch;
if ( ! mimeType ) {
return;
}
mimePrefixMatch = mimeType.match( /^([^\/]+)\// );
if ( mimePrefixMatch ) {
return mimePrefixMatch[ 1 ];
}
},
/**
* Given a media string, File, or object, returns the MIME type if one can
* be determined.
*
* @example
* getMimeType( 'example.gif' );
* getMimeType( { URL: 'https://wordpress.com/example.gif' } );
* getMimeType( { mime_type: 'image/gif' } );
* // All examples return 'image/gif'
*
* @param {(string|File|Object)} media Media object or string
* @return {string} Mime type of the media, if known
*/
getMimeType: function( media ) {
if ( ! media ) {
return;
}
if ( media.mime_type ) {
return media.mime_type;
} else if ( 'File' in window && media instanceof window.File ) {
return media.type;
}
let extension = MediaUtils.getFileExtension( media );
if ( ! extension ) {
return;
}
extension = extension.toLowerCase();
if ( MimeTypes.hasOwnProperty( extension ) ) {
return MimeTypes[ extension ];
}
},
/**
* Given an array of media objects, returns a filtered array composed of
* items from the original array matching the specified mime prefix.
*
* @param {Array} items Array of media objects
* @param {string} mimePrefix A mime prefix, e.g. "image"
* @return {Array} Filtered array of matching media objects
*/
filterItemsByMimePrefix: function( items, mimePrefix ) {
return items.filter( function( item ) {
return MediaUtils.getMimePrefix( item ) === mimePrefix;
} );
},
/**
* Given an array of media objects, returns a copy sorted by media date.
*
* @param {Array} items Array of media objects
* @return {Array} Sorted array of media objects
*/
sortItemsByDate: function( items ) {
var copy = items.slice( 0 );
copy.sort( function( a, b ) {
var dateCompare;
if ( a.date && b.date ) {
dateCompare = Date.parse( b.date ) - Date.parse( a.date );
// We only return the result of a date comaprison if item dates
// are set and the dates are not equal...
if ( 0 !== dateCompare ) {
return dateCompare;
}
}
// ...otherwise, we return the greater of the two item IDs
return b.ID - a.ID;
} );
return copy;
},
/**
* Returns true if the site can be trusted to accurately report its allowed
* file types. Returns false otherwise.
*
* Jetpack currently does not sync the allowed file types
* option, so we must assume that all file types are supported.
*
* @param {Object} site Site object
* @return {Boolean} Site allowed file types are accurate
*/
isSiteAllowedFileTypesToBeTrusted: function( site ) {
return ! site || ! site.jetpack;
},
/**
* Returns an array of supported file extensions for the specified site.
*
* @param {Object} site Site object
* @return {Array} Supported file extensions
*/
getAllowedFileTypesForSite: function( site ) {
if ( ! site ) {
return [];
}
return site.options.allowed_file_types;
},
/**
* Returns true if the specified item is a valid file in a Premium plan,
* or false otherwise.
*
* @param {Object} item Media object
* @param {Object} site Site object
* @return {Boolean} Whether the Premium plan supports the item
*/
isSupportedFileTypeInPremium: function( item, site ) {
if ( ! site || ! item ) {
return false;
}
if ( ! MediaUtils.isSiteAllowedFileTypesToBeTrusted( site ) ) {
return true;
}
return VideoPressFileTypes.some( function( allowed ) {
return allowed.toLowerCase() === item.extension.toLowerCase();
} );
},
/**
* Returns true if the specified item is a valid file for the given site,
* or false otherwise. A file is valid if the sites allowable file types
* contains the item's type.
*
* @param {Object} item Media object
* @param {Object} site Site object
* @return {Boolean} Whether the site supports the item
*/
isSupportedFileTypeForSite: function( item, site ) {
if ( ! site || ! item ) {
return false;
}
if ( ! MediaUtils.isSiteAllowedFileTypesToBeTrusted( site ) ) {
return true;
}
return MediaUtils.getAllowedFileTypesForSite( site ).some( function( allowed ) {
return allowed.toLowerCase() === item.extension.toLowerCase();
} );
},
/**
* Returns true if the specified item exceeds the maximum upload size for
* the given site. Returns null if the bytes are invalid, the max upload
* size for the site is unknown or a video is being uploaded for a Jetpack
* site with VideoPress enabled. Otherwise, returns true.
*
* @param {Object} item Media object
* @param {Object} site Site object
* @return {?Boolean} Whether the size exceeds the site maximum
*/
isExceedingSiteMaxUploadSize: function( item, site ) {
const bytes = item.size;
if ( ! site || ! site.options ) {
return null;
}
if ( ! isFinite( bytes ) || ! site.options.max_upload_size ) {
return null;
}
if (
site.jetpack &&
site.isModuleActive( 'videopress' ) &&
site.versionCompare( '4.5', '>=' ) &&
startsWith( MediaUtils.getMimeType( item ), 'video/' )
) {
return null;
}
return bytes > site.options.max_upload_size;
},
/**
* Returns true if the provided media object is a VideoPress video item.
*
* @param {Object} item Media object
* @return {Boolean} Whether the media is a VideoPress video item
*/
isVideoPressItem: function( item ) {
if ( ! item || ! item.videopress_guid ) {
return false;
}
return REGEXP_VIDEOPRESS_GUID.test( item.videopress_guid );
},
/**
* Returns a human-readable string representing the specified seconds
* duration.
*
* @example
* MediaUtils.playtime( 7 ); // -> "0:07"
*
* @param {number} duration Duration in seconds
* @return {string} Human-readable duration
*/
playtime: function( duration ) {
if ( isNaN( duration ) ) {
return;
}
const hours = Math.floor( duration / 3600 ),
minutes = Math.floor( duration / 60 ) % 60,
seconds = Math.floor( duration ) % 60;
let playtime = [ minutes, seconds ]
.map( function( value ) {
return ( '0' + value ).slice( -2 );
} )
.join( ':' );
if ( hours ) {
playtime = [ hours, playtime ].join( ':' );
}
playtime = playtime.replace( /^(00:)+/g, '' );
if ( -1 === playtime.indexOf( ':' ) ) {
playtime = '0:' + playtime;
}
return playtime.replace( /^0(\d)(.*)/, '$1$2' );
},
/**
* Returns an object containing width and height dimenions in pixels for
* the thumbnail size, optionally for a given site. If the size cannot be
* determined or a site is not passed, a fallback default value is used.
*
* @param {String} size Thumbnail size
* @param {Object} site Site object
* @return {Object} Width and height dimensions
*/
getThumbnailSizeDimensions: function( size, site ) {
var width, height;
if ( site && site.options ) {
width = site.options[ 'image_' + size + '_width' ];
height = site.options[ 'image_' + size + '_height' ];
}
if ( size in ThumbnailSizeDimensions ) {
width = width || ThumbnailSizeDimensions[ size ].width;
height = height || ThumbnailSizeDimensions[ size ].height;
}
return { width, height };
},
/**
* Given an array of media items, returns a gallery shortcode using an
* optional set of parameters.
*
* @param {Object} settings Gallery settings
* @return {String} Gallery shortcode
*/
generateGalleryShortcode: function( settings ) {
var attrs;
if ( ! settings.items.length ) {
return;
}
// gallery images are passed in as an array of objects
// in settings.items but we just need the IDs set to attrs.ids
attrs = Object.assign(
{
ids: settings.items.map( item => item.ID ).join(),
},
settings
);
delete attrs.items;
if ( ! includes( GalleryColumnedTypes, attrs.type ) ) {
delete attrs.columns;
}
if ( ! includes( GallerySizeableTypes, attrs.type ) ) {
delete attrs.size;
}
attrs = omitBy( attrs, function( value, key ) {
return GalleryDefaultAttrs[ key ] === value;
} );
// WordPress expects all lowercase
if ( attrs.orderBy ) {
attrs.orderby = attrs.orderBy;
delete attrs.orderBy;
}
return Shortcode.stringify( {
tag: 'gallery',
type: 'single',
attrs: attrs,
} );
},
/**
* Returns true if the specified user is capable of deleting the media
* item, or false otherwise.
*
* @param {Object} item Media item
* @param {Object} user User object
* @param {Object} site Site object
* @return {Boolean} Whether user can delete item
*/
canUserDeleteItem( item, user, site ) {
if ( user.ID === item.author_ID ) {
return site.capabilities.delete_posts;
}
return site.capabilities.delete_others_posts;
},
/**
* Wrapper method for the HTML canvas toBlob() function. Polyfills if the
* function does not exist
*
* @param {Object} canvas the canvas element
* @param {Function} callback function to process the blob after it is extracted
* @param {String} type image type to be extracted
* @param {Number} quality extracted image quality
*/
canvasToBlob( canvas, callback, type, quality ) {
if ( ! HTMLCanvasElement.prototype.toBlob ) {
Object.defineProperty( HTMLCanvasElement.prototype, 'toBlob', {
value: function( polyfillCallback, polyfillType, polyfillQuality ) {
const binStr = atob( this.toDataURL( polyfillType, polyfillQuality ).split( ',' )[ 1 ] ),
len = binStr.length,
arr = new Uint8Array( len );
for ( let i = 0; i < len; i++ ) {
arr[ i ] = binStr.charCodeAt( i );
}
polyfillCallback(
new Blob( [ arr ], {
type: polyfillType || 'image/png',
} )
);
},
} );
}
canvas.toBlob( callback, type, quality );
},
/**
* Returns true if specified item is currently being uploaded (i.e. is transient).
*
* @param {Object} item Media item
* @return {Boolean} Whether item is being uploaded
*/
isItemBeingUploaded( item ) {
if ( ! item ) {
return null;
}
return !! item.transient;
},
isTransientPreviewable( item ) {
return !! ( item && item.URL );
},
/**
* Returns an object describing a transient media item which can be used in
* optimistic rendering prior to media persistence to server.
*
* @param {(String|Object|Blob|File)} file URL or File object
* @return {Object} Transient media object
*/
createTransientMedia( file ) {
const transientMedia = {
transient: true,
ID: uniqueId( 'media-' ),
};
if ( 'string' === typeof file ) {
// Generate from string
Object.assign( transientMedia, {
file: file,
title: path.basename( file ),
extension: MediaUtils.getFileExtension( file ),
mime_type: MediaUtils.getMimeType( file ),
} );
} else if ( file.thumbnails ) {
// Generate from a file data object
Object.assign( transientMedia, {
file: file.URL,
title: file.name,
extension: file.extension,
mime_type: file.mime_type,
guid: file.URL,
URL: file.URL,
external: true,
} );
} else {
// Handle the case where a an object has been passed that wraps a
// Blob and contains a fileName
const fileContents = file.fileContents || file;
const fileName = file.fileName || file.name;
// Generate from window.File object
const fileUrl = window.URL.createObjectURL( fileContents );
Object.assign( transientMedia, {
URL: fileUrl,
guid: fileUrl,
file: fileName,
title: file.title || path.basename( fileName ),
extension: MediaUtils.getFileExtension( file.fileName || fileContents ),
mime_type: MediaUtils.getMimeType( file.fileName || fileContents ),
// Size is not an API media property, though can be useful for
// validation purposes if known
size: fileContents.size,
} );
}
return transientMedia;
},
};
export default MediaUtils;