Skip to content

Commit

Permalink
Implement media import via URL -- list view
Browse files Browse the repository at this point in the history
  • Loading branch information
fushar committed Jan 20, 2025
1 parent 6cab52d commit 24a4df4
Show file tree
Hide file tree
Showing 7 changed files with 206 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: minor
Type: added

Implement media import via URL
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ public static function load_wpcom_user_features() {
require_once __DIR__ . '/features/wpcom-dashboard-widgets/wpcom-dashboard-widgets.php';
require_once __DIR__ . '/features/wpcom-locale/sync-locale-from-calypso-to-atomic.php';
require_once __DIR__ . '/features/wpcom-media/wpcom-external-media-import.php';
require_once __DIR__ . '/features/wpcom-media/wpcom-media-url-import.php';
require_once __DIR__ . '/features/wpcom-plugins/wpcom-plugins.php';
require_once __DIR__ . '/features/wpcom-profile-settings/profile-settings-link-to-wpcom.php';
require_once __DIR__ . '/features/wpcom-profile-settings/profile-settings-notices.php';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { __ } from '@wordpress/i18n';
import clsx from 'clsx';
import { useState } from 'react';

import './style.scss';

const WpcomMediaUrlImportForm = ( { ajaxUrl, action, nonce } ) => {
const [ url, setUrl ] = useState( '' );

const [ show, setShow ] = useState( false );
const [ isUploading, setIsUploading ] = useState( false );
const [ isUploaded, setIsUploaded ] = useState( false );

const handleUrlChange = e => {
setUrl( e.target.value );
};

const handleSubmit = async e => {
if ( isUploading ) {
return false;
}
try {
new URL( url ); // eslint-disable-line no-new
} catch {
return false;
}
e.preventDefault();

const formData = new FormData();
formData.append( 'action', action );
formData.append( 'image_url', url );
formData.append( '_ajax_nonce', nonce );

setIsUploading( true );

const response = await fetch( ajaxUrl, {
method: 'POST',
body: formData,
} );

const { success, data } = await response.json();

if ( success ) {
window.wp.media.model.Attachment.get( data.attachment_id ).fetch( {
success: function ( attachment ) {
window.wp.media.frame.content.get().collection.add( attachment );

setIsUploading( false );

setIsUploaded( true );
setTimeout( () => {
setIsUploaded( false );
setUrl( '' );
}, 2000 );
},
} );
} else {
setIsUploading( false );
// window.alert( data[ 0 ].message );
}

return false;
};

const renderLink = () => {
return (
<a href="#" onClick={ () => setShow( true ) }>
{ __( 'Upload from URL', 'jetpack-mu-wpcom' ) }
</a>
);
};

const renderForm = () => {
let buttonText = __( 'Upload', 'jetpack-mu-wpcom' );
if ( isUploaded ) {
buttonText = __( 'Uploaded!', 'jetpack-mu-wpcom' );
} else if ( isUploading ) {
buttonText = __( 'Uploading…', 'jetpack-mu-wpcom' );
}

return (
<form onSubmit="return false;">
<input
type="url"
value={ url }
onChange={ handleUrlChange }
placeholder={ __( 'Enter media URL', 'jetpack-mu-wpcom' ) }
required
readOnly={ isUploading || isUploaded }
/>
<button
className={ clsx( 'button', 'button-primary', {
'updating-message': isUploading,
'updated-message': isUploaded,
} ) }
onClick={ handleSubmit }
readOnly={ isUploading }
disabled={ isUploaded }
>
{ buttonText }
</button>
</form>
);
};

return <div className="wpcom-media-url-import-form">{ show ? renderForm() : renderLink() }</div>;
};

export default WpcomMediaUrlImportForm;
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.wpcom-media-url-import-form {
input {
width: 100%;
max-width: 600px;
margin-bottom: 5px;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import WpcomMediaUrlImportForm from './wpcom-media-url-import-form';

const props = typeof window === 'object' ? window.JETPACK_MU_WPCOM_MEDIA_URL_IMPORT : {};

document.addEventListener( 'DOMContentLoaded', function () {
const observer = new MutationObserver( mutations => {
mutations.forEach( mutation => {
if ( mutation.addedNodes.length > 0 ) {
const container = document.getElementById( 'wpcom-media-url-import' );
if ( container ) {
const root = ReactDOM.createRoot( container );
root.render( <WpcomMediaUrlImportForm { ...props } /> );
observer.disconnect();
}
}
} );
} );
observer.observe( document.body, { childList: true, subtree: true } );
} );
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

Check failure on line 1 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Class file names should be based on the class name with "class-" prepended. Expected class-dummyendpoint.php, but found wpcom-media-url-import.php. (WordPress.Files.FileName.InvalidClassFileName)
/**
* WordPress.com media URL import functionality.
*
*
* @package automattic/jetpack-mu-wpcom

Check failure on line 6 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

There must be exactly one blank line before the tags in a doc comment (Generic.Commenting.DocComment.SpacingBeforeTags)
*/

use Automattic\Jetpack\Connection\Manager as Jetpack_Connection;

Check warning on line 9 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Use statements are not alphabetically sorted (MediaWiki.Classes.UnsortedUseStatements.UnsortedUse)

Check warning on line 9 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Unused use statement "Jetpack_Connection" (MediaWiki.Classes.UnusedUseStatement.UnusedUse)

Check failure on line 9 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / Static analysis

NOOPError PhanUnreferencedUseNormal Possibly zero references to use statement for classlike/namespace Jetpack_Connection (\Automattic\Jetpack\Connection\Manager)
use Automattic\Jetpack\Connection\Client;

Check warning on line 10 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Unused use statement "Client" (MediaWiki.Classes.UnusedUseStatement.UnusedUse)

Check failure on line 10 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / Static analysis

NOOPError PhanUnreferencedUseNormal Possibly zero references to use statement for classlike/namespace Client (\Automattic\Jetpack\Connection\Client)

function wpcom_media_url_import() {

Check failure on line 12 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Missing doc comment for function wpcom_media_url_import() (Squiz.Commenting.FunctionComment.Missing)
?>

Check failure on line 13 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Tabs must be used to indent lines; spaces are not allowed (Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed)
<div id="wpcom-media-url-import"></div>
<?php

Check failure on line 15 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Tabs must be used to indent lines; spaces are not allowed (Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed)
}
add_action('post-plupload-upload-ui', 'wpcom_media_url_import', 20 );

Check failure on line 17 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Expected 1 spaces after opening parenthesis; 0 found (PEAR.Functions.FunctionCallSignature.SpaceAfterOpenBracket)

/**
* Enqueue the assets of the wpcom media URL import.
*/
function enqueue_wpcom_media_url_import() {
$handle = jetpack_mu_wpcom_enqueue_assets( 'wpcom-media-url-import', array( 'js', 'css' ) );

$data = wp_json_encode(
array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'action' => 'wpcom_media_url_import',
'nonce' => wp_create_nonce('wpcom_media_url_import'),

Check failure on line 29 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Expected 1 spaces after opening parenthesis; 0 found (PEAR.Functions.FunctionCallSignature.SpaceAfterOpenBracket)

Check failure on line 29 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Expected 1 spaces before closing parenthesis; 0 found (PEAR.Functions.FunctionCallSignature.SpaceBeforeCloseBracket)
)
);

wp_add_inline_script(
$handle,
"window.JETPACK_MU_WPCOM_MEDIA_URL_IMPORT = $data;",
'before'
);
}
add_action('post-plupload-upload-ui', 'enqueue_wpcom_media_url_import' );

Check failure on line 39 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Expected 1 spaces after opening parenthesis; 0 found (PEAR.Functions.FunctionCallSignature.SpaceAfterOpenBracket)

require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php';
class DummyEndpoint extends WPCOM_JSON_API_Endpoint {

Check failure on line 42 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

A file should either contain function declarations or OO structure declarations, but not both. Found 3 function declaration(s) and 1 OO structure declaration(s). The first function declaration was found on line 12; the first OO declaration was found on line 42 (Universal.Files.SeparateFunctionsFromOO.Mixed)

Check failure on line 42 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / Static analysis

UndefError PhanUndeclaredExtendedClass Class extends undeclared class \WPCOM_JSON_API_Endpoint
public function callback( $path = '', $blog_id = 0 ) {}

Check warning on line 43 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Unused function parameter $path. (VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable)

Check warning on line 43 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Unused function parameter $blog_id. (VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable)
}

function wpcom_handle_media_url_import() {
check_ajax_referer( 'wpcom_media_url_import' );

$image_url = esc_url_raw( $_POST['image_url'] );

$endpoint = new DummyEndpoint( array() );

Check failure on line 51 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / Static analysis

ParamError PhanParamTooMany Call with 1 arg(s) to \DummyEndpoint::__construct() which only takes 0 arg(s) defined at src/features/wpcom-media/wpcom-media-url-import.php:42
$result = $endpoint->handle_media_creation_v1_1( array(), array( $image_url ) );

Check warning on line 52 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / PHP Code Sniffer (non-excluded files only)

Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space (Generic.Formatting.MultipleStatementAlignment.NotSameWarning)

Check failure on line 52 in projects/packages/jetpack-mu-wpcom/src/features/wpcom-media/wpcom-media-url-import.php

View workflow job for this annotation

GitHub Actions / Static analysis

UndefError PhanUndeclaredMethod Call to undeclared method \DummyEndpoint::handle_media_creation_v1_1

if ( count( $result['media_ids'] ) > 0 ) {
$attachment_id = $result['media_ids'][0];
return wp_send_json_success( array( 'attachment_id' => $attachment_id ) );
}
if ( count( $result['errors'] ) > 0 ) {
$error = $result['errors'][0];
return wp_send_json_error( new WP_Error( $error['error'], $error['message'] ) );
}
}
add_action('wp_ajax_wpcom_media_url_import', 'wpcom_handle_media_url_import');
1 change: 1 addition & 0 deletions projects/packages/jetpack-mu-wpcom/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ module.exports = [
'./src/features/wpcom-documentation-links/wpcom-documentation-links.ts',
'wpcom-external-media-import-page':
'./src/features/wpcom-media/wpcom-external-media-import.js',
'wpcom-media-url-import': './src/features/wpcom-media/wpcom-media-url-import.js',
'wpcom-plugins-banner': './src/features/wpcom-plugins/js/banner.js',
'wpcom-plugins-banner-style': './src/features/wpcom-plugins/css/banner.css',
'wpcom-profile-settings-link-to-wpcom':
Expand Down

0 comments on commit 24a4df4

Please sign in to comment.