summaryrefslogtreecommitdiffstats
path: root/src/main.lib/Extensions/StringExtensions.cs
blob: b9b9a84304183418056adae2735490c255158ffe (plain)
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
using PKISharp.WACS.Services;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace PKISharp.WACS.Extensions
{
    public static class StringExtensions
    {
        public static string? CleanUri(this Uri? uri)
        {
            if (uri == null)
            {
                return null;
            }
            var str = uri.ToString();
            if (!string.IsNullOrEmpty(uri.UserInfo))
            {
                str = str.Replace($"{uri.UserInfo}@", "");
            }
            str = str.Replace("https://", "").Replace("http://", "");
            return str.CleanPath();
        }

        public static string? CleanPath(this string? fileName)
        {
            if (fileName == null)
            {
                return null;
            }
            return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
        }

        public static string ReplaceNewLines(this string input) => Regex.Replace(input, @"\r\n?|\n", " ");

        public static string ConvertPunycode(this string input)
        {
            if (!string.IsNullOrEmpty(input) && (input.StartsWith("xn--") || input.Contains(".xn--")))
            {
                return new IdnMapping().GetUnicode(input);
            }
            else
            {
                return input;
            }
        }

        public static List<string>? ParseCsv(this string? input)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return null;
            }
            return input.
                Split(',').
                Where(x => !string.IsNullOrWhiteSpace(x)).
                Select(x => x.Trim().ToLower()).
                Distinct().
                ToList();
        }

        public static bool ValidFile(this string? input, ILogService logService)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                logService.Error("No path specified");
                return false;
            }
            try
            {
                var fi = new FileInfo(Environment.ExpandEnvironmentVariables(input));
                if (!fi.Exists)
                {
                    logService.Error("File {path} does not exist", fi.FullName);
                    return false;
                }
                return true;
            }
            catch
            {
                logService.Error("Unable to parse path {path}", input);
                return false;
            }
        }

        public static bool ValidPath(this string? input, ILogService logService)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                logService.Error("No path specified");
                return false;
            }
            try
            {
                var di = new DirectoryInfo(Environment.ExpandEnvironmentVariables(input));
                if (!di.Exists)
                {
                    logService.Error("Directory {path} does not exist", di.FullName);
                    return false;
                }
                return true;
            }
            catch
            {
                logService.Error("Unable to parse path {path}", input);
                return false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static string PatternToRegex(this string pattern)
        {
            pattern = pattern.Replace("\\\\", SlashEscape);
            pattern = pattern.Replace("\\,", CommaEscape);
            pattern = pattern.Replace("\\*", StarEscape);
            pattern = pattern.Replace("\\?", QuestionEscape);
            var parts = pattern.ParseCsv();
            return $"^({string.Join('|', parts.Select(x => Regex.Escape(x).PatternToRegexPart()))})$";
        }

        private const string SlashEscape = "~slash~";
        private const string CommaEscape = "~comma~";
        private const string StarEscape = "~star~";
        private const string QuestionEscape = "~question~";

        public static string EscapePattern(this string pattern)
        {
            return pattern.
               Replace("\\", "\\\\").
               Replace(",", "\\,").
               Replace("*", "\\*").
               Replace("?", "\\?");
        }

        private static string PatternToRegexPart(this string pattern)
        {
            return pattern.
                Replace("\\*", ".*").
                Replace("\\?", ".").
                Replace(SlashEscape, "\\\\").
                Replace(CommaEscape, ",").
                Replace(StarEscape, "\\*").
                Replace(QuestionEscape, "\\?");
        }


        public static string SHA1(this string original)
        {
            using var sha1 = new SHA1Managed();
            var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(original));
            return string.Concat(hash.Select(b => b.ToString("x2")));
        }
    }
}