-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFilesService.cs
209 lines (174 loc) · 6.95 KB
/
FilesService.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using ServiceStack;
using ServiceStack.IO;
using ServiceStack.VirtualPath;
namespace RestFiles
{
/// <summary>
/// Define your ServiceStack web service request (i.e. the Request DTO).
/// </summary>
[Route("/restfiles/files")]
[Route("/restfiles/files/{Path*}")]
public class Files
{
public string Path { get; set; }
public string TextContents { get; set; }
public bool ForDownload { get; set; }
}
public class File
{
public string Name { get; set; }
public string Extension { get; set; }
public long FileSizeBytes { get; set; }
public DateTime ModifiedDate { get; set; }
public bool IsTextFile { get; set; }
}
public class FileResult
{
public string Name { get; set; }
public string Extension { get; set; }
public long FileSizeBytes { get; set; }
public DateTime ModifiedDate { get; set; }
public bool IsTextFile { get; set; }
public string Contents { get; set; }
}
public class FilesResponse : IHasResponseStatus
{
public FolderResult Directory { get; set; }
public FileResult File { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class Folder
{
public string Name { get; set; }
public DateTime ModifiedDate { get; set; }
public int FileCount { get; set; }
}
public class FolderResult
{
public FolderResult()
{
Folders = new List<Folder>();
Files = new List<File>();
}
public List<Folder> Folders { get; set; }
public List<File> Files { get; set; }
}
/// <summary>
/// Define your ServiceStack web service request (i.e. Request DTO).
/// </summary>
public class FilesService : Service
{
private static readonly string RootDirectory = "restfiles/files";
static readonly HashSet<string> TextFileExtensions = new HashSet<string>("txt,sln,proj,cs,config,asax,css,htm,html,xml,js,md".Split(','));
static readonly HashSet<string> ExcludeDirectories = new HashSet<string>("bin,Properties".Split(','));
public object Get(Files request)
{
var targetPath = GetAndValidateExistingPath(request);
var isDirectory = VirtualFiles.IsDirectory(targetPath);
if (!isDirectory && request.ForDownload)
return new HttpResult(VirtualFiles.GetFile(targetPath), asAttachment: true);
var response = isDirectory
? new FilesResponse { Directory = GetFolderResult(targetPath) }
: new FilesResponse { File = GetFileResult(targetPath) };
return response;
}
public object Post(Files request)
{
var targetDir = GetPath(request);
if (VirtualFiles.IsFile(targetDir))
throw new NotSupportedException(
"POST only supports uploading new files. Use PUT to replace contents of an existing file");
foreach (var uploadedFile in base.Request.Files)
{
var newFilePath = targetDir.CombineWith(uploadedFile.FileName);
VirtualFiles.WriteFile(newFilePath, uploadedFile.InputStream);
}
return new FilesResponse();
}
public void Put(Files request)
{
var targetFile = VirtualFiles.GetFile(GetAndValidateExistingPath(request));
if (!TextFileExtensions.Contains(targetFile.Extension))
throw new NotSupportedException("PUT Can only update text files, not: " + targetFile.Extension);
if (request.TextContents == null)
throw new ArgumentNullException("TextContents");
VirtualFiles.WriteFile(targetFile.VirtualPath, request.TextContents);
}
public void Delete(Files request)
{
var targetFile = GetAndValidateExistingPath(request);
VirtualFiles.DeleteFile(targetFile);
}
private FolderResult GetFolderResult(string targetPath)
{
var result = new FolderResult();
var dir = VirtualFiles.GetDirectory(targetPath);
foreach (var subDir in dir.Directories)
{
if (ExcludeDirectories.Contains(subDir.Name)) continue;
result.Folders.Add(new Folder
{
Name = subDir.Name,
ModifiedDate = subDir.LastModified,
FileCount = subDir.GetFiles().Count(),
});
}
foreach (var fileInfo in dir.GetFiles())
{
result.Files.Add(new File
{
Name = fileInfo.Name,
Extension = fileInfo.Extension,
FileSizeBytes = fileInfo.Length,
ModifiedDate = fileInfo.LastModified,
IsTextFile = TextFileExtensions.Contains(fileInfo.Extension),
});
}
return result;
}
private string GetPath(Files request)
{
return RootDirectory.CombineWith(GetSafePath(request.Path));
}
private string GetAndValidateExistingPath(Files request)
{
var targetPath = GetPath(request);
if (!VirtualFiles.IsFile(targetPath) && !VirtualFiles.IsDirectory(targetPath))
throw new HttpError(HttpStatusCode.NotFound, new FileNotFoundException("Could not find: " + request.Path));
return targetPath;
}
private FileResult GetFileResult(string filePath)
{
var file = VirtualFiles.GetFile(filePath);
var isTextFile = TextFileExtensions.Contains(file.Extension);
return new FileResult
{
Name = file.Name,
Extension = file.Extension,
FileSizeBytes = file.Length,
IsTextFile = isTextFile,
Contents = isTextFile ? VirtualFiles.GetFile(file.VirtualPath).ReadAllText() : null,
ModifiedDate = file.LastModified,
};
}
public static string GetSafePath(string filePath)
{
if (string.IsNullOrEmpty(filePath)) return string.Empty;
//Strip invalid chars
foreach (var invalidChar in Path.GetInvalidPathChars())
{
filePath = filePath.Replace(invalidChar.ToString(), String.Empty);
}
return filePath
.TrimStart('.', '/', '\\') //Remove illegal chars at the start
.Replace('\\', '/') //Switch all to use the same seperator
.Replace("../", string.Empty) //Remove access to top-level directories anywhere else
.Replace('/', Path.DirectorySeparatorChar); //Switch all to use the OS seperator
}
}
}