Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.21% covered (warning)
84.21%
64 / 76
80.00% covered (warning)
80.00%
4 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
Rest_Controller
84.21% covered (warning)
84.21%
64 / 76
80.00% covered (warning)
80.00%
4 / 5
14.77
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_rest_routes
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 stats_video_plays_args
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
1
 permissions_callback
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_stats_video_plays
69.23% covered (warning)
69.23%
27 / 39
0.00% covered (danger)
0.00%
0 / 1
12.91
1<?php
2/**
3 * The VideoPress REST Controller.
4 *
5 * Registers the `/jetpack/v4/videopress/*` routes backing the
6 * modernized wp-build dashboard: a proxy to the WPCOM
7 * `sites/{id}/stats/video-plays` endpoint for the Overview screen's
8 * KPI / trends / top-N cards, and the Playlists tab's routes
9 * ( see Playlist_Manager ).
10 *
11 * @package automattic/jetpack-videopress
12 */
13
14namespace Automattic\Jetpack\VideoPress;
15
16use Automattic\Jetpack\Connection\Client;
17use Jetpack_Options;
18use WP_Error;
19use WP_REST_Request;
20use WP_REST_Server;
21
22/**
23 * REST routes for the modernized VideoPress admin UI.
24 */
25class Rest_Controller {
26
27    /**
28     * REST namespace used by this package's modernization routes.
29     *
30     * @var string
31     */
32    const REST_NAMESPACE = 'jetpack/v4/videopress';
33
34    /**
35     * Hook the route registration on `rest_api_init`.
36     *
37     * @return void
38     */
39    public static function init() {
40        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
41    }
42
43    /**
44     * Register the VideoPress REST routes.
45     *
46     * @return void
47     */
48    public static function register_rest_routes() {
49        register_rest_route(
50            self::REST_NAMESPACE,
51            '/stats/video-plays',
52            array(
53                'methods'             => WP_REST_Server::READABLE,
54                'callback'            => array( __CLASS__, 'get_stats_video_plays' ),
55                'permission_callback' => array( __CLASS__, 'permissions_callback' ),
56                'args'                => self::stats_video_plays_args(),
57            )
58        );
59
60        Playlist_Manager::register_rest_routes();
61        Transcript_Index::register_rest_routes();
62    }
63
64    /**
65     * Query params accepted by the video-plays proxy. Forwarded verbatim
66     * to WPCOM after permission and shape validation. `complete_stats` and
67     * `check_stats_module` are always forced by the callback and are
68     * therefore not exposed as incoming params.
69     *
70     * @return array
71     */
72    private static function stats_video_plays_args() {
73        return array(
74            'period'     => array(
75                'description' => __( 'Period unit: day, week, month, or year.', 'jetpack-videopress-pkg' ),
76                'type'        => 'string',
77                'enum'        => array( 'day', 'week', 'month', 'year' ),
78            ),
79            'num'        => array(
80                'description' => __( 'Number of periods to include.', 'jetpack-videopress-pkg' ),
81                'type'        => 'integer',
82                'minimum'     => 1,
83                'maximum'     => 365,
84            ),
85            'date'       => array(
86                'description' => __( 'Most recent day to include in results (YYYY-MM-DD).', 'jetpack-videopress-pkg' ),
87                'type'        => 'string',
88                'format'      => 'date',
89            ),
90            'start_date' => array(
91                'description' => __( 'Starting date for range queries (YYYY-MM-DD).', 'jetpack-videopress-pkg' ),
92                'type'        => 'string',
93                'format'      => 'date',
94            ),
95        );
96    }
97
98    /**
99     * Permission callback. Admin-gated. The upstream call is blog-signed,
100     * matching the existing `Stats::fetch_video_plays` path; no user-level
101     * WPCOM connection is required.
102     *
103     * @return bool
104     */
105    public static function permissions_callback() {
106        return current_user_can( 'manage_options' );
107    }
108
109    /**
110     * Proxy the video-plays stats endpoint.
111     *
112     * Forwards the allowed query params to WPCOM (REST v1.1, blog-signed
113     * — matching the existing `Stats::fetch_video_plays` path) and forces
114     * `complete_stats=true`. `check_stats_module=false` is also forced so the
115     * report loads for standalone VideoPress sites without the Jetpack Stats
116     * module active, matching `Stats::fetch_video_plays`. In complete-stats
117     * mode, each day entry carries
118     * `total.views`, `total.impressions`, and `total.watch_time` (in hours)
119     * plus a per-video `data[]` array whose entries have `post_id`, `title`,
120     * `views`, `impressions`, `watch_time` (hours), and `retention_rate`.
121     * The `plays` field is NOT returned in complete-stats mode.
122     *
123     * @param WP_REST_Request $request Incoming request.
124     * @return mixed Decoded JSON response from WPCOM, or WP_Error on failure.
125     */
126    public static function get_stats_video_plays( WP_REST_Request $request ) {
127        $blog_id = (int) Jetpack_Options::get_option( 'id' );
128        if ( ! $blog_id ) {
129            return new WP_Error(
130                'videopress_stats_not_connected',
131                esc_html__( 'This site is not connected to WordPress.com.', 'jetpack-videopress-pkg' ),
132                array( 'status' => 400 )
133            );
134        }
135
136        $params = array(
137            'complete_stats'     => 'true',
138            'check_stats_module' => 'false',
139        );
140        foreach ( array_keys( self::stats_video_plays_args() ) as $key ) {
141            $value = $request->get_param( $key );
142            if ( $value !== null && $value !== '' ) {
143                $params[ $key ] = $value;
144            }
145        }
146
147        $path     = sprintf(
148            'sites/%d/stats/video-plays?%s',
149            $blog_id,
150            http_build_query( $params )
151        );
152        $response = Client::wpcom_json_api_request_as_blog( $path );
153
154        if ( is_wp_error( $response ) ) {
155            return new WP_Error(
156                'videopress_stats_request_failed',
157                $response->get_error_message(),
158                array( 'status' => 500 )
159            );
160        }
161
162        $status = (int) wp_remote_retrieve_response_code( $response );
163        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
164
165        if ( 200 !== $status ) {
166            $message = is_array( $body ) && isset( $body['message'] )
167                ? (string) $body['message']
168                : esc_html__( 'Unable to fetch VideoPress stats.', 'jetpack-videopress-pkg' );
169            return new WP_Error(
170                'videopress_stats_request_failed',
171                $message,
172                array( 'status' => $status ? $status : 500 )
173            );
174        }
175
176        return rest_ensure_response( $body );
177    }
178}