Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.61% covered (warning)
75.61%
499 / 660
30.00% covered (danger)
30.00%
6 / 20
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_REST_API_V2_Endpoint_VideoPress
75.61% covered (warning)
75.61%
496 / 656
30.00% covered (danger)
30.00%
6 / 20
351.71
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 register_routes
98.78% covered (success)
98.78%
242 / 245
0.00% covered (danger)
0.00%
0 / 1
12
 videopress_get_settings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 videopress_update_settings
81.25% covered (warning)
81.25%
26 / 32
0.00% covered (danger)
0.00%
0 / 1
11.80
 videopress_promote_attachment
100.00% covered (success)
100.00%
82 / 82
100.00% covered (success)
100.00%
1 / 1
18
 promote_lock_key
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 promote_is_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 promote_site_has_videopress
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 promote_load_primitives
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
6.02
 promote_video_info
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 promote_find_any_guid
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 promote_transcode
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 videopress_video_belong_to_site
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 wpcom_poster_request
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
12
 get_video_attachment_id
72.73% covered (warning)
72.73%
8 / 11
0.00% covered (danger)
0.00%
0 / 1
9.30
 videopress_block_update_poster
21.05% covered (danger)
21.05%
4 / 19
0.00% covered (danger)
0.00%
0 / 1
3.97
 videopress_block_get_poster
30.77% covered (danger)
30.77%
4 / 13
0.00% covered (danger)
0.00%
0 / 1
3.33
 videopress_upload_jwt
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
20
 videopress_playback_jwt
51.35% covered (warning)
51.35%
19 / 37
0.00% covered (danger)
0.00%
0 / 1
7.88
 videopress_block_update_meta
