Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.00% covered (warning)
84.00%
63 / 75
80.00% covered (warning)
80.00%
4 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
Rest_Controller
84.00% covered (warning)
84.00%
63 / 75
80.00% covered (warning)
80.00%
4 / 5
14.80
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%
11 / 11
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    }
62
63    /**
64     * Query params accepted by the video-plays proxy. Forwarded verbatim
65     * to WPCOM after permission and shape validation. `complete_stats` and
66     * `check_stats_module` are always forced by the callback and are
67     * therefore not exposed as incoming params.
68     *
69     * @return array
70     */
71    private static function stats_video_plays_args() {
72        return array(
73            'period'     => array(
74                'description' => __( 'Period unit: day, week, month, or year.', 'jetpack-videopress-pkg' ),
75                'type'        => 'string',
76                'enum'        => array( 'day', 'week', 'month', 'year' ),
77            ),
78            'num'        => array(
79                'description' => __( 'Number of periods to include.', 'jetpack-videopress-pkg' ),
80                'type'        => 'integer',
81                'minimum'     => 1,
82                'maximum'     => 365,
83            ),
84            'date'       => array(
85                'description' => __( 'Most recent day to include in results (YYYY-MM-DD).', 'jetpack-videopress-pkg' ),
86                'type'        => 'string',
87                'format'      => 'date',
88            ),
89            'start_date' => array(
90                'description' => __( 'Starting date for range queries (YYYY-MM-DD).', 'jetpack-videopress-pkg' ),
91                'type'        => 'string',
92                'format'      => 'date',
93            ),
94        );
95    }
96
97    /**
98     * Permission callback. Admin-gated. The upstream call is blog-signed,
99     * matching the existing `Stats::fetch_video_plays` path; no user-level
100     * WPCOM connection is required.
101     *
102     * @return bool
103     */
104    public static function permissions_callback() {
105        return current_user_can( 'manage_options' );
106    }
107
108    /**
109     * Proxy the video-plays stats endpoint.
110     *
111     * Forwards the allowed query params to WPCOM (REST v1.1, blog-signed
112     * — matching the existing `Stats::fetch_video_plays` path) and forces
113     * `complete_stats=true`. `check_stats_module=false` is also forced so the
114     * report loads for standalone VideoPress sites without the Jetpack Stats
115     * module active, matching `Stats::fetch_video_plays`. In complete-stats
116     * mode, each day entry carries
117     * `total.views`, `total.impressions`, and `total.watch_time` (in hours)
118     * plus a per-video `data[]` array whose entries have `post_id`, `title`,
119     * `views`, `impressions`, `watch_time` (hours), and `retention_rate`.
120     * The `plays` field is NOT returned in complete-stats mode.
121     *
122     * @param WP_REST_Request $request Incoming request.
123     * @return mixed Decoded JSON response from WPCOM, or WP_Error on failure.
124     */
125    public static function get_stats_video_plays( WP_REST_Request $request ) {
126        $blog_id = (int) Jetpack_Options::get_option( 'id' );
127        if ( ! $blog_id ) {
128            return new WP_Error(
129                'videopress_stats_not_connected',
130                esc_html__( 'This site is not connected to WordPress.com.', 'jetpack-videopress-pkg' ),
131                array( 'status' => 400 )
132            );
133        }
134
135        $params = array(
136            'complete_stats'     => 'true',
137            'check_stats_module' => 'false',
138        );
139        foreach ( array_keys( self::stats_video_plays_args() ) as $key ) {
140            $value = $request->get_param( $key );
141            if ( $value !== null && $value !== '' ) {
142                $params[ $key ] = $value;
143            }
144        }
145
146        $path     = sprintf(
147            'sites/%d/stats/video-plays?%s',
148            $blog_id,
149            http_build_query( $params )
150        );
151        $response = Client::wpcom_json_api_request_as_blog( $path );
152
153        if ( is_wp_error( $response ) ) {
154            return new WP_Error(
155                'videopress_stats_request_failed',
156                $response->get_error_message(),
157                array( 'status' => 500 )
158            );
159        }
160
161        $status = (int) wp_remote_retrieve_response_code( $response );
162        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
163
164        if ( 200 !== $status ) {
165            $message = is_array( $body ) && isset( $body['message'] )
166                ? (string) $body['message']
167                : esc_html__( 'Unable to fetch VideoPress stats.', 'jetpack-videopress-pkg' );
168            return new WP_Error(
169                'videopress_stats_request_failed',
170                $message,
171                array( 'status' => $status ? $status : 500 )
172            );
173        }
174
175        return rest_ensure_response( $body );
176    }
177}