Improve API base URL handling for downloads and logging

Refactored API and Blazor client to dynamically construct download URLs using the configured API base URL instead of hardcoded localhost addresses. Enhanced root endpoint and startup logs to reflect environment-specific URLs. Added GetBaseUrl() to ITuneRipperApiService for consistent URL generation.
This commit is contained in:
Michal Vrba
2025-12-16 14:46:05 +01:00
parent 879fbd4a53
commit 471010c536
3 changed files with 100 additions and 58 deletions
+35 -15
View File
@@ -1,4 +1,4 @@
using TuneRipper.Api.Services; using TuneRipper.Api.Services;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -45,7 +45,22 @@ app.UseCors("BlazorPolicy");
app.UseAuthorization(); app.UseAuthorization();
// Add root endpoint with startup info // Add root endpoint with startup info
app.MapGet("/", (IWebHostEnvironment env) => new app.MapGet("/", (IWebHostEnvironment env, HttpContext context) =>
{
// Get the current request's base URL
var request = context.Request;
var baseUrl = $"{request.Scheme}://{request.Host}";
// Determine URLs based on environment
var httpsUrl = app.Environment.IsDevelopment()
? "https://localhost:7160"
: baseUrl;
var httpUrl = app.Environment.IsDevelopment()
? "http://localhost:5112"
: baseUrl.Replace("https://", "http://");
return new
{ {
service = "TuneRipper API", service = "TuneRipper API",
version = "1.0.0", version = "1.0.0",
@@ -54,8 +69,8 @@ app.MapGet("/", (IWebHostEnvironment env) => new
environment = env.EnvironmentName, environment = env.EnvironmentName,
urls = new urls = new
{ {
https = "https://localhost:7160", https = httpsUrl,
http = "http://localhost:5112" http = httpUrl
}, },
endpoints = new endpoints = new
{ {
@@ -85,20 +100,25 @@ app.MapGet("/", (IWebHostEnvironment env) => new
httpFile = "Use api-tests.http to test endpoints", httpFile = "Use api-tests.http to test endpoints",
startWith = "GET /api/health to verify API is running" startWith = "GET /api/health to verify API is running"
} }
};
}); });
app.MapControllers(); app.MapControllers();
// Log startup information // Log startup information with dynamic URLs
app.Logger.LogInformation("?? TuneRipper API is starting..."); var isDevelopment = app.Environment.IsDevelopment();
app.Logger.LogInformation("?? Environment: {Environment}", app.Environment.EnvironmentName); var httpsLogUrl = isDevelopment ? "https://localhost:7160" : "[Production HTTPS URL]";
app.Logger.LogInformation("?? API will be available at:"); var httpLogUrl = isDevelopment ? "http://localhost:5112" : "[Production HTTP URL]";
app.Logger.LogInformation(" ?? HTTPS: https://localhost:7160");
app.Logger.LogInformation(" ?? HTTP: http://localhost:5112"); app.Logger.LogInformation("🚀 TuneRipper API is starting...");
app.Logger.LogInformation("?? Health check: /api/health"); app.Logger.LogInformation("🌍 Environment: {Environment}", app.Environment.EnvironmentName);
app.Logger.LogInformation("?? API info: /"); app.Logger.LogInformation("🌐 API will be available at:");
app.Logger.LogInformation("?? Static files served from: /downloads/*"); app.Logger.LogInformation(" 🔒 HTTPS: {HttpsUrl}", httpsLogUrl);
app.Logger.LogInformation("?? Session-based downloads supported"); app.Logger.LogInformation(" 🔓 HTTP: {HttpUrl}", httpLogUrl);
app.Logger.LogInformation("?? Automatic ZIP file creation enabled"); 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(); app.Run();
+16 -8
View File
@@ -428,8 +428,9 @@
Logger.LogInformation("Downloading session ZIP for session: {SessionId}", currentSessionId); Logger.LogInformation("Downloading session ZIP for session: {SessionId}", currentSessionId);
// Create the download URL for the ZIP file // Create the download URL for the ZIP file using the configured API base URL
var zipDownloadUrl = $"https://localhost:7160/api/download/zip/{currentSessionId}"; var baseUrl = ApiService.GetBaseUrl();
var zipDownloadUrl = $"{baseUrl}/api/download/zip/{currentSessionId}";
// Use browser to download the ZIP file // Use browser to download the ZIP file
await JSRuntime.InvokeVoidAsync("open", zipDownloadUrl, "_blank"); await JSRuntime.InvokeVoidAsync("open", zipDownloadUrl, "_blank");
@@ -628,17 +629,24 @@
// Use the actual video title from API // Use the actual video title from API
string title = currentVideoDetails?.Title ?? result.VideoDetails?.Title ?? ExtractTitleFromUrl(youtubeUrl); string title = currentVideoDetails?.Title ?? result.VideoDetails?.Title ?? ExtractTitleFromUrl(youtubeUrl);
// Create the session-aware download URL // Create the session-aware download URL using the configured API base URL
string downloadUrl; string downloadUrl;
if (!string.IsNullOrEmpty(result.DownloadUrl) && result.DownloadUrl.Contains(sessionId)) if (!string.IsNullOrEmpty(result.DownloadUrl) && result.DownloadUrl.StartsWith("http"))
{ {
// Server provided a session-aware download URL // Server provided a full download URL
downloadUrl = result.DownloadUrl.StartsWith("http") ? result.DownloadUrl : $"https://localhost:7160{result.DownloadUrl}"; downloadUrl = result.DownloadUrl;
}
else if (!string.IsNullOrEmpty(result.DownloadUrl) && result.DownloadUrl.StartsWith("/"))
{
// Server provided a relative URL, make it absolute using the API base URL
var baseUrl = ApiService.GetBaseUrl();
downloadUrl = $"{baseUrl}{result.DownloadUrl}";
} }
else else
{ {
// Construct session-aware download URL // Construct session-aware download URL using the API base URL
downloadUrl = $"https://localhost:7160/api/download/{sessionId}/{jobId}"; var baseUrl = ApiService.GetBaseUrl();
downloadUrl = $"{baseUrl}/api/download/{sessionId}/{jobId}";
} }
downloadLinks.Add(new DownloadItem downloadLinks.Add(new DownloadItem
@@ -22,6 +22,10 @@ public interface ITuneRipperApiService
Task<string?> CreateSessionAsync(); Task<string?> CreateSessionAsync();
Task<bool> ValidateSessionAsync(string sessionId); Task<bool> ValidateSessionAsync(string sessionId);
Task<bool> RefreshSessionAsync(string sessionId); Task<bool> RefreshSessionAsync(string sessionId);
// Add methods to get base URL for constructing download URLs
string GetBaseUrl();
Task<HttpClient> GetHttpClientAsync();
} }
public class SessionZipInfo public class SessionZipInfo
@@ -580,4 +584,14 @@ public class TuneRipperApiService : ITuneRipperApiService
return false; return false;
} }
} }
public string GetBaseUrl()
{
return _httpClient.BaseAddress?.ToString().TrimEnd('/') ?? "https://localhost:7160";
}
public Task<HttpClient> GetHttpClientAsync()
{
return Task.FromResult(_httpClient);
}
} }