-
Notifications
You must be signed in to change notification settings - Fork 3
/
Utility.cs
76 lines (69 loc) · 2.41 KB
/
Utility.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
// ReSharper disable UnusedMember.Global
namespace Hi3Helper.Http
{
internal static class Utility
{
internal static Uri ToUri(this string? urlString)
{
if (!Uri.TryCreate(urlString, UriKind.RelativeOrAbsolute, out Uri? url))
throw new InvalidOperationException($"URL string is not a valid url: {urlString}");
return url;
}
internal static async ValueTask<long> GetUrlContentLengthAsync(
this Uri uri,
HttpClient client,
int retryCount,
TimeSpan retryInterval,
TimeSpan timeoutInterval,
CancellationToken token)
{
int currentRetry = 0;
Start:
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = uri
};
HttpResponseMessage? message = null;
CancellationTokenSource cancelTimeoutToken = new CancellationTokenSource(timeoutInterval);
CancellationTokenSource coopToken = CancellationTokenSource.CreateLinkedTokenSource(cancelTimeoutToken.Token, token);
try
{
request.Headers.Range = new RangeHeaderValue(0, null);
message = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, coopToken.Token);
return message.Content.Headers.ContentLength ?? 0;
}
catch (TaskCanceledException) when (token.IsCancellationRequested) { throw; }
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
catch (Exception)
{
currentRetry++;
if (currentRetry > retryCount)
throw;
await Task.Delay(retryInterval, token);
goto Start;
}
finally
{
request.Dispose();
message?.Dispose();
cancelTimeoutToken.Dispose();
coopToken.Dispose();
}
}
internal static bool IsStreamCanSeeLength(this Stream stream)
{
try
{
_ = stream.Length;
return true;
}
catch { return false; }
}
}
}