-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathFilesController.cs
More file actions
205 lines (171 loc) · 8.08 KB
/
FilesController.cs
File metadata and controls
205 lines (171 loc) · 8.08 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
197
198
199
200
201
202
203
204
205
using Azure.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using Signum.Utilities.Reflection;
using System.Collections.Concurrent;
using System.IO;
namespace Signum.Files;
public class FilesController : ControllerBase
{
[HttpGet("api/files/downloadFile/{fileId}")]
public FileStreamResult DownloadFile(string fileId)
{
var file = Database.Retrieve<FileEntity>(PrimaryKey.Parse(fileId, typeof(FileEntity)));
return MimeMapping.GetFileStreamResult(new MemoryStream(file.BinaryFile), file.FileName);
}
[HttpGet("api/files/downloadFilePath/{filePathId}")]
public FileStreamResult DownloadFilePath(string filePathId)
{
var filePath = Database.Retrieve<FilePathEntity>(PrimaryKey.Parse(filePathId, typeof(FilePathEntity)));
Response.GetTypedHeaders().CacheControl = FilesCacheControl(filePath);
return MimeMapping.GetFileStreamResult(filePath.OpenRead(), filePath.FileName);
}
[HttpGet("api/files/downloadEmbeddedFilePath/{rootType}/{id}")]
public FileStreamResult? DownloadFilePathEmbedded(string rootType, string id, string route, string? rowId)
{
var type = TypeLogic.GetType(rootType);
var propertyRoute = PropertyRoute.Parse(type, route);
var primaryKey = PrimaryKey.Parse(id, type);
var makeQuery = queryBuilderCache.GetOrAdd(propertyRoute, pr =>
{
if (propertyRoute.Type != typeof(FilePathEmbedded))
throw new InvalidOperationException($"Route {route} doesn't point to a FilePathEmbedded");
var mlistRoute = propertyRoute.GetMListItemsRoute()!;
if (mlistRoute == null)
return giGetSimpleQuery.GetInvoker(type)(propertyRoute);
else
return giGetMListQuery.GetInvoker(type, mlistRoute.Type)(propertyRoute, mlistRoute);
});
var fpe = makeQuery(primaryKey, rowId);
if (fpe == null)
return null;
Response.GetTypedHeaders().CacheControl = FilesCacheControl(fpe);
return MimeMapping.GetFileStreamResult(fpe.OpenRead(), fpe.FileName);
}
private static CacheControlHeaderValue FilesCacheControl(IFilePath fpe) => new()
{
Private = true,
MaxAge = TimeSpan.FromSeconds(FilePathLogic.MaxAge(fpe))
};
static ConcurrentDictionary<PropertyRoute, Func<PrimaryKey, string?, FilePathEmbedded?>> queryBuilderCache =
new ConcurrentDictionary<PropertyRoute, Func<PrimaryKey, string?, FilePathEmbedded?>>();
static GenericInvoker<Func<PropertyRoute, Func<PrimaryKey, string?, FilePathEmbedded?>>> giGetSimpleQuery =
new((propertyRoute) => GetSimpleQuery<Entity>(propertyRoute));
static Func<PrimaryKey, string?, FilePathEmbedded?> GetSimpleQuery<T>(PropertyRoute propertyRoute)
where T : Entity
{
var selector = propertyRoute.GetLambdaExpression<T, FilePathEmbedded?>(false);
return (pk, rowId) =>
{
return Database.Query<T>()
.Where(a => a.Id == pk)
.Select(selector)
.SingleEx();
};
}
static GenericInvoker<Func<PropertyRoute, PropertyRoute, Func<PrimaryKey, string?, FilePathEmbedded?>>> giGetMListQuery =
new((route, mlistRoute) => GetMListQuery<Entity, EmbeddedEntity>(route, mlistRoute));
static Func<PrimaryKey, string?, FilePathEmbedded?> GetMListQuery<T, M>(PropertyRoute route, PropertyRoute mlistRoute)
where T : Entity
{
var mlistExpression = mlistRoute.Parent!.GetLambdaExpression<T, MList<M>>(false);
var elementExpression = route.GetLambdaExpression<M, FilePathEmbedded>(false, mlistRoute);
var mlistPkType = Schema.Current.TableMList(mlistExpression).PrimaryKey.Type;
return (pk, rowId) => {
var rowIdPk = new PrimaryKey((IComparable)ReflectionTools.ChangeType(rowId, mlistPkType)!);
return Database.MListQuery(mlistExpression)
.Where(mle => mle.Parent.Id == pk && mle.RowId == rowIdPk)
.Select(mle => elementExpression.Evaluate(mle.Element))
.SingleEx();
};
}
[HttpPost("api/files/startUpload")]
public async Task<StartUploadResponse> StartUpload([FromBody] StartUploadRequest request, CancellationToken token)
{
var fileType = SymbolLogic<FileTypeSymbol>.ToSymbol(request.FileTypeKey);
var algorithm = FileTypeLogic.GetAlgorithm(fileType);
IFilePath fpe = CreateEmptyFile(request.Type, fileType, request.FileName, null);
var uploadId = await algorithm.StartUpload(fpe, token);
return new StartUploadResponse { Suffix = fpe.Suffix, UploadId = uploadId };
}
public class StartUploadRequest
{
public string FileTypeKey { get; set; }
public string FileName { get; set; }
public string Type { get; set; }
}
public class StartUploadResponse
{
public string Suffix { get; set; }
public string? UploadId { get; set; }
}
[HttpPost("api/files/uploadChunk")]
public async Task<ChunkInfo> UploadChunk(
[FromQuery] string fileName,
[FromQuery] string fileTypeKey,
[FromQuery] string suffix,
[FromQuery] string type,
[FromQuery] int chunkIndex,
[FromQuery] string? uploadId,
CancellationToken token)
{
var fileType = SymbolLogic<FileTypeSymbol>.ToSymbol(fileTypeKey);
var algorithm = FileTypeLogic.GetAlgorithm(fileType);
IFilePath fpe = CreateEmptyFile(type, fileType, fileName, suffix);
using MemoryStream ms = new MemoryStream();
await Request.Body.CopyToAsync(ms, token);
ms.Position = 0;
var chunkInfo = await algorithm.UploadChunk(fpe, chunkIndex, ms, uploadId, token);
return chunkInfo;
}
static IFilePath CreateEmptyFile(string type, FileTypeSymbol fileType, string fileName, string? suffix)
{
if (type == typeof(FilePathEmbedded).Name)
return new FilePathEmbedded(fileType, fileName, null!) { Suffix = suffix! };
if (type == TypeLogic.TryGetCleanName(typeof(FilePathEntity)))
return new FilePathEntity(fileType, fileName, null!) { Suffix = suffix! };
throw new UnexpectedValueException(type);
}
[HttpPost("api/files/finishUpload")]
public async Task<FinishUploadResponse> FinishUpload([FromBody] FinishUploadRequest request, CancellationToken token)
{
var fileType = SymbolLogic<FileTypeSymbol>.ToSymbol(request.FileTypeKey);
var algorithm = FileTypeLogic.GetAlgorithm(fileType);
IFilePath fpe = CreateEmptyFile(request.Type, fileType, request.FileName, request.Suffix);
await algorithm.FinishUpload(fpe, request.Chunks, request.UploadId, token);
return new FinishUploadResponse { Hash = fpe.Hash!, FileLength = fpe.FileLength, FullWebPath = fpe.FullWebPath() };
}
public class FinishUploadRequest
{
public string FileTypeKey { get; set; }
public string FileName { get; set; }
public string Suffix { get; set; }
public string Type { get; set; }
public List<ChunkInfo> Chunks { get; set; }
public string? UploadId { get; set; }
}
public class FinishUploadResponse
{
public long FileLength { get; set; }
public string Hash { get; set; }
public string? FullWebPath { get; internal set; }
}
[HttpPost("api/files/abortUpload")]
public async Task<IActionResult> AbortUpload([FromBody] AbortUploadRequest request, CancellationToken token)
{
var fileType = SymbolLogic<FileTypeSymbol>.ToSymbol(request.FileTypeKey);
var algorithm = FileTypeLogic.GetAlgorithm(fileType);
IFilePath fpe = CreateEmptyFile(request.Type, fileType, request.FileName, request.Suffix);
await algorithm.AbortUpload(fpe, request.UploadId, token);
return Ok();
}
public class AbortUploadRequest
{
public string FileTypeKey { get; set; }
public string FileName { get; set; }
public string Suffix { get; set; }
public string Type { get; set; }
public string? UploadId { get; set; }
}
}