2020-08-11 06:53:43 +08:00
|
|
|
// Copyright (c) Microsoft Corporation
|
|
|
|
// The Microsoft Corporation licenses this file to you under the MIT license.
|
|
|
|
// See the LICENSE file in the project root for more information.
|
|
|
|
|
|
|
|
using System;
|
2021-07-05 22:26:31 +08:00
|
|
|
using System.Linq;
|
2020-08-11 06:53:43 +08:00
|
|
|
using Microsoft.Plugin.Uri.Interfaces;
|
|
|
|
|
|
|
|
namespace Microsoft.Plugin.Uri.UriHelper
|
|
|
|
{
|
|
|
|
public class ExtendedUriParser : IUriParser
|
|
|
|
{
|
|
|
|
public bool TryParse(string input, out System.Uri result)
|
|
|
|
{
|
|
|
|
if (string.IsNullOrEmpty(input))
|
|
|
|
{
|
|
|
|
result = default;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle common cases UriBuilder does not handle
|
2020-10-31 07:43:09 +08:00
|
|
|
// Using CurrentCulture since this is a user typed string
|
|
|
|
if (input.EndsWith(":", StringComparison.CurrentCulture)
|
|
|
|
|| input.EndsWith(".", StringComparison.CurrentCulture)
|
2021-07-05 22:26:31 +08:00
|
|
|
|| input.EndsWith(":/", StringComparison.CurrentCulture)
|
|
|
|
|| input.All(char.IsDigit))
|
2020-08-11 06:53:43 +08:00
|
|
|
{
|
|
|
|
result = default;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
var urlBuilder = new UriBuilder(input);
|
2021-07-16 19:38:26 +08:00
|
|
|
var hadDefaultPort = urlBuilder.Uri.IsDefaultPort;
|
|
|
|
urlBuilder.Port = hadDefaultPort ? -1 : urlBuilder.Port;
|
|
|
|
|
|
|
|
if (!input.Contains("HTTP://", StringComparison.OrdinalIgnoreCase) &&
|
|
|
|
!input.Contains("FTPS://", StringComparison.OrdinalIgnoreCase))
|
|
|
|
{
|
|
|
|
urlBuilder.Scheme = System.Uri.UriSchemeHttps;
|
|
|
|
}
|
2020-08-11 06:53:43 +08:00
|
|
|
|
|
|
|
result = urlBuilder.Uri;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
catch (System.UriFormatException)
|
|
|
|
{
|
|
|
|
result = default;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|