-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathExtensions.cs
More file actions
363 lines (314 loc) · 13.3 KB
/
Extensions.cs
File metadata and controls
363 lines (314 loc) · 13.3 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
using System.ComponentModel;
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using Grayjay.ClientServer.Models;
using Grayjay.ClientServer.Pooling;
using Grayjay.Engine;
using Grayjay.Engine.Pagers;
using Grayjay.ClientServer.Proxy;
using Grayjay.Engine.Models.Video.Additions;
namespace Grayjay.ClientServer
{
public static class Extensions
{
public static GrayjayPlugin FromPool(this GrayjayPlugin client, PlatformMultiClientPool pool)
=> pool.GetClientPooled(client);
public static PagerResult<T> AsPagerResult<T>(this IPager<T> pager)
{
var results = pager.GetResults();
var hasMore = pager.HasMorePages();
return new PagerResult<T>()
{
PagerID = pager.ID,
Results = results,
HasMore = hasMore
};
}
public static PagerResult<R> AsPagerResult<T, R>(this IPager<T> pager, Func<T, bool> filter, Func<T, R> modifier)
{
var results = pager.GetResults().Where(filter).Select(modifier).ToArray();
var hasMore = pager.HasMorePages();
return new PagerResult<R>()
{
PagerID = pager.ID,
Results = results,
HasMore = hasMore
};
}
public static PagerResult<R> AsPagerResult<T, R>(this IPager<T> pager, Func<T, R> modifier)
{
var results = pager.GetResults().Select(modifier).ToArray();
var hasMore = pager.HasMorePages();
return new PagerResult<R>()
{
PagerID = pager.ID,
Results = results,
HasMore = hasMore
};
}
public static byte[] DecodeBase64(this string base64)
{
if (base64.Length == 0)
return new byte[0];
int padding = 4 - (base64.Length % 4);
if (padding < 4)
base64 += new string('=', padding);
return Convert.FromBase64String(base64);
}
public static byte[] DecodeBase64Url(this string base64)
{
if (base64.Length == 0)
return new byte[0];
base64 = base64.Replace('-', '+').Replace('_', '/');
int padding = 4 - (base64.Length % 4);
if (padding < 4)
base64 += new string('=', padding);
return Convert.FromBase64String(base64);
}
public static string EncodeBase64(this byte[] bytes)
{
return Convert.ToBase64String(bytes);
}
public static string EncodeBase64NoPadding(this byte[] bytes)
{
return Convert.ToBase64String(bytes).Replace("=", "");
}
public static string EncodeBase64Url(this byte[] bytes)
{
string base64 = Convert.ToBase64String(bytes);
base64 = base64.Replace('+', '-').Replace('/', '_');
return base64.TrimEnd('=');
}
public static TimeSpan NowDiff(this DateTime current)
{
return DateTime.Now.Subtract(current);
}
public static async Task SkipAsync(this Stream stream, int size, CancellationToken cancellationToken)
{
byte[] buffer = new byte[8192];
int remaining = size;
while (remaining > 0)
{
int toRead = Math.Min(buffer.Length, remaining);
int read = await stream.ReadAsync(buffer, 0, toRead, cancellationToken);
if (read == 0)
{
throw new EndOfStreamException("End of stream reached before skip could be completed.");
}
remaining -= read;
}
}
private const long CountInGbit = 1_000_000_000;
private const long CountInMbit = 1_000_000;
private const long CountInKbit = 1_000;
public static string ToHumanBitrate(this int value) => ((long)value).ToHumanBitrate();
public static string ToHumanBitrate(this long value)
{
long v = Math.Abs(value);
if (v >= CountInGbit)
return $"{value / CountInGbit}gbps";
else if (v >= CountInMbit)
return $"{value / CountInMbit}mbps";
else if (v >= CountInKbit)
return $"{value / CountInKbit}kbps";
return $"{value}bps";
}
private static readonly string DecimalFormat = "0.00";
public static string ToHumanBytesSpeed(this int value) => ((long)value).ToHumanBytesSpeed();
public static string ToHumanBytesSpeed(this long value)
{
long v = Math.Abs(value);
string formattedValue = value.ToString();
if (v >= CountInGbit)
formattedValue = $"{(value / (double)CountInGbit).ToString(DecimalFormat)}GB/s";
else if (v >= CountInMbit)
formattedValue = $"{(value / (double)CountInMbit).ToString(DecimalFormat)}MB/s";
else if (v >= CountInKbit)
formattedValue = $"{(value / (double)CountInKbit).ToString(DecimalFormat)}KB/s";
return formattedValue;
}
public static string ToHumanBytesSize(this int value, bool withDecimal = true) => ((long)value).ToHumanBytesSize(withDecimal);
public static string ToHumanBytesSize(this long value, bool withDecimal = true)
{
long v = Math.Abs(value);
string formattedValue = value.ToString();
if (withDecimal)
{
if (v >= CountInGbit)
formattedValue = $"{(value / (double)CountInGbit).ToString(DecimalFormat)}GB";
else if (v >= CountInMbit)
formattedValue = $"{(value / (double)CountInMbit).ToString(DecimalFormat)}MB";
else if (v >= CountInKbit)
formattedValue = $"{(value / (double)CountInKbit).ToString(DecimalFormat)}KB";
}
else
{
if (v >= CountInGbit)
formattedValue = $"{(value / (double)CountInGbit).ToString("0")}GB";
else if (v >= CountInMbit)
formattedValue = $"{(value / (double)CountInMbit).ToString("0")}MB";
else if (v >= CountInKbit)
formattedValue = $"{(value / (double)CountInKbit).ToString("0")}KB";
}
return formattedValue;
}
public static long DifferenceNowMinutes(this DateTime date)
{
return (long)DateTime.Now.Subtract(date).TotalMinutes;
}
public static long DifferenceNowSeconds(this DateTime date)
{
return (long)DateTime.Now.Subtract(date).TotalSeconds;
}
const string _allowedFileNameCharacters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz-.";
public static string SanitizeFileName(this string fileName)
{
foreach(char invalidChar in fileName.Distinct().Where(x=>!_allowedFileNameCharacters.Contains(x)))
fileName = fileName.Replace(invalidChar, '_');
return fileName;
}
// Windows MAX_PATH is 260; reserve some room for the directory prefix.
private const int MaxFileNameLength = 200;
/// <summary>
/// Truncates a file name (after sanitization) so that the base name fits within
/// <see cref="MaxFileNameLength"/> characters, preserving the extension.
/// </summary>
public static string TruncateFileName(this string fileName)
{
if (fileName.Length <= MaxFileNameLength)
return fileName;
string ext = Path.GetExtension(fileName); // e.g. ".mp4"
string baseName = Path.GetFileNameWithoutExtension(fileName);
int allowedBase = MaxFileNameLength - ext.Length;
if (allowedBase < 1) allowedBase = 1;
return baseName.Substring(0, Math.Min(baseName.Length, allowedBase)) + ext;
}
public static string SanitizeFileNameWithPath(this string path)
{
string dirName = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
foreach (char invalidChar in fileName.Distinct().Where(x => !_allowedFileNameCharacters.Contains(x)))
fileName = fileName.Replace(invalidChar, '_');
return Path.Combine(dirName, fileName);
}
public static string ToUrlAddress(this IPAddress address)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
return address.ToString();
else if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
if (address.IsIPv4MappedToIPv6)
return address.MapToIPv4().ToString();
else
{
string hostAddr = address.ToString();
int index = hostAddr.IndexOf('%');
if (index != -1)
{
string addrPart = hostAddr.Substring(0, index);
string scopeId = hostAddr.Substring(index + 1);
return $"[{addrPart}%25{scopeId}]";
}
else
return $"[{hostAddr}]";
}
}
else
throw new ArgumentException("Invalid address type", nameof(address));
}
public static string EnsureAbsoluteUrl(this string path, Uri baseUri)
{
Uri? resultUri;
if (Uri.TryCreate(path, UriKind.Absolute, out resultUri))
{
if ((resultUri.Scheme == Uri.UriSchemeHttp) || (resultUri.Scheme == Uri.UriSchemeHttps))
return path;
}
resultUri = new Uri(baseUri, path);
return resultUri.ToString();
}
public static string EnsureAbsoluteUrl(this string path, string baseUrl)
{
Uri baseUri = new Uri(baseUrl);
return path.EnsureAbsoluteUrl(baseUri);
}
public static string Capitalize(this string value)
{
if (string.IsNullOrEmpty(value))
return value;
return char.ToUpper(value[0]) + value.Substring(1);
}
/*
public static bool MatchesDomain(this string domain, string queryDomain)
{
if (queryDomain.StartsWith("."))
return domain.EndsWith(queryDomain) || domain == queryDomain.TrimStart('.');
else
return domain == queryDomain;
}*/
public static Func<string, HttpProxyRequest, (string, HttpProxyRequest)> ToProxyFunc(this IRequestModifier mod)
{
return (url, req) =>
{
var headers = req.Headers;
var modReq = mod.ModifyRequest(url, headers);
/*
foreach(var header in modReq.Headers)
{
var key = req.Headers.Keys.FirstOrDefault(x => x.Equals(header.Key, StringComparison.OrdinalIgnoreCase));
if (key != null)
req.Headers[key] = header.Value;
else
req.Headers.Add(header.Key, header.Value);
}*/
if(modReq.Headers != null)
req.Headers = new Dictionary<string, string>(modReq.Headers, StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(modReq.Url))
modReq.Url = url;
return (modReq.Url, req);
};
}
public static Func<HttpProxyRequest, HttpProxyResponse> ToProxyFunc(this RequestExecutor exe)
{
throw new NotImplementedException();
}
public static string VideoContainerToExtension(this string container) {
if (container.Contains("video/mp4") || container == "application/vnd.apple.mpegurl")
return "mp4";
else if (container.Contains("application/x-mpegURL"))
return "m3u8";
else if (container.Contains("video/3gpp"))
return "3gp";
else if (container.Contains("video/quicktime"))
return "mov";
else if (container.Contains("video/webm"))
return "webm";
else if (container.Contains("video/x-matroska"))
return "mkv";
else
//throw new InvalidDataException("Could not determine container type for audio (" + container + ")");
//else
return "video";
}
public static string AudioContainerToExtension(this string container)
{
if (container.Contains("audio/mp4"))
return "mp4a";
else if (container.Contains("audio/mpeg"))
return "mpga";
else if (container.Contains("audio/mp3"))
return "mp3";
else if (container.Contains("audio/webm"))
return "webm";
else if (container == "application/vnd.apple.mpegurl")
return "mp4";
else
//throw new InvalidDataException("Could not determine container type for audio (" + container + ")");
//else
return "audio";
}
}
}