NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

using anh_cus_dev_api01.Models;
using Azure.Storage.Blobs;
using System.IO.Compression;


public interface IMultiDownloadService
{
Task<DownloadResult> DownloadAsync(MultiDownloadRequest request);
}

public class MultiDownloadService : IMultiDownloadService
{
private readonly BlobServiceClient _blobServiceClient;
private readonly IConfiguration _configuration;

public MultiDownloadService(
BlobServiceClient blobServiceClient,
IConfiguration configuration)
{
_blobServiceClient = blobServiceClient;
_configuration = configuration;
}

public async Task<DownloadResult> DownloadAsync(MultiDownloadRequest request)
{
var containerName = _configuration["BlobStorage:ContainerName"];
if (string.IsNullOrWhiteSpace(containerName))
throw new Exception("BlobStorage:ContainerName is missing.");

var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);

if ((request.Attachments == null || !request.Attachments.Any()) &&
(request.Emails == null || !request.Emails.Any()))
throw new ArgumentException("No files provided");

// SINGLE FILE DOWNLOAD (attachments only, no emails)
if (request.Attachments?.Count == 1 && (request.Emails == null || !request.Emails.Any()))
{
var file = request.Attachments.First();
var blobName = GetBlobNameFromUrl(file.BlobPath, containerName);
var blobClient = containerClient.GetBlobClient(blobName);

if (!await blobClient.ExistsAsync())
throw new Exception($"Blob does not exist: {blobClient.Uri}");

var stream = new MemoryStream();
await blobClient.DownloadToAsync(stream);
stream.Position = 0;

return new DownloadResult
{
Stream = stream,
ContentType = "application/octet-stream",
FileName = file.FileName
};
}

// MULTI FILE DOWNLOAD (ZIP)
var zipStream = new MemoryStream();

using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
var usedNamesPerFolder = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);

// 🔹 ADD EMAILS AND THEIR ATTACHMENTS
if (request.Emails != null)
{
if (!usedNamesPerFolder.ContainsKey("ROOT"))
usedNamesPerFolder["ROOT"] = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

foreach (var email in request.Emails)
{
// Add email body (eml or html) at ROOT
if (!string.IsNullOrWhiteSpace(email.EmlLocation))
{
var emailBlobName = GetBlobNameFromUrl(email.EmlLocation, containerName);
var emailBlobClient = containerClient.GetBlobClient(emailBlobName);

if (await emailBlobClient.ExistsAsync())
{
var emailFileName = Path.GetFileName(emailBlobName);
var safeEmailName = ResolveDuplicateName(emailFileName, usedNamesPerFolder["ROOT"]);

var entry = archive.CreateEntry(safeEmailName);
using var entryStream = entry.Open();
await emailBlobClient.DownloadToAsync(entryStream);
}
}

// Add attachments for this email
if (email.Attachments != null)
{
foreach (var file in email.Attachments)
{
var blobName = GetBlobNameFromUrl(file.BlobPath, containerName);
var blobClient = containerClient.GetBlobClient(blobName);

if (!await blobClient.ExistsAsync())
continue;

var folderName = !string.IsNullOrWhiteSpace(file.Classification)
? SanitizeFolderName(file.Classification)
: "Others";

if (!usedNamesPerFolder.ContainsKey(folderName))
usedNamesPerFolder[folderName] = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

var usedNames = usedNamesPerFolder[folderName];
var safeFileName = ResolveDuplicateName(file.FileName, usedNames);

var zipEntryPath = $"{folderName}/{safeFileName}";
var entry = archive.CreateEntry(zipEntryPath);
using var entryStream = entry.Open();
await blobClient.DownloadToAsync(entryStream);
}
}
}
}

// 🔹 ADD ATTACHMENTS NOT LINKED TO EMAILS
if (request.Attachments != null)
{
foreach (var file in request.Attachments)
{
var blobName = GetBlobNameFromUrl(file.BlobPath, containerName);
var blobClient = containerClient.GetBlobClient(blobName);

if (!await blobClient.ExistsAsync())
continue;

var folderName = !string.IsNullOrWhiteSpace(file.Classification)
? SanitizeFolderName(file.Classification)
: "Others";

if (!usedNamesPerFolder.ContainsKey(folderName))
usedNamesPerFolder[folderName] = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

var usedNames = usedNamesPerFolder[folderName];
var safeFileName = ResolveDuplicateName(file.FileName, usedNames);

var zipEntryPath = $"{folderName}/{safeFileName}";
var entry = archive.CreateEntry(zipEntryPath);
using var entryStream = entry.Open();
await blobClient.DownloadToAsync(entryStream);
}
}
}

zipStream.Position = 0;

// ZIP NAME FORMAT
var accountName20 = GetFirst20Characters(request.GroupName);
var timeStamp = DateTime.Now.ToString("yyyyMMdd HHmm");
var zipFileName = $"{accountName20} {request.DocIngestionId} {timeStamp}.zip";

return new DownloadResult
{
Stream = zipStream,
ContentType = "application/zip",
FileName = zipFileName
};
}
private string GetFirst20Characters(string input)
{
if (string.IsNullOrWhiteSpace(input))
return "";

input = input.Trim();

return input.Length <= 20
? input
: input.Substring(0, 20);
}

private string SanitizeFolderName(string folderName)
{
foreach (var invalidChar in Path.GetInvalidFileNameChars())
{
folderName = folderName.Replace(invalidChar, '_');
}

return folderName.Trim();
}

private string GetBlobNameFromUrl(string blobUrl, string containerName)
{
var uri = new Uri(blobUrl);

var prefix = $"/{containerName}/";

if (!uri.AbsolutePath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
throw new Exception($"Blob URL does not match container: {blobUrl}");

var blobPath = uri.AbsolutePath.Substring(prefix.Length);

blobPath = Uri.UnescapeDataString(blobPath);

return blobPath;
}

// Resolve duplicate file names in zip
private string ResolveDuplicateName(string fileName, HashSet<string> usedNames)
{
var originalName = fileName;
var counter = 1;

while (usedNames.Contains(fileName))
{
var name = Path.GetFileNameWithoutExtension(originalName);
var ext = Path.GetExtension(originalName);
fileName = $"{name}_{counter++}{ext}";
}

usedNames.Add(fileName);
return fileName;
}
}

     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.