59 lines
2.0 KiB
C#
59 lines
2.0 KiB
C#
using System.Text.Json;
|
|
using DotBased.Monads;
|
|
using Manager.YouTube.Models.Innertube;
|
|
using Manager.YouTube.Parsers;
|
|
using Manager.YouTube.Util;
|
|
|
|
namespace Manager.YouTube;
|
|
|
|
public static class NetworkService
|
|
{
|
|
public static async Task<Result<ClientState>> GetClientStateAsync(YouTubeClient client)
|
|
{
|
|
var origin = "https://www.youtube.com/";
|
|
var httpRequest = new HttpRequestMessage
|
|
{
|
|
Method = HttpMethod.Get,
|
|
RequestUri = new Uri(origin)
|
|
};
|
|
httpRequest.Headers.IfModifiedSince = new DateTimeOffset(DateTime.UtcNow);
|
|
httpRequest.Headers.UserAgent.ParseAdd(client.UserAgent);
|
|
|
|
if (client.SapisidCookie != null)
|
|
{
|
|
httpRequest.Headers.Authorization = AuthenticationUtilities.GetSapisidHashHeader(client.SapisidCookie.Value, origin);
|
|
httpRequest.Headers.Add("Origin", origin);
|
|
}
|
|
|
|
var http = client.GetHttpClient();
|
|
if (http == null)
|
|
{
|
|
return ResultError.Fail("Unable to get http client!");
|
|
}
|
|
|
|
var response = await http.SendAsync(httpRequest);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
var responseResult = await response.Content.ReadAsStringAsync();
|
|
return Result<ClientState>.Fail(ResultError.Fail(responseResult));
|
|
}
|
|
var responseHtml = await response.Content.ReadAsStringAsync();
|
|
var clientStateResult = HtmlParser.GetJsonFromScriptFunction(responseHtml, "ytcfg.set");
|
|
if (clientStateResult is { IsSuccess: false, Error: not null })
|
|
{
|
|
return clientStateResult.Error;
|
|
}
|
|
|
|
ClientState? clientState;
|
|
try
|
|
{
|
|
clientState = JsonSerializer.Deserialize<ClientState>(clientStateResult.Value);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
return ResultError.Error(e, "Error while parsing JSON!");
|
|
}
|
|
|
|
return clientState == null ? ResultError.Fail("Unable to parse client state!") : clientState;
|
|
}
|
|
} |