File size: 18,771 Bytes
1e92f2d | 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 | import { PLAN_PREMIUM, getPlan } from '@automattic/calypso-products';
import page from '@automattic/calypso-router';
import { localizeUrl } from '@automattic/i18n-utils';
import { withMobileBreakpoint } from '@automattic/viewport-react';
import clsx from 'clsx';
import { localize } from 'i18n-calypso';
import { groupBy, isEmpty, map, size, values } from 'lodash';
import PropTypes from 'prop-types';
import { Component } from 'react';
import { connect } from 'react-redux';
import MediaListData from 'calypso/components/data/media-list-data';
import Notice from 'calypso/components/notice';
import NoticeAction from 'calypso/components/notice/notice-action';
import { withGooglePhotosPickerSession } from 'calypso/data/media/with-google-photos-picker-session';
import { gaRecordEvent } from 'calypso/lib/analytics/ga';
import TrackComponentView from 'calypso/lib/analytics/track-component-view';
import { recordTracksEvent } from 'calypso/lib/analytics/tracks';
import {
ValidationErrors as MediaValidationErrors,
MEDIA_IMAGE_RESIZER,
MEDIA_IMAGE_THUMBNAIL,
SCALE_TOUCH_GRID,
} from 'calypso/lib/media/constants';
import InlineConnection from 'calypso/sites/marketing/connections/inline-connection';
import { pauseGuidedTour, resumeGuidedTour } from 'calypso/state/guided-tours/actions';
import { getGuidedTourState } from 'calypso/state/guided-tours/selectors';
import { clearMediaErrors, changeMediaSource } from 'calypso/state/media/actions';
import { getPreference } from 'calypso/state/preferences/selectors';
import { canCurrentUser } from 'calypso/state/selectors/can-current-user';
import getMediaLibrarySelectedItems from 'calypso/state/selectors/get-media-library-selected-items';
import { deleteKeyringConnection } from 'calypso/state/sharing/keyring/actions';
import {
isKeyringConnectionsFetching,
getKeyringConnectionsByName,
} from 'calypso/state/sharing/keyring/selectors';
import { getSiteSlug, isJetpackSite } from 'calypso/state/sites/selectors';
import { getSelectedSiteId } from 'calypso/state/ui/selectors';
import MediaLibraryExternalHeader from './external-media-header';
import GooglePhotosAuthUpgrade from './google-photos-auth-upgrade';
import GooglePhotosPickerButton from './google-photos-picker-button';
import MediaLibraryHeader from './header';
import MediaLibraryList from './list';
import './content.scss';
const noop = () => {};
const first = ( arr ) => arr[ 0 ];
function getMediaScalePreference( state, isMobile ) {
const mediaScale = getPreference( state, 'mediaScale' );
// On mobile viewport, return the media scale value of 0.323 (3 columns per row)
// regardless of stored preference value, if it's not 1.
if ( isMobile && mediaScale !== 1 ) {
return SCALE_TOUCH_GRID;
}
// On non-mobile viewport, return the media scale value of 0.323 if the stored
// preference value is greater than 0.323.
if ( ! isMobile && mediaScale > SCALE_TOUCH_GRID ) {
return SCALE_TOUCH_GRID;
}
return mediaScale;
}
export class MediaLibraryContent extends Component {
static propTypes = {
site: PropTypes.object,
mediaValidationErrors: PropTypes.object,
filter: PropTypes.string,
filterRequiresUpgrade: PropTypes.bool,
search: PropTypes.string,
source: PropTypes.string,
onSourceChange: PropTypes.func,
containerWidth: PropTypes.number,
single: PropTypes.bool,
scrollable: PropTypes.bool,
onAddMedia: PropTypes.func,
onMediaScaleChange: PropTypes.func,
postId: PropTypes.number,
isConnected: PropTypes.bool,
isBreakpointActive: PropTypes.bool,
mediaScale: PropTypes.number,
};
static defaultProps = {
mediaValidationErrors: Object.freeze( {} ),
onAddMedia: noop,
source: '',
};
componentDidMount() {
if ( this.props.photosPickerApiEnabled ) {
! this.props?.photosPickerSession && this.props?.createPhotosPickerSession();
}
}
componentDidUpdate( prevProps ) {
if ( this.props.shouldPauseGuidedTour !== prevProps.shouldPauseGuidedTour ) {
this.props.toggleGuidedTour( this.props.shouldPauseGuidedTour );
}
if (
! this.hasGoogleExpired( prevProps ) &&
this.hasGoogleExpired( this.props ) &&
this.props.googleConnection
) {
// As soon as we detect Google has expired, remove the connection from the keyring so we
// are prompted to connect again
this.props.deleteKeyringConnection( this.props.googleConnection );
}
if (
! this.isGoogleConnectedAndVisible( prevProps ) &&
this.isGoogleConnectedAndVisible( this.props ) &&
this.hasGoogleExpired( this.props )
) {
// We have transitioned from an invalid Google status to a valid one - migration is complete
// Force a refresh of the list - this won't happen automatically as we've cached our previous failed query.
this.props.changeMediaSource( this.props.site.ID );
}
}
isGoogleConnectedAndVisible( props ) {
const { googleConnection, source } = props;
if ( source === 'google_photos' && googleConnection && googleConnection.status === 'ok' ) {
return true;
}
return false;
}
hasGoogleExpired( props ) {
const { mediaValidationErrorTypes, source } = props;
if (
source === 'google_photos' &&
mediaValidationErrorTypes.indexOf( MediaValidationErrors.SERVICE_AUTH_FAILED ) !== -1
) {
return true;
}
return false;
}
hasGoogleInvalidConnection( props ) {
const { googleConnection, source } = props;
return source === 'google_photos' && googleConnection && googleConnection.status === 'invalid';
}
renderErrors() {
const { isJetpack, mediaValidationErrorTypes, site, siteSlug, translate } = this.props;
return map( groupBy( mediaValidationErrorTypes ), ( occurrences, errorType ) => {
let message;
let onDismiss;
const i18nOptions = {
count: occurrences.length,
args: {
occurrences: occurrences.length,
planName: getPlan( PLAN_PREMIUM )?.getTitle(),
},
};
if ( site ) {
onDismiss = () => this.props.clearMediaErrors( site.ID, errorType );
}
let status = 'is-error';
let upgradeNudgeName = undefined;
let upgradeNudgeFeature = undefined;
let actionText = undefined;
let actionLink = undefined;
let tryAgain = false;
let externalAction = false;
switch ( errorType ) {
case MediaValidationErrors.FILE_TYPE_NOT_IN_PLAN:
status = 'is-warning';
upgradeNudgeName = 'plan-media-storage-error-video';
upgradeNudgeFeature = 'video-upload';
message = translate(
'%(occurrences)d file could not be uploaded because your site does not support video files. Upgrade to the %(planName)s plan for video support.',
'%(occurrences)d files could not be uploaded because your site does not support video files. Upgrade to the %(planName)s plan for video support.',
i18nOptions
);
break;
case MediaValidationErrors.FILE_TYPE_UNSUPPORTED:
message = translate(
'%(occurrences)d file could not be uploaded because the file type is not supported.',
'%(occurrences)d files could not be uploaded because their file types are unsupported.',
i18nOptions
);
actionText = translate( 'See supported file types' );
actionLink = localizeUrl( 'https://wordpress.com/support/accepted-filetypes/' );
externalAction = true;
break;
case MediaValidationErrors.UPLOAD_VIA_URL_404:
message = translate(
'%(occurrences)d file could not be uploaded because no image exists at the specified URL.',
'%(occurrences)d files could not be uploaded because no images exist at the specified URLs',
i18nOptions
);
break;
case MediaValidationErrors.EXCEEDS_MAX_UPLOAD_SIZE:
message = translate(
'%(occurrences)d file could not be uploaded because it exceeds the maximum upload size.',
'%(occurrences)d files could not be uploaded because they exceed the maximum upload size.',
i18nOptions
);
break;
case MediaValidationErrors.NOT_ENOUGH_SPACE:
upgradeNudgeName = 'plan-media-storage-error';
upgradeNudgeFeature = 'extra-storage';
message = translate(
'%(occurrences)d file could not be uploaded because there is not enough space left.',
'%(occurrences)d files could not be uploaded because there is not enough space left.',
i18nOptions
);
break;
case MediaValidationErrors.EXCEEDS_PLAN_STORAGE_LIMIT:
if ( isJetpack ) {
actionText = translate( 'Upgrade Plan' );
actionLink = `/checkout/${ siteSlug }/jetpack_videopress`;
externalAction = true;
} else {
upgradeNudgeName = 'plan-media-storage-error';
upgradeNudgeFeature = 'extra-storage';
}
message = translate(
'%(occurrences)d file could not be uploaded because you have reached your plan storage limit.',
'%(occurrences)d files could not be uploaded because you have reached your plan storage limit.',
i18nOptions
);
break;
case MediaValidationErrors.SERVICE_AUTH_FAILED:
message = this.getAuthFailMessageForSource();
status = 'is-warning';
tryAgain = false;
break;
case MediaValidationErrors.SERVICE_FAILED:
message = translate( 'We are unable to retrieve your full media library.' );
tryAgain = true;
break;
case MediaValidationErrors.SERVICE_UNAVAILABLE:
message = this.getServiceUnavailableMessageForSource();
tryAgain = true;
break;
default:
message = translate(
'%(occurrences)d file could not be uploaded because an error occurred while uploading.',
'%(occurrences)d files could not be uploaded because errors occurred while uploading.',
i18nOptions
);
break;
}
return (
<Notice key={ errorType } status={ status } text={ message } onDismissClick={ onDismiss }>
{ this.renderNoticeAction( upgradeNudgeName, upgradeNudgeFeature ) }
{ actionText && (
<NoticeAction href={ actionLink } external={ externalAction }>
{ actionText }
</NoticeAction>
) }
{ tryAgain && this.renderTryAgain() }
</Notice>
);
} );
}
getAuthFailMessageForSource() {
const { translate, source } = this.props;
if ( source === 'google_photos' ) {
return translate(
'We are moving to a new and faster Photos from Google service. Please reconnect to continue accessing your photos.'
);
}
// Generic message. Nothing should use this, but just in case.
return translate( 'Your service has been disconnected. Please reconnect to continue.' );
}
getServiceUnavailableMessageForSource() {
const { translate, source } = this.props;
if ( source === 'pexels' ) {
return translate(
'We were unable to connect to the Pexels service. Please try again later.'
);
}
if ( source === 'openverse' ) {
return translate( 'We were unable to connect to Openverse. Please try again later.' );
}
return translate(
'We were unable to connect to the external service. Please try again later.'
);
}
renderTryAgain() {
return (
<NoticeAction onClick={ this.retryList }>{ this.props.translate( 'Retry' ) }</NoticeAction>
);
}
retryList = () => {
this.props.changeMediaSource( this.props.site.ID );
};
renderNoticeAction( upgradeNudgeName, upgradeNudgeFeature ) {
if ( ! upgradeNudgeName ) {
return null;
}
const eventName = 'calypso_upgrade_nudge_impression';
const eventProperties = {
cta_name: upgradeNudgeName,
cta_feature: upgradeNudgeFeature,
};
return (
<NoticeAction
external
href={
upgradeNudgeFeature
? `/plans/compare/${ this.props.siteSlug }?feature=${ upgradeNudgeFeature }`
: `/plans/${ this.props.siteSlug }`
}
onClick={ this.recordPlansNavigation.bind(
this,
'calypso_upgrade_nudge_cta_click',
eventProperties
) }
>
{ this.props.translate( 'Upgrade Plan' ) }
<TrackComponentView eventName={ eventName } eventProperties={ eventProperties } />
</NoticeAction>
);
}
recordPlansNavigation( tracksEvent, tracksData ) {
gaRecordEvent( 'Media', 'Clicked Upload Error Action' );
recordTracksEvent( tracksEvent, tracksData );
}
goToSharing = ( ev ) => {
ev.preventDefault();
page( `/marketing/connections/${ this.props.site.slug }` );
};
renderGooglePhotosConnect() {
const { translate } = this.props;
const connectMessage = translate(
'To get started, connect your site to your Google Photos library.'
);
return (
<div className="media-library__connect-message">
<p>
<img
src="/calypso/images/sharing/google-photos-logo-text.svg?v=20241124"
width="400"
alt={ translate( 'Google Photos' ) }
/>
</p>
<p>{ connectMessage }</p>
<InlineConnection serviceName="google_photos" />
</div>
);
}
renderConnectExternalMedia() {
const { source } = this.props;
switch ( source ) {
case 'google_photos':
return this.renderGooglePhotosConnect();
}
return null;
}
getThumbnailType() {
return this.props.source !== '' ? MEDIA_IMAGE_THUMBNAIL : MEDIA_IMAGE_RESIZER;
}
needsToBeConnected() {
const { source, isConnected } = this.props;
// We're on an external service and not connected - need connecting
if ( source !== '' && ! isConnected ) {
return true;
}
// We're think we're connected to an external service but are really expired
if ( source !== '' && isConnected && this.hasGoogleExpired( this.props ) ) {
return true;
}
// We're on an internal service, or an external service that is connected and not expired
return false;
}
renderMediaList() {
if ( ! this.props.site || ( this.props.isRequesting && ! this.hasRequested ) ) {
this.hasRequested = true; // We only want to do this once
return (
<MediaLibraryList
key="list-loading"
filterRequiresUpgrade={ this.props.filterRequiresUpgrade }
mediaScale={ this.props.mediaScale }
/>
);
}
if ( this.hasGoogleInvalidConnection( this.props ) ) {
return <GooglePhotosAuthUpgrade connection={ this.props.googleConnection } />;
}
if ( this.needsToBeConnected() ) {
return this.renderConnectExternalMedia();
}
if (
this.props.photosPickerApiEnabled &&
'google_photos' === this.props.source &&
! this.props.photosPickerSession?.mediaItemsSet
) {
return <GooglePhotosPickerButton />;
}
const listKey = [
'list',
this.props.site.ID,
this.props.search,
this.props.filter,
this.props.source,
].join( '-' );
return (
<MediaListData
siteId={ this.props.site.ID }
postId={ this.props.postId }
filter={ this.props.filter }
search={ this.props.search }
source={ this.props.source }
>
<MediaLibraryList
key={ listKey }
site={ this.props.site }
filter={ this.props.filter }
filterRequiresUpgrade={ this.props.filterRequiresUpgrade }
search={ this.props.search }
containerWidth={ this.props.containerWidth }
thumbnailType={ this.getThumbnailType() }
single={ this.props.single }
scrollable={ this.props.scrollable }
onSourceChange={ this.props.onSourceChange }
mediaScale={ this.props.mediaScale }
/>
</MediaListData>
);
}
renderHeader() {
if ( this.needsToBeConnected() ) {
return null;
}
if ( this.props.source !== '' ) {
// Hide the header until we have the media items set from Google Photos
if (
'google_photos' === this.props.source &&
this.props.photosPickerApiEnabled &&
! this.props.photosPickerSession?.mediaItemsSet
) {
return null;
}
const hasRefreshButton =
'pexels' !== this.props.source &&
'openverse' !== this.props.source &&
! this.props.photosPickerApiEnabled;
return (
<MediaLibraryExternalHeader
onMediaScaleChange={ this.props.onMediaScaleChange }
site={ this.props.site }
visible={ ! this.props.isRequesting }
canCopy={ this.props.postId === undefined }
postId={ this.props.postId }
source={ this.props.source }
onSourceChange={ this.props.onSourceChange }
selectedItems={ this.props.selectedItems }
sticky={ ! this.props.scrollable }
hasAttribution={ 'pexels' === this.props.source }
hasRefreshButton={ hasRefreshButton }
mediaScale={ this.props.mediaScale }
photosPickerApiEnabled={ this.props.photosPickerApiEnabled }
photosPickerSession={ this.props.photosPickerSession }
createPhotosPickerSession={ this.props.createPhotosPickerSession }
deletePhotosPickerSession={ this.props.deletePhotosPickerSession }
isCreatingPhotosPickerSession={ this.props.isCreatingPhotosPickerSession }
/>
);
}
if ( ! this.props.filterRequiresUpgrade ) {
return (
<MediaLibraryHeader
site={ this.props.site }
filter={ this.props.filter }
onMediaScaleChange={ this.props.onMediaScaleChange }
onAddMedia={ this.props.onAddMedia }
onAddAndEditImage={ this.props.onAddAndEditImage }
selectedItems={ this.props.selectedItems }
onViewDetails={ this.props.onViewDetails }
onDeleteItem={ this.props.onDeleteItem }
sticky={ ! this.props.scrollable }
mediaScale={ this.props.mediaScale }
/>
);
}
return null;
}
render() {
const classNames = clsx( 'media-library__content', {
'has-no-upload-button': ! this.props.displayUploadMediaButton,
} );
return (
<div className={ classNames }>
{ this.renderHeader() }
{ this.renderErrors() }
{ this.renderMediaList() }
</div>
);
}
}
export default withMobileBreakpoint(
connect(
( state, ownProps ) => {
const guidedTourState = getGuidedTourState( state );
const selectedSiteId = getSelectedSiteId( state );
const mediaValidationErrorTypes = values( ownProps.mediaValidationErrors ).map( first );
const shouldPauseGuidedTour =
! isEmpty( guidedTourState.tour ) && 0 < size( mediaValidationErrorTypes );
const googleConnection = getKeyringConnectionsByName( state, 'google_photos' );
return {
siteSlug: ownProps.site ? getSiteSlug( state, ownProps.site.ID ) : '',
isJetpack: isJetpackSite( state, selectedSiteId ),
isRequesting: isKeyringConnectionsFetching( state ),
displayUploadMediaButton: canCurrentUser( state, ownProps.site.ID, 'publish_posts' ),
mediaValidationErrorTypes,
shouldPauseGuidedTour,
googleConnection: googleConnection.length === 1 ? googleConnection[ 0 ] : null, // There can be only one
selectedItems: getMediaLibrarySelectedItems( state, ownProps.site?.ID ),
mediaScale: getMediaScalePreference( state, ownProps.isBreakpointActive ),
};
},
{
toggleGuidedTour: ( shouldPause ) => ( dispatch ) => {
dispatch( shouldPause ? pauseGuidedTour() : resumeGuidedTour() );
},
deleteKeyringConnection,
clearMediaErrors,
changeMediaSource,
}
)( withGooglePhotosPickerSession( localize( MediaLibraryContent ) ) )
);
|