Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@

/**
* Most IDs the status route answers for in one request (Transcoding::MAX_STATUS_IDS).
*/
const MAX_IDS_PER_REQUEST = 100;

/**
* Class to check the Transcoding status from API.
*/
Expand All @@ -24,29 +29,45 @@ class TranscodingChecker {
return nonce ? { headers: { 'X-WP-Nonce': nonce } } : {};
}

async fetchStatusOnce( postIds ) {
const url = this.buildUrl( postIds );
if ( ! url ) {
return;
/**
* Fetch the status of every ID, in requests of at most MAX_IDS_PER_REQUEST.
*
* @param {Array} postIds Attachment IDs.
* @return {Promise<Object|null>} Statuses keyed by ID, or null when there is no valid ID.
*/
async fetchBatches( postIds ) {
const validIds = postIds.map( ( id ) => parseInt( id ) ).filter( ( id ) => Number.isInteger( id ) && id > 0 );
if ( validIds.length === 0 ) {
return null;
}

const requests = [];
for ( let start = 0; start < validIds.length; start += MAX_IDS_PER_REQUEST ) {
const url = this.buildUrl( validIds.slice( start, start + MAX_IDS_PER_REQUEST ) );
requests.push( fetch( url, this.requestOptions() ).then( ( response ) => response.json() ) );
}

return Object.assign( {}, ...( await Promise.all( requests ) ) );
}

async fetchStatusOnce( postIds ) {
try {
const response = await fetch( url, this.requestOptions() );
const data = await response.json();
const data = await this.fetchBatches( postIds );
if ( ! data ) {
return;
}
this.updateCallback( data );
} catch ( error ) {
throw error;
}
}

async fetchStatus() {
const url = this.buildUrl( this.postIds );
if ( ! url ) {
return;
}

try {
const response = await fetch( url, this.requestOptions() );
const data = await response.json();
const data = await this.fetchBatches( this.postIds );
if ( ! data ) {
return;
}

this.updateCallback( data );
this.filterPostIds( data );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,32 @@ describe( 'TranscodingChecker — request', () => {
expect( global.fetch ).toHaveBeenCalledWith( expect.any( String ), {} );
} );
} );

describe( 'TranscodingChecker — batches', () => {
it( 'asks for at most 100 IDs a request and merges the answers', async () => {
const ids = Array.from( { length: 250 }, ( unused, index ) => index + 1 );
const callback = jest.fn();
global.fetch = jest.fn( ( url ) => {
const asked = new URL( url ).searchParams.getAll( 'ids[]' );
return Promise.resolve( {
json: () => Promise.resolve( Object.fromEntries( asked.map( ( id ) => [ id, { status: 'transcoded' } ] ) ) ),
} );
} );

await new TranscodingChecker( 'https://example.test/status', callback, ids ).fetchStatusOnce( ids );

expect( global.fetch ).toHaveBeenCalledTimes( 3 );
global.fetch.mock.calls.forEach( ( [ url ] ) => {
expect( new URL( url ).searchParams.getAll( 'ids[]' ).length ).toBeLessThanOrEqual( 100 );
} );
expect( Object.keys( callback.mock.calls[ 0 ][ 0 ] ) ).toHaveLength( 250 );
} );

it( 'sends one request for a short list', async () => {
global.fetch = jest.fn().mockResolvedValue( { json: () => Promise.resolve( {} ) } );

await new TranscodingChecker( 'https://example.test/status', jest.fn(), [ 5, 6 ] ).fetchStatusOnce( [ 5, 6 ] );

expect( global.fetch ).toHaveBeenCalledTimes( 1 );
} );
} );
28 changes: 28 additions & 0 deletions inc/classes/class-seo.php
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,23 @@ public function add_video_duration_for_video_seo( $response, $post ) {
return $response;
}

/**
* Whether a post's content is public: viewable by anyone, and not behind a
* password. Video schema describes the post's content, so it is only printed
* where that content is public, never on a draft, private, scheduled or
* password-protected post.
*
* @since n.e.x.t
*
* @param int $post_id Post ID.
* @return bool
*/
private function is_post_content_public( $post_id ) {
$post = get_post( $post_id ); // godam-coverage-ignore -- is_post_content_public(): $post_id is the queried post (the current page), never an attachment.

return $post && empty( $post->post_password ) && is_post_publicly_viewable( $post );
}

/**
* Outputs structured data for VideoObject schema on singular pages.
*
Expand All @@ -933,6 +950,12 @@ public function add_video_seo_schema() {
return;
}

// The cached schema describes the post's content, so only print it where
// that content is public.
if ( ! $this->is_post_content_public( $post_id ) ) {
return;
}

// Read cached SEO schema from post meta (fast!).
$cached_schemas = get_post_meta( $post_id, self::VIDEO_SEO_SCHEMA_META_KEY, true ); // godam-coverage-ignore -- add_video_seo_schema(): $post_id is get_queried_object_id() (the current page); reads that page's own cached SEO meta, not attachment data.

Expand Down Expand Up @@ -1852,6 +1875,11 @@ public function output_render_time_video_seo_schema() {
// as an unrelated post (description fallback, re-save queue, clip URLs).
$post_id = is_singular() ? get_queried_object_id() : 0;

// Not on a post whose content is not public, as for the cached output.
if ( $post_id > 0 && ! $this->is_post_content_public( $post_id ) ) {
return;
}

$output_schemas = array();
foreach ( $this->render_collected_schemas as $video ) {
// Skip videos already emitted by the cached wp_head output. This
Expand Down
5 changes: 2 additions & 3 deletions inc/classes/rest-api/class-ads.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,8 @@ public function get_video_ad_tag_url( $request ) {
*/
do_action( 'rtgodam_before_attachment_lookup' );
try {
// Check if the video exists.
$video = get_post( $video_id );
if ( empty( $video ) || 'attachment' !== $video->post_type ) {
// Check if the video exists and may be seen: media the visitor may not see answers like a missing one.
if ( ! rtgodam_can_view_attachment( $video_id ) ) {
return '';
}

Expand Down
5 changes: 2 additions & 3 deletions inc/classes/rest-api/class-dynamic-shortcode.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,8 @@ public function render_shortcode( WP_REST_Request $request ) {
*/
do_action( 'rtgodam_before_attachment_lookup' );
try {
$attachment = get_post( $id );

if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
// Media the visitor may not see answers exactly like a missing one.
if ( ! rtgodam_can_view_attachment( $id ) ) {
return new WP_REST_Response(
array(
'status' => 'error',
Expand Down
4 changes: 3 additions & 1 deletion inc/classes/rest-api/class-meta-rest-fields.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ public function add_meta_rest_fields() {
* @since 2.2.0
*/
do_action( 'rtgodam_before_attachment_lookup' );
$value = get_post_meta( $post['id'], 'rtgodam_meta', true );
// The stored GoDAM settings (layers, chapters and so on) are for people who write posts,
// whose editor previews read them, and for whoever can edit the file.
$value = current_user_can( 'edit_posts' ) || current_user_can( 'edit_post', $post['id'] ) ? get_post_meta( $post['id'], 'rtgodam_meta', true ) : null;
do_action( 'rtgodam_after_attachment_lookup' );
return $value;
},
Expand Down
58 changes: 45 additions & 13 deletions inc/classes/rest-api/class-transcoding.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,30 @@ class Transcoding extends Base {
*/
const DEFAULT_MEDIA_TYPE = 'video';

/**
* Most attachment IDs the public status route answers for in one request.
*
* The route is open to visitors and reads several meta rows per ID, so a longer
* list is refused. 100 is the largest page WordPress's own REST collections
* return; the media library sends its IDs in batches of that size.
*
* @since n.e.x.t
*
* @var int
*/
const MAX_STATUS_IDS = 100;

/**
* Seconds after a status update during which a transcoded video that has no
* thumbnail yet is still reported as generating one. About the three polls,
* five seconds apart, that the media library used to count.
*
* @since n.e.x.t
*
* @var int
*/
const THUMBNAIL_WAIT_SECONDS = 15;

/**
* Media types that can be fetched for transcoding, mapped to the MIME types they cover.
*
Expand Down Expand Up @@ -145,9 +169,11 @@ public function get_rest_routes() {
'ids' => array(
'required' => true,
'type' => 'array',
'maxItems' => self::MAX_STATUS_IDS,
'description' => __( 'The array of attachment IDs.', 'godam' ),
// The callback enforces maxItems: core only checks it through rest_validate_request_arg().
'validate_callback' => function ( $param ) {
return is_array( $param );
return is_array( $param ) && count( $param ) <= self::MAX_STATUS_IDS;
},
),
),
Expand Down Expand Up @@ -259,6 +285,7 @@ public function update_transcoding_status( \WP_REST_Request $request ) {

update_post_meta( $attachment_id, 'rtgodam_transcoding_status', $status );
update_post_meta( $attachment_id, 'rtgodam_transcoding_progress', $progress );
update_post_meta( $attachment_id, 'rtgodam_transcoding_status_updated', time() );

do_action( 'rtgodam_after_attachment_lookup' );
wp_send_json_success(
Expand All @@ -271,6 +298,8 @@ public function update_transcoding_status( \WP_REST_Request $request ) {
/**
* Return transcoding status of a media.
*
* Reads only. IDs the user may not see are left out, as if they were missing.
*
* @param \WP_REST_Request $request REST request object.
*
* @return WP_REST_Response|WP_Error
Expand All @@ -282,6 +311,13 @@ public function get_transcoding_status( \WP_REST_Request $request ) {
$response_object = array();

foreach ( $attachment_ids as $attachment_id ) {
$attachment_id = absint( $attachment_id );

// Leave out media the user may not see, and IDs that aren't media, alike.
if ( ! rtgodam_can_view_attachment( $attachment_id ) ) {
continue;
}

$status_object = $this->get_status_object_from_attachment( $attachment_id );
$response_object[ $attachment_id ] = $status_object;
}
Expand All @@ -298,9 +334,9 @@ public function get_transcoding_status( \WP_REST_Request $request ) {
*/
private function get_status_object_from_attachment( int $attachment_id ) {
/**
* Fires before reading/writing this attachment's transcoding-status
* metadata (job ID, status, error code/message, progress, thumbnail
* ID, and the thumbnail-retry counter), so integrations that
* Fires before reading this attachment's transcoding-status metadata
* (job ID, status, error code/message, progress, thumbnail ID, and
* the time of the last status update), so integrations that
* centralize media on another site can switch context first. Wrapped
* in try/finally because this method returns early from several
* branches below.
Expand Down Expand Up @@ -371,24 +407,20 @@ private function get_status_object_from_attachment( int $attachment_id ) {
// Check if media has thumbnail generated after transcoding.
$thumbnail_id = get_post_meta( $attachment_id, 'rtgodam_media_video_thumbnail', true );

// Handle retry logic for missing thumbnails when transcoding is complete.
// A thumbnail missing right after transcoding may still be on its way. Report 95%
// for a short while after the status was set, then carry on without it. This is a
// read: the time was stored when the status was updated, nothing is written here.
if ( 'transcoded' === strtolower( $status ) && empty( $thumbnail_id ) ) {
$retry_count = intval( get_post_meta( $attachment_id, 'rtgodam_thumbnail_retry_count', true ) );
$max_retries = 3;

if ( $retry_count < $max_retries ) {
// Increment retry count.
update_post_meta( $attachment_id, 'rtgodam_thumbnail_retry_count', $retry_count + 1 );
$status_updated = intval( get_post_meta( $attachment_id, 'rtgodam_transcoding_status_updated', true ) );

// Return transcoding status with 95% progress to indicate waiting for thumbnail.
if ( $status_updated && time() - $status_updated < self::THUMBNAIL_WAIT_SECONDS ) {
return array(
'status' => 'transcoding',
'progress' => 95,
'message' => __( 'Transcoding complete, generating thumbnail...', 'godam' ),
'thumbnail' => '',
);
}
// If max retries reached, continue with normal flow (return transcoded status without thumbnail).
}

return array(
Expand Down
Loading
Loading