75 lines
2.2 KiB
C#
75 lines
2.2 KiB
C#
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);
|
|
|
|
/// <summary>
|
|
/// Extracts the video ID from a YouTube URL or returns the input if it's already a video ID.
|
|
/// </summary>
|
|
/// <param name="input">The YouTube URL or video ID</param>
|
|
/// <returns>The extracted video ID or null if invalid</returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validates if the input is a valid YouTube video ID.
|
|
/// </summary>
|
|
/// <param name="input">The video ID to validate</param>
|
|
/// <returns>True if the input is a valid video ID</returns>
|
|
public static bool IsValidVideoId(string? input)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(input))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return ShortUrlRegex.IsMatch(input);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validates if the input is a valid YouTube URL or video ID.
|
|
/// </summary>
|
|
/// <param name="input">The URL or video ID to validate</param>
|
|
/// <returns>True if the input is a valid YouTube URL or video ID</returns>
|
|
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);
|
|
}
|
|
}
|