Skip to content

Commit 4c08086

Browse files
committed
Show media on GoDAM's public routes only where WordPress would show it
The preview and embed pages, the video shortcode, ad tag and transcoding status routes, and the video gallery listing now follow WordPress's own media visibility instead of answering for any media ID. Media is shown when it is unattached, or when the post it was uploaded to is published (or has another public status) and has no password the visitor has not entered. Users who can edit the media always see it, and users who can read a private or draft parent, or edit a password-protected one, see its media. Media used on a publicly viewable post counts as public whichever post it was uploaded to, using the media usage index, so a video uploaded while drafting one post keeps working in the player, gallery, lightbox and embed of the published page that uses it. Media a visitor may not see is treated like a missing ID. The result can be adjusted with the new rtgodam_can_view_attachment filter. - rtgodam_can_view_attachment() answers for one attachment; the gallery listing applies the same rule in SQL (rtgodam_public_media_query_clauses) so paging and counts stay correct. - The transcoding status route takes at most 100 IDs per request and leaves out IDs the user may not see. Reading the status no longer writes: the short wait for a thumbnail after transcoding is based on the time of the last status update, stored when the status is set, instead of a counter incremented on every read. The media library requests statuses in batches of 100. - The rtgodam_meta REST field on attachments returns the stored settings only to users who can write posts (for editor previews) or edit the attachment. - Video schema is printed only for posts whose content is public: not drafts, private, scheduled or password-protected posts. - Add unit tests for each of these.
1 parent d9b9888 commit 4c08086

14 files changed

Lines changed: 1928 additions & 51 deletions

‎assets/src/js/media-library/transcoding-status/transcoding-checker.js‎

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11

2+
/**
3+
* Most IDs the status route answers for in one request (Transcoding::MAX_STATUS_IDS).
4+
*/
5+
const MAX_IDS_PER_REQUEST = 100;
6+
27
/**
38
* Class to check the Transcoding status from API.
49
*/
@@ -24,29 +29,45 @@ class TranscodingChecker {
2429
return nonce ? { headers: { 'X-WP-Nonce': nonce } } : {};
2530
}
2631

