Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
43 changes: 39 additions & 4 deletions inc/classes/rest-api/class-analytics.php
Original file line number Diff line number Diff line change
Expand Up @@ -525,13 +525,48 @@ public function get_rest_routes() {
* Each route proxies the site's stored API key and account token to the
* analytics microservice, so none may answer anonymous callers. Access
* matches the Analytics and Media Editor menus' `upload_files` capability
* (authors and above). It also stops unauthenticated requests from
* triggering uncached upstream calls.
* (authors and above), for a video the user can edit, as the Media Editor
* asks. It also stops unauthenticated requests from triggering uncached
* upstream calls.
*
* @param WP_REST_Request $request REST API request.
* @return bool Whether the current user may read per-video analytics.
*/
public function check_analytics_read_permission() {
return current_user_can( 'upload_files' );
public function check_analytics_read_permission( WP_REST_Request $request ) {
return current_user_can( 'upload_files' ) && $this->can_read_video_analytics( $request->get_param( 'video_id' ) );
}

/**
* Whether the current user may read the analytics of a video: an attachment of
* this site that they can edit, which is what the Media Editor asks before it
* opens a video. Editors and administrators can edit every attachment; an
* author can edit their own.
*
* @since n.e.x.t
*
* @param int|string $video_id Attachment ID of the video.
* @return bool
*/
public function can_read_video_analytics( $video_id ) {
$video_id = absint( $video_id );

if ( ! $video_id ) {
return false;
}

/**
* Fires before this attachment-specific capability check, so
* integrations that centralize media on another site can switch
* context first.
*
* @since 2.2.0
*/
do_action( 'rtgodam_before_attachment_lookup' );
$video = get_post( $video_id );
$can_read = $video && 'attachment' === $video->post_type && current_user_can( 'edit_post', $video_id );
do_action( 'rtgodam_after_attachment_lookup' );

return (bool) $can_read;
}

/**
Expand Down
158 changes: 147 additions & 11 deletions inc/classes/rest-api/class-engagement.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,9 @@ public function get_rest_routes() {
/**
* Get all activities for a video.
*
* Answers only for a video of this site that the visitor can see. For any other
* video the answer is the same as for a video nobody has engaged with.
*
* @param WP_REST_Request $request Request Object.
*
* @return WP_REST_Response
Expand All @@ -268,6 +271,23 @@ public function get_activities( $request ) {
return $this->site_origin_unavailable_response( 500 );
}

$transcoder_job_id = $this->get_visible_transcoder_job_id( $video_id );

if ( null === $transcoder_job_id ) {
return new WP_REST_Response(
array(
'status' => 'success',
'data' => array(
'is_liked' => false,
'likes_count' => 0,
'comments' => array(),
'comments_count' => 0,
),
),
200
);
}

$account_credentials = $this->access_credentials_check();

if ( $account_credentials instanceof WP_REST_Response ) {
Expand All @@ -288,8 +308,6 @@ public function get_activities( $request ) {
$response_data['views_count'] = array_sum( $analytics_data['processed_analytics']['post_views'] ?? array() );
}

$transcoder_job_id = $this->get_transcoder_job_id( $video_id );

$likes = $this->get_likes( $transcoder_job_id, $account_credentials );
$response_data['is_liked'] = $likes['has_liked_by_user'];
$response_data['likes_count'] = $likes['likes'];
Expand Down Expand Up @@ -442,7 +460,11 @@ public function user_hit_like( $request ) {
$current_user = rtgodam_get_current_logged_in_user_data();
$current_user_email = $current_user['email'];
$current_user_name = $current_user['name'];
$transcoder_job_id = $this->get_transcoder_job_id( $video_id );
$transcoder_job_id = $this->get_visible_transcoder_job_id( $video_id );

if ( null === $transcoder_job_id ) {
return $this->video_not_available_response();
}

$query_params = array(
'api_key' => $account_credentials['api_key'],
Expand Down Expand Up @@ -529,7 +551,11 @@ public function user_comment( $request ) {
$current_user = rtgodam_get_current_logged_in_user_data();
$current_user_email = $current_user['email'];
$current_user_name = $current_user['name'];
$transcoder_job_id = $this->get_transcoder_job_id( $video_id );
$transcoder_job_id = $this->get_visible_transcoder_job_id( $video_id );

if ( null === $transcoder_job_id ) {
return $this->video_not_available_response();
}

// Only the author may edit a comment, whatever id the browser sends.
if ( 'edit' === $comment_type ) {
Expand Down Expand Up @@ -1174,14 +1200,50 @@ public function engagement_permission_check() {
/**
* Returns the transcoding job ID for a given video ID.
*
* @param int|string $video_id The video ID. If it starts with 'cmmid_', the rest is the transcoding job ID.
* The job ID always comes from an attachment of this site, never from the
* request itself: a numeric video ID is an attachment ID, and `cmmid_` followed
* by a job ID stands for the attachment that carries that job ID.
*
* @param int|string $video_id The video ID: an attachment ID, or 'cmmid_' and the transcoding job ID of one.
*
* @return string|null The transcoding job ID, or null if not found.
* @return string|null The transcoding job ID, or null if this site has no such video.
*/
public function get_transcoder_job_id( $video_id ) {
if ( 0 === strpos( $video_id, 'cmmid_' ) ) {
return preg_replace( '/^cmmid_/', '', $video_id );
}
return $this->find_transcoder_job_id( $video_id, false );
}

/**
* Returns the transcoding job ID for a video of this site that the current user can see.
*
* A video is visible when rtgodam_can_view_attachment() says so, as on
* GoDAM's other public routes: it is unattached, the post it was uploaded to
* is public or readable by the current user, the user can edit it, or it is
* used on a publicly viewable post.
*
* @since n.e.x.t
*
* @param int|string $video_id The video ID: an attachment ID, or 'cmmid_' and the transcoding job ID of one.
*
* @return string|null The transcoding job ID, or null if this site has no such video or the current user cannot see it.
*/
public function get_visible_transcoder_job_id( $video_id ) {
return $this->find_transcoder_job_id( $video_id, true );
}

/**
* Finds the transcoding job ID of a video through the attachments of this site.
*
* @since n.e.x.t
*
* @param int|string $video_id The video ID: an attachment ID, or 'cmmid_' and the transcoding job ID of one.
* @param bool $visible_only Whether to skip attachments the current user cannot see.
*
* @return string|null The transcoding job ID, or null if there is none.
*/
private function find_transcoder_job_id( $video_id, $visible_only ) {
$video_id = (string) $video_id;
$named_job = '';
$candidates = array();

/**
* Fires before reading this attachment's transcoding job ID, so
Expand All @@ -1191,10 +1253,84 @@ public function get_transcoder_job_id( $video_id ) {
* @since 2.2.0
*/
do_action( 'rtgodam_before_attachment_lookup' );
$transcoder_job_id = get_post_meta( $video_id, 'rtgodam_transcoding_job_id', true );

if ( 0 === strpos( $video_id, 'cmmid_' ) ) {
$named_job = substr( $video_id, strlen( 'cmmid_' ) );

if ( '' !== $named_job ) {
// Central media keeps its job ID as the attachment's job ID or GoDAM ID.
$candidates = get_posts( // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.get_posts_get_posts
array(
'post_type' => 'attachment',
'post_status' => 'any',
'posts_per_page' => 10,
'fields' => 'ids',
'no_found_rows' => true,
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for finding the attachment by its job ID.
'relation' => 'OR',
array(
'key' => 'rtgodam_transcoding_job_id',
'value' => $named_job,
),
array(
'key' => '_godam_original_id',
'value' => $named_job,
),
),
)
);
}
} elseif ( ctype_digit( $video_id ) && (int) $video_id > 0 ) {
$candidates = array( (int) $video_id );
}

$jobs = array();

foreach ( $candidates as $attachment_id ) {
$attachment = get_post( $attachment_id );

if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
continue;
}

$job_id = '' !== $named_job ? $named_job : get_post_meta( $attachment->ID, 'rtgodam_transcoding_job_id', true );

if ( ! empty( $job_id ) ) {
$jobs[ $attachment->ID ] = (string) $job_id;
}
}

do_action( 'rtgodam_after_attachment_lookup' );

return ! empty( $transcoder_job_id ) ? $transcoder_job_id : null;
// rtgodam_can_view_attachment() brackets its own lookup, so it runs once the lookup above has closed.
foreach ( $jobs as $attachment_id => $job_id ) {
if ( ! $visible_only || rtgodam_can_view_attachment( $attachment_id ) ) {
return $job_id;
}
}

return null;
}

