[CHANGE] Client cookie init

This commit is contained in:
max
2025-09-22 13:41:02 +02:00
parent 9e81e221c6
commit 1903cb2938

View File

@@ -21,30 +21,33 @@ public sealed class YouTubeClient : IDisposable
public Cookie? SapisidCookie => CookieContainer.GetAllCookies()["SAPISID"]; public Cookie? SapisidCookie => CookieContainer.GetAllCookies()["SAPISID"];
public HttpClient HttpClient { get; } public HttpClient HttpClient { get; }
private YouTubeClient(CookieCollection cookies, string userAgent) private YouTubeClient(CookieCollection? cookies, string userAgent)
{ {
if (string.IsNullOrWhiteSpace(userAgent)) if (string.IsNullOrWhiteSpace(userAgent))
{ {
throw new ArgumentNullException(nameof(userAgent)); throw new ArgumentNullException(nameof(userAgent));
} }
UserAgent = userAgent; UserAgent = userAgent;
if (cookies.Count == 0) if (cookies == null || cookies.Count == 0)
{ {
Id = $"anon_{Guid.NewGuid()}"; Id = $"anon_{Guid.NewGuid()}";
IsAnonymous = true; IsAnonymous = true;
} }
else
{
CookieContainer.Add(cookies); CookieContainer.Add(cookies);
}
HttpClient = new HttpClient(GetHttpClientHandler()); HttpClient = new HttpClient(GetHttpClientHandler());
} }
/// <summary> /// <summary>
/// Loads the given cookies and fetch client state. /// Loads the given cookies and fetch client state.
/// </summary> /// </summary>
/// <param name="cookies">The cookies to use for making requests. Empty collection for anonymous requests.</param> /// <param name="cookies">The cookies to use for making requests. Empty collection or null for anonymous requests.</param>
/// <param name="userAgent">The user agent to use for the requests. Only WEB client is supported.</param> /// <param name="userAgent">The user agent to use for the requests. Only WEB client is supported.</param>
/// <returns></returns> /// <returns></returns>
public static async Task<Result<YouTubeClient>> CreateAsync(CookieCollection cookies, string userAgent) public static async Task<Result<YouTubeClient>> CreateAsync(CookieCollection? cookies, string userAgent)
{ {
var client = new YouTubeClient(cookies, userAgent); var client = new YouTubeClient(cookies, userAgent);
var clientInitializeResult = await client.FetchClientDataAsync(); var clientInitializeResult = await client.FetchClientDataAsync();