-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFunctionContainer.cs
341 lines (295 loc) · 12.7 KB
/
FunctionContainer.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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using Azure.Storage.Blobs;
using Azure.Storage.Queues;
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Rest;
using SeeSayMicroservices.Utils.Extensions;
using SeeSayMicroservices.Configuration;
using SeeSayMicroservices.Models.Dto;
using SeeSayMicroservices.Services.Abstractions;
namespace SeeSayMicroservices;
public class FunctionContainer
{
private readonly ComputerVisionClient computerVisionClient;
private readonly IDatabaseConnectionFactory connectionFactory;
private readonly ILogger<FunctionContainer> logger;
private readonly IMapper mapper;
private readonly string ngrokUrl;
public FunctionContainer(ComputerVisionClient computerVisionClient,
IDatabaseConnectionFactory connectionFactory,
ILogger<FunctionContainer> logger, IMapper mapper, IOptions<Ngrok> ngrokOptions)
{
this.computerVisionClient = computerVisionClient;
this.connectionFactory = connectionFactory;
this.logger = logger;
this.mapper = mapper;
ngrokUrl = ngrokOptions.Value.TunnelUrl;
}
[FunctionName("negotiate")]
public static SignalRConnectionInfo GetSignalRInfo(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")]
HttpRequest req,
[SignalRConnectionInfo(HubName = "chat")]
SignalRConnectionInfo connectionInfo)
{
return connectionInfo;
}
[FunctionName("SendMessage")]
public static Task SendMessage(
[SignalRTrigger("chat", "messages", "SendMessage")]
InvocationContext invocationContext,
[SignalR(HubName = "chat")] IAsyncCollector<SignalRMessage> signalRMessages)
{
return signalRMessages.AddAsync(
new SignalRMessage
{
Target = "newMessage",
Arguments = invocationContext.Arguments
});
}
[FunctionName("broadcast")]
public static async Task Broadcast(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")]
object message,
[SignalR(HubName = "chat")] IAsyncCollector<SignalRMessage> signalRMessages)
{
await signalRMessages.AddAsync(
new SignalRMessage
{
Target = "newMessage",
Arguments = new[] { message }
});
}
[FunctionName("CheckImageForInappropriateContent")]
public async Task<IActionResult> CheckImageForInappropriateContent(
[HttpTrigger(AuthorizationLevel.Anonymous, "post",
Route = "check")]
HttpRequest request,
[Queue("description-tickets")] QueueClient descriptionTicketsQueue,
[Blob("images/{rand-guid}.jpg")] BlobClient blobClient,
[SignalR(HubName = "chat")] IAsyncCollector<SignalRMessage> signalRMessages)
{
var ticket = mapper.Map<IFormCollection, TicketDto>(request.Form);
if (ticket is null)
throw new InvalidOperationException("Invalid request body");
// Read the image from the form data
var imageFile = request.Form.Files["image"];
if (imageFile is null)
return new BadRequestResult();
await using var imageStream = new MemoryStream();
await imageFile.CopyToAsync(imageStream);
imageStream.Position = 0;
await using var imageStreamClone = new MemoryStream();
await imageStream.CopyToAsync(imageStreamClone);
logger.LogInformation(
"{BaseLogMessage}: receive a request to check image for inappropriate content from user with ID {UserId}",
GetBaseLogMessage(nameof(CheckImageForInappropriateContent)), ticket.UserId);
await signalRMessages.AddAsync(
new SignalRMessage
{
Target = "processing_start",
Arguments = new object[] { "Uploading image..." },
ConnectionId = ticket.SignalConnectionId
}
);
ImageAnalysis response = default!;
string? errorMessage = default;
try
{
imageStream.Position = 0;
response = await computerVisionClient.AnalyzeImageInStreamAsync(imageStream,
new List<VisualFeatureTypes?>
{
VisualFeatureTypes.Adult
});
imageStream.Close();
}
catch (ComputerVisionErrorResponseException exception)
{
errorMessage = exception.Body.Error.Message;
}
catch (Exception exception)
{
errorMessage = exception.Message;
}
if (!string.IsNullOrWhiteSpace(errorMessage))
{
logger.LogWarning(
"{BaseLogMessage}: image was sent to the checking for inappropriate content, but the received response was unsuccessful. Message: {ErrorMessage}",
GetBaseLogMessage(nameof(DescribeImage)), errorMessage);
await signalRMessages.AddAsync(
new SignalRMessage
{
Target = "error_external",
Arguments = new object[] { "Error while uploading image. Please try later." }
}
);
const string Query = "DELETE FROM Posts WHERE Id = @PostId";
using var connection = connectionFactory.CreateConnection();
await connection.ExecuteAsync(Query, new
{
ticket.PostId
});
return new InternalServerErrorResult();
}
if (response.Adult?.IsInappropriateContent() is true)
{
string query =
"UPDATE AspNetUsers SET LockoutEnabled = @NewLockoutEnabled WHERE Id = @UserId";
using var connection = connectionFactory.CreateConnection();
await connection.ExecuteAsync(query, new
{
NewLockoutEnabled = true,
ticket.UserId
});
query = "DELETE FROM Posts WHERE Id = @PostId";
await connection.ExecuteAsync(query, new
{
ticket.PostId
});
connection.Close();
logger.LogInformation(
"{BaseLogMessage}: user '{UserId}' has been banned for uploading an image with inappropriate content",
GetBaseLogMessage(nameof(CheckImageForInappropriateContent)), ticket.UserId);
logger.LogWarning(
"{BaseLogMessage}: image has been detected to contain inappropriate content. Removing an image from processing pipeline",
GetBaseLogMessage(nameof(CheckImageForInappropriateContent)));
await signalRMessages.AddAsync(
new SignalRMessage
{
Target = "error_ban",
Arguments = new object[] { "The image contains inappropriate content. You have been banned for violating the terms of service." },
ConnectionId = ticket.SignalConnectionId
});
return new BadRequestResult();
}
logger.LogInformation(
"{BaseLogMessage}: image was successfully checked for inappropriate content. Saving it",
nameof(CheckImageForInappropriateContent));
imageStreamClone.Position = 0;
await blobClient.UploadAsync(imageStreamClone);
logger.LogInformation(
"{BaseLogMessage}: image was successfully saved at URL '{ImageUrl}'. Saving it to database",
nameof(CheckImageForInappropriateContent), blobClient.Uri);
var imageUrl = blobClient.Uri.ToString();
await SaveImagePath(imageUrl, ticket.PostId);
ticket.ImageUrl = imageUrl;
if (ticket.ShouldAutoGenerateDescription)
{
logger.LogInformation(
"{BaseLogMessage}: image was successfully processed, sending it next to processing pipeline to descripting",
nameof(CheckImageForInappropriateContent));
await descriptionTicketsQueue.SendMessageAsync(JsonSerializer.Serialize(ticket));
}
else
{
logger.LogInformation(
"{BaseLogMessage}: image was successfully processed and its not requires generating description, processing finished",
nameof(CheckImageForInappropriateContent));
await signalRMessages.AddAsync(
new SignalRMessage
{
Target = "processing_finish",
Arguments = new object[] { "Image was successfully uploaded!" }
}
);
}
return new OkResult();
}
[FunctionName("DescribeImage")]
public async Task DescribeImage([QueueTrigger("description-tickets")] TicketDto ticket, [SignalR(HubName = "chat")] IAsyncCollector<SignalRMessage> signalRMessages)
{
ticket.ImageUrl = ticket.ImageUrl.ToNgrokUrl(ngrokUrl);
logger.LogInformation(
"{BaseLogMessage}: received a request to describe image by URL '{ImageUrl}'",
GetBaseLogMessage(nameof(DescribeImage)), ticket.ImageUrl);
string? errorMessage = null;
IHttpOperationResponse<ImageDescription> response = default!;
try
{
response = await computerVisionClient.DescribeImageWithHttpMessagesAsync(ticket.ImageUrl);
if (!response.Response.IsSuccessStatusCode)
{
errorMessage = response.Response.ReasonPhrase;
}
}
catch (ComputerVisionErrorResponseException exception)
{
errorMessage = exception.Body.Error.Message;
}
catch (Exception exception)
{
errorMessage = exception.Message;
}
if (!string.IsNullOrWhiteSpace(errorMessage))
{
logger.LogWarning(
"{BaseLogMessage}: image '{ImageUrl}' was sent to the describing, but the received response was unsuccessful. Message: {ErrorMessage}",
GetBaseLogMessage(nameof(DescribeImage)), ticket.ImageUrl,
response.Response.ReasonPhrase);
await signalRMessages.AddAsync(
new SignalRMessage
{
Target = "error_external",
Arguments = new object[] { "Error while uploading image. Please try later." },
ConnectionId = ticket.SignalConnectionId
});
return;
}
var description = response.Body.Captions.First()
.Text;
await SaveImageDescription(description, ticket.PostId);
logger.LogInformation(
"{BaseLogMessage}: successfully saved described image '{ImageUrl}' with description '{Description}'",
GetBaseLogMessage(nameof(DescribeImage)), ticket.ImageUrl, description);
await signalRMessages.AddAsync(
new SignalRMessage
{
Target = "processing_finish",
Arguments = new object[] { "Image was successfully uploaded!" },
ConnectionId = ticket.SignalConnectionId
});
}
#region Utils
private async Task SaveImagePath(string imagePath, int postId)
{
const string Query =
"UPDATE Posts SET ImagePath = @ImagePath WHERE Id = @PostId";
using var connection = connectionFactory.CreateConnection();
await connection.ExecuteAsync(Query, new { ImagePath = imagePath, PostId = postId });
connection.Close();
}
private async Task SaveImageDescription(string imageDescription, int postId)
{
const string Query = "UPDATE Posts SET Description = @ImageDescription WHERE Id = @PostId";
using var connection = connectionFactory.CreateConnection();
await connection.ExecuteAsync(Query, new { ImageDescription = imageDescription, PostId = postId });
}
private static string GetBaseLogMessage(string methodName, HttpRequest? request = null)
{
var messageBuilder = new StringBuilder();
messageBuilder.Append('[')
.Append(request is not null ? request.Method : "UTILITY")
.Append($"] {nameof(FunctionContainer)}.{methodName}");
return messageBuilder.ToString();
}
#endregion
}