Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix drag-n-drop image orientation of preview #5020

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
211 changes: 130 additions & 81 deletions client/lib/media/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ var Dispatcher = require( 'dispatcher' ),
PostEditStore = require( 'lib/posts/post-edit-store' ),
MediaStore = require( './store' ),
MediaListStore = require( './list-store' ),
MediaValidationStore = require( './validation-store' );
MediaValidationStore = require( './validation-store' ),
ImageOrientationUtils = require( './image-orientation-utils' );

/**
* Module variables
Expand Down Expand Up @@ -90,7 +91,7 @@ MediaActions.fetchNextPage = function( siteId ) {
} );
};

MediaActions.add = function( siteId, files ) {
MediaActions.add = function( siteId, files, options = {} ) {
if ( files instanceof window.FileList ) {
files = [ ...files ];
}
Expand All @@ -99,91 +100,139 @@ MediaActions.add = function( siteId, files ) {
files = [ files ];
}

// We offset the current time when generating a fake date for the transient
// media so that the first uploaded media doesn't suddenly become newest in
// the set once it finishes uploading. This duration is pretty arbitrary,
// but one would hope that it would never take this long to upload an item.
const baseTime = Date.now() + ONE_YEAR_IN_MILLISECONDS;

return files.reduce( ( lastUpload, file, i ) => {
// Generate a fake transient media item that can be rendered into the list
// immediately, even before the media has persisted to the server
const id = uniqueId( 'media-' );
const transientMedia = {
ID: id,
'transient': true,
// Assign a date such that the first item will be the oldest at the
// time of upload, as this is expected order when uploads finish
date: new Date( baseTime - ( files.length - i ) ).toISOString()
};

if ( 'string' === typeof file ) {
// Generate from string
assign( transientMedia, {
file: file,
extension: MediaUtils.getFileExtension( file ),
mime_type: MediaUtils.getMimeType( file ),
title: path.basename( file )
} );
} else {
// Generate from window.File object
const fileUrl = window.URL.createObjectURL( file );
assign( transientMedia, {
URL: fileUrl,
guid: fileUrl,
file: file.name,
extension: MediaUtils.getFileExtension( file.name ),
mime_type: MediaUtils.getMimeType( file.name ),
title: path.basename( file.name ),
// Size is not an API media property, though can be useful for
// validation purposes if known
size: file.size
} );
}
const createMedia = () => {
// We offset the current time when generating a fake date for the transient
// media so that the first uploaded media doesn't suddenly become newest in
// the set once it finishes uploading. This duration is pretty arbitrary,
// but one would hope that it would never take this long to upload an item.
const baseTime = Date.now() + ONE_YEAR_IN_MILLISECONDS;

let media = [];
const mediaPromises = files.map( ( file, i ) => {
// Generate a fake transient media item that can be rendered into the list
// immediately, even before the media has persisted to the server
const id = uniqueId( 'media-' );
const transientMedia = {
ID: id,
'transient': true,
// Assign a date such that the first item will be the oldest at the
// time of upload, as this is expected order when uploads finish
date: new Date( baseTime - ( files.length - i ) ).toISOString()
};

Dispatcher.handleViewAction( {
type: 'CREATE_MEDIA_ITEM',
siteId: siteId,
data: transientMedia
} );
let createTransientMedia = () => {
if ( 'string' === typeof file ) {
assign( transientMedia, {
file: file,
extension: MediaUtils.getFileExtension( file ),
mime_type: MediaUtils.getMimeType( file ),
title: path.basename( file )
} );
return Promise.resolve();
}

assign( transientMedia, {
file: file.name,
extension: MediaUtils.getFileExtension( file.name ),
mime_type: MediaUtils.getMimeType( file.name ),
title: path.basename( file.name ),
// Size is not an API media property, though can be useful for
// validation purposes if known
size: file.size
} );

// Abort upload if file fails to pass validation.
if ( MediaValidationStore.getErrors( siteId, id ).length ) {
return Promise.resolve();
}

// Determine upload mechanism by object type
const isUrl = 'string' === typeof file;
const addHandler = isUrl ? 'addMediaUrls' : 'addMediaFiles';

// Assign parent ID if currently editing post
const post = PostEditStore.get();
if ( post && post.ID && ! isPlainObject( file ) ) {
file = {
parent_id: post.ID,
[ isUrl ? 'url' : 'file' ]: file
// If the image is a JPEG, fix the image orientation
if ( 'image/jpeg' === transientMedia.mime_type ) {
return ImageOrientationUtils.fixImageOrientation( file ).then( blobUrl => {
assign( transientMedia, {
URL: blobUrl,
guid: blobUrl
} );
} );
}

// Generate from window.File object
const fileUrl = window.URL.createObjectURL( file );
assign( transientMedia, {
URL: fileUrl,
guid: fileUrl
} );
return Promise.resolve();
};
}

debug( 'Uploading media to %d from %o', siteId, file );
return lastUpload.then( () => {
// Achieve series upload by waiting for the previous promise to
// resolve before starting this item's upload
const action = { type: 'RECEIVE_MEDIA_ITEM', id, siteId };
return wpcom.site( siteId )[ addHandler ]( {}, file ).then( ( data ) => {
Dispatcher.handleServerAction( Object.assign( action, {
data: data.media[ 0 ]
} ) );
// also refetch media limits
Dispatcher.handleServerAction( {
type: 'FETCH_MEDIA_LIMITS',
siteId: siteId

return createTransientMedia().then( () => {
Dispatcher.handleViewAction( {
type: 'CREATE_MEDIA_ITEM',
siteId: siteId,
data: transientMedia
} );

media.push( {
file: file,
transientMedia: transientMedia
} );
} ).catch( ( error ) => {
Dispatcher.handleServerAction( Object.assign( action, { error } ) );
} );
} );
}, Promise.resolve() );

return Promise.all( mediaPromises ).then( () => media );
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than building an array via push, we can leverage the fact that Promise.all calls its thenable with an array of results from each promise, which is exactly how you've constructed this anyways.

e.g.

Promise.all( [
    Promise.resolve( { ID: 1 } ),
    Promise.resolve( { ID: 2 } ),
    Promise.resolve( { ID: 3 } )
] ).then( ( media ) => { /* ... */ } );

