Skip to content

Commit

Permalink
blob images seed
Browse files Browse the repository at this point in the history
  • Loading branch information
kolosovpetro committed Apr 24, 2023
1 parent 8e52be9 commit 9b6992b
Show file tree
Hide file tree
Showing 11 changed files with 98 additions and 44 deletions.
4 changes: 3 additions & 1 deletion MangoAPI.Application/Interfaces/IBlobService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ namespace MangoAPI.Application.Interfaces;

public interface IBlobService
{
string GetBlobAsync(string fileName);
Task<string> GetBlobUrlAsync(string fileName);

Task<bool> UploadFileBlobAsync(Stream stream, string contentType, string uniqueName);

Task<bool> DeleteBlobAsync(string fileName);

bool UploadFolderToBlob(string folderPath);
}
67 changes: 62 additions & 5 deletions MangoAPI.Application/Services/BlobService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,31 @@ public BlobService(BlobServiceClient blobClient, IBlobServiceSettings blobServic
this.blobServiceSettings = blobServiceSettings;
}

public string GetBlobAsync(string fileName)
public async Task<string> GetBlobUrlAsync(string fileName)
{
var containerClient = blobClient.GetBlobContainerClient(blobServiceSettings.MangoBlobContainerName);
var containerClient = await GetContainerClientAsync(blobServiceSettings.MangoBlobContainerName);
var client = containerClient.GetBlobClient(fileName);

return client.Uri.AbsoluteUri;
var blobExists = await client.ExistsAsync();

if (!blobExists.Value)
{
throw new FileNotFoundException("Blob file was not found at storage account.");
}

var blobUrl = $"{blobServiceSettings.MangoBlobAccess}/{fileName}";

return blobUrl;
}

public async Task<bool> UploadFileBlobAsync(Stream stream, string contentType, string uniqueName)
{
var blobContainerName = blobServiceSettings.MangoBlobContainerName;
var containerClient = GetContainerClient(blobContainerName);

var containerClient = await GetContainerClientAsync(blobContainerName);

var client = containerClient.GetBlobClient(uniqueName);

var headers = new BlobHttpHeaders { ContentType = contentType };
var result = await client.UploadAsync(stream, headers);

Expand All @@ -52,11 +64,56 @@ public async Task<bool> DeleteBlobAsync(string fileName)
return result.Value;
}

public bool UploadFolderToBlob(string folderPath)
{
var containerClient = GetContainerClient(blobServiceSettings.MangoBlobContainerName);

var combinePath = Path.Combine(AppContext.BaseDirectory, folderPath);

var files = Directory.GetFiles(combinePath);

foreach (var file in files)
{
var fileName = Path.GetFileName(file);

var client = containerClient.GetBlobClient(fileName);

var fileExists = client.Exists();

if (fileExists.Value)
{
continue;
}

using var stream = File.OpenRead(file);

var headers = new BlobHttpHeaders { ContentType = "image/jpg" };

client.Upload(stream, headers);
}

return true;
}

private async Task<BlobContainerClient> GetContainerClientAsync(string blobContainerName)
{
var containerClient = blobClient.GetBlobContainerClient(blobContainerName);

await containerClient.CreateIfNotExistsAsync();

await containerClient.SetAccessPolicyAsync(PublicAccessType.BlobContainer);

return containerClient;
}

