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
5 changes: 4 additions & 1 deletion projects/packages/premium-analytics/.phan/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
array(
// WooCommerce stubs for the TEMPORARY interim sync module port (WOOA7S-1550).
// WooCommerce is a runtime, not composer, dependency; these let Phan resolve WC symbols.
'+stubs' => array( 'woocommerce', 'woocommerce-internal' ),
// 'wpcom' also pulls in wpcomsh's wpcom-features files (.phan/config.base.php),
// which is where wpcom_site_has_feature() is defined — it is not in the
// generated wpcom stubs.
'+stubs' => array( 'woocommerce', 'woocommerce-internal', 'wpcom' ),
'exclude_file_regex' => array(
'build/',
// Test WooCommerce stubs would redefine the WC symbols the +stubs above provide.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: changed

Make the Top videos widget, the Videos report, and the video detail page unavailable on sites without VideoPress, matching the Calypso Stats gating.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ declare module '@automattic/jetpack-script-data' {
has_store_data: boolean;
// Whether CSV export controls should render. Defaults to true server-side.
csv_exports_enabled?: boolean;
// Whether the site runs VideoPress, which gates the video surfaces.
has_videopress?: boolean;
};
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
/**
* External dependencies
*/
import { isSimpleSite } from '@automattic/jetpack-script-data';
import { getScriptData, isSimpleSite } from '@automattic/jetpack-script-data';
/**
* Internal dependencies
*/
import { getReportDefinition } from './registry';

jest.mock( '@automattic/jetpack-script-data', () => ( {
isSimpleSite: jest.fn( () => true ),
getScriptData: jest.fn(),
} ) );

const mockIsSimpleSite = isSimpleSite as jest.Mock;
const mockGetScriptData = getScriptData as jest.Mock;

/**
* Point the mocked script data at a site with or without VideoPress.
*
* @param hasVideoPress - Whether the site runs VideoPress.
*/
function setVideoPress( hasVideoPress: boolean ) {
mockGetScriptData.mockReturnValue( { premium_analytics: { has_videopress: hasVideoPress } } );
}

describe( 'getReportDefinition', () => {
beforeEach( () => {
mockIsSimpleSite.mockReturnValue( true );
setVideoPress( true );
} );

it( 'returns undefined for an unknown report', () => {
Expand Down Expand Up @@ -51,4 +63,20 @@ describe( 'getReportDefinition', () => {

expect( getReportDefinition( 'posts' )?.id ).toBe( 'posts' );
} );

it( 'returns the videos report on sites running VideoPress', () => {
expect( getReportDefinition( 'videos' )?.id ).toBe( 'videos' );
} );

it( 'hides the videos report without VideoPress', () => {
setVideoPress( false );

expect( getReportDefinition( 'videos' ) ).toBeUndefined();
} );

it( 'hides the videos report when the site never published the flag', () => {
mockGetScriptData.mockReturnValue( undefined );

expect( getReportDefinition( 'videos' ) ).toBeUndefined();
} );
} );
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { isVideoPressAvailable } from '../site-readiness';
// Import the tab resolver from `config/tabs` directly rather than the report's
// `config` barrel. `route.ts` imports this registry in `beforeLoad`, so the
// registry must stay free of React/UI at module scope; the `config/index.ts`
Expand Down Expand Up @@ -162,6 +163,10 @@ export const REPORTS: Record< string, ReportDefinition > = {
id: 'videos',
getTitle: () => __( 'Videos', 'jetpack-premium-analytics-pkg' ),
getDescription: () => __( 'See how your videos perform.', 'jetpack-premium-analytics-pkg' ),
// Play counts only exist for VideoPress-hosted videos, and Calypso gates
// its Videos module on the same signal. Mirrors the widget-level gate in
// `src/widget-type-support.php`.
isAvailable: isVideoPressAvailable,
load: () => import( './videos/page' ),
},
utm: {
Expand Down
15 changes: 15 additions & 0 deletions projects/packages/premium-analytics/routes/site-readiness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,18 @@ export function isPremiumAnalyticsInitialSyncFinished(): boolean {
isSimpleSite() || ( getScriptData()?.premium_analytics?.initial_full_sync_finished ?? 0 ) > 0
);
}

/**
* Check whether the site's VideoPress-backed surfaces should be shown.
*
* Defaults to false, unlike the sibling `csv_exports_enabled` flag: showing the
* video surfaces on a site that cannot produce play data is the empty report
* this gate exists to remove. Safe to default that way because every path that
* renders the dashboard runs `Analytics::load_dashboard_components()`, which
* registers the filter that injects the flag (`src/videopress-availability.php`).
*
* @return Whether VideoPress is available on this site.
*/
export function isVideoPressAvailable(): boolean {
return getScriptData()?.premium_analytics?.has_videopress ?? false;
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,29 @@ const validOrigins = [
[ 'utm', 'UTM', 'campaign' ],
] as const;

/**
* Point the script data at a site with or without VideoPress. `videos` is only a
* valid origin on sites running VideoPress, and the report registry reads that
* from script data.
*
* @param hasVideoPress - Whether the site runs VideoPress.
*/
function setVideoPress( hasVideoPress: boolean ) {
Object.defineProperty( window, 'JetpackScriptData', {
configurable: true,
value: { premium_analytics: { has_videopress: hasVideoPress } },
} );
}

describe( 'useDetailBreadcrumbs', () => {
beforeEach( () => {
setVideoPress( true );
} );

afterAll( () => {
delete window.JetpackScriptData;
} );

it.each( validOrigins )(
'adds the %s report before the detail title',
( report, label, section ) => {
Expand Down Expand Up @@ -86,6 +108,19 @@ describe( 'useDetailBreadcrumbs', () => {
expect( result.current ).toEqual( [ { label: 'Detail title' } ] );
} );

// `?origin=videos` outlives the feature: it survives in shared URLs, browser
// history, and bookmarks taken before a site turned VideoPress off. A known
// but unavailable report must be as unlinkable as an unknown one, or the crumb
// points at a page the route guard bounces straight back to the dashboard.
it( 'drops the videos crumb on a site without VideoPress', () => {
setVideoPress( false );
mockSearch( 'videos' );

const { result } = renderHook( () => useDetailBreadcrumbs( 'A video' ) );

expect( result.current ).toEqual( [ { label: 'A video' } ] );
} );

// The origin is untrusted: it is a plain query param anyone can edit, so an
// inherited object property must not read as a report either.
it.each( [ 'bogus', 'constructor', 'toString' ] )( 'ignores the %s report id', report => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { needsReportDateParamsSeed } from '@jetpack-premium-analytics/data';
import {
isPremiumAnalyticsInitialSyncFinished,
isPremiumAnalyticsSiteConnected,
isVideoPressAvailable,
} from '../site-readiness';
import { route } from './route';

Expand All @@ -21,6 +22,7 @@ jest.mock( '@jetpack-premium-analytics/data', () => ( {
jest.mock( '../site-readiness', () => ( {
isPremiumAnalyticsSiteConnected: jest.fn( () => true ),
isPremiumAnalyticsInitialSyncFinished: jest.fn( () => true ),
isVideoPressAvailable: jest.fn( () => true ),
} ) );

jest.mock( '@wordpress/route', () => ( {
Expand Down Expand Up @@ -74,6 +76,14 @@ describe( 'video detail route.beforeLoad', () => {
}
);

it( 'redirects home without VideoPress', async () => {
( isVideoPressAvailable as jest.Mock ).mockReturnValueOnce( false );

await expect( beforeLoad( { videoId: '42' }, settledSearch ) ).rejects.toMatchObject( {
to: '/',
} );
} );

it( 'passes through a settled URL without redirecting', async () => {
await expect( beforeLoad( { videoId: '42' }, settledSearch ) ).resolves.toBeUndefined();
} );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { ensureDashboardEntities } from '../dashboard-entities';
import {
isPremiumAnalyticsInitialSyncFinished,
isPremiumAnalyticsSiteConnected,
isVideoPressAvailable,
} from '../site-readiness';

type VideoDetailParams = { videoId?: string };
Expand All @@ -33,8 +34,8 @@ function isValidVideoId( value: string | undefined ): value is string {
/**
* Route lifecycle for the video detail page.
*
* The page is available only to connected sites after the initial analytics
* sync, and only for positive integer attachment IDs.
* The page is available only to connected sites running VideoPress, after the
* initial analytics sync, and only for positive integer attachment IDs.
*/
export const route = {
beforeLoad: async ( {
Expand All @@ -49,6 +50,13 @@ export const route = {
throw redirect( { to: '/syncing' } );
}

// Kept apart from the id check below: a bookmarked URL on a site without
// VideoPress and a malformed one are different events, even though both
// currently land on the dashboard.
if ( ! isVideoPressAvailable() ) {
throw redirect( { to: '/' } );
}

const videoId = params?.videoId;
if ( ! isValidVideoId( videoId ) ) {
throw redirect( { to: '/' } );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,15 @@ function mockSummary( overrides: Record< string, unknown > = {} ) {
}

describe( 'video detail stage', () => {
// The page only renders on sites running VideoPress, and the report registry
// behind the Videos crumb reads that from script data.
beforeAll( () => {
Object.defineProperty( window, 'JetpackScriptData', {
configurable: true,
value: { premium_analytics: { has_videopress: true } },
} );
} );

beforeEach( () => {
jest.clearAllMocks();
mockDashboardLayouts.length = 0;
Expand All @@ -148,6 +157,10 @@ describe( 'video detail stage', () => {
};
} );

afterAll( () => {
delete window.JetpackScriptData;
} );

it( 'shows a not-found state with a date-preserving link back to Videos', () => {
mockSummary( { isNotFound: true } );

Expand Down
7 changes: 7 additions & 0 deletions projects/packages/premium-analytics/src/class-analytics.php
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,13 @@ private static function load_dashboard_components() {
require_once __DIR__ . '/csv-exports.php';
}
configure_csv_exports();

// VideoPress availability for the client's video routes. The widget layer
// reads the same signal through widget-type-support.php.
if ( ! function_exists( __NAMESPACE__ . '\\configure_videopress_availability' ) ) {
require_once __DIR__ . '/videopress-availability.php';
}
configure_videopress_availability();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ function get_dashboard_default_section_layouts() {
'max' => 10,
)
),
// Row 4: VideoPress + clicks + authors.
// Row 4: VideoPress (sites running VideoPress only) + clicks + authors.
get_dashboard_default_widget_instance(
'default-videopress-widget-instance',
'jpa/videopress',
Expand Down
105 changes: 105 additions & 0 deletions projects/packages/premium-analytics/src/videopress-availability.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php
/**
* VideoPress availability, shared by the widget layer and the client routes.
*
* Calypso gates its Videos module on the `videopress` plan feature, which
* `wpcom_site_has_feature()` answers on the WPCOM platform. That function does
* not exist off-platform. `Current_Plan::supports()` grants `videopress` to
* every plan because of the free tier, while
* `Product::get_site_features_from_wpcom()` can make a synchronous WPCOM
* request and answers entitlement rather than whether VideoPress is running.
* The off-platform question is therefore answered from the module or plugin.
*
* The canonical gates already exist: `VideoPress\Status::is_active()` for the
* off-platform branch, the WPCOM arm of `Current_Plan::supports()` for the
* platform one. Neither `jetpack-videopress` nor `jetpack-plans` is in this
* package's dependency graph, so the detection below is local by necessity.
* Widen the graph before writing another detector.
*
* @package automattic/jetpack-premium-analytics
*/

namespace Automattic\Jetpack\PremiumAnalytics;

use Automattic\Jetpack\Constants;
use Automattic\Jetpack\Modules;
use Automattic\Jetpack\Status\Host;

/**
* Filter controlling whether the VideoPress-backed surfaces are available.
*
* @var string
*/
const VIDEOPRESS_AVAILABLE_FILTER = 'jetpack_premium_analytics_videopress_available';

/**
* Whether the site can produce VideoPress play data.
*
* Atomic reads the plan feature alongside Simple, not the module: wpcomsh
* provides `wpcom_site_has_feature()` there, and the VideoPress module has no
* `Auto Activate` header, so a plan that includes VideoPress routinely comes
* with the module off. wpcomsh grants `videopress` to every business-and-higher
* plan and WoA only exists on those, so the platform branch effectively gates
* Simple alone: an Atomic site with the module off keeps the video surfaces.
* That is intended — hosting is service-level on WPCOM, so the module would be
* a false negative there.
*
* Off-platform the question becomes "is VideoPress running here", not "is it
* paid for" — without the module there is no new play data to report. That is
* deliberately narrower than `Initial_State::has_videopress_access()`, which
* never looks at the module and counts the paid storage tiers instead.
*
* `Current_Plan::supports( 'videopress' )` is avoided because off-platform it
* returns true for every plan, thanks to the VideoPress free tier.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking; nothing in the logic needs to change. One ask: on the is_videopress_available() docblock.

The off-platform branch is VideoPress\Status::is_active(), the same two signals and the gate four places in the VideoPress package already use. The platform branch is the WPCOM hijack inside Current_Plan::supports(). Neither is reachable: jetpack-plans and jetpack-videopress aren't in this package's dependency graph, so local detection is the only option today.

The docblock rules out Current_Plan::supports() on semantic grounds, which is right, but doesn't mention Status::is_active(), which is semantically this branch and only out of reach. Worth naming it plus the boundary, so the next person finds the trail instead of writing a fifth detector.

Also worth stating: the platform branch never fires on Atomic, since wpcomsh grants videopress to WPCOM_BUSINESS_AND_HIGHER_PLANS and WoA only exists there. I don't think that's wrong (hosting is service-level on WPCOM, so the module is a false negative), but the effective coverage is Simple plus self-hosted, and an Atomic site with the module off and no videos keeps both empty surfaces.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch. I've named it in the docblock along with why it's out of reach.

*
* @return bool Whether Premium Analytics treats VideoPress as available.
*/
function is_videopress_available() {
if ( ( new Host() )->is_wpcom_platform() ) {
$is_available = function_exists( 'wpcom_site_has_feature' ) && \wpcom_site_has_feature( 'videopress' );
} else {
// `false` skips the module registry the standalone Premium Analytics plugin
// does not ship, which would otherwise report every module inactive.
$is_available = ( new Modules() )->is_active( 'videopress', false )
|| Constants::is_defined( 'JETPACK_VIDEOPRESS_ROOT_FILE' );
}

/**
* Filters whether Premium Analytics treats VideoPress as available.
*
* Hides the Top videos widget, the Videos report, and the video detail page
* when false.
*
* @param bool $is_available Whether VideoPress was detected in the current request.
*/
return (bool) apply_filters( VIDEOPRESS_AVAILABLE_FILTER, $is_available );
}

/**
* Configures the VideoPress script data.
*
* @return void
*/
function configure_videopress_availability() {
add_filter( 'jetpack_admin_js_script_data', __NAMESPACE__ . '\\inject_videopress_script_data', 20 );
}

/**
* Injects the VideoPress availability flag into JetpackScriptData.
*
* The client cannot read `site.plan.features` for this: that key is only
* populated when the Publicize package happens to be loaded, which the
* standalone Premium Analytics plugin never loads.
*
* @param array $data The script data passed by the assets package.
* @return array
*/
function inject_videopress_script_data( array $data ): array {
if ( ! isset( $data['premium_analytics'] ) || ! is_array( $data['premium_analytics'] ) ) {
$data['premium_analytics'] = array();
}

$data['premium_analytics']['has_videopress'] = is_videopress_available();

return $data;
}
Loading
Loading