diff --git a/inc/classes/class-embed.php b/inc/classes/class-embed.php index 466c8da497..e3b5a3fe97 100644 --- a/inc/classes/class-embed.php +++ b/inc/classes/class-embed.php @@ -31,6 +31,15 @@ class Embed { */ const LLMS_AV_PROG_AUTO_PLAY_OPTION = 'llms_av_prog_auto_play'; + /** + * Attachment IDs found for GoDAM job IDs during this request; 0 when none. + * + * @since n.e.x.t + * + * @var array + */ + private $attachment_ids_by_job = array(); + /** * Construct method. */ @@ -45,6 +54,7 @@ protected function __construct() { */ public function setup_hooks() { add_action( 'init', array( $this, 'register_oembed_provider' ) ); + add_action( 'init', array( $this, 'register_local_embed_handler' ) ); add_filter( 'pre_oembed_result', array( $this, 'pre_oembed_result' ), 10, 2 ); } @@ -80,6 +90,15 @@ public function pre_oembed_result( $data, string $url ) { return null; } + // A video that's in this site's media library plays in the site's own + // player, so it doesn't depend on GoDAM's oEmbed API, which only + // embeds videos shared publicly. + $local_html = $this->get_local_embed_html( $url ); + + if ( '' !== $local_html ) { + return $local_html; + } + $embed_url = RTGODAM_API_BASE . '/api/method/godam_core.api.oembed.get_oembed'; $response = wp_remote_post( @@ -119,6 +138,182 @@ public function pre_oembed_result( $data, string $url ) { return null; } + /** + * Register an embed handler for GoDAM share URLs of videos in the media library. + * + * WordPress runs embed handlers before its oEmbed cache when it embeds a + * URL in post content (and when ACF's oEmbed field falls back to it), so + * the player renders, with its scripts, on every view. The oEmbed HTML + * cache would keep the markup but skip the scripts. + * + * @since n.e.x.t + * + * @return void + */ + public function register_local_embed_handler() { + $host = wp_parse_url( RTGODAM_API_BASE, PHP_URL_HOST ); + + if ( ! is_string( $host ) || '' === $host ) { + return; + } + + wp_embed_register_handler( + 'godam-local-video', + '#^https?://' . preg_quote( $host, '#' ) . '/web/video/[A-Za-z0-9_-]+/?(?:[?\#].*)?$#i', + array( $this, 'render_local_embed' ), + 9 + ); + } + + /** + * Embed handler callback: render a GoDAM share URL with the site's own player. + * + * @since n.e.x.t + * + * @param array $matches The regex matches. + * @param array $attr Embed attributes. + * @param string $url The URL being embedded. + * + * @return string|false The player HTML, or false to let WordPress try oEmbed. + */ + public function render_local_embed( $matches, $attr, $url ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed -- signature set by wp_embed_register_handler(). + $html = $this->get_local_embed_html( (string) $url ); + + return '' === $html ? false : $html; + } + + /** + * Render a GoDAM share URL with the site's own player, when its video is in the media library. + * + * The share URL is RTGODAM_API_BASE/web/video/. The Vimeo + * migration writes these into ACF fields; they can also be pasted into + * content. + * + * @since n.e.x.t + * + * @param string $url GoDAM share URL. + * + * @return string The player HTML, or '' when the URL isn't a share URL of a video in the media library. + */ + public function get_local_embed_html( string $url ): string { + if ( ! $this->is_godam_url( $url ) ) { + return ''; + } + + $job_id = self::get_share_url_job_id( $url ); + + if ( '' === $job_id ) { + return ''; + } + + $attachment_id = $this->find_attachment_id_by_job_id( $job_id ); + + if ( $attachment_id <= 0 ) { + return ''; + } + + /** + * Filters whether a GoDAM share URL renders with the site's own player. + * + * Return false to embed the video through GoDAM's oEmbed API instead, + * as LifterLMS lessons do: their player integration talks to the + * embedded iframe. + * + * @since n.e.x.t + * + * @param bool $render_locally Whether to render with the site's own player. Default true. + * @param string $url The GoDAM share URL. + * @param int $attachment_id ID of the video in the media library. + */ + if ( ! apply_filters( 'rtgodam_render_share_url_locally', true, $url, $attachment_id ) ) { + return ''; + } + + return (string) do_shortcode( sprintf( '[godam_video id="%d"]', $attachment_id ) ); + } + + /** + * Read the GoDAM job ID from a share URL. + * + * @since n.e.x.t + * + * @param string $url GoDAM share URL, RTGODAM_API_BASE/web/video/. + * + * @return string The job ID, or '' when the URL has none. + */ + public static function get_share_url_job_id( string $url ): string { + $path = wp_parse_url( $url, PHP_URL_PATH ); + + if ( is_string( $path ) && preg_match( '#^/web/video/([A-Za-z0-9_-]+)/?$#', $path, $matches ) ) { + return $matches[1]; + } + + return ''; + } + + /** + * Find the media library attachment for a GoDAM job ID. + * + * Matches transcoded uploads (`rtgodam_transcoding_job_id`) and media + * imported from GoDAM, including migrated Vimeo videos + * (`_godam_original_id`). + * + * @since n.e.x.t + * + * @param string $job_id GoDAM job ID. + * + * @return int Attachment ID, or 0 when none. + */ + private function find_attachment_id_by_job_id( string $job_id ): int { + if ( isset( $this->attachment_ids_by_job[ $job_id ] ) ) { + return $this->attachment_ids_by_job[ $job_id ]; + } + + global $wpdb; + + if ( ! is_object( $wpdb ) ) { + return 0; + } + + /** + * Fires before looking the attachment up, so integrations that + * centralize media on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + + try { + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- cached per request in $attachment_ids_by_job. + $attachment_id = (int) $wpdb->get_var( + $wpdb->prepare( + "SELECT pm.post_id + FROM {$wpdb->postmeta} pm + INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id + WHERE pm.meta_key IN ('rtgodam_transcoding_job_id', '_godam_original_id') + AND pm.meta_value = %s + AND p.post_type = 'attachment' + AND p.post_status <> 'trash' + ORDER BY pm.post_id ASC + LIMIT 1", + $job_id + ) + ); + } finally { + /** + * Fires after the lookup, so integrations can restore the + * context switched in `rtgodam_before_attachment_lookup`. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); + } + + $this->attachment_ids_by_job[ $job_id ] = $attachment_id; + + return $attachment_id; + } + /** * Check whether a URL is on GoDAM's own host. * diff --git a/inc/classes/lifter-lms/class-lifter-lms.php b/inc/classes/lifter-lms/class-lifter-lms.php index 7d54d73e8a..7afad0ab4a 100644 --- a/inc/classes/lifter-lms/class-lifter-lms.php +++ b/inc/classes/lifter-lms/class-lifter-lms.php @@ -50,6 +50,29 @@ private function setup_hooks() { add_filter( 'godam_player_block_attributes', array( $this, 'modify_godam_player_block_attributes' ) ); add_filter( 'lifterlms_available_integrations', array( $this, 'add_godam_integration' ) ); + + add_filter( 'rtgodam_render_share_url_locally', array( $this, 'keep_share_url_embeds_in_lifterlms' ) ); + } + + /** + * Keep GoDAM share URLs embedded through GoDAM's oEmbed API on LifterLMS pages. + * + * The LifterLMS Advanced Videos integration tracks progress and autoplays + * the next lesson by talking to the embedded GoDAM iframe, so a share URL + * on a LifterLMS page is not swapped for the site's own player. + * + * @since n.e.x.t + * + * @param bool $render_locally Whether to render the share URL with the site's own player. + * + * @return bool + */ + public function keep_share_url_embeds_in_lifterlms( $render_locally ) { + if ( $this->is_lifterlms_active() && $this->is_lifterlms_advanced_video_active() && $this->is_lifterlms_content() ) { + return false; + } + + return $render_locally; } /** diff --git a/inc/classes/rest-api/class-video-migration.php b/inc/classes/rest-api/class-video-migration.php index 872706333f..1bab70374e 100644 --- a/inc/classes/rest-api/class-video-migration.php +++ b/inc/classes/rest-api/class-video-migration.php @@ -2,7 +2,8 @@ /** * Register REST API endpoints for Video Migration. * - * This class handles the migration of Vimeo videos in Gutenberg blocks. + * This class handles the migration of core video blocks, and of Vimeo videos + * in Gutenberg blocks, Elementor, WPBakery and ACF fields. * * @since 1.4.0 * @@ -13,6 +14,12 @@ defined( 'ABSPATH' ) || exit; +use RTGODAM\Inc\Vimeo_Migration\Acf_Source; +use RTGODAM\Inc\Vimeo_Migration\Elementor_Source; +use RTGODAM\Inc\Vimeo_Migration\Vimeo_Resolver; +use RTGODAM\Inc\Vimeo_Migration\Vimeo_Url; +use RTGODAM\Inc\Vimeo_Migration\WPBakery_Source; + /** * Class Video_Migration * @@ -20,6 +27,15 @@ */ class Video_Migration extends Base { + /** + * Slug of the Gutenberg block source in the Vimeo migration status. + * + * @since n.e.x.t + * + * @var string + */ + const GUTENBERG_SOURCE = 'gutenberg'; + /** * Construct method. */ @@ -248,10 +264,21 @@ public function migrate_videos( $request ) { 'message' => __( 'Migration queued for processing', 'godam' ), ); - // For Vimeo migration, also track embed block counts. + // For Vimeo migration, also track counts per place the videos sit in. if ( 'vimeo' === $migration_type ) { + $include_acf = rest_sanitize_boolean( $request->get_param( 'include_acf' ) ) && Acf_Source::is_active(); + $initial_status['vimeo_blocks_found'] = 0; $initial_status['vimeo_blocks_migrated'] = 0; + $initial_status['include_acf'] = $include_acf; + $initial_status['vimeo_sources'] = array(); + + foreach ( $this->get_active_vimeo_sources( $include_acf ) as $source ) { + $initial_status['vimeo_sources'][ $source ] = array( + 'found' => 0, + 'migrated' => 0, + ); + } } update_option( $wp_option_key, $initial_status ); @@ -292,14 +319,23 @@ public function process_full_video_migration( $migration_type ) { // Get all post types that support Gutenberg editor. $post_types = $this->get_gutenberg_enabled_post_types(); - if ( empty( $post_types ) ) { + // Find all posts that need migration. + $all_post_ids = empty( $post_types ) ? array() : $this->find_all_posts_for_migration( $post_types ); + + // The Vimeo migration also covers page builders and custom fields, whose + // posts may not use the block editor at all. + if ( 'vimeo' === $migration_type ) { + $all_post_ids = array_merge( $all_post_ids, $this->find_vimeo_source_post_ids( ! empty( $status['include_acf'] ) ) ); + $all_post_ids = array_values( array_unique( array_map( 'intval', $all_post_ids ) ) ); + sort( $all_post_ids ); + } + + if ( empty( $post_types ) && empty( $all_post_ids ) ) { $this->update_migration_status_error( $wp_option_key, __( 'No post types with Gutenberg support found', 'godam' ) ); return; } - // Find all posts that need migration. - $all_post_ids = $this->find_all_posts_for_migration( $post_types ); - $total_posts = count( $all_post_ids ); + $total_posts = count( $all_post_ids ); if ( 0 === $total_posts ) { $this->complete_migration_with_no_posts( $wp_option_key ); @@ -484,23 +520,25 @@ public function migrate_post_batch_video_blocks( $migration_type, $post_ids, $ba $migration_status = get_option( $wp_option_key, array() ); $processed_count = 0; - // Track Vimeo embed block counts for this batch. - $vimeo_found_in_batch = 0; - $vimeo_migrated_in_batch = 0; + // Track Vimeo video counts for this batch, per place they sit in. + $vimeo_sources_in_batch = array(); + $include_acf = ! empty( $migration_status['include_acf'] ); + $vimeo_resolver = 'vimeo' === $migration_type ? new Vimeo_Resolver( $this ) : null; foreach ( $post_ids as $post_id ) { try { + $post_changed = false; + // Migrate individual post. if ( 'core' === $migration_type ) { $post_changed = $this->migrate_single_post_video_blocks( $post_id ); } elseif ( 'vimeo' === $migration_type ) { - $result = $this->migrate_single_post_vimeo_blocks( $post_id ); - if ( is_array( $result ) ) { - $post_changed = (bool) ( $result['changed'] ?? false ); - $vimeo_found_in_batch += (int) ( $result['found'] ?? 0 ); - $vimeo_migrated_in_batch += (int) ( $result['migrated'] ?? 0 ); - } else { - $post_changed = (bool) $result; + $result = $this->migrate_single_post_vimeo( (int) $post_id, $include_acf, $vimeo_resolver ); + $post_changed = $result['changed']; + + foreach ( $result['sources'] as $source => $counts ) { + $vimeo_sources_in_batch[ $source ]['found'] = ( $vimeo_sources_in_batch[ $source ]['found'] ?? 0 ) + $counts['found']; + $vimeo_sources_in_batch[ $source ]['migrated'] = ( $vimeo_sources_in_batch[ $source ]['migrated'] ?? 0 ) + $counts['migrated']; } } @@ -520,14 +558,25 @@ public function migrate_post_batch_video_blocks( $migration_type, $post_ids, $ba if ( ! empty( $migration_status ) ) { $lock_key = 'godam_' . $migration_type . '_video_migration_lock'; if ( $this->acquire_migration_lock( $lock_key ) ) { - // Re-read inside the lock to ensure we have the latest value before increment. - $migration_status = get_option( $wp_option_key, array() ); + // Re-read inside the lock, from the database: this request's + // option cache still holds the value from when it started. + $migration_status = $this->get_fresh_option( $wp_option_key ); + + // The run was aborted while this batch ran: don't bring it back. + if ( empty( $migration_status ) ) { + $this->release_migration_lock( $lock_key ); + return $processed_count; + } + $migration_status['done'] = ( $migration_status['done'] ?? 0 ) + count( $post_ids ); - // Accumulate Vimeo embed block counts if applicable. + // Accumulate Vimeo video counts if applicable. if ( 'vimeo' === $migration_type ) { - $migration_status['vimeo_blocks_found'] = ( $migration_status['vimeo_blocks_found'] ?? 0 ) + $vimeo_found_in_batch; - $migration_status['vimeo_blocks_migrated'] = ( $migration_status['vimeo_blocks_migrated'] ?? 0 ) + $vimeo_migrated_in_batch; + $migration_status['vimeo_sources'] = $this->add_vimeo_source_counts( $migration_status['vimeo_sources'] ?? array(), $vimeo_sources_in_batch ); + + // Kept for integrations that read them: Gutenberg block counts. + $migration_status['vimeo_blocks_found'] = (int) ( $migration_status['vimeo_sources'][ self::GUTENBERG_SOURCE ]['found'] ?? 0 ); + $migration_status['vimeo_blocks_migrated'] = (int) ( $migration_status['vimeo_sources'][ self::GUTENBERG_SOURCE ]['migrated'] ?? 0 ); } // Calculate progress percentage. @@ -550,11 +599,11 @@ public function migrate_post_batch_video_blocks( $migration_type, $post_ids, $ba $migration_status['completed'] = current_time( 'mysql' ); if ( 'vimeo' === $migration_type ) { $migration_status['message'] = sprintf( - /* translators: 1: total posts processed, 2: migrated Vimeo embeds, 3: total Vimeo embeds found */ - __( 'Migration completed! Processed %1$d posts. Migrated %2$d out of %3$d Vimeo Embed Blocks found.', 'godam' ), + /* translators: 1: total posts processed, 2: replaced Vimeo videos, 3: total Vimeo videos found */ + __( 'Migration completed! Processed %1$d posts. Replaced %2$d of %3$d Vimeo videos found.', 'godam' ), (int) ( $migration_status['total'] ?? 0 ), - (int) ( $migration_status['vimeo_blocks_migrated'] ?? 0 ), - (int) ( $migration_status['vimeo_blocks_found'] ?? 0 ) + (int) array_sum( array_column( $migration_status['vimeo_sources'] ?? array(), 'migrated' ) ), + (int) array_sum( array_column( $migration_status['vimeo_sources'] ?? array(), 'found' ) ) ); } else { $migration_status['message'] = sprintf( @@ -569,20 +618,51 @@ public function migrate_post_batch_video_blocks( $migration_type, $post_ids, $ba $this->release_migration_lock( $lock_key ); } else { // As a fallback if we fail to acquire the lock after retries, attempt a best-effort update. - $migration_status['done'] = ( $migration_status['done'] ?? 0 ) + count( $post_ids ); - update_option( $wp_option_key, $migration_status ); + $migration_status = $this->get_fresh_option( $wp_option_key ); + + if ( ! empty( $migration_status ) ) { + $migration_status['done'] = ( $migration_status['done'] ?? 0 ) + count( $post_ids ); + update_option( $wp_option_key, $migration_status ); + } } } return $processed_count; } + /** + * Read an option from the database rather than this request's cache. + * + * Batches run in parallel requests, and each request caches options when + * it starts, so a plain get_option() can return a value another batch has + * since replaced. + * + * @since n.e.x.t + * + * @param string $option Option name. + * + * @return array The option value, or an empty array when it isn't set. + */ + private function get_fresh_option( string $option ): array { + wp_cache_delete( $option, 'options' ); + wp_cache_delete( 'alloptions', 'options' ); + wp_cache_delete( 'notoptions', 'options' ); + + $value = get_option( $option, array() ); + + return is_array( $value ) ? $value : array(); + } + /** * Acquire a short-lived lock for migration status updates. * - * Uses add_option as a mutex. If an existing lock is expired, it will be taken over. + * The lock is a row in the options table, created with INSERT IGNORE so + * only one request can create it, and taken over only when it has + * expired and still holds the expiry that was read. Both go straight to + * the database: the option cache of a long-running request goes stale. * * @since 1.4.0 + * @since n.e.x.t Uses atomic queries instead of cached option reads, and waits longer. * * @param string $lock_key Unique option key for the lock. * @param int $timeout_s Lock expiry seconds. @@ -591,24 +671,49 @@ public function migrate_post_batch_video_blocks( $migration_type, $post_ids, $ba * * @return bool True if the lock was acquired, false otherwise. */ - private function acquire_migration_lock( string $lock_key, int $timeout_s = 5, int $retry_ms = 100, int $max_wait_s = 5 ): bool { - $lock_expires_at = time() + $timeout_s; - $deadline = microtime( true ) + $max_wait_s; + private function acquire_migration_lock( string $lock_key, int $timeout_s = 30, int $retry_ms = 100, int $max_wait_s = 30 ): bool { + global $wpdb; - // First attempt: create the option if it doesn't exist. - if ( add_option( $lock_key, $lock_expires_at, '', 'no' ) ) { - return true; - } + $deadline = microtime( true ) + $max_wait_s; - while ( microtime( true ) < $deadline ) { - $current = (int) get_option( $lock_key, 0 ); - if ( $current < time() ) { - // Lock expired; take ownership. - update_option( $lock_key, $lock_expires_at ); + do { + $lock_expires_at = (string) ( time() + $timeout_s ); + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- an atomic insert is the lock. + $inserted = $wpdb->query( + $wpdb->prepare( + "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", + $lock_key, + $lock_expires_at + ) + ); + + if ( 1 === (int) $inserted ) { return true; } + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- the cached value can be stale. + $current = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $lock_key ) ); + + // Lock expired: take it over, unless another request just did. + if ( null !== $current && (int) $current < time() ) { + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- conditional update is the takeover. + $updated = $wpdb->update( + $wpdb->options, + array( 'option_value' => $lock_expires_at ), + array( + 'option_name' => $lock_key, + 'option_value' => (string) $current, + ) + ); + + if ( 1 === (int) $updated ) { + return true; + } + } + usleep( $retry_ms * 1000 ); - } + } while ( microtime( true ) < $deadline ); return false; } @@ -623,7 +728,11 @@ private function acquire_migration_lock( string $lock_key, int $timeout_s = 5, i * @return void */ private function release_migration_lock( string $lock_key ) { - delete_option( $lock_key ); + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- the lock row is written directly, see acquire_migration_lock(). + $wpdb->delete( $wpdb->options, array( 'option_name' => $lock_key ) ); + wp_cache_delete( $lock_key, 'options' ); } /** @@ -648,18 +757,57 @@ private function migrate_single_post_video_blocks( $post_id ) { $this->traverse_and_migrate_core_video_blocks_recursive( $blocks, $changed ); if ( $changed ) { - $new_content = serialize_blocks( $blocks ); - wp_update_post( // godam-coverage-ignore -- migrate_single_post_video_blocks(): rewrites the HOST post's own post_content after migrating its embedded core/video block, not attachment data — see the get_post( $post_id ) call above. - array( - 'ID' => $post_id, - 'post_content' => $new_content, - ) - ); + $this->update_post_content( (int) $post_id, serialize_blocks( $blocks ) ); } return $changed; } + /** + * Save a migrated post's content exactly as given. + * + * The content is slashed, because wp_update_post() expects slashed + * data: unslashed, the JSON escapes in block attributes (a backslash + * followed by u0026, for example) lose their backslash. + * + * The background job runs without a logged-in user, so kses would also + * strip markup the post's author was allowed to save, such as an + * `', + ) + ), + ); + }, + ); + + add_shortcode( + 'godam_video', + static function ( $atts ) { + return '
'; + } + ); + } + + protected function tearDown(): void { + remove_shortcode( 'godam_video' ); + $GLOBALS['wpdb'] = $this->previous_wpdb; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- restores the original. + unset( $GLOBALS['rtgodam_stub'], $GLOBALS['rtgodam_hooks'] ); + parent::tearDown(); + } + + /** + * Embed without its constructor (it registers WP hooks). + * + * @return Embed + */ + private function embed(): Embed { + return ( new \ReflectionClass( Embed::class ) )->newInstanceWithoutConstructor(); + } + + public function test_a_share_url_of_a_library_video_renders_the_sites_player() { + $html = $this->embed()->pre_oembed_result( null, 'https://api.test/web/video/vimeomock01' ); + + $this->assertSame( '
', $html ); + $this->assertSame( array(), $GLOBALS['rtgodam_stub']['posts'], 'GoDAM\'s oEmbed API is not asked.' ); + } + + public function test_the_embed_handler_renders_the_same_player() { + $url = 'https://api.test/web/video/vimeomock01?org=abc'; + + $this->assertSame( '
', $this->embed()->render_local_embed( array( $url ), array(), $url ) ); + } + + public function test_a_video_not_in_the_library_still_goes_to_the_oembed_api() { + $embed = $this->embed(); + + $this->assertFalse( $embed->render_local_embed( array(), array(), 'https://api.test/web/video/unknown01' ) ); + + $html = $embed->pre_oembed_result( null, 'https://api.test/web/video/unknown01' ); + + $this->assertCount( 1, $GLOBALS['rtgodam_stub']['posts'] ); + $this->assertStringContainsString( 'https://api.test/web/embed/other', $html ); + } + + public function test_a_filter_can_keep_the_oembed_iframe() { + add_filter( + 'rtgodam_render_share_url_locally', + static function () { + return false; + } + ); + + $html = $this->embed()->pre_oembed_result( null, 'https://api.test/web/video/vimeomock01' ); + + $this->assertCount( 1, $GLOBALS['rtgodam_stub']['posts'] ); + $this->assertStringContainsString( 'embed(); + + $embed->get_local_embed_html( 'https://api.test/web/video/vimeomock01' ); + $embed->get_local_embed_html( 'https://api.test/web/video/vimeomock01' ); + $embed->get_local_embed_html( 'https://api.test/web/video/unknown01' ); + $embed->get_local_embed_html( 'https://api.test/web/video/unknown01' ); + + $this->assertSame( array( 'vimeomock01', 'unknown01' ), $this->wpdb->lookups ); + } + + public function test_urls_off_godams_host_are_not_looked_up() { + $this->assertSame( '', $this->embed()->get_local_embed_html( 'https://example.test/web/video/vimeomock01' ) ); + $this->assertSame( array(), $this->wpdb->lookups ); + } + + /** + * Share URLs and the job ID each holds. + * + * @return array + */ + public function share_urls(): array { + return array( + 'plain' => array( 'https://api.test/web/video/3fqjd5bmpr', '3fqjd5bmpr' ), + 'with org query' => array( 'https://api.test/web/video/3fqjd5bmpr?org=d731f9ddfb', '3fqjd5bmpr' ), + 'trailing slash' => array( 'https://api.test/web/video/3fqjd5bmpr/', '3fqjd5bmpr' ), + 'embed page' => array( 'https://api.test/web/embed/3fqjd5bmpr', '' ), + 'deeper path' => array( 'https://api.test/web/video/3fqjd5bmpr/edit', '' ), + 'no job id' => array( 'https://api.test/web/video/', '' ), + 'odd characters' => array( 'https://api.test/web/video/abc%27def', '' ), + ); + } + + /** + * @dataProvider share_urls + * + * @param string $url Share URL. + * @param string $expected Job ID it holds. + */ + public function test_reads_the_job_id( string $url, string $expected ) { + $this->assertSame( $expected, Embed::get_share_url_job_id( $url ) ); + } +} diff --git a/tests/php/VimeoMigrationAcfTest.php b/tests/php/VimeoMigrationAcfTest.php new file mode 100644 index 0000000000..097d7c0385 --- /dev/null +++ b/tests/php/VimeoMigrationAcfTest.php @@ -0,0 +1,158 @@ + + */ + const FIELD_TYPES = array( + 'field_godam_vt_oembed' => 'oembed', + 'field_godam_vt_url' => 'url', + 'field_godam_vt_text' => 'text', + 'field_godam_vt_group' => 'group', + 'field_godam_vt_group_url' => 'url', + 'field_godam_vt_group_oembed' => 'oembed', + ); + + protected function setUp(): void { + parent::setUp(); + $GLOBALS['rtgodam_stub'] = array(); + $GLOBALS['rtgodam_hooks'] = array(); + } + + protected function tearDown(): void { + unset( $GLOBALS['rtgodam_stub'] ); + $GLOBALS['rtgodam_hooks'] = array(); + parent::tearDown(); + } + + /** + * The stored post meta, as get_post_meta( $post_id ) returns it. + * + * @return array + */ + private function fixture(): array { + return json_decode( file_get_contents( dirname( __DIR__ ) . '/fixtures/vimeo-migration/acf-post-meta.json' ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- local test fixture. + } + + /** + * Source with a fake resolver and a fake acf_get_field(). + * + * @param array|null $video What the resolver returns. + * + * @return Acf_Source + */ + private function source( $video = array( 'share_url' => self::SHARE_URL ) ): Acf_Source { + return new Acf_Source( + static function () use ( $video ) { + return $video; + }, + static function ( string $key ) { + return isset( self::FIELD_TYPES[ $key ] ) ? array( + 'key' => $key, + 'type' => self::FIELD_TYPES[ $key ], + ) : false; + } + ); + } + + /** + * Run the migration over meta. + * + * @param Acf_Source $source Source. + * @param array $meta Post meta. + * + * @return array{0: array, 1: array} Updates, counts. + */ + private function migrate( Acf_Source $source, array $meta ): array { + $counts = array( + 'found' => 0, + 'migrated' => 0, + ); + $updates = $source->migrate_meta( $meta, $counts ); + + return array( $updates, $counts ); + } + + public function test_replaces_oembed_and_url_fields_including_group_subfields() { + list( $updates, $counts ) = $this->migrate( $this->source(), $this->fixture() ); + + $this->assertSame( + array( + 'vimeo_oembed' => self::SHARE_URL, + 'vimeo_url' => self::SHARE_URL, + 'vimeo_group_nested_url' => self::SHARE_URL, + 'vimeo_group_nested_oembed' => self::SHARE_URL, + ), + $updates, + 'The Text field keeps its Vimeo link.' + ); + $this->assertSame( + array( + 'found' => 4, + 'migrated' => 4, + ), + $counts + ); + } + + public function test_keeps_fields_when_the_video_is_not_in_godam_central() { + list( $updates, $counts ) = $this->migrate( $this->source( null ), $this->fixture() ); + + $this->assertSame( array(), $updates ); + $this->assertSame( + array( + 'found' => 4, + 'migrated' => 0, + ), + $counts + ); + } + + public function test_skips_a_value_with_no_acf_field_reference() { + list( $updates, $counts ) = $this->migrate( + $this->source(), + array( 'some_plugin_video' => array( 'https://vimeo.com/1126119215' ) ) + ); + + $this->assertSame( array(), $updates ); + $this->assertSame( 0, $counts['found'] ); + } + + public function test_a_filter_can_add_field_types() { + add_filter( + 'rtgodam_vimeo_migration_acf_field_types', + static function ( $types ) { + $types[] = 'text'; + return $types; + } + ); + + list( $updates ) = $this->migrate( $this->source(), $this->fixture() ); + + $this->assertSame( self::SHARE_URL, $updates['vimeo_text'] ); + } +} diff --git a/tests/php/VimeoMigrationElementorTest.php b/tests/php/VimeoMigrationElementorTest.php new file mode 100644 index 0000000000..f8068a95cb --- /dev/null +++ b/tests/php/VimeoMigrationElementorTest.php @@ -0,0 +1,302 @@ +resolved_urls = array(); + } + + protected function tearDown(): void { + unset( $GLOBALS['rtgodam_stub'] ); + $GLOBALS['rtgodam_hooks'] = array(); + parent::tearDown(); + } + + /** + * The stored element tree. + * + * @return array + */ + private function fixture(): array { + return json_decode( file_get_contents( dirname( __DIR__ ) . '/fixtures/vimeo-migration/elementor-data.json' ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- local test fixture. + } + + /** + * A resolver that knows the test video. + * + * @return callable + */ + private function resolver(): callable { + return function ( string $url ) { + $this->resolved_urls[] = $url; + + return array( + 'id' => 501, + 'url' => 'https://cdn.example.org/501/video.mp4', + 'title' => 'Screen Recording', + 'sources' => array( + array( + 'src' => 'https://cdn.example.org/501/video.mpd', + 'type' => 'application/dash+xml', + ), + ), + 'share_url' => 'https://app.godam.io/web/video/3fqjd5bmpr', + ); + }; + } + + /** + * Run the migration over a tree. + * + * @param array $elements Element tree. + * @param callable $resolve Resolver. + * + * @return array{0: array, 1: array, 2: bool} New tree, counts, changed. + */ + private function migrate( array $elements, callable $resolve ): array { + $counts = array( + 'found' => 0, + 'migrated' => 0, + ); + $changed = false; + $result = ( new Elementor_Source( $resolve ) )->migrate_elements( $elements, 4909, $counts, $changed ); + + return array( $result, $counts, $changed ); + } + + public function test_replaces_vimeo_video_widgets_and_counts_the_background_video() { + list( $tree, $counts, $changed ) = $this->migrate( $this->fixture(), $this->resolver() ); + + $this->assertTrue( $changed ); + $this->assertSame( + array( + 'found' => 3, + 'migrated' => 2, + ), + $counts, + 'Two Video widgets replaced; the background video is found but kept.' + ); + $this->assertSame( array( self::VIMEO_URL, self::VIMEO_URL ), $this->resolved_urls ); + + // Background video on the container is left as it is. + $this->assertSame( 'container', $tree[0]['elType'] ); + $this->assertSame( self::VIMEO_URL, $tree[0]['settings']['background_video_link'] ); + + // Nested widget, default settings. + $nested = $tree[0]['elements'][0]['elements'][0]; + $this->assertSame( 'a1b2c03', $nested['id'] ); + $this->assertSame( 'godam-video', $nested['widgetType'] ); + $this->assertSame( 'widget', $nested['elType'] ); + $this->assertSame( + array( + 'video-file' => array( + 'id' => 501, + 'url' => 'https://cdn.example.org/501/video.mp4', + 'title' => 'Screen Recording', + 'name' => 'video.mp4', + 'icon' => '', + ), + 'aspect_ratio' => '16:9', + ), + $nested['settings'] + ); + } + + public function test_maps_playback_overlay_and_advanced_settings() { + list( $tree ) = $this->migrate( $this->fixture(), $this->resolver() ); + + $widget = $tree[0]['elements'][1]; + $settings = $widget['settings']; + + $this->assertSame( 'a1b2c04', $widget['id'] ); + $this->assertSame( 'godam-video', $widget['widgetType'] ); + $this->assertSame( 'yes', $settings['autoplay'] ); + $this->assertSame( 'yes', $settings['muted'] ); + $this->assertSame( 'yes', $settings['loop'] ); + $this->assertSame( 'yes', $settings['show_in_lightbox'] ); + $this->assertSame( 'responsive', $settings['aspect_ratio'], 'Elementor 21:9 has no GoDAM equivalent.' ); + $this->assertSame( + array( + 'id' => 4810, + 'url' => 'https://example.org/wp-content/uploads/poster.jpeg', + ), + $settings['poster'] + ); + $this->assertSame( 'my-vimeo-video', $settings['_css_classes'] ); + $this->assertSame( '20', $settings['_margin']['top'] ); + + foreach ( array( 'video_type', 'vimeo_url', 'mute', 'lightbox', 'show_image_overlay', 'image_overlay' ) as $dropped ) { + $this->assertArrayNotHasKey( $dropped, $settings ); + } + } + + public function test_leaves_youtube_widgets_alone() { + list( $tree ) = $this->migrate( $this->fixture(), $this->resolver() ); + + $this->assertSame( $this->fixture()[0]['elements'][2], $tree[0]['elements'][2] ); + } + + public function test_keeps_widgets_when_the_video_is_not_in_godam_central() { + $fixture = $this->fixture(); + + list( $tree, $counts, $changed ) = $this->migrate( + $fixture, + static function () { + return null; + } + ); + + $this->assertFalse( $changed ); + $this->assertSame( $fixture, $tree ); + $this->assertSame( + array( + 'found' => 3, + 'migrated' => 0, + ), + $counts + ); + } + + public function test_skips_a_vimeo_url_from_a_dynamic_tag() { + $elements = array( + array( + 'id' => 'd1', + 'elType' => 'widget', + 'widgetType' => 'video', + 'settings' => array( + 'video_type' => 'vimeo', + 'vimeo_url' => self::VIMEO_URL, + '__dynamic__' => array( 'vimeo_url' => '[elementor-tag id="1" name="acf-url" settings="%7B%7D"]' ), + ), + 'elements' => array(), + ), + ); + + list( $tree, $counts, $changed ) = $this->migrate( $elements, $this->resolver() ); + + $this->assertFalse( $changed ); + $this->assertSame( $elements, $tree ); + $this->assertSame( 1, $counts['found'] ); + $this->assertSame( array(), $this->resolved_urls ); + } + + public function test_ignores_a_stale_vimeo_url_on_a_youtube_widget() { + $elements = array( + array( + 'id' => 'y1', + 'elType' => 'widget', + 'widgetType' => 'video', + 'settings' => array( + 'video_type' => 'youtube', + 'youtube_url' => 'https://www.youtube.com/watch?v=XHOmBV4js_E', + 'vimeo_url' => self::VIMEO_URL, + ), + 'elements' => array(), + ), + ); + + list( , $counts, $changed ) = $this->migrate( $elements, $this->resolver() ); + + $this->assertFalse( $changed ); + $this->assertSame( 0, $counts['found'] ); + } + + public function test_keeps_only_advanced_keys_of_dynamic_and_global_settings() { + $element = array( + 'id' => 'g1', + 'elType' => 'widget', + 'widgetType' => 'video', + 'settings' => array( + 'video_type' => 'vimeo', + 'vimeo_url' => self::VIMEO_URL, + 'color' => '#ff0000', + 'hide_mobile' => 'hidden-mobile', + '__globals__' => array( + 'color' => 'globals/colors?id=primary', + '_background_color' => 'globals/colors?id=secondary', + ), + '__dynamic__' => array( '_element_id' => '[elementor-tag id="2" name="post-id" settings="%7B%7D"]' ), + ), + 'elements' => array(), + ); + + $settings = Elementor_Source::build_godam_video_element( $element, ( $this->resolver() )( self::VIMEO_URL ) )['settings']; + + $this->assertSame( array( '_background_color' => 'globals/colors?id=secondary' ), $settings['__globals__'] ); + $this->assertSame( array( '_element_id' => '[elementor-tag id="2" name="post-id" settings="%7B%7D"]' ), $settings['__dynamic__'] ); + $this->assertSame( 'hidden-mobile', $settings['hide_mobile'] ); + $this->assertArrayNotHasKey( 'color', $settings ); + } + + public function test_a_filter_can_migrate_another_widget() { + add_filter( + 'rtgodam_migrate_elementor_vimeo_element_result', + static function ( $args ) { + if ( 'custom-vimeo' !== ( $args['element']['widgetType'] ?? '' ) ) { + return $args; + } + + $args['element']['widgetType'] = 'godam-video'; + $args['changed'] = true; + $args['found'] = 1; + $args['migrated'] = 1; + + return $args; + } + ); + + $elements = array( + array( + 'id' => 'c1', + 'elType' => 'widget', + 'widgetType' => 'custom-vimeo', + 'settings' => array( 'url' => self::VIMEO_URL ), + 'elements' => array(), + ), + ); + + list( $tree, $counts, $changed ) = $this->migrate( $elements, $this->resolver() ); + + $this->assertTrue( $changed ); + $this->assertSame( 'godam-video', $tree[0]['widgetType'] ); + $this->assertSame( + array( + 'found' => 1, + 'migrated' => 1, + ), + $counts + ); + } +} diff --git a/tests/php/VimeoMigrationWpbakeryTest.php b/tests/php/VimeoMigrationWpbakeryTest.php new file mode 100644 index 0000000000..3b7acf1a32 --- /dev/null +++ b/tests/php/VimeoMigrationWpbakeryTest.php @@ -0,0 +1,122 @@ + 501, + 'url' => 'https://cdn.example.org/501/video.mp4', + ) : null; + } + ); + } + + public function test_replaces_vimeo_video_players() { + $source = $this->source(); + $result = $source->migrate_content( $this->fixture() ); + + $expected = '[vc_row][vc_column]' + . '[godam_video id="501" aspect_ratio="responsive" css=".vc_custom_1762850000001{margin-top: 20px !important;}"]' + . '[vc_video link="https://www.youtube.com/watch?v=XHOmBV4js_E"]' + . '[/vc_column][/vc_row]' + . '[vc_row][vc_column][vc_tta_tabs][vc_tta_section title="Tab 1" tab_id="tab-vimeo-1"]' + . '[godam_video id="501" aspect_ratio="16:9"]' + . '[/vc_tta_section][/vc_tta_tabs][/vc_column][/vc_row]'; + + $this->assertSame( $expected, $result ); + $this->assertSame( + array( + 'found' => 2, + 'migrated' => 2, + ), + $source->get_counts() + ); + } + + public function test_keeps_players_when_the_video_is_not_in_godam_central() { + $source = new WPBakery_Source( + static function () { + return null; + } + ); + + $this->assertSame( $this->fixture(), $source->migrate_content( $this->fixture() ) ); + $this->assertSame( + array( + 'found' => 2, + 'migrated' => 0, + ), + $source->get_counts() + ); + } + + public function test_leaves_an_escaped_shortcode_alone() { + $content = 'Use [[vc_video link="' . self::VIMEO_URL . '"]] to embed a video.'; + $source = $this->source(); + + $this->assertSame( $content, $source->migrate_content( $content ) ); + $this->assertSame( 0, $source->get_counts()['found'] ); + } + + public function test_decodes_a_wpbakery_encoded_link() { + $source = $this->source(); + $result = $source->migrate_content( '[vc_video link="' . self::VIMEO_URL . '" el_aspect="169"]' ); + + $this->assertSame( '[godam_video id="501" aspect_ratio="16:9"]', $result ); + } + + public function test_content_without_video_players_is_unchanged() { + $content = '[vc_row][vc_column][vc_column_text]See https://vimeo.com/1126119215[/vc_column_text][/vc_column][/vc_row]'; + $source = $this->source(); + + $this->assertSame( $content, $source->migrate_content( $content ) ); + $this->assertSame( 0, $source->get_counts()['found'] ); + } +} diff --git a/tests/php/VimeoResolverTest.php b/tests/php/VimeoResolverTest.php new file mode 100644 index 0000000000..0e760a2e81 --- /dev/null +++ b/tests/php/VimeoResolverTest.php @@ -0,0 +1,84 @@ + 'https://cdn.example.org/501/video.mp4', + 'title' => 'Screen Recording', + 'post_meta_by_id' => array( + 501 => array( 'rtgodam_transcoding_job_id' => '3fqjd5bmpr' ), + ), + ); + + $this->migration = ( new \ReflectionClass( Vimeo_Migration_Double::class ) )->newInstanceWithoutConstructor(); + } + + protected function tearDown(): void { + unset( $GLOBALS['rtgodam_stub'] ); + parent::tearDown(); + } + + public function test_resolves_a_vimeo_url_to_the_godam_video() { + $video = ( new Vimeo_Resolver( $this->migration ) )->resolve( 'https://vimeo.com/1126119215?fl=pl&fe=sh' ); + + $this->assertSame( + array( + 'id' => 501, + 'url' => 'https://cdn.example.org/501/video.mp4', + 'title' => 'Screen Recording', + 'share_url' => RTGODAM_API_BASE . '/web/video/3fqjd5bmpr', + ), + $video + ); + } + + public function test_looks_each_video_up_once() { + $resolver = new Vimeo_Resolver( $this->migration ); + + $resolver->resolve( 'https://vimeo.com/1126119215?fl=pl&fe=sh' ); + $resolver->resolve( 'https://player.vimeo.com/video/1126119215' ); + $resolver->resolve( 'https://vimeo.com/76979871' ); + + $this->assertSame( + array( 'https://vimeo.com/1126119215?fl=pl&fe=sh', 'https://vimeo.com/76979871' ), + $this->migration->lookups + ); + } + + public function test_returns_null_when_godam_central_has_not_imported_the_video() { + $this->migration->attachment_id = null; + $resolver = new Vimeo_Resolver( $this->migration ); + + $this->assertNull( $resolver->resolve( 'https://vimeo.com/1126119215' ) ); + $this->assertNull( $resolver->resolve( 'https://vimeo.com/1126119215' ) ); + $this->assertCount( 1, $this->migration->lookups, 'A failed lookup is cached too.' ); + } + + public function test_builds_the_share_url() { + $this->assertSame( RTGODAM_API_BASE . '/web/video/3fqjd5bmpr', Vimeo_Resolver::build_share_url( '3fqjd5bmpr' ) ); + $this->assertSame( '', Vimeo_Resolver::build_share_url( ' ' ) ); + } +} diff --git a/tests/php/VimeoUrlTest.php b/tests/php/VimeoUrlTest.php new file mode 100644 index 0000000000..eeff506ccd --- /dev/null +++ b/tests/php/VimeoUrlTest.php @@ -0,0 +1,81 @@ + + */ + public function vimeo_urls(): array { + return array( + 'plain' => array( 'https://vimeo.com/1126119215', '1126119215' ), + 'share link with query' => array( 'https://vimeo.com/1126119215?fl=pl&fe=sh', '1126119215' ), + 'www host' => array( 'https://www.vimeo.com/76979871', '76979871' ), + 'unlisted hash' => array( 'https://vimeo.com/76979871/8272103f6e', '76979871' ), + 'player embed' => array( 'https://player.vimeo.com/video/76979871?h=8272103f6e', '76979871' ), + 'protocol relative' => array( '//player.vimeo.com/video/76979871', '76979871' ), + 'channel' => array( 'https://vimeo.com/channels/staffpicks/76979871', '76979871' ), + 'group' => array( 'https://vimeo.com/groups/shortfilms/videos/76979871', '76979871' ), + 'showcase' => array( 'https://vimeo.com/showcase/9876543/video/76979871', '76979871' ), + 'album' => array( 'https://vimeo.com/album/9876543/video/76979871', '76979871' ), + 'manage' => array( 'https://vimeo.com/manage/videos/76979871', '76979871' ), + 'surrounding whitespace' => array( " https://vimeo.com/76979871\n", '76979871' ), + ); + } + + /** + * @dataProvider vimeo_urls + * + * @param string $url Vimeo URL. + * @param string $expected_id Video ID it holds. + */ + public function test_reads_the_video_id( string $url, string $expected_id ) { + $this->assertTrue( Vimeo_Url::is_vimeo_url( $url ) ); + $this->assertSame( $expected_id, Vimeo_Url::get_video_id( $url ) ); + } + + /** + * Values that are not a link to a single Vimeo video. + * + * @return array + */ + public function not_vimeo_urls(): array { + return array( + 'other host' => array( 'https://www.youtube.com/watch?v=XHOmBV4js_E' ), + 'lookalike host' => array( 'https://notvimeo.com/76979871' ), + 'vimeo host as subdomain' => array( 'https://vimeo.com.example.org/76979871' ), + 'vimeo only in the query' => array( 'https://example.org/?next=https://vimeo.com/76979871' ), + 'vimeo profile, no video' => array( 'https://vimeo.com/someuser' ), + 'vimeo home page' => array( 'https://vimeo.com/' ), + 'not http' => array( 'ftp://vimeo.com/76979871' ), + 'empty string' => array( '' ), + 'not a string' => array( 76979871 ), + 'url inside text' => array( 'Watch https://vimeo.com/76979871 now' ), + ); + } + + /** + * @dataProvider not_vimeo_urls + * + * @param mixed $value Value to check. + */ + public function test_rejects_values_that_are_not_a_vimeo_video( $value ) { + $this->assertFalse( Vimeo_Url::is_vimeo_url( $value ) ); + } +} diff --git a/tests/stubs/class-embed-wpdb-double.php b/tests/stubs/class-embed-wpdb-double.php new file mode 100644 index 0000000000..26795201dd --- /dev/null +++ b/tests/stubs/class-embed-wpdb-double.php @@ -0,0 +1,70 @@ + attachment ID map and records each + * prepared query, so a test can tell how often the database was asked. + * + * @package GoDAM + */ + +namespace RTGODAM\Tests; + +/** + * Class Embed_Wpdb_Double + */ +class Embed_Wpdb_Double { + + /** + * Post meta table name. + * + * @var string + */ + public $postmeta = 'wp_postmeta'; + + /** + * Posts table name. + * + * @var string + */ + public $posts = 'wp_posts'; + + /** + * Attachment IDs by job ID. + * + * @var array + */ + public $attachments = array(); + + /** + * Job IDs looked up, in order. + * + * @var string[] + */ + public $lookups = array(); + + /** + * Keep the query and its argument together. + * + * @param string $query Query with a %s placeholder. + * @param string $value Job ID. + * + * @return array{0: string, 1: string} + */ + public function prepare( $query, $value ) { + return array( $query, $value ); + } + + /** + * Answer the lookup from the map. + * + * @param array{0: string, 1: string} $prepared What prepare() returned. + * + * @return string|null + */ + public function get_var( $prepared ) { + $this->lookups[] = $prepared[1]; + + return isset( $this->attachments[ $prepared[1] ] ) ? (string) $this->attachments[ $prepared[1] ] : null; + } +} diff --git a/tests/stubs/class-vimeo-migration-double.php b/tests/stubs/class-vimeo-migration-double.php new file mode 100644 index 0000000000..8b5e5be4e0 --- /dev/null +++ b/tests/stubs/class-vimeo-migration-double.php @@ -0,0 +1,43 @@ +lookups[] = $vimeo_url; + + return null === $this->attachment_id ? new \WP_Error( 'invalid_response', 'Invalid response from GoDAM Central.' ) : $this->attachment_id; + } +} diff --git a/tests/stubs/vimeo-migration-functions.php b/tests/stubs/vimeo-migration-functions.php new file mode 100644 index 0000000000..8a6f3fba2e --- /dev/null +++ b/tests/stubs/vimeo-migration-functions.php @@ -0,0 +1,30 @@ +