-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathMimeTypeFunctions.ttinclude
More file actions
196 lines (165 loc) · 6.77 KB
/
MimeTypeFunctions.ttinclude
File metadata and controls
196 lines (165 loc) · 6.77 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
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Net" #>
<#@ import namespace="Newtonsoft.Json" #>
<#@ assembly name="$(PkgNewtonsoft_Json)\lib\net45\Newtonsoft.Json.dll" #>
<#@ assembly name="System.Core" #>
<#+
private class MimeType
{
public MimeType()
{
Extensions = new List<string>();
}
public string Source { get; set; }
public List<string> Extensions { get; }
public bool Compressible { get; set; }
public string Charset { get; set; }
}
private static IList<(string Extension, string Type)> GetMediaTypeList()
{
using var client = new WebClient();
var json = client.DownloadString(new Uri("https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json"));
var mimeTypes = JsonConvert.DeserializeObject<Dictionary<string, MimeType>>(json);
return GetMediaTypes(mimeTypes).ToList();
}
private static IEnumerable<(string Extension, string Type)> GetMediaTypes(IEnumerable<KeyValuePair<string, MimeType>> mimeTypes)
=> mimeTypes.Where(x => x.Value.Extensions.Any())
.SelectMany(x => x.Value.Extensions.Select(e => (e, x.Key)))
.Where(x => x.Item1.Length <= 8 && x.Item1.All(char.IsLetterOrDigit))
.GroupBy(x => x.Item1)
.Select(x => x.First())
.OrderBy(x => x.Item1, StringComparer.InvariantCulture);
public void GenerateClass(bool includeAttributes)
{
#>
// <auto-generated />
#nullable enable
#pragma warning disable
namespace $rootnamespace$
{
using global::System;
using global::System.Linq;
using global::System.Collections.Generic;
using global::System.Diagnostics;
using global::System.Diagnostics.CodeAnalysis;
using global::System.Runtime.CompilerServices;
/// <summary>
/// Provides utilities for mapping file names and extensions to MIME-types.
/// </summary>
[CompilerGenerated]
[DebuggerNonUserCode]
public static class MimeTypes
{
private const string DefaultFallbackMimeType = "application/octet-stream";
private static string s_fallbackMimeType;
/// <summary>
/// The fallback MIME-type. Defaults to <c>application/octet-stream</c>.
/// </summary>
[AllowNull]
public static string FallbackMimeType
{
get => s_fallbackMimeType;
set => s_fallbackMimeType = value ?? DefaultFallbackMimeType;
}
private static readonly Dictionary<string, string> s_typeMap;
static MimeTypes()
{
s_fallbackMimeType = DefaultFallbackMimeType;
s_typeMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
<#+ foreach (var mediaType in GetMediaTypeList()) { #>
{ "<#= mediaType.Item1 #>", "<#= mediaType.Item2 #>" },
<#+ } #>
};
}
/// <summary>
/// Attempts to fetch all available file extensions for a MIME-type.
/// </summary>
/// <param name="mimeType">The name of the MIME-type</param>
/// <returns>All available extensions for the given MIME-type</returns>
public static IEnumerable<string> GetMimeTypeExtensions(string mimeType)
{
if (mimeType is null)
{
throw new ArgumentNullException(nameof(mimeType));
}
return s_typeMap
.Where(keyPair => string.Equals(keyPair.Value, mimeType, StringComparison.OrdinalIgnoreCase))
.Select(keyPair => keyPair.Key);
}
/// <summary>
/// Attempts to validate MIME-type.
/// </summary>
/// <param name="mimeType">The name of the MIME-type</param>
/// <returns><c>true</c> if a MIME-type was found, <c>false</c> otherwise</returns>
public static bool IsValidMimeType(string mimeType)
{
if (mimeType is null)
{
throw new ArgumentNullException(nameof(mimeType));
}
return s_typeMap
.Any(keyPair => string.Equals(keyPair.Value, mimeType, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Tries to get the MIME-type for the given file name.
/// </summary>
/// <param name="fileName">The name of the file.</param>
/// <param name="mimeType">The MIME-type for the given file name.</param>
/// <returns><c>true</c> if a MIME-type was found, <c>false</c> otherwise.</returns>
public static bool TryGetMimeType(string? fileName, [NotNullWhen(true)] out string? mimeType)
{
if (fileName is null)
{
mimeType = null;
return false;
}
var dotIndex = fileName.LastIndexOf('.');
if (dotIndex != -1 && fileName.Length > dotIndex + 1)
{
return s_typeMap.TryGetValue(fileName.Substring(dotIndex + 1), out mimeType);
}
mimeType = null;
return false;
}
/// <summary>
/// Gets the MIME-type for the given file name,
/// or <see cref="FallbackMimeType"/> if a mapping doesn't exist.
/// </summary>
/// <param name="fileName">The name of the file.</param>
/// <returns>The MIME-type for the given file name.</returns>
public static string GetMimeType(string fileName)
{
if (fileName is null)
{
throw new ArgumentNullException(nameof(fileName));
}
return TryGetMimeType(fileName, out var result) ? result : FallbackMimeType;
}
}
}
<#+ if (includeAttributes) { #>
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>Specifies that null is allowed as an input even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property)]
internal sealed class AllowNullAttribute : Attribute { }
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class NotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
}
<#+ } #>
#pragma warning enable
<#+
}
#>