-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathS3BlobProvider.cs
More file actions
266 lines (241 loc) · 10.9 KB
/
S3BlobProvider.cs
File metadata and controls
266 lines (241 loc) · 10.9 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
using Amazon.S3.Model;
using Amazon.S3;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Unity.GrantManager.Applications;
using Volo.Abp.BlobStoring;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Validation;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Routing;
namespace Unity.GrantManager.Attachments;
public partial class S3BlobProvider : BlobProviderBase, ITransientDependency
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IApplicationAttachmentRepository _applicationAttachmentRepository;
private readonly IAssessmentAttachmentRepository _assessmentAttachmentRepository;
private readonly AmazonS3Client _amazonS3Client;
public S3BlobProvider(IHttpContextAccessor httpContextAccessor, IApplicationAttachmentRepository attachmentRepository, IAssessmentAttachmentRepository assessmentAttachmentRepository, IConfiguration configuration)
{
_httpContextAccessor = httpContextAccessor;
_applicationAttachmentRepository = attachmentRepository;
_assessmentAttachmentRepository = assessmentAttachmentRepository;
AmazonS3Config s3config = new()
{
RegionEndpoint = null,
ServiceURL = configuration["S3:Endpoint"],
AllowAutoRedirect = true,
ForcePathStyle = true
};
AmazonS3Client s3Client = new(
configuration["S3:AccessKeyId"],
configuration["S3:SecretAccessKey"],
s3config
);
_amazonS3Client = s3Client;
}
public override async Task<bool> DeleteAsync(BlobProviderDeleteArgs args)
{
string s3ObjectKey = args.BlobName;
var httpContext = _httpContextAccessor.HttpContext ?? throw new InvalidOperationException("No active HttpContext.");
var form = httpContext.Request?.Form ?? throw new InvalidOperationException("No form data in the current request.");
string attachmentType = form.TryGetValue("AttachmentType", out var typeValue) ? typeValue.ToString() : string.Empty;
string attachmentTypeId = form.TryGetValue("AttachmentTypeId", out var idValue) ? idValue.ToString() : string.Empty;
var config = args.Configuration.GetS3BlobProviderConfiguration();
var deleteObjectRequest = new DeleteObjectRequest
{
BucketName = config.Bucket,
Key = EscapeKeyFileName(s3ObjectKey)
};
await _amazonS3Client.DeleteObjectAsync(deleteObjectRequest);
if (attachmentType == "Application")
{
if (attachmentTypeId.IsNullOrEmpty())
{
throw new AbpValidationException("Missing ApplicationId");
}
IQueryable<ApplicationAttachment> queryableAttachment = _applicationAttachmentRepository.GetQueryableAsync().Result;
ApplicationAttachment? attachment = queryableAttachment.FirstOrDefault(a => a.S3ObjectKey.Equals(s3ObjectKey) && a.ApplicationId.Equals(new Guid(attachmentTypeId.ToString())));
if (attachment != null)
{
await _applicationAttachmentRepository.DeleteAsync(attachment);
}
}
else if (attachmentType == "Assessment")
{
if (attachmentTypeId.IsNullOrEmpty())
{
throw new AbpValidationException("Missing AssessmentId");
}
IQueryable<AssessmentAttachment> queryableAttachment = _assessmentAttachmentRepository.GetQueryableAsync().Result;
AssessmentAttachment? attachment = queryableAttachment.FirstOrDefault(a => a.S3ObjectKey.Equals(s3ObjectKey) && a.AssessmentId.Equals(new Guid(attachmentTypeId.ToString())));
if (attachment != null)
{
await _assessmentAttachmentRepository.DeleteAsync(attachment);
}
}
else
{
throw new AbpValidationException("Wrong AttachmentType:"+attachmentType);
}
return await Task.FromResult(true);
}
private static string EscapeKeyFileName(string s3ObjectKey)
{
Regex regex= S3KeysRegex();
string[] keys = regex.Split(s3ObjectKey);
string escapedName = Uri.EscapeDataString(keys[^1]);
keys[^1] = escapedName;
return string.Join("", keys);
}
[GeneratedRegex("(/)")]
private static partial Regex S3KeysRegex();
public override Task<bool> ExistsAsync(BlobProviderExistsArgs args)
{
throw new NotImplementedException();
}
public override async Task<Stream?> GetOrNullAsync(BlobProviderGetArgs args)
{
var config = args.Configuration.GetS3BlobProviderConfiguration();
var getObjectRequest = new GetObjectRequest
{
BucketName = config.Bucket,
Key = EscapeKeyFileName(args.BlobName)
};
using GetObjectResponse response = await _amazonS3Client.GetObjectAsync(getObjectRequest);
MemoryStream memoryStream = new();
using Stream responseStream = response.ResponseStream;
await responseStream.CopyToAsync(memoryStream);
return memoryStream;
}
private static string GetMimeType(string fileName)
{
var provider = new FileExtensionContentTypeProvider();
if (!provider.TryGetContentType(fileName, out var contentType))
{
contentType = "application/octet-stream";
}
return contentType;
}
public override async Task SaveAsync(BlobProviderSaveArgs args)
{
var httpContext = _httpContextAccessor.HttpContext ?? throw new InvalidOperationException("No active HttpContext.");
var queryParams = httpContext.Request?.Query ?? throw new InvalidOperationException("No query parameters in the current request.");
var routeData = _httpContextAccessor.HttpContext.GetRouteData();
var assessmentId = routeData.Values["assessmentId"];
if (assessmentId != null)
{
queryParams.TryGetValue("userId", out StringValues currentUserId);
queryParams.TryGetValue("userName", out StringValues currentUserName);
#pragma warning disable CS8604 // Possible null reference argument.
await UploadAssessmentAttachment(args, assessmentId.ToString(), currentUserId.ToString());
#pragma warning restore CS8604 // Possible null reference argument.
}
else
{
var applicationId = routeData.Values["applicationId"];
if(applicationId != null)
{
queryParams.TryGetValue("userId", out StringValues currentUserId);
queryParams.TryGetValue("userName", out StringValues currentUserName);
#pragma warning disable CS8604 // Possible null reference argument.
await UploadApplicationAttachment(args, applicationId.ToString(), currentUserId.ToString());
#pragma warning restore CS8604 // Possible null reference argument.
}
else
{
throw new AbpValidationException("Missing parameter: applicationId/assessmentId");
}
}
}
private async Task UploadAssessmentAttachment(BlobProviderSaveArgs args, string assessmentId, string currentUserId)
{
var config = args.Configuration.GetS3BlobProviderConfiguration();
var bucket = config.Bucket;
var folder = args.Configuration.GetS3BlobProviderConfiguration().AssessmentS3Folder;
if (!folder.EndsWith('/'))
{
folder += "/";
}
folder += assessmentId;
var key = folder + "/" + args.BlobName;
var escapedKey = folder + "/" + Uri.EscapeDataString(args.BlobName);
var mimeType = GetMimeType(args.BlobName);
await UploadToS3(args, bucket, escapedKey, mimeType);
IQueryable<AssessmentAttachment> queryableAttachment = _assessmentAttachmentRepository.GetQueryableAsync().Result;
AssessmentAttachment? attachment = queryableAttachment.FirstOrDefault(a => a.S3ObjectKey.Equals(key) && a.AssessmentId.Equals(new Guid(assessmentId)));
if (attachment == null)
{
await _assessmentAttachmentRepository.InsertAsync(
new AssessmentAttachment
{
AssessmentId = new Guid(assessmentId),
S3ObjectKey = key,
UserId = new Guid(currentUserId),
FileName = args.BlobName,
Time = DateTime.UtcNow,
});
}
else
{
attachment.UserId = new Guid(currentUserId);
attachment.FileName = args.BlobName;
attachment.Time = DateTime.UtcNow;
await _assessmentAttachmentRepository.UpdateAsync(attachment);
}
}
private async Task UploadApplicationAttachment(BlobProviderSaveArgs args, string applicationId, string currentUserId)
{
var config = args.Configuration.GetS3BlobProviderConfiguration();
var bucket = config.Bucket;
var folder = args.Configuration.GetS3BlobProviderConfiguration().ApplicationS3Folder;
if (!folder.EndsWith('/'))
{
folder += "/";
}
folder += applicationId;
var key = folder + "/" + args.BlobName;
var escapedKey = folder + "/" + Uri.EscapeDataString(args.BlobName);
var mimeType = GetMimeType(args.BlobName);
await UploadToS3(args,bucket, escapedKey, mimeType);
IQueryable<ApplicationAttachment> queryableAttachment = _applicationAttachmentRepository.GetQueryableAsync().Result;
ApplicationAttachment? attachment = queryableAttachment.FirstOrDefault(a => a.S3ObjectKey.Equals(key) && a.ApplicationId.Equals(new Guid(applicationId)));
if (attachment == null)
{
await _applicationAttachmentRepository.InsertAsync(
new ApplicationAttachment
{
ApplicationId = new Guid(applicationId),
S3ObjectKey = key,
UserId = new Guid(currentUserId),
FileName = args.BlobName,
Time = DateTime.UtcNow,
});
}
else
{
attachment.UserId = new Guid(currentUserId);
attachment.FileName = args.BlobName;
attachment.Time = DateTime.UtcNow;
await _applicationAttachmentRepository.UpdateAsync(attachment);
}
}
public async Task UploadToS3(BlobProviderSaveArgs args, string bucket, string key, string mimeType)
{
PutObjectRequest putRequest = new()
{
BucketName = bucket,
Key = key,
ContentType = mimeType,
InputStream = args.BlobStream,
};
await _amazonS3Client.PutObjectAsync(putRequest);
}
}