-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
HtmlDirectoryFormatter.cs
215 lines (194 loc) · 7.99 KB
/
HtmlDirectoryFormatter.cs
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;
namespace Microsoft.AspNetCore.StaticFiles
{
/// <summary>
/// Generates an HTML view for a directory.
/// </summary>
public class HtmlDirectoryFormatter : IDirectoryFormatter
{
private const string TextHtmlUtf8 = "text/html; charset=utf-8";
private HtmlEncoder _htmlEncoder;
/// <summary>
/// Constructs the <see cref="HtmlDirectoryFormatter"/>.
/// </summary>
/// <param name="encoder">The character encoding representation to use.</param>
public HtmlDirectoryFormatter(HtmlEncoder encoder)
{
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
_htmlEncoder = encoder;
}
/// <summary>
/// Generates an HTML view for a directory.
/// </summary>
public virtual Task GenerateContentAsync(HttpContext context, IEnumerable<IFileInfo> contents)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (contents == null)
{
throw new ArgumentNullException(nameof(contents));
}
context.Response.ContentType = TextHtmlUtf8;
if (HttpMethods.IsHead(context.Request.Method))
{
// HEAD, no response body
return Task.CompletedTask;
}
PathString requestPath = context.Request.PathBase + context.Request.Path;
var builder = new StringBuilder();
builder.AppendFormat(
@"<!DOCTYPE html>
<html lang=""{0}"">", CultureInfo.CurrentUICulture.TwoLetterISOLanguageName);
builder.AppendFormat(@"
<head>
<title>{0} {1}</title>", HtmlEncode(Resources.HtmlDir_IndexOf), HtmlEncode(requestPath.Value));
builder.Append(@"
<style>
body {
font-family: ""Segoe UI"", ""Segoe WP"", ""Helvetica Neue"", 'RobotoRegular', sans-serif;
font-size: 14px;}
header h1 {
font-family: ""Segoe UI Light"", ""Helvetica Neue"", 'RobotoLight', ""Segoe UI"", ""Segoe WP"", sans-serif;
font-size: 28px;
font-weight: 100;
margin-top: 5px;
margin-bottom: 0px;}
#index {
border-collapse: separate;
border-spacing: 0;
margin: 0 0 20px; }
#index th {
vertical-align: bottom;
padding: 10px 5px 5px 5px;
font-weight: 400;
color: #a0a0a0;
text-align: center; }
#index td { padding: 3px 10px; }
#index th, #index td {
border-right: 1px #ddd solid;
border-bottom: 1px #ddd solid;
border-left: 1px transparent solid;
border-top: 1px transparent solid;
box-sizing: border-box; }
#index th:last-child, #index td:last-child {
border-right: 1px transparent solid; }
#index td.length, td.modified { text-align:right; }
a { color:#1ba1e2;text-decoration:none; }
a:hover { color:#13709e;text-decoration:underline; }
</style>
</head>
<body>
<section id=""main"">");
builder.AppendFormat(@"
<header><h1>{0} <a href=""/"">/</a>", HtmlEncode(Resources.HtmlDir_IndexOf));
string cumulativePath = "/";
foreach (var segment in requestPath.Value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries))
{
cumulativePath = cumulativePath + segment + "/";
builder.AppendFormat(@"<a href=""{0}"">{1}/</a>",
HtmlEncode(cumulativePath), HtmlEncode(segment));
}
builder.AppendFormat(CultureInfo.CurrentUICulture,
@"</h1></header>
<table id=""index"" summary=""{0}"">
<thead>
<tr><th abbr=""{1}"">{1}</th><th abbr=""{2}"">{2}</th><th abbr=""{3}"">{4}</th></tr>
</thead>
<tbody>",
HtmlEncode(Resources.HtmlDir_TableSummary),
HtmlEncode(Resources.HtmlDir_Name),
HtmlEncode(Resources.HtmlDir_Size),
HtmlEncode(Resources.HtmlDir_Modified),
HtmlEncode(Resources.HtmlDir_LastModified));
foreach (var subdir in contents.Where(info => info.IsDirectory))
{
// Collect directory metadata in a try...catch in case the file is deleted while we're getting the data.
// The metadata is retrieved prior to calling AppendFormat so if it throws, we won't have written a row
// to the table.
try
{
builder.AppendFormat(@"
<tr class=""directory"">
<td class=""name""><a href=""./{0}/"">{0}/</a></td>
<td></td>
<td class=""modified"">{1}</td>
</tr>",
HtmlEncode(subdir.Name),
HtmlEncode(subdir.LastModified.ToString(CultureInfo.CurrentCulture)));
}
catch (DirectoryNotFoundException)
{
// The physical DirectoryInfo class doesn't appear to throw for either
// of Name or LastWriteTimeUtc (which backs LastModified in the physical provider)
// if the directory doesn't exist. However, we don't know what other providers might do.
// Just skip this directory. It was deleted while we were enumerating.
}
catch (FileNotFoundException)
{
// The physical DirectoryInfo class doesn't appear to throw for either
// of Name or LastWriteTimeUtc (which backs LastModified in the physical provider)
// if the directory doesn't exist. However, we don't know what other providers might do.
// Just skip this directory. It was deleted while we were enumerating.
}
}
foreach (var file in contents.Where(info => !info.IsDirectory))
{
// Collect file metadata in a try...catch in case the file is deleted while we're getting the data.
// The metadata is retrieved prior to calling AppendFormat so if it throws, we won't have written a row
// to the table.
try
{
builder.AppendFormat(@"
<tr class=""file"">
<td class=""name""><a href=""./{0}"">{0}</a></td>
<td class=""length"">{1}</td>
<td class=""modified"">{2}</td>
</tr>",
HtmlEncode(file.Name),
HtmlEncode(file.Length.ToString("n0", CultureInfo.CurrentCulture)),
HtmlEncode(file.LastModified.ToString(CultureInfo.CurrentCulture)));
}
catch (DirectoryNotFoundException)
{
// There doesn't appear to be a case where DirectoryNotFound is thrown in the physical provider,
// but we don't know what other providers might do.
// Just skip this file. It was deleted while we were enumerating.
}
catch (FileNotFoundException)
{
// Just skip this file. It was deleted while we were enumerating.
}
}
builder.Append(@"
</tbody>
</table>
</section>
</body>
</html>");
string data = builder.ToString();
byte[] bytes = Encoding.UTF8.GetBytes(data);
context.Response.ContentLength = bytes.Length;
return context.Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
private string HtmlEncode(string body)
{
return _htmlEncoder.Encode(body);
}
}
}