feat: Add validation for YouTube URL and enhance image upload experience in creator's album editor

This commit is contained in:
2025-04-24 03:20:08 -04:00
parent 7503f89e3f
commit c16dddb8dd
6 changed files with 483 additions and 142 deletions

View File

@@ -0,0 +1,64 @@
using System.Text.RegularExpressions;
namespace Hutopy.Web.Common.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
var 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);
}
}