So if you were to change media.push( {} ) to return {};, you could drop the .then() here and eliminate the media variable.

};

const uploadMedia = ( media ) => {
return media.reduce( ( lastUpload, item ) => {
// Abort upload if file fails to pass validation.
if ( MediaValidationStore.getErrors( siteId, item.transientMedia.ID ).length ) {
return Promise.resolve();
}

let file = item.file;

// Determine upload mechanism by object type
const isUrl = 'string' === typeof file;
const addHandler = isUrl ? 'addMediaUrls' : 'addMediaFiles';

// Assign parent ID if currently editing post
const post = PostEditStore.get();

if ( post && post.ID && ! isPlainObject( file ) ) {
file = {
parent_id: post.ID,
[ isUrl ? 'url' : 'file' ]: file
};
}

debug( 'Uploading media to %d from %o', siteId, file );
return lastUpload.then( () => {
// Achieve series upload by waiting for the previous promise to
// resolve before starting this item's upload
const action = { type: 'RECEIVE_MEDIA_ITEM', id: item.transientMedia.ID, siteId };

return wpcom.site( siteId )[ addHandler ]( {}, file )
.then( data => {
Dispatcher.handleServerAction( Object.assign( action, {
data: data.media[ 0 ]
} ) );
// also refetch media limits
Dispatcher.handleServerAction( {
type: 'FETCH_MEDIA_LIMITS',
siteId: siteId
} );
} )
.catch( error => {
Dispatcher.handleServerAction( Object.assign( action, { error } ) );
} );
} );
}, Promise.resolve() );
};

const create = createMedia();

if ( options.waitForUpload ) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we or do we plan to use waitForUpload ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanted to be consistent with what existed before. Previously, the final promise resolved when the uploading was complete. The tests use waitForUpload.

return create.then( media => uploadMedia( media ) );
}

create.then( media => uploadMedia( media ) );

return create;
};

MediaActions.edit = function( siteId, item ) {
Expand Down
76 changes: 76 additions & 0 deletions client/lib/media/image-orientation-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* External dependencies
*/
import loadImage from 'blueimp-load-image';
import 'blueimp-canvas-to-blob';

/**
* @returns { int } Orientation of the image
*
* @param { File } file -- The `window.File` object representing the image
*/
export function getImageOrientation( file ) {
return new Promise( resolve => {
loadImage.parseMetaData( file, data => {
resolve( data.exif ? data.exif.get( 'Orientation' ) : -1 );
}, {
// Save on computation by disabling the following Exif properties
// (Although technically all Exif data is stored in the first 256 KiB,
// so it's really not that *big* of a deal)
disableExifThumbnail: true,
disableExifSub: true,
disableExifGps: true
} );
} );
}

/**
* Change the orientation of an image to the specified value
*
* @returns { string } Blob URL pointing to the re-oriented image
*
* @param { string } url -- The image URL
* @param { int } orientation -- Desired orientation
* @param { object } options -- List of options available here:
* https://github.com/blueimp/JavaScript-Load-Image#options
*/
export function changeImageOrientation( url, orientation, options = {} ) {
return new Promise( ( resolve, reject ) => {
loadImage(
url,
result => {
if ( 'error' === result.type ) {
reject( new Error( 'Unable to change image orientation' ) );
} else {
result.toBlob( blob => resolve( blob ) );
}
},
Object.assign( { orientation }, options )
);
} );
}

/**
* Fixes the image orientation to be the "up" position
*
* @returns { string } Blob URL pointing to the re-oriented image
*
* @param { object } file -- The image file
* @param { object } options -- List of options available here:
* https://github.com/blueimp/JavaScript-Load-Image#options
*/
export function fixImageOrientation( file, options = {} ) {
return getImageOrientation( file )
.then( orientation => {
// If the orientation is <= 1 (where 1 is "top", and anything less
// than that means there was no Exif data), then no further orientation
// changes are necessary.
if ( 1 >= orientation ) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if you were going for "Yoda" style here, but (a) this tends not to apply to greater/less than operators because they're difficult to read (reference) and (b) is optional for Calypso anyways (reference). I tend to use them myself, mostly for consistency when moving between WordPress PHP and JavaScript.

return loadImage.createObjectURL( file );
}

return changeImageOrientation( file, orientation, options )
.then( blob => loadImage.createObjectURL( blob ) )
.catch( () => loadImage.createObjectURL( file ) );
} );
}
Loading