YouTubeUrlHelper.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Text.RegularExpressions;
  2. namespace Application.Abstractions.YouTube;
  3. /// <summary>
  4. /// YouTube URL에서 채널 ID, 핸들, 비디오 ID를 추출하는 유틸리티
  5. /// </summary>
  6. public static partial class YouTubeUrlHelper
  7. {
  8. /// <summary>
  9. /// YouTube URL에서 Channel ID 추출
  10. /// 지원 형식:
  11. /// - https://www.youtube.com/channel/UCxxxxxxxxx
  12. /// - https://www.youtube.com/@handle
  13. /// - https://youtube.com/c/CustomName
  14. /// </summary>
  15. public static (string? channelId, string? handle) ExtractChannelInfo(string url)
  16. {
  17. if (string.IsNullOrWhiteSpace(url))
  18. {
  19. return (null, null);
  20. }
  21. // /channel/UCxxxxx 형식
  22. var channelMatch = ChannelIdRegex().Match(url);
  23. if (channelMatch.Success)
  24. {
  25. return (channelMatch.Groups[1].Value, null);
  26. }
  27. // /@handle 형식
  28. var handleMatch = HandleRegex().Match(url);
  29. if (handleMatch.Success)
  30. {
  31. return (null, handleMatch.Groups[1].Value);
  32. }
  33. // /c/CustomName 형식 → 핸들로 처리
  34. var customMatch = CustomUrlRegex().Match(url);
  35. if (customMatch.Success)
  36. {
  37. return (null, customMatch.Groups[1].Value);
  38. }
  39. return (null, null);
  40. }
  41. /// <summary>
  42. /// YouTube URL에서 Video ID 추출
  43. /// 지원 형식:
  44. /// - https://www.youtube.com/watch?v=xxxxxxxxxxx
  45. /// - https://youtu.be/xxxxxxxxxxx
  46. /// - https://www.youtube.com/live/xxxxxxxxxxx
  47. /// </summary>
  48. public static string? ExtractVideoId(string url)
  49. {
  50. if (string.IsNullOrWhiteSpace(url))
  51. {
  52. return null;
  53. }
  54. var match = VideoIdRegex().Match(url);
  55. return match.Success ? match.Groups[1].Value : null;
  56. }
  57. [GeneratedRegex(@"youtube\.com/channel/(UC[\w-]+)", RegexOptions.IgnoreCase)]
  58. private static partial Regex ChannelIdRegex();
  59. [GeneratedRegex(@"youtube\.com/@([\w.-]+)", RegexOptions.IgnoreCase)]
  60. private static partial Regex HandleRegex();
  61. [GeneratedRegex(@"youtube\.com/c/([\w.-]+)", RegexOptions.IgnoreCase)]
  62. private static partial Regex CustomUrlRegex();
  63. [GeneratedRegex(@"(?:youtube\.com/watch\?v=|youtu\.be/|youtube\.com/live/)([\w-]{11})", RegexOptions.IgnoreCase)]
  64. private static partial Regex VideoIdRegex();
  65. }