private BlobContainerClient GetContainerClient(string blobContainerName)
{
var containerClient = blobClient.GetBlobContainerClient(blobContainerName);

containerClient.CreateIfNotExists();

containerClient.SetAccessPolicy(PublicAccessType.BlobContainer);

return containerClient;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task<Result<UpdateChannelPictureResponse>> Handle(

await dbContext.SaveChangesAsync(cancellationToken);

var blobUrl = blobService.GetBlobAsync(uniqueFileName);
var blobUrl = await blobService.GetBlobUrlAsync(uniqueFileName);
var response = UpdateChannelPictureResponse.FromSuccess(blobUrl, uniqueFileName);

return responseFactory.SuccessResponse(response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public async Task<Result<UpdateProfilePictureResponse>> Handle(
}

var file = request.PictureFile;

var uniqueFileName = FileNameHelper.CreateUniqueFileName(file.FileName);

await blobService.UploadFileBlobAsync(file.OpenReadStream(), request.ContentType, uniqueFileName);
Expand All @@ -55,7 +56,8 @@ public async Task<Result<UpdateProfilePictureResponse>> Handle(

await dbContext.SaveChangesAsync(cancellationToken);

var newUserPictureUrl = blobService.GetBlobAsync(uniqueFileName);
var newUserPictureUrl = await blobService.GetBlobUrlAsync(uniqueFileName);

var response = UpdateProfilePictureResponse.FromSuccess(newUserPictureUrl, uniqueFileName);

return responseFactory.SuccessResponse(response);
Expand Down
30 changes: 4 additions & 26 deletions MangoAPI.BusinessLogic/DependencyInjection/AzureBlobInitializer.cs
Original file line number Diff line number Diff line change
@@ -1,42 +1,20 @@
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using MangoAPI.Application.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;

namespace MangoAPI.BusinessLogic.DependencyInjection;

public static class AzureBlobInitializer
{
private const string SeedImagesFolder = "../../../../img/seed_images";

public static void InitializeAzureBlob(this IApplicationBuilder app)
{
using var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope();

var blobClient = serviceScope.ServiceProvider.GetService<BlobServiceClient>();
var blobServiceSettings = serviceScope.ServiceProvider.GetService<IBlobServiceSettings>();

var containerClient = blobClient.GetBlobContainerClient(blobServiceSettings.MangoBlobContainerName);
containerClient.CreateIfNotExists();
containerClient.SetAccessPolicy(PublicAccessType.BlobContainer);

var files = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "../../../../img/seed_images"));
foreach (var filePath in files)
{
var fileName = filePath.Split(@"\")[^1];
var client = containerClient.GetBlobClient(fileName);
var result = client.Exists();
if (result.Value)
{
continue;
}

using var stream = File.OpenRead(filePath);
var blobService = serviceScope.ServiceProvider.GetService<IBlobService>();

var headers = new BlobHttpHeaders { ContentType = "image/jpg" };
client.Upload(stream, headers);
}
blobService.UploadFolderToBlob(SeedImagesFolder);
}
}
8 changes: 6 additions & 2 deletions MangoAPI.Domain/Constants/EnvironmentConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public static class EnvironmentConstants
public const string BlobContainer = "BlobContainer";

public const string BlobAccess = "BlobAccess";

public const string MangoUserPassword = "MangoUserPassword";
}

public const string MigrateDatabase = "MigrateDatabase";

public const string InitializeBlob = "InitializeBlob";
}
2 changes: 1 addition & 1 deletion MangoAPI.Domain/Constants/GreetingsConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ public static class GreetingsConstants
public const string Hello = "Greetings, new user! I'm glad you decided to join our messenger. " +
"Here you will be able to communicate with your friends and family and receive interesting information. " +
"I hope you will have a lot of fun using our messenger. You are welcome!";

public const string Guide = "How to use the messenger: https://www.youtube.com/watch?v=3lh3we1DrEY";
}
2 changes: 0 additions & 2 deletions MangoAPI.Domain/Constants/ResponseMessageCodes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ public static class ResponseMessageCodes
public const string ContactNotFound = "CONTACT_NOT_FOUND";
public const string CannotAddSelfToContacts = "CANNOT_ADD_SELF_TO_CONTACTS";
public const string CannotCreateSelfChat = "CANNOT_CREATE_SELF_CHAT";
public const string MaximumOwnerChatsExceeded100 = "MAXIMUM_OWNER_CHATS_EXCEEDED_100";
public const string InvalidRequestModel = "INVALID_REQUEST_FORMAT";
public const string KeyExchangeRequestNotFound = "KEY_EXCHANGE_REQUEST_NOT_FOUND";
public const string MessageNotFound = "MESSAGE_NOT_FOUND";
Expand All @@ -42,7 +41,6 @@ public static class ResponseMessageCodes
{ ContactNotFound, "User is not found in your contact list." },
{ CannotAddSelfToContacts, "You cannot add yourself to the contacts." },
{ CannotCreateSelfChat, "You cannot create a direct chat with yourself." },
{ MaximumOwnerChatsExceeded100, "One user cannot create more than 100 channels." },
{ InvalidRequestModel, "Invalid request format. Correct input data and try again." },
{
KeyExchangeRequestNotFound,
Expand Down
4 changes: 2 additions & 2 deletions MangoAPI.Domain/Constants/RoutingConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ public static class RoutingConstants
public const string Settings = "/settings";

public const string CreateGroup = "/createGroup";

public const string Register = "/register";

public const string Login = "/login";
}
15 changes: 13 additions & 2 deletions MangoAPI.Presentation/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,19 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
app.Map(RoutingConstants.Register, builder => builder.UseSpa(spa => spa.Options.SourcePath = "/wwwroot"));
app.Map(RoutingConstants.Login, builder => builder.UseSpa(spa => spa.Options.SourcePath = "/wwwroot"));

app.MigrateDatabase();
app.InitializeAzureBlob();
var shouldMigrateDatabase = configuration.GetValue<bool>(EnvironmentConstants.MigrateDatabase);

if (shouldMigrateDatabase)
{
app.MigrateDatabase();
}

var shouldInitializeBlob = configuration.GetValue<bool>(EnvironmentConstants.InitializeBlob);

if (shouldInitializeBlob)
{
app.InitializeAzureBlob();
}
}

public void ConfigureServices(IServiceCollection services)
Expand Down
4 changes: 3 additions & 1 deletion MangoAPI.Presentation/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,7 @@
"BlobUrl": "AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;DefaultEndpointsProtocol=http;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;",
"BlobContainer": "mangocontainer",
"BlobAccess": "http://127.0.0.1:10000/devstoreaccount1/mangocontainer",
"MangoUserPassword": "124fjfklse423342"
"MangoUserPassword": "124fjfklse423342",
"MigrateDatabase": true,
"InitializeBlob": true
}

0 comments on commit 9b6992b

Please sign in to comment.