library.network.maui/Network/NetworkHelper.cs

69 lines
2.2 KiB
C#

namespace Blahblah.Library.Network;
public partial class NetworkHelper
{
public const string AcceptAll = "*/*";
public const string AcceptHttp = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
public const string AcceptImage = "image/webp,image/*,*/*;q=0.8";
public const string AcceptJpegImage = "image/jpeg,image/*,*/*;q=0.8";
public const string AcceptJson = "application/json";
const string AcceptHeader = "Accept";
const string ReferrerHeader = "Referer";
const int Timeout = 30;
const int ImageTimeout = 60;
public static CancellationTokenSource TimeoutTokenSource => new(Timeout * 1000);
public static CancellationTokenSource ImageTimeoutTokenSource => new(ImageTimeout * 1000);
static string? proxyHost;
static int? proxyPort;
public static void SetProxy(string? host = null, int? port = null)
{
//bool changed = proxyHost != host || proxyPort != port;
proxyHost = host;
proxyPort = port;
/*
if (changed)
{
// TODO: background download
}
//*/
}
public static NetworkHelper CreateSession(int timeout = Timeout, bool useCookie = true, bool waitsConnectivity = true, Dictionary<string, string>? additionalHeaders = null)
{
var helper = new NetworkHelper(timeout, useCookie, waitsConnectivity, additionalHeaders);
return helper;
}
public static NetworkHelper CreateImageSession(int timeout = ImageTimeout, bool useCookie = false, bool waitsConnectivity = false, Dictionary<string, string>? additionalHeaders = null)
{
return CreateSession(timeout, false, false, additionalHeaders);
}
public string? Accept { get; set; }
public string? Referrer { get; set; }
readonly object sync = new();
public partial Task<NetworkResult<string>> GetContentAsync(string url, StringHandler? process = null, CancellationToken token = default);
}
public class HttpResponseException : Exception
{
public int StatusCode { get; }
public string Url { get; }
public HttpResponseException(int code, string url) : base($"HTTP response failed with status code {code}, url: {url}")
{
StatusCode = code;
Url = url;
}
}