/**
* The refusal for a video the current user may not like or comment on.
*
* The same answer for a video that is not on this site, one that does not exist
* and one the current user cannot see.
*
* @since n.e.x.t
*
* @return WP_REST_Response
*/
private function video_not_available_response() {
return new WP_REST_Response(
array(
'status' => 'error',
'message' => __( 'This video is not available.', 'godam' ),
'errorType' => 'video_not_available',
),
403
);
}

/**
Expand Down
7 changes: 6 additions & 1 deletion pages/analytics/Analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import videojs from 'video.js';
import { arrowLeft, info } from '@wordpress/icons';
import { ERROR_TYPE } from '../shared/enums';
import AnalyticsUnavailableNotice from '../shared/AnalyticsUnavailableNotice';
import AnalyticsForbiddenNotice, { isAnalyticsForbidden } from './AnalyticsForbiddenNotice';
import { canViewStoreData } from '../shared/canViewStoreData';
import { formatWatchTime } from '../utils/formatters';
import UpgradePlanAnalyticsBg from '../../assets/src/images/upgrade-plan-analytics-bg.webp';
Expand Down Expand Up @@ -134,6 +135,7 @@ const Analytics = ( { attachmentID } ) => {
data: analyticsDataFetched,
isLoading: isAnalyticsDataLoading,
isError: isAnalyticsDataError,
error: analyticsDataError,
} = useFetchAnalyticsDataQuery(
{ videoId: attachmentID, siteUrl },
{ skip: ! attachmentID || shouldSkipAnalytics },
Expand Down Expand Up @@ -203,7 +205,9 @@ const Analytics = ( { attachmentID } ) => {
// Connected, but the analytics backend is unreachable (server down) or returned
// a microservice error. Gated on a valid key so it never shows for a
// disconnected site — that case is handled by the onboarding overlay.
const analyticsUnreachable = !! window.userData?.validApiKey && !! attachmentID && ! shouldSkipAnalytics && ( isAnalyticsDataError || analyticsDataFetched?.errorType === ERROR_TYPE.MICROSERVICE_ERROR );
// The route refused this video for this user (an Author opening someone else's video), not an outage.
const analyticsForbidden = isAnalyticsDataError && isAnalyticsForbidden( analyticsDataError );
const analyticsUnreachable = !! window.userData?.validApiKey && !! attachmentID && ! shouldSkipAnalytics && ! analyticsForbidden && ( isAnalyticsDataError || analyticsDataFetched?.errorType === ERROR_TYPE.MICROSERVICE_ERROR );

// charts.js (KPIs + geography + Views-by-Source) renders from this global.
window.analyticsDataFetched = rangedAnalyticsData ?? analyticsDataFetched;
Expand Down Expand Up @@ -565,6 +569,7 @@ const Analytics = ( { attachmentID } ) => {
</div>

{ analyticsUnreachable && <AnalyticsUnavailableNotice area="analytics" /> }
{ analyticsForbidden && <AnalyticsForbiddenNotice /> }

<div
id="media-not-found-overlay"
Expand Down
40 changes: 40 additions & 0 deletions pages/analytics/AnalyticsForbiddenNotice.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { Notice } from '@wordpress/components';

/**
* Internal dependencies
*/
import '../shared/analytics-unavailable.scss';

