Add project files.
This commit is contained in:
8
Core.Blueprint.Storage/Adapters/BlobAddDto.cs
Normal file
8
Core.Blueprint.Storage/Adapters/BlobAddDto.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace Core.Blueprint.Storage
|
||||
{
|
||||
public class BlobAddDto
|
||||
{
|
||||
public string? FileName { get; set; }
|
||||
public byte[] FileContent { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
12
Core.Blueprint.Storage/Adapters/BlobDownloadAdapter.cs
Normal file
12
Core.Blueprint.Storage/Adapters/BlobDownloadAdapter.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Core.Blueprint.Storage.Adapters
|
||||
{
|
||||
class BlobDownloadAdapter
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Core.Blueprint.Storage.Adapters
|
||||
{
|
||||
public class BlobDownloadUriAdapter
|
||||
{
|
||||
public Uri Uri { get; set; } = null!;
|
||||
public string Name { get; set; } = null!;
|
||||
public string? Status { get; set; }
|
||||
}
|
||||
}
|
||||
13
Core.Blueprint.Storage/Adapters/BlobFileAdapter.cs
Normal file
13
Core.Blueprint.Storage/Adapters/BlobFileAdapter.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace Core.Blueprint.Storage
|
||||
{
|
||||
public class BlobFileAdapter
|
||||
{
|
||||
public string? Uri { get; set; }
|
||||
public string Name { get; set; } = null!;
|
||||
public string? DateUpload { get; set; }
|
||||
public string? ContentType { get; set; }
|
||||
public long? Size { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public string? ShortDate { get; set; }
|
||||
}
|
||||
}
|
||||
15
Core.Blueprint.Storage/Adapters/BlobStorageAdapter.cs
Normal file
15
Core.Blueprint.Storage/Adapters/BlobStorageAdapter.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Core.Blueprint.Storage
|
||||
{
|
||||
public class BlobStorageAdapter
|
||||
{
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
public string Content { get; set; } = string.Empty;
|
||||
public string DownloadUrl { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
16
Core.Blueprint.Storage/Adapters/BlobStorageFolder.cs
Normal file
16
Core.Blueprint.Storage/Adapters/BlobStorageFolder.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Core.Blueprint.Storage.Adapters
|
||||
{
|
||||
public record BlobStorageFolder
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public List<BlobStorageFolder> SubFolders { get; set; } = [];
|
||||
public List<BlobStorageFilesAdapter> Files { get; set; } = [];
|
||||
}
|
||||
public record BlobStorageFilesAdapter(string Content, string Name, string ContentType, string DownloadUrl);
|
||||
}
|
||||
66
Core.Blueprint.Storage/Adapters/Trie/TrieNode.cs
Normal file
66
Core.Blueprint.Storage/Adapters/Trie/TrieNode.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
|
||||
namespace Core.Blueprint.Storage
|
||||
{
|
||||
public class TrieNode
|
||||
{
|
||||
public Dictionary<char, TrieNode> Children { get; private set; }
|
||||
public bool IsEndOfWord { get; set; }
|
||||
|
||||
public TrieNode()
|
||||
{
|
||||
Children = [];
|
||||
IsEndOfWord = false;
|
||||
}
|
||||
}
|
||||
public class Trie
|
||||
{
|
||||
private readonly TrieNode _root;
|
||||
|
||||
public Trie()
|
||||
{
|
||||
_root = new TrieNode();
|
||||
}
|
||||
|
||||
public void Insert(string word)
|
||||
{
|
||||
var node = _root;
|
||||
foreach (var ch in word)
|
||||
{
|
||||
if (!node.Children.ContainsKey(ch))
|
||||
{
|
||||
node.Children[ch] = new TrieNode();
|
||||
}
|
||||
node = node.Children[ch];
|
||||
}
|
||||
node.IsEndOfWord = true;
|
||||
}
|
||||
|
||||
public List<string> SearchByPrefix(string? prefix)
|
||||
{
|
||||
var results = new List<string>();
|
||||
var node = _root;
|
||||
foreach (var ch in prefix)
|
||||
{
|
||||
if (!node.Children.ContainsKey(ch))
|
||||
{
|
||||
return results;
|
||||
}
|
||||
node = node.Children[ch];
|
||||
}
|
||||
SearchByPrefixHelper(node, prefix, results);
|
||||
return results;
|
||||
}
|
||||
|
||||
private void SearchByPrefixHelper(TrieNode node, string currentPrefix, List<string> results)
|
||||
{
|
||||
if (node.IsEndOfWord)
|
||||
{
|
||||
results.Add(currentPrefix);
|
||||
}
|
||||
foreach (var kvp in node.Children)
|
||||
{
|
||||
SearchByPrefixHelper(kvp.Value, currentPrefix + kvp.Key, results);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
38
Core.Blueprint.Storage/Configuration/RegisterBlueprint.cs
Normal file
38
Core.Blueprint.Storage/Configuration/RegisterBlueprint.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using Azure.Identity;
|
||||
using Core.Blueprint.Storage.Contracts;
|
||||
using Core.Blueprint.Storage.Provider;
|
||||
using Microsoft.Extensions.Azure;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Core.Blueprint.Storage.Configuration
|
||||
{
|
||||
public static class RegisterBlueprint
|
||||
{
|
||||
public static IServiceCollection AddBlobStorage(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
|
||||
var blobConnection = configuration.GetConnectionString("BlobStorage");
|
||||
|
||||
if (blobConnection == null || string.IsNullOrWhiteSpace(blobConnection))
|
||||
{
|
||||
throw new ArgumentException("The BlobStorage configuration section is missing or empty.");
|
||||
}
|
||||
|
||||
var chainedCredentials = new ChainedTokenCredential(
|
||||
new ManagedIdentityCredential(),
|
||||
new SharedTokenCacheCredential(),
|
||||
new VisualStudioCredential(),
|
||||
new VisualStudioCodeCredential()
|
||||
);
|
||||
services.AddAzureClients(cfg =>
|
||||
{
|
||||
cfg.AddBlobServiceClient(new Uri(blobConnection)).WithCredential(chainedCredentials);
|
||||
});
|
||||
|
||||
services.AddScoped<IBlobStorageProvider, BlobStorageProvider>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
181
Core.Blueprint.Storage/Contracts/IBlobStorageProvider.cs
Normal file
181
Core.Blueprint.Storage/Contracts/IBlobStorageProvider.cs
Normal file
@@ -0,0 +1,181 @@
|
||||
using Azure;
|
||||
using Azure.Storage.Blobs;
|
||||
using Azure.Storage.Blobs.Models;
|
||||
using Azure.Storage.Sas;
|
||||
using Core.Blueprint.Storage.Adapters;
|
||||
|
||||
namespace Core.Blueprint.Storage.Contracts
|
||||
{
|
||||
/// <summary>
|
||||
/// Defines a contract for managing blobs and containers in Azure Blob Storage.
|
||||
/// </summary>
|
||||
public interface IBlobStorageProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates the blob container if it does not exist.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="Response{T}"/> containing the container information.</returns>
|
||||
Task<Response<BlobContainerInfo>> CreateIfNotExistsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the blob container if it exists.
|
||||
/// </summary>
|
||||
Task DeleteIfExistsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets properties of the blob container.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="Response{T}"/> containing container properties.</returns>
|
||||
Task<Response<BlobContainerProperties>> GetPropertiesAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Sets metadata for the blob container.
|
||||
/// </summary>
|
||||
/// <param name="metadata">The metadata to set for the container.</param>
|
||||
Task SetMetadataAsync(IDictionary<string, string> metadata);
|
||||
|
||||
/// <summary>
|
||||
/// Uploads a blob to the container.
|
||||
/// </summary>
|
||||
/// <param name="blobName">The name of the blob.</param>
|
||||
/// <param name="content">The content to upload.</param>
|
||||
/// <returns>A <see cref="Response{T}"/> containing blob content information.</returns>
|
||||
Task<Response<BlobContentInfo>> UploadBlobAsync(string blobName, Stream content);
|
||||
|
||||
/// <summary>
|
||||
/// Downloads a blob from the container.
|
||||
/// </summary>
|
||||
/// <param name="blobName">The name of the blob.</param>
|
||||
/// <returns>A <see cref="Response{T}"/> containing blob download information.</returns>
|
||||
/// <exception cref="FileNotFoundException">Thrown if the blob does not exist.</exception>
|
||||
Task<Response<BlobDownloadInfo>> DownloadBlobAsync(string blobName);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a blob from the container.
|
||||
/// </summary>
|
||||
/// <param name="blobName">The name of the blob.</param>
|
||||
Task<bool> DeleteBlobAsync(string blobName);
|
||||
|
||||
/// <summary>
|
||||
/// Lists all blobs in the container with an optional prefix.
|
||||
/// </summary>
|
||||
/// <param name="prefix">The prefix to filter blobs.</param>
|
||||
/// <returns>A collection of <see cref="BlobItem"/>.</returns>
|
||||
Task<IEnumerable<BlobItem>> ListBlobItemAsync(string? prefix = null);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the account information for the associated Blob Service Client.
|
||||
/// </summary>
|
||||
/// <param name="cancellation">
|
||||
/// A <see cref="CancellationToken"/> that can be used to cancel the operation.
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous operation. The task result contains the
|
||||
/// <see cref="AccountInfo"/> object, which provides details about the account, such as the SKU
|
||||
/// and account kind.
|
||||
Task<AccountInfo> GetAccountInfoAsync(CancellationToken cancellation);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a blob client for a specific blob.
|
||||
/// </summary>
|
||||
/// <param name="blobName">The name of the blob.</param>
|
||||
/// <returns>A <see cref="BlobClient"/> for the blob.</returns>
|
||||
BlobClient GetBlobClient(string blobName);
|
||||
|
||||
/// <summary>
|
||||
/// Lists blobs hierarchically using a delimiter.
|
||||
/// </summary>
|
||||
/// <param name="prefix">The prefix to filter blobs.</param>
|
||||
/// <param name="delimiter">The delimiter to use for hierarchy.</param>
|
||||
/// <returns>A collection of <see cref="BlobHierarchyItem"/>.</returns>
|
||||
Task<IEnumerable<BlobHierarchyItem>> ListBlobsByHierarchyAsync(string? prefix = null, string delimiter = "/");
|
||||
|
||||
/// <summary>
|
||||
/// Generates a SAS token for the container with specified permissions.
|
||||
/// </summary>
|
||||
/// <param name="permissions">The permissions to assign to the SAS token.</param>
|
||||
/// <param name="expiresOn">The expiration time for the SAS token.</param>
|
||||
/// <returns>A <see cref="Uri"/> containing the SAS token.</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown if SAS URI generation is not supported.</exception>
|
||||
Uri GenerateContainerSasUri(BlobContainerSasPermissions permissions, DateTimeOffset expiresOn);
|
||||
|
||||
/// <summary>
|
||||
/// Acquires a lease on the blob container.
|
||||
/// </summary>
|
||||
/// <param name="proposedId">The optional proposed lease ID.</param>
|
||||
/// <param name="duration">The optional lease duration.</param>
|
||||
/// <returns>A <see cref="Response{T}"/> containing lease information.</returns>
|
||||
Task<Response<BlobLease>> AcquireLeaseAsync(string? proposedId = null, TimeSpan? duration = null);
|
||||
|
||||
/// <summary>
|
||||
/// Releases a lease on the blob container.
|
||||
/// </summary>
|
||||
/// <param name="leaseId">The lease ID to release.</param>
|
||||
Task ReleaseLeaseAsync(string leaseId);
|
||||
|
||||
/// <summary>
|
||||
/// Sets access policies for the blob container.
|
||||
/// </summary>
|
||||
/// <param name="accessType">The type of public access to allow.</param>
|
||||
/// <param name="identifiers">The optional list of signed identifiers for access policy.</param>
|
||||
Task SetAccessPolicyAsync(PublicAccessType accessType, IEnumerable<BlobSignedIdentifier>? identifiers = null);
|
||||
|
||||
/// <summary>
|
||||
/// Lists blobs in the container with an optional prefix.
|
||||
/// </summary>
|
||||
/// <param name="prefix">The prefix to filter blobs.</param>
|
||||
/// <returns>A collection of <see cref="BlobFileAdapter"/>.</returns>
|
||||
Task<IEnumerable<BlobFileAdapter>> ListBlobsAsync(string? prefix = null);
|
||||
|
||||
/// <summary>
|
||||
/// Uploads a blob to the container.
|
||||
/// </summary>
|
||||
/// <param name="newBlob">The blob to upload.</param>
|
||||
/// <returns>A <see cref="BlobFileAdapter"/> representing the uploaded blob.</returns>
|
||||
Task<BlobFileAdapter> UploadBlobAsync(BlobAddDto newBlob);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a blob from the container.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the blob to delete.</param>
|
||||
/// <returns>A <see cref="BlobFileAdapter"/> representing the deleted blob, or null if the blob was not found.</returns>
|
||||
Task<BlobFileAdapter?> DeleteBlobsAsync(string fileName);
|
||||
|
||||
/// <summary>
|
||||
/// Downloads a blob's content.
|
||||
/// </summary>
|
||||
/// <param name="blobName">The name of the blob.</param>
|
||||
/// <returns>A <see cref="BlobDownloadInfo"/> representing the downloaded blob.</returns>
|
||||
/// <exception cref="FileNotFoundException">Thrown if the blob does not exist.</exception>
|
||||
Task<BlobDownloadInfo> DownloadBlobsAsync(string blobName);
|
||||
|
||||
/// <summary>
|
||||
/// Generates a secure download URI for a specified blob in the storage container.
|
||||
/// </summary>
|
||||
/// <param name="blobName">The name of the blob for which the download URI is being generated.</param>
|
||||
/// <returns>
|
||||
/// An instance of <see cref="BlobDownloadUriAdapter"/> containing the generated URI, blob name, and status.
|
||||
/// </returns>
|
||||
/// <remarks>
|
||||
/// The generated URI includes a Shared Access Signature (SAS) token, which allows secure, time-limited access to the blob.
|
||||
/// The SAS token grants read-only access to the blob for a duration of 5 minutes starting from the current time.
|
||||
/// </remarks>
|
||||
/// <exception cref="ArgumentNullException">Thrown if <paramref name="blobName"/> is null or empty.</exception>
|
||||
/// <exception cref="StorageException">Thrown if there is an issue communicating with the Azure Blob service.</exception>
|
||||
BlobDownloadUriAdapter GenerateBlobDownloadUri(string blobName);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the hierarchical folder structure.
|
||||
/// </summary>
|
||||
/// <param name="prefix">The prefix to start the hierarchy retrieval.</param>
|
||||
/// <returns>A list of <see cref="BlobStorageFolder"/> representing the folder structure.</returns>
|
||||
Task<List<BlobStorageFolder>> GetFolderHierarchyAsync(string prefix);
|
||||
|
||||
/// <summary>
|
||||
/// Lists neighboring folders based on a prefix.
|
||||
/// </summary>
|
||||
/// <param name="prefix">The prefix to search for neighboring folders.</param>
|
||||
/// <returns>A dictionary grouping folder names by their prefix.</returns>
|
||||
Task<Dictionary<string, List<string>>> ListNeighborFoldersAsync(string? prefix);
|
||||
}
|
||||
}
|
||||
17
Core.Blueprint.Storage/Core.Blueprint.Storage.csproj
Normal file
17
Core.Blueprint.Storage/Core.Blueprint.Storage.csproj
Normal file
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.Identity" Version="1.13.1" />
|
||||
<PackageReference Include="Azure.Storage.Blobs" Version="12.23.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Azure" Version="1.9.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
372
Core.Blueprint.Storage/Provider/BlobStorageProvider.cs
Normal file
372
Core.Blueprint.Storage/Provider/BlobStorageProvider.cs
Normal file
@@ -0,0 +1,372 @@
|
||||
using Azure;
|
||||
using Azure.Storage.Blobs;
|
||||
using Azure.Storage.Blobs.Models;
|
||||
using Azure.Storage.Blobs.Specialized;
|
||||
using Azure.Storage.Sas;
|
||||
using Core.Blueprint.Storage.Adapters;
|
||||
using Core.Blueprint.Storage.Contracts;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace Core.Blueprint.Storage.Provider
|
||||
{
|
||||
public sealed class BlobStorageProvider : IBlobStorageProvider
|
||||
{
|
||||
private readonly BlobServiceClient _blobServiceClient;
|
||||
private readonly BlobContainerClient _blobContainerClient;
|
||||
private readonly string _containerName;
|
||||
private readonly Trie _trie = new Trie();
|
||||
|
||||
public BlobStorageProvider(BlobServiceClient blobServiceClient, IConfiguration configuration)
|
||||
{
|
||||
_blobServiceClient = blobServiceClient;
|
||||
_containerName = configuration.GetSection("BlobStorage:ContainerName").Value ?? "";
|
||||
|
||||
if (string.IsNullOrEmpty(_containerName))
|
||||
throw new ArgumentException("Blob container cannot be null or empty.");
|
||||
|
||||
_blobContainerClient = blobServiceClient.GetBlobContainerClient(_containerName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the blob container if it does not exist.
|
||||
/// </summary>
|
||||
public async Task<Response<BlobContainerInfo>> CreateIfNotExistsAsync()
|
||||
{
|
||||
return await _blobContainerClient.CreateIfNotExistsAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the blob container if it exists.
|
||||
/// </summary>
|
||||
public async Task DeleteIfExistsAsync()
|
||||
{
|
||||
await _blobContainerClient.DeleteIfExistsAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets properties of the blob container.
|
||||
/// </summary>
|
||||
public async Task<Response<BlobContainerProperties>> GetPropertiesAsync()
|
||||
{
|
||||
return await _blobContainerClient.GetPropertiesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets metadata for the blob container.
|
||||
/// </summary>
|
||||
public async Task SetMetadataAsync(IDictionary<string, string> metadata)
|
||||
{
|
||||
await _blobContainerClient.SetMetadataAsync(metadata);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Uploads a blob to the container.
|
||||
/// </summary>
|
||||
public async Task<Response<BlobContentInfo>> UploadBlobAsync(string blobName, Stream content)
|
||||
{
|
||||
var blobClient = _blobContainerClient.GetBlobClient(blobName);
|
||||
return await blobClient.UploadAsync(content, overwrite: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads a blob from the container.
|
||||
/// </summary>
|
||||
public async Task<Response<BlobDownloadInfo>> DownloadBlobAsync(string blobName)
|
||||
{
|
||||
var blobClient = _blobContainerClient.GetBlobClient(blobName);
|
||||
return await blobClient.DownloadAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a blob from the container.
|
||||
/// </summary>
|
||||
public async Task<bool> DeleteBlobAsync(string blobName)
|
||||
{
|
||||
var blobClient = _blobContainerClient.GetBlobClient(blobName);
|
||||
return await blobClient.DeleteIfExistsAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lists all blobs in the container with an optional prefix.
|
||||
/// </summary>
|
||||
public async Task<IEnumerable<BlobItem>> ListBlobItemAsync(string? prefix = null)
|
||||
{
|
||||
var blobs = new List<BlobItem>();
|
||||
|
||||
await foreach (var blobItem in _blobContainerClient.GetBlobsAsync(prefix: prefix))
|
||||
{
|
||||
blobs.Add(blobItem);
|
||||
}
|
||||
|
||||
return blobs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the account information for the associated Blob Service Client.
|
||||
/// </summary>
|
||||
/// <param name="cancellation">
|
||||
/// A <see cref="CancellationToken"/> that can be used to cancel the operation.
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous operation. The task result contains the
|
||||
/// <see cref="AccountInfo"/> object, which provides details about the account, such as the SKU
|
||||
/// and account kind.
|
||||
public async Task<AccountInfo> GetAccountInfoAsync(CancellationToken cancellation)
|
||||
{
|
||||
return await _blobServiceClient.GetAccountInfoAsync(cancellation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a blob client for a specific blob.
|
||||
/// </summary>
|
||||
public BlobClient GetBlobClient(string blobName)
|
||||
{
|
||||
return _blobContainerClient.GetBlobClient(blobName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lists blobs hierarchically using a delimiter.
|
||||
/// </summary>
|
||||
public async Task<IEnumerable<BlobHierarchyItem>> ListBlobsByHierarchyAsync(string? prefix = null, string delimiter = "/")
|
||||
{
|
||||
var blobs = new List<BlobHierarchyItem>();
|
||||
|
||||
await foreach (var blobHierarchyItem in _blobContainerClient.GetBlobsByHierarchyAsync(prefix: prefix, delimiter: delimiter))
|
||||
{
|
||||
blobs.Add(blobHierarchyItem);
|
||||
}
|
||||
|
||||
return blobs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a SAS token for the container with specified permissions.
|
||||
/// </summary>
|
||||
public Uri GenerateContainerSasUri(BlobContainerSasPermissions permissions, DateTimeOffset expiresOn)
|
||||
{
|
||||
if (!_blobContainerClient.CanGenerateSasUri)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot generate SAS URI. Ensure the client is authorized with account key credentials.");
|
||||
}
|
||||
|
||||
var sasBuilder = new BlobSasBuilder
|
||||
{
|
||||
BlobContainerName = _blobContainerClient.Name,
|
||||
Resource = "c", // c for container
|
||||
ExpiresOn = expiresOn
|
||||
};
|
||||
|
||||
sasBuilder.SetPermissions(permissions);
|
||||
return _blobContainerClient.GenerateSasUri(sasBuilder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Acquires a lease on the blob container.
|
||||
/// </summary>
|
||||
public async Task<Response<BlobLease>> AcquireLeaseAsync(string? proposedId = null, TimeSpan? duration = null)
|
||||
{
|
||||
return await _blobContainerClient.GetBlobLeaseClient(proposedId).AcquireAsync(duration ?? TimeSpan.FromSeconds(60));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases a lease on the blob container.
|
||||
/// </summary>
|
||||
public async Task ReleaseLeaseAsync(string leaseId)
|
||||
{
|
||||
await _blobContainerClient.GetBlobLeaseClient(leaseId).ReleaseAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets access policies for the blob container.
|
||||
/// </summary>
|
||||
public async Task SetAccessPolicyAsync(PublicAccessType accessType, IEnumerable<BlobSignedIdentifier>? identifiers = null)
|
||||
{
|
||||
await _blobContainerClient.SetAccessPolicyAsync(accessType, identifiers);
|
||||
}
|
||||
/// <summary>
|
||||
/// Lists blobs in the container with an optional prefix.
|
||||
/// </summary>
|
||||
public async Task<IEnumerable<BlobFileAdapter>> ListBlobsAsync(string? prefix = null)
|
||||
{
|
||||
var blobs = new List<BlobFileAdapter>();
|
||||
|
||||
await foreach (BlobItem blob in _blobContainerClient.GetBlobsAsync(prefix: prefix))
|
||||
{
|
||||
blobs.Add(new BlobFileAdapter
|
||||
{
|
||||
Name = blob.Name,
|
||||
Uri = $"{_blobContainerClient.Uri}/{blob.Name}",
|
||||
ContentType = blob.Properties.ContentType,
|
||||
Size = blob.Properties.ContentLength,
|
||||
DateUpload = blob.Properties.LastModified?.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
|
||||
ShortDate = blob.Properties.LastModified?.UtcDateTime.ToString("MM-dd-yyyy"),
|
||||
Status = "Available"
|
||||
});
|
||||
}
|
||||
|
||||
return blobs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Uploads a blob to the container.
|
||||
/// </summary>
|
||||
public async Task<BlobFileAdapter> UploadBlobAsync(BlobAddDto newBlob)
|
||||
{
|
||||
var blobClient = _blobContainerClient.GetBlobClient(newBlob.FileName);
|
||||
|
||||
using var stream = new MemoryStream(newBlob.FileContent);
|
||||
await blobClient.UploadAsync(stream, overwrite: true);
|
||||
|
||||
var properties = await blobClient.GetPropertiesAsync();
|
||||
|
||||
return new BlobFileAdapter
|
||||
{
|
||||
Name = newBlob.FileName ?? "",
|
||||
Uri = blobClient.Uri.ToString(),
|
||||
ContentType = properties.Value.ContentType,
|
||||
Size = properties.Value.ContentLength,
|
||||
DateUpload = properties.Value.LastModified.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
|
||||
ShortDate = properties.Value.LastModified.UtcDateTime.ToString("MM-dd-yyyy"),
|
||||
Status = "Uploaded"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a blob from the container.
|
||||
/// </summary>
|
||||
public async Task<BlobFileAdapter?> DeleteBlobsAsync(string fileName)
|
||||
{
|
||||
var blobClient = _blobContainerClient.GetBlobClient(fileName);
|
||||
|
||||
if (await blobClient.ExistsAsync())
|
||||
{
|
||||
var properties = await blobClient.GetPropertiesAsync();
|
||||
var _response = await blobClient.DeleteIfExistsAsync();
|
||||
|
||||
return new BlobFileAdapter
|
||||
{
|
||||
Name = fileName,
|
||||
Uri = blobClient.Uri.ToString(),
|
||||
ContentType = properties.Value.ContentType,
|
||||
Size = properties.Value.ContentLength,
|
||||
DateUpload = properties.Value.LastModified.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
|
||||
ShortDate = properties.Value.LastModified.UtcDateTime.ToString("MM-dd-yyyy"),
|
||||
Status = _response ? "Deleted" : "Failed to delete"
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads a blob's content.
|
||||
/// </summary>
|
||||
public async Task<BlobDownloadInfo> DownloadBlobsAsync(string blobName)
|
||||
{
|
||||
var blobClient = _blobContainerClient.GetBlobClient(blobName);
|
||||
|
||||
if (!await blobClient.ExistsAsync())
|
||||
{
|
||||
throw new FileNotFoundException($"Blob '{blobName}' does not exist in the container '{_containerName}'.");
|
||||
}
|
||||
|
||||
return await blobClient.DownloadAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a secure download URI for a specified blob in the storage container.
|
||||
/// </summary>
|
||||
/// <param name="blobName">The name of the blob for which the download URI is being generated.</param>
|
||||
/// <returns>
|
||||
/// An instance of <see cref="BlobDownloadUriAdapter"/> containing the generated URI, blob name, and status.
|
||||
/// </returns>
|
||||
/// <remarks>
|
||||
/// The generated URI includes a Shared Access Signature (SAS) token, which allows secure, time-limited access to the blob.
|
||||
/// The SAS token grants read-only access to the blob for a duration of 5 minutes starting from the current time.
|
||||
/// </remarks>
|
||||
/// <exception cref="ArgumentNullException">Thrown if <paramref name="blobName"/> is null or empty.</exception>
|
||||
/// <exception cref="StorageException">Thrown if there is an issue communicating with the Azure Blob service.</exception>
|
||||
public BlobDownloadUriAdapter GenerateBlobDownloadUri(string blobName)
|
||||
{
|
||||
var delegationKey = _blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow,
|
||||
DateTimeOffset.UtcNow.AddHours(2));
|
||||
|
||||
var blob = _blobContainerClient.GetBlobClient(blobName);
|
||||
|
||||
var sasBuilder = new BlobSasBuilder()
|
||||
{
|
||||
BlobContainerName = blob.BlobContainerName,
|
||||
BlobName = blob.Name,
|
||||
Resource = "b",
|
||||
StartsOn = DateTimeOffset.UtcNow,
|
||||
ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5),
|
||||
};
|
||||
sasBuilder.SetPermissions(BlobAccountSasPermissions.Read);
|
||||
sasBuilder.Protocol = SasProtocol.Https;
|
||||
|
||||
var blobUriBuilder = new BlobUriBuilder(blob.Uri)
|
||||
{
|
||||
Sas = sasBuilder.ToSasQueryParameters(delegationKey, _blobServiceClient.AccountName)
|
||||
};
|
||||
|
||||
return new BlobDownloadUriAdapter
|
||||
{
|
||||
Uri = blobUriBuilder.ToUri(),
|
||||
Name = blob.Name,
|
||||
Status = "Available"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the hierarchical folder structure.
|
||||
/// </summary>
|
||||
public async Task<List<BlobStorageFolder>> GetFolderHierarchyAsync(string prefix)
|
||||
{
|
||||
var rootFolder = new BlobStorageFolder { Name = prefix };
|
||||
await PopulateFolderAsync(rootFolder, prefix);
|
||||
return new List<BlobStorageFolder> { rootFolder };
|
||||
}
|
||||
|
||||
private async Task PopulateFolderAsync(BlobStorageFolder folder, string? prefix)
|
||||
{
|
||||
await foreach (var blobHierarchy in _blobContainerClient.GetBlobsByHierarchyAsync(prefix: prefix, delimiter: "/"))
|
||||
{
|
||||
if (blobHierarchy.IsPrefix)
|
||||
{
|
||||
var subFolder = new BlobStorageFolder { Name = blobHierarchy.Prefix.TrimEnd('/') };
|
||||
folder.SubFolders.Add(subFolder);
|
||||
await PopulateFolderAsync(subFolder, blobHierarchy.Prefix);
|
||||
}
|
||||
else
|
||||
{
|
||||
folder.Files.Add(new BlobStorageFilesAdapter(Content: blobHierarchy.Prefix, //Fix
|
||||
Name: blobHierarchy.Blob.Name,
|
||||
ContentType: "",
|
||||
DownloadUrl: $"{_blobContainerClient.Uri}/{blobHierarchy.Blob.Name}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<Dictionary<string, List<string>>> ListNeighborFoldersAsync(string? prefix)
|
||||
{
|
||||
await ListFoldersInTrieAsync(prefix);
|
||||
|
||||
var groupedFolders = _trie.SearchByPrefix(prefix)
|
||||
.OrderBy(folder => folder)
|
||||
.GroupBy(folder => folder.Substring(0, 1))
|
||||
.ToDictionary(group => group.Key, group => group.ToList());
|
||||
|
||||
return groupedFolders;
|
||||
}
|
||||
private async Task ListFoldersInTrieAsync(string? prefix)
|
||||
{
|
||||
await foreach (var blobHierarchy in _blobContainerClient.GetBlobsByHierarchyAsync(prefix: prefix, delimiter: "/"))
|
||||
{
|
||||
if (blobHierarchy.IsPrefix)
|
||||
{
|
||||
var folderName = blobHierarchy.Prefix.TrimEnd('/').Split('/').Last();
|
||||
_trie.Insert(folderName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user