85 lines
2.4 KiB
C#
85 lines
2.4 KiB
C#
using System.Net;
|
|
using DotBased.Monads;
|
|
using Manager.YouTube.Models;
|
|
|
|
namespace Manager.YouTube;
|
|
|
|
public sealed class YouTubeClient : IDisposable
|
|
{
|
|
public string Id { get; private set; } = "";
|
|
public string? UserAgent { get; set; }
|
|
public CookieContainer CookieContainer { get; } = new() { PerDomainCapacity = 50 };
|
|
public ClientExternalData External { get; set; } = new();
|
|
public Cookie? SapisidCookie => CookieContainer.GetAllCookies()["SAPISID"];
|
|
public HttpClient? GetHttpClient() => _httpClient;
|
|
|
|
private HttpClient? _httpClient;
|
|
|
|
public YouTubeClient()
|
|
{
|
|
SetupClient();
|
|
}
|
|
|
|
private void SetupClient()
|
|
{
|
|
_httpClient?.Dispose();
|
|
|
|
var clientHandler = new HttpClientHandler
|
|
{
|
|
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
|
|
UseCookies = true,
|
|
CookieContainer = CookieContainer
|
|
};
|
|
_httpClient = new HttpClient(clientHandler);
|
|
_httpClient.DefaultRequestHeaders.Clear();
|
|
}
|
|
|
|
public async Task<Result> BuildClientAsync()
|
|
{
|
|
if (External.State is not { LoggedIn: true })
|
|
{
|
|
var state = await NetworkService.GetClientStateAsync(this);
|
|
if (!state.IsSuccess)
|
|
{
|
|
return state;
|
|
}
|
|
External.State = state.Value;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(External.State.WebPlayerContextConfig?.WebPlayerContext?.DatasyncId))
|
|
{
|
|
var datasyncResult = await NetworkService.GetDatasyncIds(this);
|
|
if (!datasyncResult.IsSuccess)
|
|
{
|
|
return datasyncResult;
|
|
}
|
|
|
|
foreach (var id in datasyncResult.Value)
|
|
{
|
|
if (External.DatasyncIds.Contains(id))
|
|
continue;
|
|
External.DatasyncIds.Add(id);
|
|
}
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(Id))
|
|
{
|
|
var accountInfoResult = await NetworkService.GetCurrentAccountIdAsync(this);
|
|
if (!accountInfoResult.IsSuccess)
|
|
{
|
|
return accountInfoResult;
|
|
}
|
|
|
|
Id = accountInfoResult.Value;
|
|
}
|
|
|
|
var accountInfo = await NetworkService.GetChannelAsync(Id, this);
|
|
|
|
return Result.Success();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_httpClient?.Dispose();
|
|
}
|
|
} |