/**
* Whether the analytics request was refused because the current user may not
* read this video's analytics: the route answers 403 for a video the user
* cannot edit, such as an Author opening someone else's video.
*
* @since n.e.x.t
*
* @param {Object|undefined} error The query's error, as RTK Query's fetchBaseQuery returns it.
* @return {boolean} True for a 403 answer.
*/
export const isAnalyticsForbidden = ( error ) => 403 === error?.status;

/**
* Shown instead of the analytics when the user may not read this video's analytics.
*
* @since n.e.x.t
*
* @return {JSX.Element} The notice.
*/
const AnalyticsForbiddenNotice = () => (
<div className="godam-analytics-forbidden" data-test-id="godam-analytics-notice-analytics-forbidden">
<Notice status="warning" isDismissible={ false }>
<strong>{ __( 'You can’t view analytics for this video.', 'godam' ) }</strong>{ ' ' }
{ __( 'Analytics is shown only for videos you can edit. Choose one of your own videos, or ask an Editor or Administrator.', 'godam' ) }
</Notice>
</div>
);

export default AnalyticsForbiddenNotice;
51 changes: 51 additions & 0 deletions pages/analytics/AnalyticsForbiddenNotice.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* Unit tests for AnalyticsForbiddenNotice: the notice the Single Video Analytics
* page shows when the analytics route refuses the video (403), so an Author who
* opens someone else's video is told why instead of being shown the
* "analytics is temporarily unavailable" notice.
*
* @package
*/

/**
* WordPress dependencies
*/
import { renderToString } from '@wordpress/element';

// Only the text matters here; the real components pull in a second copy of React.
jest.mock( '@wordpress/components', () => ( {
Notice: ( { status, children } ) => <div data-status={ status }>{ children }</div>,
} ) );
jest.mock( '../shared/analytics-unavailable.scss', () => ( {} ) );

/**
* Internal dependencies
*/
import AnalyticsForbiddenNotice, { isAnalyticsForbidden } from './AnalyticsForbiddenNotice';

describe( 'isAnalyticsForbidden', () => {
it( 'is true only for a 403 answer', () => {
expect( isAnalyticsForbidden( { status: 403, data: { code: 'rest_forbidden' } } ) ).toBe( true );
} );

it.each( [
[ 'a server error', { status: 500 } ],
[ 'a network error', { status: 'FETCH_ERROR', error: 'TypeError: Failed to fetch' } ],
[ 'a signed-out answer', { status: 401 } ],
[ 'no error', undefined ],
] )( 'is false for %s', ( label, error ) => {
expect( isAnalyticsForbidden( error ) ).toBe( false );
} );
} );

describe( 'AnalyticsForbiddenNotice', () => {
it( 'says the user cannot view this video and why', () => {
const html = renderToString( <AnalyticsForbiddenNotice /> );

expect( html ).toContain( 'godam-analytics-notice-analytics-forbidden' );
expect( html ).toContain( 'analytics for this video' );
expect( html ).toContain( 'only for videos you can edit' );
expect( html ).toContain( 'data-status="warning"' );
expect( html ).not.toContain( 'temporarily unavailable' );
} );
} );
Loading