Add "Download All in ZIP" feature for session downloads

Introduce automatic ZIP file creation and management for session-based downloads.
- Server: Add endpoints to serve and provide info about session ZIPs; VideoService now updates ZIP after each MP3 download with user-friendly filenames.
- Client: Add "Download All in ZIP" button with loading state and ZIP info; trigger browser download via JS interop; responsive and styled UI.
- API: Extend service interfaces for ZIP download/info; add SessionZipInfo model.
- Docs: Update SESSION_MANAGEMENT.md with ZIP workflow, endpoints, and UX details.
- Robust error handling and logging throughout.
This commit is contained in:
Michal Vrba
2025-12-14 11:55:53 +01:00
parent 2d2e855202
commit bf305de75f
7 changed files with 588 additions and 23 deletions
@@ -18,6 +18,108 @@ public class DownloadController : ControllerBase
_sessionService = sessionService;
}
// New endpoint to download session ZIP file
[HttpGet("zip/{sessionId}")]
public IActionResult DownloadSessionZip(string sessionId)
{
if (string.IsNullOrWhiteSpace(sessionId))
{
return BadRequest("Session ID is required");
}
if (!_sessionService.IsValidSession(sessionId))
{
return NotFound("Invalid or expired session");
}
try
{
var sessionDownloadsDir = _sessionService.GetSessionDownloadsPath(sessionId);
if (!Directory.Exists(sessionDownloadsDir))
{
_logger.LogWarning("Session downloads directory not found: {Path}", sessionDownloadsDir);
return NotFound("Session downloads directory not found");
}
var zipFileName = $"session_{sessionId}.zip";
var zipFilePath = Path.Combine(sessionDownloadsDir, zipFileName);
if (!System.IO.File.Exists(zipFilePath))
{
_logger.LogWarning("Session ZIP file not found: {ZipFile}", zipFilePath);
return NotFound("No ZIP file available for this session");
}
_logger.LogInformation("Serving session ZIP file: {ZipFile} for session: {SessionId}", zipFileName, sessionId);
var friendlyZipName = $"TuneRipper_Session_{sessionId.Substring(0, 8)}.zip";
var fileStream = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read);
return File(fileStream, "application/zip", friendlyZipName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error downloading session ZIP for session: {SessionId}", sessionId);
return StatusCode(500, $"Error downloading session ZIP: {ex.Message}");
}
}
// New endpoint to get session ZIP info
[HttpGet("zip/info/{sessionId}")]
public IActionResult GetSessionZipInfo(string sessionId)
{
if (string.IsNullOrWhiteSpace(sessionId))
{
return BadRequest("Session ID is required");
}
if (!_sessionService.IsValidSession(sessionId))
{
return NotFound("Invalid or expired session");
}
try
{
var sessionDownloadsDir = _sessionService.GetSessionDownloadsPath(sessionId);
if (!Directory.Exists(sessionDownloadsDir))
{
return NotFound("Session downloads directory not found");
}
var zipFileName = $"session_{sessionId}.zip";
var zipFilePath = Path.Combine(sessionDownloadsDir, zipFileName);
if (!System.IO.File.Exists(zipFilePath))
{
return NotFound("No ZIP file available for this session");
}
var fileInfo = new FileInfo(zipFilePath);
var mp3Count = Directory.GetFiles(sessionDownloadsDir, "*.mp3").Length;
var info = new
{
sessionId,
zipFileName,
fileSize = FormatFileSize(fileInfo.Length),
fileSizeBytes = fileInfo.Length,
mp3FilesCount = mp3Count,
createdAt = fileInfo.CreationTime,
lastModified = fileInfo.LastWriteTime,
downloadUrl = $"/api/download/zip/{sessionId}"
};
return Ok(info);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting session ZIP info for session: {SessionId}", sessionId);
return StatusCode(500, $"Error getting session ZIP info: {ex.Message}");
}
}
// New session-aware download endpoint
[HttpGet("{sessionId}/{jobId}")]
public IActionResult DownloadFileBySession(string sessionId, string jobId)
+12
View File
@@ -66,9 +66,20 @@ app.MapGet("/", (IWebHostEnvironment env) => new
get_result = "/api/video/result/{jobId}",
download = "/api/download/{jobId}",
download_by_session = "/api/download/{sessionId}/{jobId}",
download_session_zip = "/api/download/zip/{sessionId}",
session_zip_info = "/api/download/zip/info/{sessionId}",
session_create = "/api/session/create",
session_validate = "/api/session/validate/{sessionId}",
static_files = "/downloads/{fileName}",
openapi = "/openapi/v1.json"
},
features = new
{
session_management = true,
automatic_zip_creation = true,
session_based_organization = true,
backward_compatibility = true
},
testing = new
{
httpFile = "Use api-tests.http to test endpoints",
@@ -88,5 +99,6 @@ app.Logger.LogInformation("?? Health check: /api/health");
app.Logger.LogInformation("?? API info: /");
app.Logger.LogInformation("?? Static files served from: /downloads/*");
app.Logger.LogInformation("?? Session-based downloads supported");
app.Logger.LogInformation("?? Automatic ZIP file creation enabled");
app.Run();
+91
View File
@@ -5,6 +5,7 @@ using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Text;
using System.IO.Compression;
namespace TuneRipper.Api.Services;
@@ -206,6 +207,9 @@ public class VideoService : IVideoService
_logger.LogInformation("Successfully processed video. Job: {JobId}, Session: {SessionId}, File: {FileName}", jobId, sessionId, finalFileName);
// Update the session ZIP file after successful download
await UpdateSessionZipAsync(sessionId, downloadDir);
progressCallback(100, "Processing completed successfully");
return finalFileName;
@@ -218,6 +222,93 @@ public class VideoService : IVideoService
}
}
private async Task UpdateSessionZipAsync(string sessionId, string sessionDir)
{
try
{
var zipFileName = $"session_{sessionId}.zip";
var zipFilePath = Path.Combine(sessionDir, zipFileName);
// Get all MP3 files in the session directory
var mp3Files = Directory.GetFiles(sessionDir, "*.mp3")
.Where(f => !f.EndsWith(zipFileName)) // Exclude the ZIP file itself
.ToArray();
if (mp3Files.Length == 0)
{
_logger.LogWarning("No MP3 files found to add to ZIP for session: {SessionId}", sessionId);
return;
}
// Delete existing ZIP file if it exists
if (File.Exists(zipFilePath))
{
File.Delete(zipFilePath);
}
// Create new ZIP file with all MP3 files
using (var archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
{
foreach (var mp3File in mp3Files)
{
var fileName = Path.GetFileName(mp3File);
// Create user-friendly filename for ZIP entry
var friendlyFileName = CreateUserFriendlyFileName(fileName);
// Add file to ZIP
archive.CreateEntryFromFile(mp3File, friendlyFileName);
}
}
_logger.LogInformation("Updated session ZIP file: {ZipFile} with {Count} MP3 files for session: {SessionId}",
zipFileName, mp3Files.Length, sessionId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating session ZIP file for session: {SessionId}", sessionId);
// Don't throw - ZIP creation failure shouldn't break the main process
}
}
private string CreateUserFriendlyFileName(string originalFileName)
{
try
{
// Parse our pattern: jobId_title.ext
var nameWithoutExt = Path.GetFileNameWithoutExtension(originalFileName);
var extension = Path.GetExtension(originalFileName);
// Split by underscore - first part is job ID, rest is title
var underscoreIndex = nameWithoutExt.IndexOf('_');
if (underscoreIndex > 0 && underscoreIndex < nameWithoutExt.Length - 1)
{
// Extract title part (everything after the first underscore)
var titlePart = nameWithoutExt.Substring(underscoreIndex + 1);
// Convert underscores back to spaces in title
var friendlyTitle = titlePart.Replace("_", " ");
// Create a clean filename: "Title.mp3"
if (friendlyTitle.Length > 0)
{
// Remove any duplicate spaces and clean up
friendlyTitle = System.Text.RegularExpressions.Regex.Replace(friendlyTitle, @"\s+", " ").Trim();
return $"{friendlyTitle}{extension}";
}
}
// Fallback to original filename if pattern doesn't match
return originalFileName;
}
catch (Exception)
{
// If anything goes wrong, return the original filename
return originalFileName;
}
}
private string SanitizeFileName(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))