using System.Text.RegularExpressions; namespace Hutopy.Infrastructure.YouTube; public static class YouTubeUrlHelper { private static readonly Regex VideoIdRegex = new( @"(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^""&?/\s]{11})", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex ShortUrlRegex = new( @"^[a-zA-Z0-9_-]{11}$", RegexOptions.Compiled); /// /// Extracts the video ID from a YouTube URL or returns the input if it's already a video ID. /// /// The YouTube URL or video ID /// The extracted video ID or null if invalid public static string? ExtractVideoId(string? input) { if (string.IsNullOrWhiteSpace(input)) { return null; } // If it's already a valid video ID, return it if (IsValidVideoId(input)) { return input; } // Try to extract video ID from URL Match match = VideoIdRegex.Match(input); return match.Success ? match.Groups[1].Value : null; } /// /// Validates if the input is a valid YouTube video ID. /// /// The video ID to validate /// True if the input is a valid video ID public static bool IsValidVideoId(string? input) { if (string.IsNullOrWhiteSpace(input)) { return false; } return ShortUrlRegex.IsMatch(input); } /// /// Validates if the input is a valid YouTube URL or video ID. /// /// The URL or video ID to validate /// True if the input is a valid YouTube URL or video ID public static bool IsValidYouTubeUrlOrId(string? input) { if (string.IsNullOrWhiteSpace(input)) { return false; } // Check if it's a valid video ID if (IsValidVideoId(input)) { return true; } // Check if it's a valid YouTube URL return VideoIdRegex.IsMatch(input); } }