-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUrl.cs
More file actions
593 lines (360 loc) · 16.1 KB
/
Url.cs
File metadata and controls
593 lines (360 loc) · 16.1 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
using Gsemac.Collections;
using Gsemac.Collections.Extensions;
using Gsemac.IO;
using Gsemac.Text;
using Gsemac.Text.Extensions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Gsemac.Net {
public sealed class Url :
IUrl {
// Public members
public const char DirectorySeparatorChar = '/';
public const string SchemeSeparator = "://";
public string Scheme {
get => scheme;
set => SetScheme(value);
}
public string UserName { get; set; }
public string Password { get; set; }
public string Host {
get => GetHost();
set => SetHost(value);
}
public string Hostname { get; set; }
public int? Port { get; set; }
public string Path { get; set; }
public string Fragment { get; set; }
public IDictionary<string, string> QueryParameters { get; private set; }
public Url() :
this(string.Empty) {
}
public Url(string url) {
Match match = Regex.Match(url ?? string.Empty, @"^(?<scheme>.+?:)?(?:\/\/)?(?<credentials>.+?:.+?@)?(?<host>.+?)?(?<path>\/.*?)?(?<query>\?.+?)?(?<fragment>#.+?)?$");
if (!match.Success)
throw new FormatException(Properties.ExceptionMessages.MalformedUrl);
Scheme = match.Groups["scheme"].Value;
Path = match.Groups["path"].Value;
SetQueryParameters(match.Groups["query"].Value);
SetFragment(match.Groups["fragment"].Value);
// Parse the hostname and port.
SetHost(match.Groups["host"].Value);
// Parse the credentials.
SetCredentials(match.Groups["credentials"].Value);
}
public Url(IUrl url) :
this(UrlToString(url)) {
}
public Url(Uri uri) :
this(UriToString(uri)) {
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
// Add rooth path.
sb.Append(GetRoot());
if (!string.IsNullOrEmpty(Path)) {
if (!Path.StartsWith("/"))
sb.Append("/");
sb.Append(Path);
}
// Add query parameters.
if (QueryParameters is object && QueryParameters.Any()) {
sb.Append("?");
sb.Append(string.Join("&", QueryParameters.Select(p => !string.IsNullOrEmpty(p.Value) ? $"{p.Key}={Uri.EscapeDataString(p.Value)}" : p.Key)));
}
// Add fragment.
if (!string.IsNullOrWhiteSpace(Fragment)) {
sb.Append("#");
sb.Append(Fragment);
}
return sb.ToString();
}
public static Url Parse(string url) {
return new Url(url);
}
public static bool TryParse(string url, out Url result) {
try {
result = Parse(url);
return true;
}
catch (FormatException) {
result = null;
return false;
}
}
public static bool IsUrl(string value) {
return PathUtilities.IsUrl(value);
}
public static string GetDomainName(string url) {
if (string.IsNullOrWhiteSpace(url))
return string.Empty;
string hostname = GetHostname(url);
// Trim trailing periods from fully-qualified domain names.
if (!string.IsNullOrWhiteSpace(hostname))
hostname = hostname.TrimEnd('.');
string[] parts = hostname.Split('.');
string domain = hostname;
if (parts.Count() == 4 && parts.All(p => p.All(c => char.IsDigit(c)))) {
// If the hostname is an IPv4 address, return the IPv4 address as the domain name.
domain = string.Join(".", parts);
}
else if (parts.Length > 2) {
// Try smaller suffix candidates until we get a match.
IPublicSuffixList suffixList = GetPublicSuffixList();
string suffix = string.Empty;
for (int i = 1; i < parts.Length; ++i) {
string suffixCandidate = $".{string.Join(".", parts.Skip(i))}";
if (suffixList.Contains(suffixCandidate)) {
suffix = suffixCandidate;
break;
}
}
if (string.IsNullOrEmpty(suffix)) {
// If there is no suffix, just return the last two parts of the hostname.
domain = string.Join(".", parts.TakeLast(2));
}
else {
// If there is a suffix, the domain is the part before the suffix.
int suffixLength = StringUtilities.Count(suffix, ".");
domain = string.Join(".", parts.TakeLast(suffixLength + 1));
}
}
return domain;
}
public static string GetHostname(string url) {
// Returns the same value as GetHost, but with the port number removed.
if (string.IsNullOrWhiteSpace(url))
return string.Empty;
return GetHost(url)
.Split(':')
.FirstOrDefault() ?? string.Empty;
}
public static string GetHost(string url) {
if (string.IsNullOrWhiteSpace(url))
return string.Empty;
return GetOrigin(url)
.Split("//")
.LastOrDefault() ?? string.Empty;
}
public static string GetOrigin(string url) {
// The origin is composed of the scheme, host, and port (if present).
// Other information like user credentials is not included.
if (string.IsNullOrWhiteSpace(url))
return string.Empty;
Match match = Regex.Match(url ?? string.Empty, @"^(?:(?<scheme>[^\s:]+:)\/\/|\/\/)?(?:.+?:.+?@)?(?<hostname>[^\/]+)");
if (!match.Success)
return string.Empty;
return $"{match.Groups["scheme"].Value}//{match.Groups["hostname"].Value}";
}
public static string GetScheme(string url) {
// The trailing colon is included in the scheme, similar to JavaScript's "Url.protocol" property.
// https://developer.mozilla.org/en-US/docs/Web/API/URL/protocol
if (string.IsNullOrWhiteSpace(url))
return string.Empty;
string scheme = PathUtilities.GetScheme(url);
if (string.IsNullOrWhiteSpace(scheme))
return string.Empty;
return scheme + ":";
}
public static string GetQueryParameter(string url, string parameter) {
if (GetQueryParameters(url).TryGetValue(parameter, out string value))
return value;
return string.Empty;
}
public static IDictionary<string, string> GetQueryParameters(string url) {
if (TryParse(url, out Url parsedUrl))
return parsedUrl.QueryParameters;
return new Dictionary<string, string>();
}
public static string SetQueryParameter(string url, string name, string value) {
Url parsedUrl = Parse(url);
parsedUrl.QueryParameters[name] = value;
return parsedUrl.ToString();
}
public static string StripQueryParameters(string url) {
if (string.IsNullOrWhiteSpace(url))
return url;
return Regex.Replace(url, @"\?.+?(?=#|$)", string.Empty);
}
public static string StripFragment(string url) {
if (string.IsNullOrWhiteSpace(url))
return url;
int fragmentIndex = url.IndexOf("#");
return fragmentIndex < 0 ?
url :
url.Substring(0, fragmentIndex);
}
public static string Combine(params string[] parts) {
if (parts is null)
throw new ArgumentNullException(nameof(parts));
return Combine((IEnumerable<string>)parts);
}
public static string Combine(IEnumerable<string> parts) {
if (parts is null)
throw new ArgumentNullException(nameof(parts));
if (!parts.Any())
return string.Empty;
if (parts.Count() < 2)
return parts.First();
string leftPart = parts.First();
string rightPart = parts.Skip(1).First();
string result = leftPart;
if (string.IsNullOrWhiteSpace(leftPart) || PathUtilities.IsPathRooted(rightPart, new PathInfo() { IsUrl = true })) {
result = rightPart;
}
else if (!string.IsNullOrWhiteSpace(rightPart)) {
// If the path we're combining is a relative path beginning with a dot, trim the dot part.
// The path will still be treated as a relative path.
if (rightPart.StartsWith("./"))
rightPart = rightPart.TrimStart("./");
string scheme = PathUtilities.GetScheme(leftPart);
if (!string.IsNullOrWhiteSpace(scheme) && rightPart.StartsWith("//") && !rightPart.Equals("//")) {
// Prepend the new path with the scheme.
result = $"{scheme}:{rightPart}";
}
else if (rightPart.StartsWith("/")) {
// Make the new path relative to the root.
string rootUrl = PathUtilities.GetRootPath(leftPart, new PathInfo() { IsUrl = true });
string relativePath = PathUtilities.TrimLeftDirectorySeparators(rightPart);
result = $"{rootUrl}/{relativePath}";
}
else if (leftPart.EndsWith("/")) {
// Append the new path to the current path.
result = $"{leftPart}{rightPart}";
}
else if (rightPart.StartsWith("?")) {
// Replace the query parameters in the URL.
result = $"{StripQueryParameters(leftPart)}{rightPart}";
}
else if (rightPart.StartsWith("#")) {
// Replace the fragment in the URL.
result = $"{StripFragment(leftPart)}{rightPart}";
}
else {
// Replace the current directory with the new path.
string parentUrl = PathUtilities.GetParentPath(leftPart);
if (string.IsNullOrEmpty(parentUrl))
parentUrl = leftPart;
if (parentUrl.EndsWith("/"))
parentUrl = parentUrl.Substring(0, parentUrl.Length - 1);
result = $"{parentUrl}/{rightPart}";
}
}
return Combine(new[] { (result ?? "").Trim() }.Concat(parts.Skip(2)));
}
// Private members
private string scheme;
private string GetHost() {
StringBuilder sb = new StringBuilder();
// Add hostname.
sb.Append(Hostname);
// Add port.
if (Port.HasValue) {
sb.Append(":");
sb.Append(Port.Value);
}
return sb.ToString();
}
private string GetRoot() {
StringBuilder sb = new StringBuilder();
// Add scheme.
if (!string.IsNullOrWhiteSpace(Scheme)) {
sb.Append(Scheme.TrimEnd(':'));
sb.Append(":");
}
sb.Append("//");
// Add username/password.
if (!string.IsNullOrWhiteSpace(UserName)) {
sb.Append(UserName);
// If the user doesn't set a password, don't include one.
// However, if the password is the empty string, include an empty password (this is what cURL does).
// https://catonmat.net/cookbooks/curl/use-basic-http-authentication
if (!string.IsNullOrEmpty(Password) || Password is object)
sb.Append(":");
if (!string.IsNullOrEmpty(Password))
sb.Append(Password);
sb.Append("@");
}
// Add host.
sb.Append(Host);
string rootString = sb.ToString();
if (rootString.Equals("//"))
rootString = string.Empty;
return rootString;
}
private void SetScheme(string scheme) {
if (!string.IsNullOrEmpty(scheme)) {
if (!Regex.Match(scheme, @"^(?<scheme>[\w][\w+-.]+):?$").Success)
throw new ArgumentException(Properties.ExceptionMessages.SchemeContainsInvalidCharacters, nameof(scheme));
if (scheme.EndsWith(":"))
scheme = scheme.TrimEnd(':');
}
this.scheme = scheme;
}
private void SetHost(string host) {
if (!string.IsNullOrEmpty(host) && host.Contains(":")) {
string[] hostParts = host.Split(':');
Hostname = hostParts[0];
if (hostParts.Count() > 1 && int.TryParse(hostParts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int port))
Port = port;
else
throw new ArgumentException(Properties.ExceptionMessages.MalformedUrl, nameof(host));
}
else {
Hostname = host;
Port = null;
}
}
private void SetCredentials(string credentialsStr) {
if (!string.IsNullOrEmpty(credentialsStr)) {
if (credentialsStr.EndsWith("@"))
credentialsStr = credentialsStr.Substring(0, credentialsStr.Length - 1);
string[] usernamePassword = credentialsStr.Split(new[] { ':' }, 2);
if (usernamePassword.Count() == 2) {
this.UserName = usernamePassword[0];
this.Password = usernamePassword[1];
}
}
}
private void SetQueryParameters(string queryParametersStr) {
// Query parameter names are case-sensitive, so do not alter their casing.
queryParametersStr = queryParametersStr ?? "";
if (queryParametersStr.StartsWith("?"))
queryParametersStr = queryParametersStr.Substring(1);
IEnumerable<KeyValuePair<string, string>> keyValuePairs = (queryParametersStr ?? "")
.Split('&')
.Where(p => !string.IsNullOrWhiteSpace(p))
.Select(p => p.Split(new[] { '=' }, 2))
.Select(pair => new KeyValuePair<string, string>(pair.First(), Uri.UnescapeDataString(pair.Skip(1).FirstOrDefault() ?? string.Empty)));
QueryParameters = new OrderedDictionary<string, string>(keyValuePairs);
}
private void SetFragment(string fragmentStr) {
if (!string.IsNullOrEmpty(fragmentStr)) {
if (fragmentStr.StartsWith("#"))
fragmentStr = fragmentStr.Substring(1);
this.Fragment = fragmentStr;
}
}
private static IPublicSuffixList GetPublicSuffixList() {
// To determine the suffix, we use the Public Suffix List:
// https://publicsuffix.org/list/public_suffix_list.dat
IPublicSuffixListProvider provider = PublicSuffixListProvider.Default ??
new ResourcePublicSuffixListProvider();
return provider.GetList();
}
private static string UriToString(Uri uri) {
if (uri is null)
throw new ArgumentNullException(nameof(uri));
return uri.AbsoluteUri;
}
private static string UrlToString(IUrl url) {
if (url is null)
throw new ArgumentNullException(nameof(url));
return url.ToString();
}
}
}