diff --git a/admin/class-rtgodam-retranscodemedia.php b/admin/class-rtgodam-retranscodemedia.php index f276eb4ea4..e7e5d770ea 100644 --- a/admin/class-rtgodam-retranscodemedia.php +++ b/admin/class-rtgodam-retranscodemedia.php @@ -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 diff --git a/admin/class-rtgodam-transcoder-handler.php b/admin/class-rtgodam-transcoder-handler.php index 0876069013..e1ddbf1702 100644 --- a/admin/class-rtgodam-transcoder-handler.php +++ b/admin/class-rtgodam-transcoder-handler.php @@ -92,6 +92,23 @@ 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'. + * + * No leading comma, unlike $audio_extensions and $other_extensions: exploding those yields + * an empty first entry, which then matches a file with no extension at all. + * + * @since n.e.x.t + * @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'; + /** * Allowed mimetypes. * @@ -101,7 +118,6 @@ class RTGODAM_Transcoder_Handler { */ public $allowed_mimetypes = array( 'application/ogg', - 'application/pdf', ); /** @@ -125,6 +141,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, @@ -308,11 +339,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 ) @@ -334,6 +385,20 @@ public function wp_media_transcoding( $wp_metadata, $attachment_id, $autoformat $job_type = $extension; $autoformat = $extension; $options_video_thumb = 0; + } elseif ( '' !== $extension && 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 */ @@ -445,6 +510,19 @@ public function wp_media_transcoding( $wp_metadata, $attachment_id, $autoformat delete_post_meta( $attachment_id, 'rtgodam_transcoding_error_msg' ); delete_post_meta( $attachment_id, 'rtgodam_transcoding_error_code' ); + if ( 'document' === $job_type ) { + /* + * Drop any preview from a previous render of this attachment. The job row + * is reused for a retranscode or an in-place replacement, so the stored + * preview belongs to the file that WAS here — leaving it in place would + * keep serving the old document's contents until the callback arrives, and + * forever if the job fails, since the error path never reaches the + * callback's cleanup. A document with no preview shows the download-only + * panel, and 'Queued' above makes the block show progress meanwhile. + */ + delete_post_meta( $attachment_id, 'rtgodam_preview_pdf_url' ); + } + if ( $manual_retranscode ) { $failed_transcoding_attachments = get_option( 'rtgodam-failed-transcoding-attachments', array() ); diff --git a/admin/class-rtgodam-transcoder-rest-routes.php b/admin/class-rtgodam-transcoder-rest-routes.php index f3b7113b56..c9b86df5f8 100644 --- a/admin/class-rtgodam-transcoder-rest-routes.php +++ b/admin/class-rtgodam-transcoder-rest-routes.php @@ -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', @@ -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' ); @@ -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( @@ -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 { + /* + * 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'] ) ); diff --git a/admin/godam-transcoder-actions.php b/admin/godam-transcoder-actions.php index 571101a07d..e2b09511f1 100644 --- a/admin/godam-transcoder-actions.php +++ b/admin/godam-transcoder-actions.php @@ -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 ) { diff --git a/assets/src/blocks/godam-pdf/block.json b/assets/src/blocks/godam-pdf/block.json index 3be7ebf842..7d7cb3e0cf 100644 --- a/assets/src/blocks/godam-pdf/block.json +++ b/assets/src/blocks/godam-pdf/block.json @@ -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": { diff --git a/assets/src/blocks/godam-pdf/constants.js b/assets/src/blocks/godam-pdf/constants.js new file mode 100644 index 0000000000..7167d31f94 --- /dev/null +++ b/assets/src/blocks/godam-pdf/constants.js @@ -0,0 +1,163 @@ +/** + * 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 ); + +/** + * 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, but it is not sufficient on its own: + * WordPress maps .srt, .asc, .c, .cc and .h to text/plain exactly as it maps .txt, and the + * library picker filters by MIME, so every subtitle and source file in the library is + * offered alongside real documents. Those have no conversion path — the transcoder skips + * them, and the block could only ever show its "no preview" panel — so the file name has to + * agree with the MIME type whenever there is one to read. Same rule as + * rtgodam_is_supported_document_attachment() on the server. + * + * Uploads in flight and some library selections have no MIME yet, in which case the + * extension answers alone. + * + * @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 || ''; + + // `filename` is what the library reports; `url` covers uploads and URL-only selections. + const name = media.filename || media.url || ''; + + if ( mime ) { + return ( + Object.prototype.hasOwnProperty.call( SUPPORTED_DOCUMENT_TYPES, mime ) && + ! hasUnsupportedDocumentExtension( name ) + ); + } + + return isSupportedDocumentUrl( media.url || '' ); +} + +/** + * Whether a path or URL carries an extension that is known NOT to be a document. + * + * The inverse of isSupportedDocumentUrl() only for names that HAVE an extension: a name with + * none (a CDN URL ending in an id, a library item with no file name) yields false, because + * "cannot tell" must not read as "unsupported". That is what makes this safe to combine with + * a supported MIME type, and it matches how godam_is_supported_document() treats an + * attachment whose file cannot be resolved. + * + * @param {string} pathOrUrl File name, path or URL. + * @return {boolean} True only when an extension is present and unsupported. + */ +export function hasUnsupportedDocumentExtension( pathOrUrl ) { + const extension = getExtension( pathOrUrl ); + + return !! extension && ! SUPPORTED_DOCUMENT_EXTENSIONS.includes( extension ); +} + +/** + * 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 ) { + return SUPPORTED_DOCUMENT_EXTENSIONS.includes( getExtension( url ) ); +} + +/** + * Read the extension out of a file name, path or URL. + * + * @param {string} pathOrUrl File name, path or URL. + * @return {string} Lowercase extension without the leading dot, empty when there is none. + */ +function getExtension( pathOrUrl ) { + if ( ! pathOrUrl || typeof pathOrUrl !== 'string' ) { + return ''; + } + + // Strip the query string / fragment before reading the extension: CDN URLs routinely + // carry `?v=2` or `#page=3`. + const path = pathOrUrl.split( /[?#]/ )[ 0 ]; + const name = path.split( '/' ).pop(); + + if ( ! name.includes( '.' ) ) { + return ''; + } + + return name.split( '.' ).pop().toLowerCase(); +} diff --git a/assets/src/blocks/godam-pdf/edit.js b/assets/src/blocks/godam-pdf/edit.js index 98d534a1dc..d5bbd80dd9 100644 --- a/assets/src/blocks/godam-pdf/edit.js +++ b/assets/src/blocks/godam-pdf/edit.js @@ -9,7 +9,6 @@ import clsx from 'clsx'; import { isBlobURL } from '@wordpress/blob'; import { Button, - Disabled, PanelBody, RangeControl, TextControl, @@ -30,16 +29,30 @@ import { __ } from '@wordpress/i18n'; import { useDispatch, useSelect } from '@wordpress/data'; import { store as noticesStore } from '@wordpress/notices'; import { store as coreStore } from '@wordpress/core-data'; -import { useState, useEffect } from '@wordpress/element'; +import { useState, useEffect, useMemo, lazy, Suspense } from '@wordpress/element'; import { trash } from '@wordpress/icons'; /** * Internal dependencies */ import { Caption } from './caption'; +import PreviewErrorBoundary from './preview-error-boundary'; +import { + ALLOWED_MEDIA_TYPES, + DOCUMENT_ACCEPT, + IN_PROGRESS_TRANSCODING_STATUSES, + hasUnsupportedDocumentExtension, + isSupportedDocument, + isSupportedDocumentUrl, +} from './constants'; import './editor.scss'; -const ALLOWED_MEDIA_TYPES = [ 'application/pdf' ]; +// pdf.js is heavy, and most posts being edited contain no document at all. Loading it only +// when a document is actually on the canvas keeps it out of the editor's initial bundle — +// and it is the same chunk the front end uses, so it is usually already cached. +const DocumentViewer = lazy( () => + import( /* webpackChunkName: "godam-pdf-viewer" */ './viewer' ), +); /** * Format bytes → human-readable KB / MB. @@ -93,84 +106,188 @@ function PdfEdit( { const [ temporaryURL, setTemporaryURL ] = useState( attributes.blob ); // Track file info during upload so we can display a nice progress UI. const [ uploadingFile, setUploadingFile ] = useState( null ); + // What pdf.js last reported for the rendered document, committed to the `pageCount` + // attribute by the effect below once the block is selected. See onPreviewLoaded(). + const [ loadedPageCount, setLoadedPageCount ] = useState( 0 ); + // Preview URLs pdf.js could not render, so the canvas can try the next candidate and + // ultimately fall back to the download-only panel. See previewCandidates below. + const [ failedPreviewUrls, setFailedPreviewUrls ] = useState( [] ); const { createErrorNotice, createWarningNotice } = useDispatch( noticesStore ); - // Fetch attachment metadata: auto-generated cover, file size and MIME type. - const { autoGeneratedCover, fileSize, mimeType } = useSelect( ( select ) => { - if ( ! id ) { - return { autoGeneratedCover: '', fileSize: 0, mimeType: '' }; + // Fetch attachment metadata: auto-generated cover, file size, MIME type, and the + // transcoding state needed to tell "preview on its way" from "there will never be one". + const { + autoGeneratedCover, + fileSize, + hasResolvedMedia, + mimeType, + previewPdfUrl, + sourceUrl, + transcodingStatus, + } = useSelect( + ( select ) => { + if ( ! id ) { + // A document added by URL alone has no record to wait for. + return { + autoGeneratedCover: '', + fileSize: 0, + hasResolvedMedia: true, + mimeType: '', + previewPdfUrl: '', + sourceUrl: '', + transcodingStatus: '', + }; + } + const media = select( coreStore ).getEntityRecord( 'postType', 'attachment', id ); + return { + /* + * Whether the record above has actually been fetched yet, as opposed to simply + * being absent. Every field here reads as empty until the request resolves, and + * an empty transcoding status is meaningful — it is what "no job was ever + * dispatched" looks like — so without this the canvas would classify the + * document from placeholder values and show the download-only panel for a moment + * before the real data arrived. + */ + hasResolvedMedia: select( coreStore ).hasFinishedResolution( + 'getEntityRecord', + [ 'postType', 'attachment', id ], + ), + // Mirror set_media_library_thumbnail(): check video thumbnail first (set by + // GoDAM transcoding callback for WP-uploaded PDFs), then the PDF-specific key + // (set by GoDAM tab import). Both are registered show_in_rest:true. + autoGeneratedCover: media?.meta?.rtgodam_media_video_thumbnail || + media?.meta?.rtgodam_media_pdf_thumbnail || + '', + fileSize: media?.media_details?.filesize || 0, + mimeType: media?.mime_type || '', + previewPdfUrl: media?.meta?.rtgodam_preview_pdf_url || '', + // REST runs source_url through wp_get_attachment_url(), so GoDAM-tab media + // resolves to its CDN URL here just as it does server-side. + sourceUrl: media?.source_url || '', + transcodingStatus: ( media?.meta?.rtgodam_transcoding_status || '' ).toLowerCase(), + }; + }, + [ id ], + ); + + /* + * The PDF to render. Mirrors rtgodam_get_document_preview_url() on the server, so the + * canvas shows exactly what a visitor will see: + * + * - the preview PDF once Central has produced one; + * - for a plain PDF, the file itself, which needs no conversion and lets the editor + * render immediately rather than waiting on a transcode. + * + * Anything else has nothing to show yet. + */ + const isPdfSource = mimeType + ? 'application/pdf' === mimeType + : /\.pdf(?:[?#]|$)/i.test( sourceUrl || src || '' ); + + /* + * Every PDF this document could be rendered from, best first. + * + * A list rather than one URL because the editor can only find out whether pdf.js is able + * to read a URL by trying it. pdf.js fetches over XHR, where the front end's `` + * fallback does not, so a CDN that serves the file happily to visitors but sends no + * Access-Control-Allow-Origin fails here and nowhere else. Giving up on the first failure + * meant an author saw "no preview available" for a document their visitors can read. + * + * Order mirrors rtgodam_get_document_preview_url() — the generated preview, then the + * attachment's current URL, which is what a visitor is actually served — and only then + * falls back to the block's insertion-time `src`, which may be the same file on the local + * site and therefore same-origin. Non-PDF sources contribute nothing: only a preview PDF + * can represent them. + */ + const previewCandidates = useMemo( () => { + const candidates = [ previewPdfUrl ]; + + if ( isPdfSource ) { + candidates.push( sourceUrl, src ); } - const media = select( coreStore ).getEntityRecord( 'postType', 'attachment', id ); - return { - // Mirror set_media_library_thumbnail(): check video thumbnail first (set by - // GoDAM transcoding callback for WP-uploaded PDFs), then the PDF-specific key - // (set by GoDAM tab import). Both are registered show_in_rest:true. - autoGeneratedCover: media?.meta?.rtgodam_media_video_thumbnail || - media?.meta?.rtgodam_media_pdf_thumbnail || - '', - fileSize: media?.media_details?.filesize || 0, - mimeType: media?.mime_type || '', - }; - }, [ id ] ); - - // Count PDF pages client-side by fetching the raw file and scanning for - // page dictionary entries. Runs once when src is first set (or changes). - // Result is stored as a block attribute so it persists on save. - // Count pages every time src is set — this ensures previously-uploaded PDFs - // also get counted when the editor opens, not only on new uploads. - // The result is stored as an attribute so it persists after the post is saved. + + return [ ...new Set( candidates.filter( Boolean ) ) ]; + }, [ previewPdfUrl, isPdfSource, sourceUrl, src ] ); + + // The first candidate that has not already failed. Empty once they all have, which the + // states below read as "no preview", the same as having none to begin with. + const resolvedPreviewUrl = + previewCandidates.find( ( url ) => ! failedPreviewUrls.includes( url ) ) || ''; + + // A different file — or a newly generated preview — is a fresh attempt. + const candidateKey = previewCandidates.join( '|' ); useEffect( () => { - // Skip if src isn't set, or if we already have a page count (avoids - // re-downloading the file on every editor open and marking the post dirty). - // pageCount is reset to 0 in onSelectPdf when a new file is chosen, - // so a fresh count will still run after the user swaps the document. - if ( ! src || pageCount > 0 ) { + setFailedPreviewUrls( [] ); + }, [ candidateKey ] ); + + /** + * Record that the current candidate cannot be rendered, so the next one is tried. + * + * Reached both from the viewer's own error callback and from the error boundary around it. + * Guarded against duplicates because react-pdf can report one failure more than once. + */ + function onPreviewFailed() { + if ( ! resolvedPreviewUrl ) { return; } - // NOTE: fetch only works for same-origin PDFs. Cross-origin / CDN files - // are blocked by CORS and will silently leave pageCount at 0. - // For production CDN setups, consider computing the page count server-side - // at upload/transcode time and storing it in post meta instead. - const controller = new AbortController(); + setFailedPreviewUrls( ( previous ) => + previous.includes( resolvedPreviewUrl ) + ? previous + : [ ...previous, resolvedPreviewUrl ], + ); + } - fetch( src, { credentials: 'same-origin', signal: controller.signal } ) - .then( ( res ) => { - if ( ! res.ok ) { - throw new Error( 'fetch failed' ); - } - return res.arrayBuffer(); - } ) - .then( ( buffer ) => { - // Decode as latin-1 so every byte is preserved as a character. - const text = new TextDecoder( 'latin1' ).decode( buffer ); - - // Primary: /Count N inside any /Pages dictionary. - // The root /Pages node always has the highest count value. - // Note: PDF 1.5+ object streams compress the page tree, so this - // regex may not find /Count in all modern PDFs. - const countMatches = [ ...text.matchAll( /\/Count\s+(\d+)/g ) ]; - let count = countMatches.reduce( ( max, m ) => { - const n = parseInt( m[ 1 ], 10 ); - return n > max ? n : max; - }, 0 ); - - // Fallback: count leaf /Page objects (works for older/uncompressed PDFs). - if ( ! count ) { - const pageMatches = text.match( /\/Type\s*\/Page[\s/<[]/g ); - count = pageMatches ? pageMatches.length : 0; - } + /* + * The file to offer for download, mirroring rtgodam_get_document_download_url(). Always + * the original upload, never the generated preview — somebody who uploaded report.xlsx + * and got preview.pdf back will think something broke. + * + * The attachment's own URL wins over the stored `src`, which was captured when the block + * was inserted and can be stale if the file was later offloaded to a CDN. + */ + const resolvedDownloadUrl = sourceUrl || src || ''; - if ( count > 0 ) { - setAttributes( { pageCount: count } ); - } - } ) - .catch( () => {} ); // Silently ignore network / CORS / abort errors. + /** + * Record the page count reported by pdf.js. + * + * This replaces an earlier hand-rolled count that fetched the raw file and regex-scanned + * it for `/Count` entries. That could not see cross-origin CDN files (blocked by CORS) + * and missed PDF 1.5+ files whose page tree lives in a compressed object stream. pdf.js + * has already parsed the document properly by the time it tells us, so this is both + * cheaper and correct. + * + * Written only while the block is selected, and only when the number actually changes. + * Both guards matter: any attribute write during a passive page load flags the post as + * having unsaved changes, so an author who merely opened a post to read it would be met + * with the browser's "Leave site?" prompt. Blocks saved before pdf.js was introduced hold + * pageCount: 0 — the old counter could not read cross-origin files — so without the + * selection guard every one of them would rewrite itself on open. + * + * The number itself is therefore held in component state, not dropped: pdf.js reports it + * once per load, and a block that was already on the canvas when it loaded never gets a + * second callback when the author selects it later. The effect below commits it as soon as + * the block is selected, so the count really is refreshed the moment the author touches + * the block — which is also the only point at which they could act on it. + * + * @param {Object} pdf pdf.js document proxy. + */ + function onPreviewLoaded( pdf ) { + if ( pdf?.numPages > 0 ) { + setLoadedPageCount( pdf.numPages ); + } + } + + useEffect( () => { + if ( ! isSingleSelected || ! loadedPageCount ) { + return; + } - return () => { - controller.abort(); - }; - }, [ src ] ); // eslint-disable-line react-hooks/exhaustive-deps + if ( loadedPageCount !== pageCount ) { + setAttributes( { pageCount: loadedPageCount } ); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ isSingleSelected, loadedPageCount, pageCount ] ); function onUploadError( message ) { createErrorNotice( message, { type: 'snackbar' } ); @@ -201,23 +318,13 @@ function PdfEdit( { return; } - // Validate the format: reject anything that isn't a PDF. - // The MediaUpload allowedTypes filter restricts the library UI, but a - // runtime check is needed as a safety net (e.g. drag-and-drop bypasses it). - // Use the MIME string, not `media.type`: library selections expose - // `mime` ("application/pdf") while uploads expose `mime_type`; `media.type` - // is the REST post type ("attachment") for uploads and would wrongly reject them. - // Testing for equality (rather than inequality) matters: a missing MIME type - // used to pass straight through, so fall back to the extension instead of - // letting an unknown format in. - const mime = media.mime || media.mime_type || ''; - const isPdf = mime - ? 'application/pdf' === mime - : /\.pdf(?:[?#]|$)/i.test( media.url || '' ); - - if ( ! isPdf ) { + // Validate the format. The MediaUpload allowedTypes filter restricts the library UI, + // but a runtime check is needed as a safety net (e.g. drag-and-drop bypasses it). + // isSupportedDocument() prefers the MIME type and falls back to the extension, so an + // unknown format is rejected rather than passed straight through. + if ( ! isSupportedDocument( media ) ) { createWarningNotice( - __( 'Only PDF files can be attached to this block. Please select a PDF document.', 'godam' ), + __( 'That file type is not supported. Choose a PDF, Word, Excel, PowerPoint, OpenDocument, TXT or CSV file.', 'godam' ), { type: 'snackbar', isDismissible: true }, ); return; @@ -239,7 +346,7 @@ function PdfEdit( { caption: media.caption, docTitle: media.title || '', description: mediaDescription, - pageCount: 0, // Reset so useEffect re-counts pages for the new file. + pageCount: 0, // Reset so onPreviewLoaded re-counts pages for the new file. } ); setTemporaryURL(); setUploadingFile( null ); @@ -295,25 +402,70 @@ function PdfEdit( { const isCardView = previewMode === 'card'; const hasDocument = !! ( src || temporaryURL ); - // Content saved before the format was validated (or added by URL) can still hold - // a non-PDF. The front end renders nothing for those, so flag it here rather than - // showing an that just paints blank. - // Decided from the stored URL first, because that is the only signal available - // on the very first render. The attachment's MIME type arrives asynchronously, - // and waiting for it means rendering the speculatively: the browser - // fetches the file, and for a non-PDF that alone raises a download prompt - // before any notice can replace it. The MIME type still overrides the URL once - // present, since it is the authoritative answer. + /* + * Nothing about the document can be judged until its attachment record has arrived: every + * field read from it is empty until then, which is indistinguishable from a document that + * has no preview and no transcoding job. + * + * This gates the states below rather than only the download-only panel, because guessing + * early is not merely a wrong answer shown briefly — the guess feeds the viewer's `file` + * prop, and correcting it makes react-pdf destroy the in-flight load and start another. + * Every such destroy is a chance to take the whole block down (see viewer/worker.js), and + * it re-fetches the PDF for nothing. Mounting the viewer once, on the final URL, avoids + * both. + * + * A document added by URL alone has no record to wait for. + */ + const isResolvingMedia = hasDocument && ! temporaryURL && !! id && ! hasResolvedMedia; + + // Content saved before the format was validated (or added by URL) can still hold an + // unsupported file. The front end renders nothing for those, so flag it here rather than + // showing an empty frame. // - // Trade-off: a PDF served from an extension-less URL is flagged until its MIME - // arrives. Erring that way is deliberate, because the opposite error hands the - // visitor's browser a file to download. - const isUnsupported = hasDocument && ! temporaryURL && ( + // The attachment's MIME type is the authoritative answer, so this waits for it; only a + // document with no attachment at all is judged from its URL. + // + // Trade-off: a supported file served from an extension-less URL is flagged until its MIME + // arrives. Erring that way is deliberate — the opposite error would show the author a + // broken preview and imply the page is fine. + // + // A supported MIME type is not enough on its own, for the same reason the server's + // godam_is_supported_document() is not satisfied by one: text/plain covers .srt/.asc/.c/ + // .cc/.h as well as .txt, and those render nothing on the page. Only an extension that is + // present AND unsupported counts against the MIME type, so a CDN URL with no extension at + // all still goes by MIME. + const isUnsupported = hasDocument && ! temporaryURL && ! isResolvingMedia && ( mimeType - ? 'application/pdf' !== mimeType - : ! /\.pdf(?:[?#]|$)/i.test( src || '' ) + ? ( + ! ALLOWED_MEDIA_TYPES.includes( mimeType ) || + hasUnsupportedDocumentExtension( sourceUrl || src || '' ) + ) + : ! isSupportedDocumentUrl( src || '' ) ); + /* + * No preview yet. Two situations, and the author needs to be able to tell them apart + * because only one of them resolves on its own: + * + * - a transcoding job is in flight — a preview is coming, so the canvas says so and the + * author has no reason to go looking for a fix; + * - no job is running, so no preview is coming. Either one finished without producing + * anything (it failed, or the document is password protected — GoDAM Central stores + * those as-is and reports success, because it cannot convert a file it cannot open), or + * one was never dispatched at all, which is what an absent status means. A visitor sees + * the download-only panel in every one of those cases, so the canvas shows that same + * panel rather than inventing editor-only copy for a distinction the page does not draw. + * + * Judged by an allow-list of in-flight statuses, so an absent status and anything + * unrecognised land in the second bucket rather than promising a preview forever. + */ + const missingPreview = + hasDocument && ! temporaryURL && ! isResolvingMedia && ! isUnsupported && + ! resolvedPreviewUrl; + const isAwaitingPreview = + missingPreview && IN_PROGRESS_TRANSCODING_STATUSES.includes( transcodingStatus ); + const hasNoPreview = missingPreview && ! isAwaitingPreview; + const classes = clsx( className, { 'is-transient': !! temporaryURL, [ `is-preview-${ previewMode || 'default' }` ]: true, @@ -339,7 +491,7 @@ function PdfEdit( { (