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