Skip to content
Merged
7 changes: 6 additions & 1 deletion admin/class-rtgodam-retranscodemedia.php
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,15 @@ public function admin_enqueues( $hook_suffix ) {
*/
public function add_media_row_action( $actions, $post ) {

// Documents are included so files already in the library — which predate document
// support and so were never sent to GoDAM Central — can have a preview generated
// without re-uploading them. Tested against the attachment rather than its MIME alone,
// so the action is not offered on the .srt/.asc/.c/.h files that share text/plain and
// have no conversion path.
if ( (
'audio/' !== substr( $post->post_mime_type, 0, 6 ) &&
'video/' !== substr( $post->post_mime_type, 0, 6 ) &&
'application/pdf' !== $post->post_mime_type
! rtgodam_is_supported_document_attachment( $post->ID )
) ||
// Safe fallback via filter; PHPCS can't resolve dynamic capability.
// phpcs:ignore WordPress.WP.Capabilities.Undetermined
Expand Down
70 changes: 66 additions & 4 deletions admin/class-rtgodam-transcoder-handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,20 @@ class RTGODAM_Transcoder_Handler {
*/
public $other_extensions = ',pdf';

/**
* Document extensions with comma separated.
*
* Office / OpenDocument / plain-text formats, which GoDAM Central converts to a preview
* PDF. They are kept apart from $other_extensions because those map the extension
* straight onto the job type ('pdf' => job_type 'pdf'), whereas every format here shares
* the single job type 'document'.
*
* @since 2.2.0
* @access public
* @var string $document_extensions Document extensions with comma separated.
*/
public $document_extensions = ',docx,doc,xlsx,xls,pptx,ppt,odt,ods,odp,txt,csv';
Comment thread
KMchaudhary marked this conversation as resolved.
Resolved

/**
* Allowed mimetypes.
*
Expand All @@ -101,7 +115,6 @@ class RTGODAM_Transcoder_Handler {
*/
public $allowed_mimetypes = array(
'application/ogg',
'application/pdf',
);

/**
Expand All @@ -125,6 +138,21 @@ public function __construct( $no_init = false ) {
$this->api_key = get_option( 'rtgodam-api-key' );
$this->easydam_settings = get_option( 'rtgodam-settings', array() );

/*
* Document MIME types come from the shared helper rather than being duplicated in
* the property default, so the transcoder and the Document block can never disagree
* about which formats are supported. Anything not listed here is dropped by the
* mime gate in wp_media_transcoding() and never reaches GoDAM Central.
*/
$this->allowed_mimetypes = array_values(
array_unique(
array_merge(
$this->allowed_mimetypes,
array_keys( rtgodam_get_supported_document_types() )
)
)
);

$default_settings = array(
'video' => array(
'adaptive_bitrate' => false,
Expand Down Expand Up @@ -308,11 +336,31 @@ public function wp_media_transcoding( $wp_metadata, $attachment_id, $autoformat

$metadata = $wp_metadata;

$type_arry = explode( '.', $url );
$type = strtolower( $type_arry[ count( $type_arry ) - 1 ] );
$extension = pathinfo( $path, PATHINFO_EXTENSION );
$type_arry = explode( '.', $url );
$type = strtolower( $type_arry[ count( $type_arry ) - 1 ] );
// Lowercased because the extension lists below are all lowercase: an upload named
// REPORT.PDF would otherwise miss its branch and be sent as a video stream job.
$extension = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) );
$not_allowed_type = array();

/*
* A document MIME type is not sufficient on its own, because several of them are
* shared with formats that have no conversion path. WordPress maps .srt, .asc, .c,
* .cc and .h to text/plain exactly as it maps .txt, so without this a subtitle file
* would satisfy the MIME gate below, find no matching extension in any of the job
* type branches, and fall through to the default 'stream' — dispatching every
* caption upload to GoDAM Central as a video transcode that can only fail.
*
* Checked here rather than inside the gate so audio/video and application/ogg keep
* matching on MIME alone, exactly as they did before documents were supported.
*/
if (
array_key_exists( $metadata['mime_type'], rtgodam_get_supported_document_types() )
&& ! in_array( $extension, rtgodam_get_supported_document_extensions(), true )
) {
return $wp_metadata;
}

if ( (
preg_match( '/video|audio/i', $metadata['mime_type'], $type_array ) ||
in_array( $metadata['mime_type'], $this->allowed_mimetypes, true )
Expand All @@ -334,6 +382,20 @@ public function wp_media_transcoding( $wp_metadata, $attachment_id, $autoformat
$job_type = $extension;
$autoformat = $extension;
$options_video_thumb = 0;
} elseif ( in_array( $extension, explode( ',', $this->document_extensions ), true ) ) {
/*
* Office / OpenDocument / text files all share one job type. GoDAM Central
* converts them to a preview PDF (job_type 'document' routes to its document
* queue), and returns that PDF separately as `preview_pdf_url` — `download_url`
* stays the original file. `formats` names the conversion target rather than
* the source extension, unlike the 'pdf' branch above where the two coincide.
*
* Thumbnails are rasterised from page 0 of the preview by Central itself, so
* no thumbnail count is requested here.
*/
$job_type = 'document';
$autoformat = 'pdf';
$options_video_thumb = 0;
}

/** Figure out who is requesting this job */
Expand Down
69 changes: 67 additions & 2 deletions admin/class-rtgodam-transcoder-rest-routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,33 @@ public function register_routes() {
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
),

/*
* Machine-readable failure reason (DOCUMENT_TOO_LARGE,
* DOCUMENT_UNSUPPORTED_TYPE, DOCUMENT_PROCESSING_FAILED, ...). Unlike
* error_msg it is safe to surface, since it carries no file paths or
* internal detail.
*/
'error_code' => array(
'required' => false,
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
),

/*
* The converted preview PDF for a `document` job. Read from the top-level
* field rather than from files['preview_pdf']: the callback is form-encoded,
* and a nested array does not survive that encoding reliably.
*
* Absent — not empty — for job types that have no conversion step, and
* empty for a password protected document, which Central stores and
* reports as Transcoded but deliberately generates no preview for.
*/
'preview_pdf_url' => array(
'required' => false,
'type' => 'string',
'sanitize_callback' => 'esc_url_raw',
),
'job_manager_form' => array(
'required' => false,
'type' => 'string',
Expand Down Expand Up @@ -227,6 +254,7 @@ public function handle_callback( WP_REST_Request $request ) {
$job_id = $request->get_param( 'job_id' );
$file_status = $request->get_param( 'file_status' );
$error_msg = $request->get_param( 'error_msg' );
$error_code = $request->get_param( 'error_code' );
$job_for = $request->get_param( 'job_for' );
$thumbnail = $request->get_param( 'thumbnail' );
$format = $request->get_param( 'format' );
Expand All @@ -244,6 +272,16 @@ public function handle_callback( WP_REST_Request $request ) {
if ( ! empty( $error_msg ) ) {
update_post_meta( $failed_id, 'rtgodam_transcoding_error_msg', sanitize_textarea_field( $error_msg ) );
}

/*
* The status callback stores this too, but a job that fails outright may
* never send one, and the code is what distinguishes a retryable failure
* (DOCUMENT_PROCESSING_FAILED) from a permanent one (DOCUMENT_TOO_LARGE,
* DOCUMENT_UNSUPPORTED_TYPE) that should not offer a retry.
*/
if ( ! empty( $error_code ) ) {
update_post_meta( $failed_id, 'rtgodam_transcoding_error_code', sanitize_text_field( $error_code ) );
}
}
}
return new WP_REST_Response(
Expand Down Expand Up @@ -306,11 +344,38 @@ public function handle_callback( WP_REST_Request $request ) {
}
}

if ( 'pdf' === $job_type && isset( $post_array['download_url'] ) && ! empty( $post_array['download_url'] ) ) {
// Setting the transcoded PDF URL.
/*
* Documents. `pdf` is a file that needed no conversion; `document` is an
* Office / OpenDocument / text file that GoDAM Central rendered to a preview
* PDF. For both, `download_url` is the file the author uploaded, on the CDN.
*
* The two URLs are NOT interchangeable for a `document`: only the preview may
* be rendered, and only the original may be offered as a download. Somebody
* who uploads report.xlsx and downloads preview.pdf will think something broke.
*/
if ( in_array( $job_type, array( 'pdf', 'document' ), true ) && ! empty( $post_array['download_url'] ) ) {
update_post_meta( $attachment_id, 'rtgodam_transcoded_url', esc_url_raw( $post_array['download_url'] ) );
}

if ( 'document' === $job_type ) {
if ( ! empty( $post_array['preview_pdf_url'] ) ) {
update_post_meta( $attachment_id, 'rtgodam_preview_pdf_url', esc_url_raw( $post_array['preview_pdf_url'] ) );
} else {
Comment on lines +360 to +363
/*
* No preview: the document is password protected, so Central stored it
* as-is and generated nothing to render. Deleting rather than skipping
* matters — a retranscode or in-place replace reuses the same job row,
* and leaving the key alone would keep serving the *previous* render's
* preview for a file that no longer has one.
*/
delete_post_meta( $attachment_id, 'rtgodam_preview_pdf_url' );
}
} elseif ( 'pdf' === $job_type && ! empty( $post_array['download_url'] ) ) {
// A PDF is its own preview, so both keys point at the same file. Storing it
// here as well means every reader has a single key to consult.
update_post_meta( $attachment_id, 'rtgodam_preview_pdf_url', esc_url_raw( $post_array['download_url'] ) );
}

if ( 'image' === $job_type && isset( $post_array['download_url'] ) && ! empty( $post_array['download_url'] ) ) {
// Setting the transcoded Image URL.
update_post_meta( $attachment_id, 'rtgodam_transcoded_url', esc_url_raw( $post_array['download_url'] ) );
Expand Down
4 changes: 3 additions & 1 deletion admin/godam-transcoder-actions.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ function rtgodam_add_transcoded_url_field( $form_fields, $post ) {
// Check if attachment is of type video.
$mime_type = get_post_mime_type( $post->ID );

// The document test goes through the attachment, not the MIME alone: text/plain also
// covers .srt/.asc/.c/.h, which are never transcoded and so have no CDN URL to show.
$is_allowed = (
str_starts_with( $mime_type, 'video/' ) ||
str_starts_with( $mime_type, 'audio/' ) ||
str_starts_with( $mime_type, 'image/' ) ||
'application/pdf' === $mime_type
rtgodam_is_supported_document_attachment( $post->ID )
);

if ( ! $is_allowed ) {
Expand Down
4 changes: 2 additions & 2 deletions assets/src/blocks/godam-pdf/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"name": "godam/pdf",
"title": "Document",
"category": "media",
"description": "Embed a PDF file with preview.",
"keywords": [ "document", "pdf", "file", "preview", "godam" ],
"description": "Embed a document with a preview. Supports PDF, Word, Excel, PowerPoint, OpenDocument, TXT and CSV.",
"keywords": [ "document", "pdf", "doc", "docx", "word", "excel", "xlsx", "powerpoint", "pptx", "spreadsheet", "csv", "file", "preview", "godam" ],
"textdomain": "godam",
"attributes": {
"blob": {
Expand Down
117 changes: 117 additions & 0 deletions assets/src/blocks/godam-pdf/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/**
* Document formats the Document block accepts.
*
* Mirror of rtgodam_get_supported_document_types() in inc/helpers/custom-functions.php,
* which is the source of truth. tests/php/DocumentSupportTest.php parses this file and
* asserts the two lists stay identical, so edit both together.
*
* Everything except PDF is converted to a preview PDF by GoDAM Central, so the block only
* ever renders a PDF — but the media library has to accept the original upload first.
*/
export const SUPPORTED_DOCUMENT_TYPES = {
'application/pdf': 'pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
'application/msword': 'doc',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
'application/vnd.ms-excel': 'xls',
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
'application/vnd.ms-powerpoint': 'ppt',
'application/vnd.oasis.opendocument.text': 'odt',
'application/vnd.oasis.opendocument.spreadsheet': 'ods',
'application/vnd.oasis.opendocument.presentation': 'odp',
'text/plain': 'txt',
'text/csv': 'csv',
// Some servers report .csv as application/csv; Central accepts both.
'application/csv': 'csv',
};

/**
* MIME types, for MediaUpload's `allowedTypes`.
*/
export const ALLOWED_MEDIA_TYPES = Object.keys( SUPPORTED_DOCUMENT_TYPES );

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

ALLOWED_MEDIA_TYPES includes text/plain, and it is used as allowedTypes / library.type for every document picker (block, Elementor, WPBakery). WordPress maps .srt, .asc, .c, .cc, .h to text/plain too, so those files appear as selectable in the library picker even though they have no conversion path.

The upload dialog is limited by extension via DOCUMENT_ACCEPT, and the transcoder guards by extension (rtgodam_is_supported_document_attachment), but library selection filters by MIME. So a user can pick an existing .srt/.c/.h, isSupportedDocument() accepts it on MIME, and the block then only ever shows the 'no preview available' panel.

Worth deciding whether that is acceptable, or whether the picker / isSupportedDocument() should also apply the extension gate so these text/plain lookalikes are not offered as documents.


/**
* Transcoding statuses that mean a job is genuinely in flight.
*
* Lowercased mirror of the $status_messages map in inc/classes/rest-api/class-transcoding.php
* — the only enumeration of what GoDAM Central's status_callback sends — minus the terminal
* 'Transcoded'. 'Queued' is also written locally the moment Central accepts a job, in
* RTGODAM_Transcoder_Handler::wp_media_transcoding().
*
* Deliberately an allow-list. Central's value is stored verbatim with no enum or validation,
* so treating everything else as "still working" would leave a document that was never
* dispatched (no API key) promising a preview forever. An unrecognised status therefore falls
* through to the download-only panel — if Central adds a stage, add it here.
*
* Statuses are lowercased before comparison because casing is mixed: Central and
* wp_media_transcoding() use Title Case ('Queued', 'Transcoding'), while plugin-authored
* values are lowercase ('failed', 'blocked', 'not_started', 'transcoded').
*/
export const IN_PROGRESS_TRANSCODING_STATUSES = [
'queued',
'downloading',
'downloaded',
'transcoding',
];

/**
* Distinct file extensions, without the leading dot.
*/
export const SUPPORTED_DOCUMENT_EXTENSIONS = [
...new Set( Object.values( SUPPORTED_DOCUMENT_TYPES ) ),
];

/**
* Value for the file input's `accept` attribute.
*
* Extensions rather than MIME types: browsers are inconsistent about the MIME they report
* for Office files (a .docx often arrives as application/zip or application/octet-stream),
* and an accept list of MIME types alone hides those files in the OS picker.
*/
export const DOCUMENT_ACCEPT = SUPPORTED_DOCUMENT_EXTENSIONS.map(
( extension ) => `.${ extension }`,
).join( ',' );

/**
* Whether a media object selected in the editor is a format the block can display.
*
* The MIME type is authoritative when present. Uploads in flight and some library
* selections have no MIME yet, so the extension is the fallback — the same order of
* preference as godam_is_supported_document() on the server.
*
* @param {Object} media Media object from MediaUpload / MediaReplaceFlow.
* @return {boolean} True when the format is supported.
*/
export function isSupportedDocument( media ) {
if ( ! media ) {
return false;
}

// Library selections expose `mime`, uploads expose `mime_type`. `media.type` is the
// REST post type ("attachment") for uploads, so it must not be consulted here.
const mime = media.mime || media.mime_type || '';

if ( mime ) {
return Object.prototype.hasOwnProperty.call( SUPPORTED_DOCUMENT_TYPES, mime );
Comment thread
KMchaudhary marked this conversation as resolved.
Resolved
}

return isSupportedDocumentUrl( media.url || '' );
}

/**
* Whether a URL points at a format the block can display, judged by extension alone.
*
* @param {string} url Document URL.
* @return {boolean} True when the extension is supported.
*/
export function isSupportedDocumentUrl( url ) {
if ( ! url || typeof url !== 'string' ) {
return false;
}

// Strip the query string / fragment before reading the extension.
const path = url.split( /[?#]/ )[ 0 ];
const extension = path.split( '.' ).pop().toLowerCase();

return SUPPORTED_DOCUMENT_EXTENSIONS.includes( extension );
}
Loading
Loading