70.77% covered (warning)
70.77%
92 / 130
0.00% covered (danger)
0.00%
0 / 1
76.99
1<?php
2/**
3 * REST API endpoint for managing VideoPress metadata.
4 *
5 * @package automattic/jetpack
6 * @since-jetpack 9.3.0
7 * @since 0.1.3
8 */
9
10namespace Automattic\Jetpack\VideoPress;
11
12use Automattic\Jetpack\Connection\Client;
13use Automattic\Jetpack\Constants;
14use WP_Error;
15use WP_REST_Controller;
16use WP_REST_Request;
17use WP_REST_Response;
18use WP_REST_Server;
19
20if ( ! defined( 'ABSPATH' ) ) {
21    exit( 0 );
22}
23
24/**
25 * VideoPress wpcom api v2 endpoint
26 *
27 * @phan-constructor-used-for-side-effects
28 */
29class WPCOM_REST_API_V2_Endpoint_VideoPress extends WP_REST_Controller {
30    /**
31     * Constructor.
32     */
33    public function __construct() {
34        $this->namespace = 'wpcom/v2';
35        $this->rest_base = 'videopress';
36
37        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
38    }
39
40    /**
41     * Register the route.
42     */
43    public function register_routes() {
44        // Meta Route.
45        register_rest_route(
46            $this->namespace,
47            $this->rest_base . '/meta',
48            array(
49                'args'                => array(
50                    'id'              => array(
51                        'description' => __( 'The post id for the attachment.', 'jetpack-videopress-pkg' ),
52                        'type'        => 'integer',
53                        'required'    => true,
54                    ),
55                    'title'           => array(
56                        'description'       => __( 'The title of the video.', 'jetpack-videopress-pkg' ),
57                        'type'              => 'string',
58                        'sanitize_callback' => 'sanitize_text_field',
59                    ),
60                    'description'     => array(
61                        'description'       => __( 'The description of the video.', 'jetpack-videopress-pkg' ),
62                        'type'              => 'string',
63                        'sanitize_callback' => 'sanitize_textarea_field',
64                    ),
65                    'caption'         => array(
66                        'description'       => __( 'The caption of the video.', 'jetpack-videopress-pkg' ),
67                        'type'              => 'string',
68                        'sanitize_callback' => 'sanitize_textarea_field',
69                    ),
70                    'rating'          => array(
71                        'description'       => __( 'The video content rating. One of G, PG-13 or R-17', 'jetpack-videopress-pkg' ),
72                        'type'              => 'string',
73                        'sanitize_callback' => 'sanitize_text_field',
74                    ),
75                    'display_embed'   => array(
76                        'description' => __( 'Display the share menu in the player.', 'jetpack-videopress-pkg' ),
77                        'type'        => 'boolean',
78                    ),
79                    'allow_download'  => array(
80                        'description' => __( 'Display download option and allow viewers to download this video', 'jetpack-videopress-pkg' ),
81                        'type'        => 'boolean',
82                    ),
83                    'privacy_setting' => array(
84                        'description' => __( 'How to determine if the video should be public or private', 'jetpack-videopress-pkg' ),
85                        'type'        => 'integer',
86                        'enum'        => array(
87                            \VIDEOPRESS_PRIVACY::IS_PUBLIC,
88                            \VIDEOPRESS_PRIVACY::IS_PRIVATE,
89                            \VIDEOPRESS_PRIVACY::SITE_DEFAULT,
90                        ),
91                    ),
92                ),
93                'methods'             => WP_REST_Server::EDITABLE,
94                'callback'            => array( $this, 'videopress_block_update_meta' ),
95                'permission_callback' => function ( $request ) {
96                    if ( ! Data::can_perform_action() ) {
97                        return false;
98                    }
99                    // Authorize against the specific attachment the request targets,
100                    // not just the generic edit_posts capability. `id` is read from
101                    // the JSON body to match videopress_block_update_meta(), so a
102                    // Contributor cannot modify (or, via a privacy downgrade, expose)
103                    // another user's video.
104                    $params  = $request->get_json_params();
105                    $post_id = isset( $params['id'] ) ? (int) $params['id'] : 0;
106                    return current_user_can( 'edit_post', $post_id );
107                },
108            )
109        );
110
111        // Poster Route.
112        register_rest_route(
113            $this->namespace,
114            $this->rest_base . '/(?P<video_guid>[A-Za-z0-9]{8})/poster',
115            array(
116                'args' => array(
117                    'video_guid' => array(
118                        'description' => __( 'The VideoPress GUID.', 'jetpack-videopress-pkg' ), // @phan-suppress-current-line PhanPluginMixedKeyNoKey
119                        'type'        => 'string',
120                        'required'    => true,
121                    ),
122                ),
123                array(
124                    'methods'             => WP_REST_Server::READABLE,
125                    'callback'            => array( $this, 'videopress_block_get_poster' ),
126                    'permission_callback' => function ( $request ) {
127                        // Reading a poster/frame exposes video content, so require the
128                        // same per-video view authorization as playback in addition to
129                        // `read`. This closes a Subscriber+ read of any private video's
130                        // poster/frame by guid.
131                        //
132                        // `read` is kept because is_current_user_authed_for_video() has
133                        // no logged-out bail and returns true for an effectively public
134                        // video, so dropping it would make this route reachable
135                        // anonymously -- an unauthenticated amplifier for the two
136                        // outbound WordPress.com requests the handler makes.
137                        return current_user_can( 'read' )
138                            && Access_Control::instance()->is_current_user_authed_for_video( $request->get_param( 'video_guid' ), 0 );
139                    },
140                ),
141                array(
142                    'args'                => array(
143                        'at_time'              => array(
144                            'description' => __( 'The time in the video to use as the poster frame.', 'jetpack-videopress-pkg' ),
145                            'type'        => 'integer',
146                        ),
147                        'is_millisec'          => array(
148                            'description' => __( 'Whether the time is in milliseconds or seconds.', 'jetpack-videopress-pkg' ),
149                            'type'        => 'boolean',
150                        ),
151                        'poster_attachment_id' => array(
152                            'description' => __( 'The attachment id of the poster image.', 'jetpack-videopress-pkg' ),
153                            'type'        => 'integer',
154                        ),
155                    ),
156                    'methods'             => WP_REST_Server::EDITABLE,
157                    'callback'            => array( $this, 'videopress_block_update_poster' ),
158                    'permission_callback' => function ( $request ) {
159                        // Authorize the poster write against the specific video rather
160                        // than the site-wide upload_files capability alone, so an author
161                        // cannot overwrite the poster of another user's video by guid.
162                        //
163                        // upload_files is kept as a floor: for an attachment
164                        // (post_status 'inherit') core maps edit_post to edit_posts for
165                        // the post author, which a Contributor has and which does not
166                        // imply the media rights this route needs.
167                        if ( ! Data::can_perform_action() || ! current_user_can( 'upload_files' ) ) {
168                            return false;
169                        }
170
171                        $attachment_id = self::get_video_attachment_id( $request->get_param( 'video_guid' ) );
172                        if ( ! $attachment_id ) {
173                            return new WP_Error(
174                                'videopress_attachment_not_found',
175                                __( 'This video could not be found in the Media Library. Restore it from the trash, if available, and try again.', 'jetpack-videopress-pkg' ),
176                                array( 'status' => 403 )
177                            );
178                        }
179
180                        return current_user_can( 'edit_post', $attachment_id );
181                    },
182                ),
183            )
184        );
185
186        // Endpoint to know if the video metadata is editable.
187        register_rest_route(
188            $this->namespace,
189            $this->rest_base . '/(?P<video_guid>[A-Za-z0-9]{8})/check-ownership/(?P<post_id>\d+)/',
190            array(
191                'args' => array(
192                    'video_guid' => array(
193                        'description' => __( 'The VideoPress GUID.', 'jetpack-videopress-pkg' ), // @phan-suppress-current-line PhanPluginMixedKeyNoKey
194                        'type'        => 'string',
195                        'required'    => true,
196                    ),
197                    'post_id'    => array(
198                        'description' => __( 'The post id for the attachment.', 'jetpack-videopress-pkg' ),
199                        'type'        => 'integer',
200                        'required'    => true,
201                    ),
202                ),
203                array(
204                    'methods'             => WP_REST_Server::READABLE,
205                    'callback'            => array( $this, 'videopress_video_belong_to_site' ),
206                    'permission_callback' => function () {
207                        return Data::can_perform_action() && current_user_can( 'upload_files' );
208                    },
209                ),
210            )
211        );
212
213        // Token Route.
214        register_rest_route(
215            $this->namespace,
216            $this->rest_base . '/upload-jwt',
217            array(
218                'methods'             => \WP_REST_Server::EDITABLE,
219                'callback'            => array( $this, 'videopress_upload_jwt' ),
220                'permission_callback' => function () {
221                    return Data::can_perform_action() && current_user_can( 'upload_files' );
222                },
223            )
224        );
225
226        // Playback Token Route.
227        register_rest_route(
228            $this->namespace,
229            $this->rest_base . '/playback-jwt/(?P<video_guid>[A-Za-z0-9]{8})',
230            array(
231                'args'                => array(
232                    'video_guid'           => array(
233                        'description' => __( 'The VideoPress GUID.', 'jetpack-videopress-pkg' ),
234                        'type'        => 'string',
235                        'required'    => true,
236                    ),
237                    'post_id'              => array(
238                        'description' => __( 'The post the video is embedded in, used to authorize access.', 'jetpack-videopress-pkg' ),
239                        'type'        => 'integer',
240                        'required'    => false,
241                    ),
242                    'subscription_plan_id' => array(
243                        'description' => __( 'The subscription plan the premium-content block gating the video uses.', 'jetpack-videopress-pkg' ),
244                        'type'        => 'integer',
245                        'required'    => false,
246                    ),
247                ),
248                'methods'             => \WP_REST_Server::EDITABLE,
249                'callback'            => array( $this, 'videopress_playback_jwt' ),
250                'permission_callback' => function () {
251                    return current_user_can( 'read' );
252                },
253            )
254        );
255
256        // Settings Routes. Primarily for WordPress.com Simple, where the
257        // videopress/v1 namespace never reaches the REST dispatcher; the
258        // routes also register self-hosted as a harmless duplicate of
259        // videopress/v1/settings (the callbacks are host-safe).
260        register_rest_route(
261            $this->namespace,
262            $this->rest_base . '/settings',
263            array(
264                array(
265                    'methods'             => WP_REST_Server::READABLE,
266                    'callback'            => array( $this, 'videopress_get_settings' ),
267                    'permission_callback' => function () {
268                        return current_user_can( 'manage_options' );
269                    },
270                ),
271                array(
272                    'methods'             => WP_REST_Server::EDITABLE,
273                    'callback'            => array( $this, 'videopress_update_settings' ),
274                    'permission_callback' => function () {
275                        return Data::can_perform_action() && current_user_can( 'manage_options' );
276                    },
277                    'args'                => array(
278                        'videopress_videos_private_for_site' => array(
279                            'description' => __( 'If the VideoPress videos should be private by default', 'jetpack-videopress-pkg' ),
280                            'type'        => 'boolean',
281                        ),
282                        'videopress_auto_subtitles_disabled' => array(
283                            'description' => __( 'If auto-generated subtitles should be skipped for new videos', 'jetpack-videopress-pkg' ),
284                            'type'        => 'boolean',
285                        ),
286                        'videopress_player_preload_disabled' => array(
287                            'description' => __( 'If embedded players should wait for playback before preloading video data', 'jetpack-videopress-pkg' ),
288                            'type'        => 'boolean',
289                        ),
290                        'videopress_inline_player_enabled' => array(
291                            'description' => __( 'If videos should render an inline player from one shared script instead of one frame per video', 'jetpack-videopress-pkg' ),
292                            'type'        => 'boolean',
293                        ),
294                        'videopress_download_disabled'     => array(
295                            'description' => __( 'If downloads should be turned off for every video, overriding each video’s own setting', 'jetpack-videopress-pkg' ),
296                            'type'        => 'boolean',
297                        ),
298                        'videopress_share_menu_disabled'   => array(
299                            'description' => __( 'If the share menu should be hidden on every video, overriding each video’s own setting', 'jetpack-videopress-pkg' ),
300                            'type'        => 'boolean',
301                        ),
302                    ),
303                ),
304            )
305        );
306
307        // Promote Route. WordPress.com Simple only: turn an existing local
308        // video attachment into a VideoPress video in-process. The file
309        // already lives on WordPress.com storage, so unlike the self-hosted
310        // flow (which walks videopress/v1/upload/{id} pushing tus chunks)
311        // promotion is a single call: create the global videos-table row and
312        // enqueue the transcode. Lives in wpcom/v2 because videopress/v1
313        // never reaches the REST dispatcher on Simple; the callback returns
314        // a clean error on every other host.
315        register_rest_route(
316            $this->namespace,
317            $this->rest_base . '/promote/(?P<attachment_id>\d+)',
318            array(
319                'args'                => array(
320                    'attachment_id' => array(
321                        'description' => __( 'The attachment id of the video to promote.', 'jetpack-videopress-pkg' ),
322                        'type'        => 'integer',
323                        'required'    => true,
324                    ),
325                    'source'        => array(
326                        'description' => __( 'The entry surface that initiated this promotion.', 'jetpack-videopress-pkg' ),
327                        'type'        => 'string',
328                        'enum'        => array( 'dashboard_promote', 'block_editor' ),
329                    ),
330                ),
331                'methods'             => WP_REST_Server::EDITABLE,
332                'callback'            => array( $this, 'videopress_promote_attachment' ),
333                'permission_callback' => function ( $request ) {
334                    // videopress/v1/upload (the self-hosted equivalent) never reaches
335                    // the REST dispatcher on WordPress.com Simple; promotion is the
336                    // Simple path and acts on a caller-supplied attachment id, so in
337                    // addition to upload_files it needs the same per-object check to
338                    // avoid a cross-user IDOR.
339                    if ( ! Data::can_perform_action() || ! current_user_can( 'upload_files' ) ) {
340                        return false;
341                    }
342                    return current_user_can( 'edit_post', (int) $request->get_param( 'attachment_id' ) );
343                },
344            )
345        );
346    }
347
348    /**
349     * Returns the VideoPress site settings.
350     *
351     * `Data::get_videopress_settings()` is already IS_WPCOM-aware (site
352     * privacy / site type resolution), so the same callback serves every
353     * host.
354     *
355     * @return WP_REST_Response The response object.
356     */
357    public function videopress_get_settings() {
358        return rest_ensure_response( Data::get_videopress_settings() );
359    }
360
361    /**
362     * Updates the VideoPress site settings.
363     *
364     * Mirrors `VideoPress_Rest_Api_V1_Settings::update_settings()`, except
365     * on WPCOM `videopress_videos_private_for_site` is not honored:
366     * `videopress_private_enabled_for_site` is a dead option on Simple,
367     * where the site-default privacy derives from the site's own privacy
368     * setting. When a caller supplies that param on WPCOM it is not
369     * persisted, and the response reports it under `ignored` so consumers
370     * are not told a write succeeded when it was silently discarded.
371     *
372     * @param WP_REST_Request $request The request object.
373     * @return WP_REST_Response The response object.
374     */
375    public function videopress_update_settings( $request ) {
376        $private_for_site        = $request->get_param( 'videopress_videos_private_for_site' );
377        $auto_subtitles_disabled = $request->get_param( 'videopress_auto_subtitles_disabled' );
378        $player_preload_disabled = $request->get_param( 'videopress_player_preload_disabled' );
379        $inline_player_enabled   = $request->get_param( 'videopress_inline_player_enabled' );
380        $download_disabled       = $request->get_param( 'videopress_download_disabled' );
381        $share_menu_disabled     = $request->get_param( 'videopress_share_menu_disabled' );
382
383        $ignored = array();
384
385        // On WordPress.com Simple the site-default privacy derives from the
386        // site's own privacy setting, so `videopress_private_enabled_for_site`
387        // is a dead option. Drop the param rather than pretend to persist it,
388        // and surface it as ignored so the response stays truthful.
389        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
390            if ( null !== $private_for_site ) {
391                $ignored[] = 'videopress_videos_private_for_site';
392            }
393            $private_for_site = null;
394        }
395
396        if ( null !== $private_for_site ) {
397            update_option( 'videopress_private_enabled_for_site', $private_for_site );
398        }
399
400        if ( null !== $auto_subtitles_disabled ) {
401            update_option( 'videopress_auto_subtitles_disabled', $auto_subtitles_disabled );
402        }
403
404        if ( null !== $player_preload_disabled ) {
405            update_option( 'videopress_player_preload_disabled', $player_preload_disabled );
406        }
407
408        if ( null !== $inline_player_enabled ) {
409            update_option( 'videopress_inline_player_enabled', $inline_player_enabled );
410        }
411
412        if ( null !== $download_disabled ) {
413            update_option( 'videopress_download_disabled', $download_disabled );
414        }
415
416        if ( null !== $share_menu_disabled ) {
417            update_option( 'videopress_share_menu_disabled', $share_menu_disabled );
418        }
419
420        $response = array(
421            'code'    => 'success',
422            'message' => __( 'VideoPress settings updated successfully.', 'jetpack-videopress-pkg' ),
423            'data'    => 200,
424        );
425
426        if ( ! empty( $ignored ) ) {
427            $response['ignored'] = $ignored;
428            $response['message'] = __( 'VideoPress settings updated. Some settings are not configurable on this site and were ignored.', 'jetpack-videopress-pkg' );
429        }
430
431        return rest_ensure_response( $response );
432    }
433
434    /**
435     * Promote an existing local video attachment to VideoPress. WordPress.com
436     * Simple only.
437     *
438     * The population this serves: sites that uploaded videos on a plan
439     * without VideoPress and later upgraded to one that includes it â€” their
440     * pre-upgrade videos are plain attachments with no path onto VideoPress
441     * (the dashboard's self-hosted promote flow can't run on Simple).
442     *
443     * Promotion is in-place: the same attachment id gains a row in the
444     * global videos table â€” no sibling attachment is created and no
445     * `_videopress_uploaded_id` marker is written (that is the self-hosted
446     * sibling convention). The handler calls the exact primitive every
447     * direct upload to a VideoPress-enabled Simple site flows through via
448     * its `add_attachment` hook: `remote_transcode_one_video()`.
449     *
450     * @param WP_REST_Request $request The request object.
451     * @return WP_REST_Response|WP_Error
452     */
453    public function videopress_promote_attachment( $request ) {
454        if ( ! $this->promote_is_available() ) {
455            return new WP_Error(
456                'videopress_promote_not_available',
457                __( 'Promoting local videos is only available on WordPress.com sites.', 'jetpack-videopress-pkg' ),
458                array( 'status' => 404 )
459            );
460        }
461
462        $attachment_id = (int) $request->get_param( 'attachment_id' );
463        $blog_id       = get_current_blog_id();
464
465        $post = get_post( $attachment_id );
466        if ( ! $post || 'attachment' !== $post->post_type || 'trash' === $post->post_status || ! wp_attachment_is( 'video', $post ) ) {
467            return new WP_Error(
468                'videopress_promote_invalid_attachment',
469                __( 'The attachment is not a video in this site’s media library.', 'jetpack-videopress-pkg' ),
470                array( 'status' => 404 )
471            );
472        }
473
474        /*
475         * Plan gate. The native path enforces VideoPress at upload/mime time
476         * (wpcom_site_can_upload_videos()) and remote_transcode_one_video()
477         * itself checks nothing â€” without this, a site whose plan allows
478         * plain video uploads but not VideoPress could enqueue transcodes.
479         */
480        if ( ! $this->promote_site_has_videopress( $blog_id ) ) {
481            return new WP_Error(
482                'videopress_promote_not_allowed',
483                __( 'This site’s plan does not include VideoPress.', 'jetpack-videopress-pkg' ),
484                array( 'status' => 403 )
485            );
486        }
487
488        if ( ! $this->promote_load_primitives() ) {
489            return new WP_Error(
490                'videopress_promote_unavailable',
491                __( 'VideoPress is not available right now. Please try again later.', 'jetpack-videopress-pkg' ),
492                array( 'status' => 500 )
493            );
494        }
495
496        /*
497         * Already on VideoPress? Report success idempotently. Cache-busted
498         * read: the wpcom delete path does clean this key, but a stale 12h
499         * 'video-info' entry must not misreport here â€” and the fresh read
500         * re-primes the cache the primitive's own (non-busted) lookup uses.
501         */
502        $info = $this->promote_video_info( $blog_id, $attachment_id );
503        if ( $info && ! empty( $info->guid ) ) {
504            return rest_ensure_response(
505                array(
506                    'guid'               => $info->guid,
507                    'media_id'           => $attachment_id,
508                    'already_videopress' => true,
509                )
510            );
511        }
512
513        /*
514         * A soft-deleted VideoPress row may still occupy this attachment's
515         * slot: the videos table's primary key is (blog_id, post_id), so a
516         * tombstoned row makes video_create_info()'s insert fail silently
517         * and the fresh promote below would report an unexplained failure.
518         * (The tombstoned attachment renders as an ordinary local video â€”
519         * the REST fields only see live rows â€” so the UI can reach this.)
520         * Detect it and answer honestly instead. Resurrecting the row via
521         * the primitive's $redo path is a possible follow-up, but it needs
522         * rollback semantics this endpoint doesn't want to own yet.
523         */
524        if ( $this->promote_find_any_guid( $blog_id, $attachment_id ) ) {
525            return new WP_Error(
526                'videopress_promote_previously_deleted',
527                __( 'This video was previously deleted from VideoPress, so it can’t be promoted automatically. Please upload it as a new video instead.', 'jetpack-videopress-pkg' ),
528                array( 'status' => 409 )
529            );
530        }
531
532        /*
533         * remote_transcode_one_video() derives the transcoder's fetch URL
534         * from the attached file's blogs.dir path with an unguarded regex; a
535         * non-matching path (some imports/migrations) would still create the
536         * videos row and enqueue a malformed job that renders as
537         * "Processing" forever. Validate with the same pattern first
538         * (verbatim, unescaped dot included) and fail clean.
539         */
540        $path = get_attached_file( $attachment_id );
541        if ( ! $path || ! preg_match( '|/wp-content/blogs.dir\S+?files(.+)$|i', $path ) ) {
542            return new WP_Error(
543                'videopress_promote_unsupported_file',
544                __( 'This video’s file cannot be promoted automatically. Please download it and upload it again.', 'jetpack-videopress-pkg' ),
545                array( 'status' => 400 )
546            );
547        }
548
549        /*
550         * Best-effort mutex around the primitive: the pre-checks above are
551         * check-then-act, and remote_transcode_one_video() ignores
552         * video_create_info()'s outcome and queues its transcode job
553         * unconditionally â€” so two near-simultaneous promotes (double-click,
554         * two tabs) would transcode the same video twice. wp_cache_add() is
555         * atomic on the wpcom object cache; the TTL comfortably outlives the
556         * primitive's sleep(3) and self-heals if the request dies mid-hold.
557         */
558        $promote_lock = $this->promote_lock_key( $blog_id, $attachment_id );
559        if ( ! wp_cache_add( $promote_lock, 1, 'video-info', 30 ) ) {
560            return new WP_Error(
561                'videopress_promote_in_progress',
562                __( 'This video is already being promoted to VideoPress.', 'jetpack-videopress-pkg' ),
563                array( 'status' => 409 )
564            );
565        }
566
567        // A competing promotion may have finished between the first lookup and acquiring the lock.
568        $info = $this->promote_video_info( $blog_id, $attachment_id );
569        if ( $info && ! empty( $info->guid ) ) {
570            wp_cache_delete( $promote_lock, 'video-info' );
571            return rest_ensure_response(
572                array(
573                    'guid'               => $info->guid,
574                    'media_id'           => $attachment_id,
575                    'already_videopress' => true,
576                )
577            );
578        }
579
580        /*
581         * Creates the videos-table row (video_create_info()) and enqueues
582         * the async transcode job. The fresh-upload path sleep(3)s before
583         * queueing (DB-write settling), so this request takes ~3s.
584         */
585        $this->promote_transcode( $attachment_id );
586
587        /*
588         * The primitive returns bare false for every bail reason (missing
589         * attachment, already transcoded, â€¦), so verify by re-reading the
590         * videos table instead of trusting the return value.
591         */
592        $info = $this->promote_video_info( $blog_id, $attachment_id );
593
594        wp_cache_delete( $promote_lock, 'video-info' );
595
596        if ( ! $info || empty( $info->guid ) ) {
597            return new WP_Error(
598                'videopress_promote_failed',
599                __( 'The video could not be promoted to VideoPress. Please try again later.', 'jetpack-videopress-pkg' ),
600                array( 'status' => 500 )
601            );
602        }
603
604        /**
605         * Fires after a new in-process VideoPress registration is verified, before processing completes.
606         *
607         * @since 0.62.0
608         *
609         * @param object      $info    Canonical video registration.
610         * @param int         $blog_id Site where the attachment was promoted.
611         * @param string|null $source  Client-reported entry surface, or null when omitted.
612         */
613        do_action( 'jetpack_videopress_attachment_promoted', $info, $blog_id, $request->get_param( 'source' ) );
614
615        return rest_ensure_response(
616            array(
617                'guid'     => $info->guid,
618                'media_id' => $attachment_id,
619            )
620        );
621    }
622
623    /*
624     * The five methods below are the promote flow's wpcom seams. They exist
625     * so the orchestration above is unit-testable: monorepo CI can never
626     * define IS_WPCOM, so without them every branch past the host guard
627     * would be dead code under test. A WorDBless test double overrides
628     * exactly these (and nothing else) to exercise the real ordering,
629     * error contract, and mutex behavior.
630     */
631
632    /**
633     * The object-cache key serializing promotes of one attachment.
634     *
635     * @param int $blog_id       The blog id.
636     * @param int $attachment_id The attachment id.
637     * @return string
638     */
639    protected function promote_lock_key( $blog_id, $attachment_id ) {
640        return "videopress-promote-{$blog_id}-{$attachment_id}";
641    }
642
643    /**
644     * Whether the in-process promote flow is available on this host.
645     *
646     * @return bool
647     */
648    protected function promote_is_available() {
649        return defined( 'IS_WPCOM' ) && IS_WPCOM;
650    }
651
652    /**
653     * Whether the site's plan includes VideoPress.
654     *
655     * @param int $blog_id The blog to check.
656     * @return bool
657     */
658    protected function promote_site_has_videopress( $blog_id ) {
659        return function_exists( 'wpcom_site_has_videopress' ) && wpcom_site_has_videopress( $blog_id );
660    }
661
662    /**
663     * Ensure the wpcom transcode primitives are loaded.
664     *
665     * Public-api requests define ADMIN_PLUGINS, so they normally already
666     * are; this mirrors the wpcom TUS uploader's
667     * ensure_wpcom_admin_includes_present() guard for any context where
668     * they aren't. Each file is existence-checked individually so a
669     * partially-moved set mid-deploy degrades to the handler's clean error
670     * rather than a require fatal.
671     *
672     * @return bool Whether the primitives are callable.
673     */
674    protected function promote_load_primitives() {
675        if ( ! function_exists( 'remote_transcode_one_video' ) && defined( 'ABSPATH' ) ) {
676            $transcode_includes = array(
677                'class.videopress-job-base.php',
678                'class.video-job-thumbnails.php',
679                'class.video-thumbnailer.php',
680                'video-transcoder.php',
681                'transcode.php',
682            );
683            foreach ( $transcode_includes as $transcode_include ) {
684                $transcode_include_path = ABSPATH . 'wp-content/admin-plugins/videopress/' . $transcode_include;
685                if ( file_exists( $transcode_include_path ) ) {
686                    require_once $transcode_include_path;
687                }
688            }
689        }
690
691        return function_exists( 'remote_transcode_one_video' ) && function_exists( 'video_get_info_by_blogpostid' );
692    }
693
694    /**
695     * Cache-busted read of the live videos-table row for an attachment.
696     *
697     * @param int $blog_id       The blog id.
698     * @param int $attachment_id The attachment id.
699     * @return object|false The video info object, or false when no live row exists.
700     */
701    protected function promote_video_info( $blog_id, $attachment_id ) {
702        return video_get_info_by_blogpostid( $blog_id, $attachment_id, true );
703    }
704
705    /**
706     * Find any videos-table guid for the attachment, tombstoned included â€”
707     * the live-row helper can't see soft-deleted rows.
708     *
709     * @param int $blog_id       The blog id.
710     * @param int $attachment_id The attachment id.
711     * @return string|null The guid, or null when no row exists at all.
712     */
713    protected function promote_find_any_guid( $blog_id, $attachment_id ) {
714        global $wpdb;
715        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- wpcom global table; must see tombstoned rows and must not be cached.
716        return $wpdb->get_var( $wpdb->prepare( 'SELECT guid FROM videos WHERE blog_id = %d AND post_id = %d', $blog_id, $attachment_id ) );
717    }
718
719    /**
720     * Run the wpcom promote primitive for an attachment.
721     *
722     * @param int $attachment_id The attachment id.
723     * @return void
724     */
725    protected function promote_transcode( $attachment_id ) {
726        remote_transcode_one_video( $attachment_id ); // @phan-suppress-current-line PhanUndeclaredFunction -- wpcom-only (admin-plugins/videopress/transcode.php), promote_load_primitives()-guarded; not in the generated wpcom stubs yet.
727    }
728
729    /**
730     * Check whether the video belongs to the current site,
731     * considering the given post_id and the video_guid.
732     *
733     * @param WP_REST_Request $request The request object.
734     * @return WP_REST_Response True if the video belongs to the current site, false otherwise.
735     */
736    public function videopress_video_belong_to_site( $request ) {
737        $post_id    = $request->get_param( 'post_id' );
738        $video_guid = $request->get_param( 'video_guid' );
739
740        if ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) {
741            $found_guid = get_post_meta( $post_id, 'videopress_guid', true );
742        } else {
743            $blog_id    = get_current_blog_id();
744            $info       = video_get_info_by_blogpostid( $blog_id, $post_id );
745            $found_guid = $info ? $info->guid : '';
746        }
747
748        if ( ! $found_guid ) {
749            return rest_ensure_response( array( 'video-belong-to-site' => false ) );
750        }
751
752        return rest_ensure_response( array( 'video-belong-to-site' => $found_guid === $video_guid ) );
753    }
754
755    /**
756     * Hit WPCOM poster endpoint.
757     *
758     * @param string $video_guid  The VideoPress GUID.
759     * @param array  $args        Request args.
760     * @param array  $body        Request body.
761     * @param string $query       Request query.
762     * @return WP_REST_Response|WP_Error
763     */
764    public function wpcom_poster_request( $video_guid, $args, $body = null, $query = '' ) {
765        $query    = $query !== '' ? '?' . $query : '';
766        $endpoint = 'videos/' . $video_guid . '/poster' . $query;
767
768        $url = sprintf(
769            '%s/%s/v%s/%s',
770            Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
771            'rest',
772            '1.1',
773            $endpoint
774        );
775
776        $request_args = array_merge( $args, array( 'body' => $body ) );
777
778        // @phan-suppress-next-line PhanAccessMethodInternal -- Phan is correct, but the usage is intentional.
779        $result = Client::_wp_remote_request( $url, $request_args );
780
781        if ( is_wp_error( $result ) ) {
782            return rest_ensure_response( $result );
783        }
784
785        $response = $result['http_response'];
786
787        $status = $response->get_status();
788
789        $data = array(
790            'code' => $status,
791            'data' => json_decode( $response->get_data(), true ),
792        );
793
794        return rest_ensure_response(
795            new WP_REST_Response( $data, $status )
796        );
797    }
798
799    /**
800     * Resolve a VideoPress guid to its local attachment id on the current site.
801     *
802     * Returns 0 when the GUID does not belong to the current site.
803     *
804     * @internal
805     *
806     * @param string $video_guid The VideoPress GUID.
807     * @return int The attachment/post id, or 0 if it cannot be resolved.
808     */
809    public static function get_video_attachment_id( $video_guid ) {
810        if ( empty( $video_guid ) ) {
811            return 0;
812        }
813
814        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
815            $video_info = video_get_info_by_guid( $video_guid );
816            if ( empty( $video_info ) || (int) $video_info->blog_id !== get_current_blog_id() ) {
817                return 0;
818            }
819            return (int) $video_info->post_id;
820        }
821
822        // utility-functions.php is not loaded in every configuration, so fail
823        // closed rather than fatal if the resolver is unavailable.
824        if ( ! function_exists( 'videopress_get_post_by_guid' ) ) {
825            return 0;
826        }
827
828        $attachment = videopress_get_post_by_guid( $video_guid );
829        return $attachment ? (int) $attachment->ID : 0;
830    }
831
832    /**
833     * Update the a poster image via the WPCOM REST API.
834     *
835     * @param WP_REST_Request $request The request object.
836     * @return WP_REST_Response|WP_Error
837     */
838    public function videopress_block_update_poster( $request ) {
839        try {
840            $blog_id     = VideoPressToken::blog_id();
841            $token       = VideoPressToken::videopress_onetime_upload_token();
842            $video_guid  = $request->get_param( 'video_guid' );
843            $json_params = $request->get_json_params();
844
845            $args = array(
846                'method'  => 'POST',
847                'headers' => array(
848                    'content-type'  => 'application/json',
849                    'Authorization' => 'X_UPLOAD_TOKEN token="' . $token . '" blog_id="' . $blog_id . '"',
850                ),
851                // The WordPress.com poster update fetches and processes the image, which routinely exceeds WordPress's 5-second default timeout.
852                'timeout' => 30,
853            );
854
855            return $this->wpcom_poster_request(
856                $video_guid,
857                $args,
858                wp_json_encode( $json_params, JSON_UNESCAPED_SLASHES )
859            );
860        } catch ( \Exception $e ) {
861            return rest_ensure_response( new WP_Error( 'videopress_block_update_poster_error', $e->getMessage() ) );
862        }
863    }
864
865    /**
866     * Retrieves a poster image via the WPCOM REST API.
867     *
868     * @param WP_REST_Request $request the request object.
869     * @return object|WP_Error Success object or WP_Error with error details.
870     */
871    public function videopress_block_get_poster( $request ) {
872        $video_guid = $request->get_param( 'video_guid' );
873        $jwt        = VideoPressToken::videopress_playback_jwt( $video_guid );
874
875        // videopress_playback_jwt() returns rather than throws on a transport
876        // failure or a missing blog token, so surface the error instead of
877        // interpolating a WP_Error into the query string below (a fatal on PHP 8).
878        if ( is_wp_error( $jwt ) ) {
879            return rest_ensure_response( $jwt );
880        }
881
882        $args = array(
883            'method' => 'GET',
884        );
885
886        return $this->wpcom_poster_request(
887            $video_guid,
888            $args,
889            null,
890            'metadata_token=' . $jwt
891        );
892    }
893
894    /**
895     * Endpoint for getting the VideoPress Upload JWT
896     *
897     * @return WP_Rest_Response - The response object.
898     */
899    public static function videopress_upload_jwt() {
900        $has_connected_owner = Data::has_connected_owner();
901        if ( ! $has_connected_owner ) {
902            return rest_ensure_response(
903                new WP_Error(
904                    'owner_not_connected',
905                    'User not connected.',
906                    array(
907                        'code'        => 503,
908                        'connect_url' => Admin_UI::get_admin_page_url(),
909                    )
910                )
911            );
912        }
913
914        $blog_id = Data::get_blog_id();
915        if ( ! $blog_id ) {
916            return rest_ensure_response(
917                new WP_Error( 'site_not_registered', 'Site not registered.', 503 )
918            );
919        }
920
921        try {
922            $token  = VideoPressToken::videopress_upload_jwt();
923            $status = 200;
924            $data   = array(
925                'upload_token'   => $token,
926                'upload_url'     => videopress_make_resumable_upload_path( $blog_id ),
927                'upload_blog_id' => $blog_id,
928            );
929        } catch ( \Exception $e ) {
930            $status = 500;
931            $data   = array(
932                'error' => $e->getMessage(),
933            );
934
935        }
936
937        return rest_ensure_response(
938            new WP_REST_Response( $data, $status )
939        );
940    }
941
942    /**
943     * Endpoint for generating a VideoPress Playback JWT
944     *
945     * @param WP_REST_Request $request the request object.
946     * @return WP_Rest_Response - The response object.
947     */
948    public static function videopress_playback_jwt( $request ) {
949        $has_connected_owner = Data::has_connected_owner();
950        if ( ! $has_connected_owner ) {
951            return rest_ensure_response(
952                new WP_Error(
953                    'owner_not_connected',
954                    'User not connected.',
955                    array(
956                        'code'        => 503,
957                        'connect_url' => Admin_UI::get_admin_page_url(),
958                    )
959                )
960            );
961        }
962
963        $blog_id = Data::get_blog_id();
964        if ( ! $blog_id ) {
965            return rest_ensure_response(
966                new WP_Error( 'site_not_registered', 'Site not registered.', 503 )
967            );
968        }
969
970        try {
971            $video_guid = $request->get_param( 'video_guid' );
972
973            // Authorize the caller for this specific video before minting a token.
974            // The route only requires `read`, so without this a subscriber could
975            // obtain a playback token for any guid on the site (private or
976            // paywalled) by calling this endpoint directly, bypassing the
977            // front-end player's per-video access check. post_id/subscription_plan_id
978            // carry the embedding context the same way the AJAX player does.
979            $embedded_post_id = (int) $request->get_param( 'post_id' );
980            $selected_plan_id = (int) $request->get_param( 'subscription_plan_id' );
981            if ( ! Access_Control::instance()->is_current_user_authed_for_video( $video_guid, $embedded_post_id, $selected_plan_id ) ) {
982                return rest_ensure_response(
983                    new WP_Error( 'unauthorized', __( 'You cannot view this video.', 'jetpack-videopress-pkg' ), array( 'status' => 403 ) )
984                );
985            }
986
987            $token  = VideoPressToken::videopress_playback_jwt( $video_guid );
988            $status = 200;
989            $data   = array(
990                'playback_token' => $token,
991            );
992        } catch ( \Exception $e ) {
993            $status = 500;
994            $data   = array(
995                'error' => $e->getMessage(),
996            );
997
998        }
999
1000        return rest_ensure_response(
1001            new WP_REST_Response( $data, $status )
1002        );
1003    }
1004
1005    /**
1006     * Updates attachment meta and video metadata via the WPCOM REST API.
1007     *
1008     * @param WP_REST_Request $request the request object.
1009     * @return object|WP_Error Success object or WP_Error with error details.
1010     */
1011    public function videopress_block_update_meta( $request ) {
1012        $json_params = $request->get_json_params();
1013        $post_id     = $json_params['id'];
1014
1015        // The site setting overrides every video, so drop attempts to turn sharing on and keep the stored value.
1016        if ( ! empty( $json_params['display_embed'] ) && Data::get_videopress_share_menu_disabled() ) {
1017            unset( $json_params['display_embed'] );
1018        }
1019
1020        // Likewise, the download setting overrides every video: drop attempts to allow downloads and keep the stored value.
1021        if ( ! empty( $json_params['allow_download'] ) && Data::get_videopress_download_disabled() ) {
1022            unset( $json_params['allow_download'] );
1023        }
1024
1025        if ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) {
1026            $guid = get_post_meta( $post_id, 'videopress_guid', true );
1027        } else {
1028            $blog_id = get_current_blog_id();
1029            $info    = video_get_info_by_blogpostid( $blog_id, $post_id );
1030            $guid    = $info ? $info->guid : '';
1031        }
1032
1033        if ( ! $guid ) {
1034            return rest_ensure_response(
1035                new WP_Error(
1036                    'error',
1037                    __( 'This attachment cannot be updated yet.', 'jetpack-videopress-pkg' )
1038                )
1039            );
1040        }
1041
1042        $video_request_params = $json_params;
1043        unset( $video_request_params['id'] );
1044        $video_request_params['guid'] = $guid;
1045
1046        $endpoint = 'videos';
1047        $args     = array(
1048            'method'  => 'POST',
1049            'headers' => array( 'content-type' => 'application/json' ),
1050        );
1051
1052        $result = Client::wpcom_json_api_request_as_blog(
1053            $endpoint,
1054            '2',
1055            $args,
1056            wp_json_encode( $video_request_params, JSON_UNESCAPED_SLASHES ),
1057            'wpcom'
1058        );
1059
1060        if ( is_wp_error( $result ) ) {
1061            return rest_ensure_response( $result );
1062        }
1063
1064        $response_body = json_decode( wp_remote_retrieve_body( $result ) );
1065        if ( is_bool( $response_body ) && $response_body ) {
1066            /*
1067             * Title, description and caption of the video are not stored as metadata on the attachment,
1068             * but as post_content, post_title and post_excerpt on the attachment's post object.
1069             * We need to update those fields here, too.
1070             */
1071            $post_title = null;
1072            if ( isset( $json_params['title'] ) ) {
1073                $post_title = sanitize_text_field( $json_params['title'] );
1074                wp_update_post(
1075                    array(
1076                        'ID'         => $post_id,
1077                        'post_title' => $post_title,
1078                    )
1079                );
1080            }
1081
1082            $post_content = null;
1083            if ( isset( $json_params['description'] ) ) {
1084                $post_content = sanitize_textarea_field( $json_params['description'] );
1085                wp_update_post(
1086                    array(
1087                        'ID'           => $post_id,
1088                        'post_content' => $post_content,
1089                    )
1090                );
1091            }
1092
1093            $post_excerpt = null;
1094            if ( isset( $json_params['caption'] ) ) {
1095                $post_excerpt = sanitize_textarea_field( $json_params['caption'] );
1096                wp_update_post(
1097                    array(
1098                        'ID'           => $post_id,
1099                        'post_excerpt' => $post_excerpt,
1100                    )
1101                );
1102            }
1103
1104            // VideoPress data is stored in attachment meta for Jetpack sites, but not on wpcom.
1105            if ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) {
1106                $meta               = wp_get_attachment_metadata( $post_id );
1107                $should_update_meta = false;
1108
1109                if ( ! $meta ) {
1110                    return rest_ensure_response(
1111                        new WP_Error(
1112                            'error',
1113                            __( 'Attachment meta was not found.', 'jetpack-videopress-pkg' )
1114                        )
1115                    );
1116                }
1117
1118                if ( isset( $json_params['display_embed'] ) && isset( $meta['videopress']['display_embed'] ) ) {
1119                    $meta['videopress']['display_embed'] = $json_params['display_embed'];
1120                    $should_update_meta                  = true;
1121                }
1122
1123                if ( isset( $json_params['rating'] ) && isset( $meta['videopress']['rating'] ) && videopress_is_valid_video_rating( $json_params['rating'] ) ) {
1124                    $meta['videopress']['rating'] = $json_params['rating'];
1125                    $should_update_meta           = true;
1126
1127                    /** Set a new meta field so we can filter using it directly */
1128                    update_post_meta( $post_id, 'videopress_rating', $json_params['rating'] );
1129                }
1130
1131                if ( isset( $json_params['title'] ) ) {
1132                    $meta['videopress']['title'] = $post_title;
1133                    $should_update_meta          = true;
1134                }
1135
1136                if ( isset( $json_params['description'] ) ) {
1137                    $meta['videopress']['description'] = $post_content;
1138                    $should_update_meta                = true;
1139                }
1140
1141                if ( isset( $json_params['caption'] ) ) {
1142                    $meta['videopress']['caption'] = $post_excerpt;
1143                    $should_update_meta            = true;
1144                }
1145
1146                if ( isset( $json_params['poster'] ) ) {
1147                    $meta['videopress']['poster'] = $json_params['poster'];
1148                    $should_update_meta           = true;
1149                }
1150
1151                if ( isset( $json_params['allow_download'] ) ) {
1152                    $allow_download = (bool) $json_params['allow_download'];
1153                    if ( ! isset( $meta['videopress']['allow_download'] ) || $meta['videopress']['allow_download'] !== $allow_download ) {
1154                        $meta['videopress']['allow_download'] = $allow_download;
1155                        $should_update_meta                   = true;
1156                    }
1157                }
1158
1159                if ( isset( $json_params['privacy_setting'] ) ) {
1160                    $privacy_setting = $json_params['privacy_setting'];
1161                    if ( ! isset( $meta['videopress']['privacy_setting'] ) || $meta['videopress']['privacy_setting'] !== $privacy_setting ) {
1162                        $meta['videopress']['privacy_setting'] = $privacy_setting;
1163                        $should_update_meta                    = true;
1164
1165                        /** Set a new meta field so we can filter using it directly */
1166                        update_post_meta( $post_id, 'videopress_privacy_setting', $privacy_setting );
1167                    }
1168                }
1169
1170                if ( $should_update_meta ) {
1171                    wp_update_attachment_metadata( $post_id, $meta );
1172                }
1173            }
1174
1175            return rest_ensure_response(
1176                array(
1177                    'code'    => 'success',
1178                    'message' => __( 'Video meta updated successfully.', 'jetpack-videopress-pkg' ),
1179                    'data'    => 200,
1180                )
1181            );
1182        } elseif ( is_object( $response_body ) && ! empty( $response_body->code ) && is_string( $response_body->code ) ) {
1183            // WP_REST_Server reads the status only from an array; wpcom sends `{ status }` or a bare status code.
1184            $error_data = $response_body->data ?? null;
1185            if ( is_object( $error_data ) ) {
1186                $error_data = (array) $error_data;
1187            } elseif ( is_int( $error_data ) ) {
1188                $error_data = array( 'status' => $error_data );
1189            }
1190            return rest_ensure_response(
1191                new WP_Error( $response_body->code, $response_body->message ?? '', $error_data )
1192            );
1193        } else {
1194            // An HTML or empty body would otherwise build a WP_Error with no code.
1195            return new WP_Error(
1196                'videopress_meta_update_failed',
1197                __( 'WordPress.com did not confirm the video update.', 'jetpack-videopress-pkg' ),
1198                array(
1199                    'status'          => 502,
1200                    'upstream_status' => wp_remote_retrieve_response_code( $result ),
1201                )
1202            );
1203        }
1204    }
1205}
1206
1207if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1208    wpcom_rest_api_v2_load_plugin( 'Automattic\Jetpack\VideoPress\WPCOM_REST_API_V2_Endpoint_VideoPress' );
1209}