27-
async fetchStatusOnce( postIds ) {
28-
const url = this.buildUrl( postIds );
29-
if ( ! url ) {
30-
return;
32+
/**
33+
* Fetch the status of every ID, in requests of at most MAX_IDS_PER_REQUEST.
34+
*
35+
* @param {Array} postIds Attachment IDs.
36+
* @return {Promise<Object|null>} Statuses keyed by ID, or null when there is no valid ID.
37+
*/
38+
async fetchBatches( postIds ) {
39+
const validIds = postIds.map( ( id ) => parseInt( id ) ).filter( ( id ) => Number.isInteger( id ) && id > 0 );
40+
if ( validIds.length === 0 ) {
41+
return null;
3142
}
43+
44+
const requests = [];
45+
for ( let start = 0; start < validIds.length; start += MAX_IDS_PER_REQUEST ) {
46+
const url = this.buildUrl( validIds.slice( start, start + MAX_IDS_PER_REQUEST ) );
47+
requests.push( fetch( url, this.requestOptions() ).then( ( response ) => response.json() ) );
48+
}
49+
50+
return Object.assign( {}, ...( await Promise.all( requests ) ) );
51+
}
52+
53+
async fetchStatusOnce( postIds ) {
3254
try {
33-
const response = await fetch( url, this.requestOptions() );
34-
const data = await response.json();
55+
const data = await this.fetchBatches( postIds );
56+
if ( ! data ) {
57+
return;
58+
}
3559
this.updateCallback( data );
3660
} catch ( error ) {
3761
throw error;
3862
}
3963
}
4064

4165
async fetchStatus() {
42-
const url = this.buildUrl( this.postIds );
43-
if ( ! url ) {
44-
return;
45-
}
46-
4766
try {
48-
const response = await fetch( url, this.requestOptions() );
49-
const data = await response.json();
67+
const data = await this.fetchBatches( this.postIds );
68+
if ( ! data ) {
69+
return;
70+
}
5071

5172
this.updateCallback( data );
5273
this.filterPostIds( data );

‎assets/src/js/media-library/transcoding-status/transcoding-checker.test.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,32 @@ describe( 'TranscodingChecker — request', () => {
3030
expect( global.fetch ).toHaveBeenCalledWith( expect.any( String ), {} );
3131
} );
3232
} );
33+
34+
describe( 'TranscodingChecker — batches', () => {
35+
it( 'asks for at most 100 IDs a request and merges the answers', async () => {
36+
const ids = Array.from( { length: 250 }, ( unused, index ) => index + 1 );
37+
const callback = jest.fn();
38+
global.fetch = jest.fn( ( url ) => {
39+
const asked = new URL( url ).searchParams.getAll( 'ids[]' );
40+
return Promise.resolve( {
41+
json: () => Promise.resolve( Object.fromEntries( asked.map( ( id ) => [ id, { status: 'transcoded' } ] ) ) ),
42+
} );
43+
} );
44+
45+
await new TranscodingChecker( 'https://example.test/status', callback, ids ).fetchStatusOnce( ids );
46+
47+
expect( global.fetch ).toHaveBeenCalledTimes( 3 );
48+
global.fetch.mock.calls.forEach( ( [ url ] ) => {
49+
expect( new URL( url ).searchParams.getAll( 'ids[]' ).length ).toBeLessThanOrEqual( 100 );
50+
} );
51+
expect( Object.keys( callback.mock.calls[ 0 ][ 0 ] ) ).toHaveLength( 250 );
52+
} );
53+
54+
it( 'sends one request for a short list', async () => {
55+
global.fetch = jest.fn().mockResolvedValue( { json: () => Promise.resolve( {} ) } );
56+
57+
await new TranscodingChecker( 'https://example.test/status', jest.fn(), [ 5, 6 ] ).fetchStatusOnce( [ 5, 6 ] );
58+
59+
expect( global.fetch ).toHaveBeenCalledTimes( 1 );
60+
} );
61+
} );

‎inc/classes/class-seo.php‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -910,6 +910,23 @@ public function add_video_duration_for_video_seo( $response, $post ) {
910910
return $response;
911911
}
912912

913+
/**
914+
* Whether a post's content is public: viewable by anyone, and not behind a
915+
* password. Video schema describes the post's content, so it is only printed
916+
* where that content is public, never on a draft, private, scheduled or
917+
* password-protected post.
918+
*
919+
* @since n.e.x.t
920+
*
921+
* @param int $post_id Post ID.
922+
* @return bool
923+
*/
924+
private function is_post_content_public( $post_id ) {
925+
$post = get_post( $post_id ); // godam-coverage-ignore -- is_post_content_public(): $post_id is the queried post (the current page), never an attachment.
926+
927+
return $post && empty( $post->post_password ) && is_post_publicly_viewable( $post );
928+
}
929+
913930
/**
914931
* Outputs structured data for VideoObject schema on singular pages.
915932
*
@@ -933,6 +950,12 @@ public function add_video_seo_schema() {
933950
return;
934951
}
935952

953+
// The cached schema describes the post's content, so only print it where
954+
// that content is public.
955+
if ( ! $this->is_post_content_public( $post_id ) ) {
956+
return;
957+
}
958+
936959
// Read cached SEO schema from post meta (fast!).
937960
$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.
938961

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

1878+
// Not on a post whose content is not public, as for the cached output.
1879+
if ( $post_id > 0 && ! $this->is_post_content_public( $post_id ) ) {
1880+
return;
1881+
}
1882+
18551883
$output_schemas = array();
18561884
foreach ( $this->render_collected_schemas as $video ) {
18571885
// Skip videos already emitted by the cached wp_head output. This

‎inc/classes/rest-api/class-ads.php‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,8 @@ public function get_video_ad_tag_url( $request ) {
216216
*/
217217
do_action( 'rtgodam_before_attachment_lookup' );
218218
try {
219-
// Check if the video exists.
220-
$video = get_post( $video_id );
221-
if ( empty( $video ) || 'attachment' !== $video->post_type ) {
219+
// Check if the video exists and may be seen: media the visitor may not see answers like a missing one.
220+
if ( ! rtgodam_can_view_attachment( $video_id ) ) {
222221
return '';
223222
}
224223

‎inc/classes/rest-api/class-dynamic-shortcode.php‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,8 @@ public function render_shortcode( WP_REST_Request $request ) {
8888
*/
8989
do_action( 'rtgodam_before_attachment_lookup' );
9090
try {
91-
$attachment = get_post( $id );
92-
93-
if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
91+
// Media the visitor may not see answers exactly like a missing one.
92+
if ( ! rtgodam_can_view_attachment( $id ) ) {
9493
return new WP_REST_Response(
9594
array(
9695
'status' => 'error',

‎inc/classes/rest-api/class-meta-rest-fields.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,9 @@ public function add_meta_rest_fields() {
5050
* @since 2.2.0
5151
*/
5252
do_action( 'rtgodam_before_attachment_lookup' );
53-
$value = get_post_meta( $post['id'], 'rtgodam_meta', true );
53+
// The stored GoDAM settings (layers, chapters and so on) are for people who write posts,
54+
// whose editor previews read them, and for whoever can edit the file.
55+
$value = current_user_can( 'edit_posts' ) || current_user_can( 'edit_post', $post['id'] ) ? get_post_meta( $post['id'], 'rtgodam_meta', true ) : null;
5456
do_action( 'rtgodam_after_attachment_lookup' );
5557
return $value;
5658
},

‎inc/classes/rest-api/class-transcoding.php‎

Lines changed: 45 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,30 @@ class Transcoding extends Base {
3232
*/
3333
const DEFAULT_MEDIA_TYPE = 'video';
3434

35+
/**
36+
* Most attachment IDs the public status route answers for in one request.
37+
*
38+
* The route is open to visitors and reads several meta rows per ID, so a longer
39+
* list is refused. 100 is the largest page WordPress's own REST collections
40+
* return; the media library sends its IDs in batches of that size.
41+
*
42+
* @since n.e.x.t
43+
*
44+
* @var int
45+
*/
46+
const MAX_STATUS_IDS = 100;
47+
48+
/**
49+
* Seconds after a status update during which a transcoded video that has no
50+
* thumbnail yet is still reported as generating one. About the three polls,
51+
* five seconds apart, that the media library used to count.
52+
*
53+
* @since n.e.x.t
54+
*
55+
* @var int
56+
*/
57+
const THUMBNAIL_WAIT_SECONDS = 15;
58+
3559
/**
3660
* Media types that can be fetched for transcoding, mapped to the MIME types they cover.
3761
*
@@ -145,9 +169,11 @@ public function get_rest_routes() {
145169
'ids' => array(
146170
'required' => true,
147171
'type' => 'array',
172+
'maxItems' => self::MAX_STATUS_IDS,
148173
'description' => __( 'The array of attachment IDs.', 'godam' ),
174+
// The callback enforces maxItems: core only checks it through rest_validate_request_arg().
149175
'validate_callback' => function ( $param ) {
150-
return is_array( $param );
176+
return is_array( $param ) && count( $param ) <= self::MAX_STATUS_IDS;
151177
},
152178
),
153179
),
@@ -259,6 +285,7 @@ public function update_transcoding_status( \WP_REST_Request $request ) {
259285

260286
update_post_meta( $attachment_id, 'rtgodam_transcoding_status', $status );
261287
update_post_meta( $attachment_id, 'rtgodam_transcoding_progress', $progress );
288+
update_post_meta( $attachment_id, 'rtgodam_transcoding_status_updated', time() );
262289

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

284313
foreach ( $attachment_ids as $attachment_id ) {
314+
$attachment_id = absint( $attachment_id );
315+
316+
// Leave out media the user may not see, and IDs that aren't media, alike.
317+
if ( ! rtgodam_can_view_attachment( $attachment_id ) ) {
318+
continue;
319+
}
320+
285321
$status_object = $this->get_status_object_from_attachment( $attachment_id );
286322
$response_object[ $attachment_id ] = $status_object;
287323
}
@@ -298,9 +334,9 @@ public function get_transcoding_status( \WP_REST_Request $request ) {
298334
*/
299335
private function get_status_object_from_attachment( int $attachment_id ) {
300336
/**
301-
* Fires before reading/writing this attachment's transcoding-status
302-
* metadata (job ID, status, error code/message, progress, thumbnail
303-
* ID, and the thumbnail-retry counter), so integrations that
337+
* Fires before reading this attachment's transcoding-status metadata
338+
* (job ID, status, error code/message, progress, thumbnail ID, and
339+
* the time of the last status update), so integrations that
304340
* centralize media on another site can switch context first. Wrapped
305341
* in try/finally because this method returns early from several
306342
* branches below.
@@ -371,24 +407,20 @@ private function get_status_object_from_attachment( int $attachment_id ) {
371407
// Check if media has thumbnail generated after transcoding.
372408
$thumbnail_id = get_post_meta( $attachment_id, 'rtgodam_media_video_thumbnail', true );
373409

374-
// Handle retry logic for missing thumbnails when transcoding is complete.
410+
// A thumbnail missing right after transcoding may still be on its way. Report 95%
411+
// for a short while after the status was set, then carry on without it. This is a
412+
// read: the time was stored when the status was updated, nothing is written here.
375413
if ( 'transcoded' === strtolower( $status ) && empty( $thumbnail_id ) ) {
376-
$retry_count = intval( get_post_meta( $attachment_id, 'rtgodam_thumbnail_retry_count', true ) );
377-
$max_retries = 3;
378-
379-
if ( $retry_count < $max_retries ) {
380-
// Increment retry count.
381-
update_post_meta( $attachment_id, 'rtgodam_thumbnail_retry_count', $retry_count + 1 );
414+
$status_updated = intval( get_post_meta( $attachment_id, 'rtgodam_transcoding_status_updated', true ) );
382415

383-
// Return transcoding status with 95% progress to indicate waiting for thumbnail.
416+
if ( $status_updated && time() - $status_updated < self::THUMBNAIL_WAIT_SECONDS ) {
384417
return array(
385418
'status' => 'transcoding',
386419
'progress' => 95,
387420
'message' => __( 'Transcoding complete, generating thumbnail...', 'godam' ),
388421
'thumbnail' => '',
389422
);
390423
}
391-
// If max retries reached, continue with normal flow (return transcoded status without thumbnail).
392424
}
393425

394426
return array(

0 commit comments

Comments
 (0)