Files
e1lama-simple/NaiveHttpServer/MimeTypes.tt
2023-07-27 01:47:59 +04:00

96 lines
3.2 KiB
Plaintext

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Net" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<# var mediaTypes = GetMediaTypeList(); #>
// <auto-generated />
namespace <#=System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint").ToString()#>
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
/// <summary>
/// Provides utilities for mapping file names and extensions to MIME-types.
/// </summary>
[CompilerGenerated]
[DebuggerNonUserCode]
public static class MimeTypes
{
/// <summary>
/// The fallback MIME-type. Defaults to <c>application/octet-stream</c>.
/// </summary>
public static string FallbackMimeType { get; set; }
private static readonly Dictionary<string, string> TypeMap;
static MimeTypes()
{
FallbackMimeType = "application/octet-stream";
TypeMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
<# foreach (var mediaType in mediaTypes) { #>
{ "<#= mediaType.Item1 #>", "<#= mediaType.Item2 #>" },
<# } #>
};
}
/// <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)
{
var dotIndex = fileName.LastIndexOf('.');
return dotIndex != -1 &&
fileName.Length > dotIndex + 1 &&
TypeMap.TryGetValue(fileName.Substring(dotIndex + 1), out var result)
? result
: FallbackMimeType;
}
}
}
<#+
private static IList<Tuple<string, string>> GetMediaTypeList()
{
using (var client = new WebClient())
{
var list = client.DownloadString(new Uri("http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types"));
var lines = SplitString(list, '\r', '\n');
return GetMediaTypes(lines).ToList();
}
}
private static IEnumerable<Tuple<string, string>> GetMediaTypes(IEnumerable<string> lines)
{
return lines.Where(x => !x.StartsWith("#"))
.Select(line => SplitString(line, '\t', ' '))
.SelectMany(CreateMediaTypes)
.GroupBy(x => x.Item1)
.Where(x => x.Count() == 1)
.Select(x => x.Single())
.OrderBy(x => x.Item1);
}
private static string[] SplitString(string line, params char[] separator)
{
return line.Split(separator, StringSplitOptions.RemoveEmptyEntries);
}
private static IEnumerable<Tuple<string, string>> CreateMediaTypes(string[] parts)
{
return parts.Skip(1).Select(extension => Tuple.Create(extension, parts.First()));
}
#>