Add editorconfig and analyzers, format backend code

This commit is contained in:
2026-09-24 04:54:17 +02:00
parent 87c3f97529
commit c8fe28b07b
367 changed files with 12179 additions and 12459 deletions
@@ -1,248 +1,247 @@
using Microsoft.Extensions.Logging;
using Musify.Application.Contracts;
using Musify.Infrastructure.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using Musify.Application.Contracts;
using Musify.Infrastructure.Configuration;
namespace Musify.Infrastructure.Services
namespace Musify.Infrastructure.Services;
public partial class AudioService(ILogger<AudioService> logger,
AudioConfiguration audioConfiguration)
: IAudioTranscoderService
{
public partial class AudioService(ILogger<AudioService> logger,
AudioConfiguration audioConfiguration)
: IAudioTranscoderService
private record FfmpegExecutionResult(int ExitCode, string StandardOutput, string StandardError);
[GeneratedRegex(@"Duration:\s*(\d+):(\d{2}):(\d{2}(?:\.\d+)?)", RegexOptions.IgnoreCase)]
private static partial Regex DurationRegex();
public async Task<AudioTranscodeResult> TranscodeToAudioFileAsync(Stream audioStream, string destinationPath, CancellationToken cancellationToken)
{
record FfmpegExecutionResult(int ExitCode, string StandardOutput, string StandardError);
[GeneratedRegex(@"Duration:\s*(\d+):(\d{2}):(\d{2}(?:\.\d+)?)", RegexOptions.IgnoreCase)]
private static partial Regex DurationRegex();
public async Task<AudioTranscodeResult> TranscodeToAudioFileAsync(Stream audioStream, string destinationPath, CancellationToken cancellationToken)
try
{
try
{
Directory.CreateDirectory(destinationPath);
Directory.CreateDirectory(destinationPath);
logger.LogInformation("Starting audio transcoding for {DestinationPath}", destinationPath);
logger.LogInformation("Starting audio transcoding for {DestinationPath}", destinationPath);
var executionResult = await ExecuteFfmpegWithInputAsync(
BuildAudioFileArguments(destinationPath, audioConfiguration.Ffmpeg),
destinationPath,
audioStream,
"TranscodeToAudioFile",
cancellationToken);
if (executionResult.ExitCode != 0)
{
logger.LogError("Audio transcoding failed with exit code {ExitCode}. Output: {StandardOutput}, Error: {StandardError}",
executionResult.ExitCode, executionResult.StandardOutput, executionResult.StandardError);
return new AudioTranscodeResult(executionResult.ExitCode, TimeSpan.Zero);
}
logger.LogInformation("Audio transcoding completed for {DestinationPath}", destinationPath);
var outputPath = Path.Combine(destinationPath, audioConfiguration.Ffmpeg.OutputFileName);
var duration = await GetAudioDurationAsync(outputPath, cancellationToken);
return new AudioTranscodeResult(executionResult.ExitCode, duration);
}
catch (TimeoutException timeoutException)
{
logger.LogError(timeoutException, "Audio transcoding timed out after {Timeout} for {DestinationPath}", audioConfiguration.TranscodingTimeout, destinationPath);
throw;
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to transcode audio for {DestinationPath}", destinationPath);
throw;
}
}
async Task<TimeSpan> GetAudioDurationAsync(string filePath, CancellationToken cancellationToken)
{
var executionResult = await ExecuteFfmpegAsync(
BuildProbeDurationArguments(filePath),
Path.GetDirectoryName(filePath) ?? Environment.CurrentDirectory,
"ProbeAudioDuration",
var executionResult = await ExecuteFfmpegWithInputAsync(
BuildAudioFileArguments(destinationPath, audioConfiguration.Ffmpeg),
destinationPath,
audioStream,
"TranscodeToAudioFile",
cancellationToken);
var match = DurationRegex().Match(executionResult.StandardError);
if (!match.Success)
throw new InvalidOperationException($"Could not determine audio duration for {filePath}.");
if (executionResult.ExitCode != 0)
{
logger.LogError("Audio transcoding failed with exit code {ExitCode}. Output: {StandardOutput}, Error: {StandardError}",
executionResult.ExitCode, executionResult.StandardOutput, executionResult.StandardError);
return new AudioTranscodeResult(executionResult.ExitCode, TimeSpan.Zero);
}
var hours = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
var minutes = int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
var seconds = double.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture);
logger.LogInformation("Audio transcoding completed for {DestinationPath}", destinationPath);
return new TimeSpan(hours, minutes, 0) + TimeSpan.FromSeconds(seconds);
var outputPath = Path.Combine(destinationPath, audioConfiguration.Ffmpeg.OutputFileName);
var duration = await GetAudioDurationAsync(outputPath, cancellationToken);
return new AudioTranscodeResult(executionResult.ExitCode, duration);
}
public async Task<bool> IsValidAudioFileAsync(string filePath, CancellationToken cancellationToken)
catch (TimeoutException timeoutException)
{
if (!File.Exists(filePath))
{
logger.LogWarning("Audio validation requested for non-existing file {FilePath}", filePath);
return false;
}
logger.LogError(timeoutException, "Audio transcoding timed out after {Timeout} for {DestinationPath}", audioConfiguration.TranscodingTimeout, destinationPath);
throw;
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to transcode audio for {DestinationPath}", destinationPath);
throw;
}
}
try
{
logger.LogDebug("Validating audio file {FilePath}", filePath);
private async Task<TimeSpan> GetAudioDurationAsync(string filePath, CancellationToken cancellationToken)
{
var executionResult = await ExecuteFfmpegAsync(
BuildProbeDurationArguments(filePath),
Path.GetDirectoryName(filePath) ?? Environment.CurrentDirectory,
"ProbeAudioDuration",
cancellationToken);
var executionResult = await ExecuteFfmpegAsync(
BuildValidateAudioArguments(filePath),
Path.GetDirectoryName(filePath) ?? Environment.CurrentDirectory,
"ValidateAudioFile",
cancellationToken);
var match = DurationRegex().Match(executionResult.StandardError);
if (!match.Success)
throw new InvalidOperationException($"Could not determine audio duration for {filePath}.");
var isValid = executionResult.ExitCode == 0;
if (!isValid)
{
logger.LogWarning("Audio validation failed for {FilePath}: {StandardError}", filePath, executionResult.StandardError);
}
else
{
logger.LogDebug("Audio validation successful for {FilePath}", filePath);
}
var hours = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
var minutes = int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
var seconds = double.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture);
return isValid;
}
catch (TimeoutException timeoutException)
{
logger.LogError(timeoutException, "Audio validation timed out for {FilePath}", filePath);
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to validate audio file {FilePath}", filePath);
}
return new TimeSpan(hours, minutes, 0) + TimeSpan.FromSeconds(seconds);
}
public async Task<bool> IsValidAudioFileAsync(string filePath, CancellationToken cancellationToken)
{
if (!File.Exists(filePath))
{
logger.LogWarning("Audio validation requested for non-existing file {FilePath}", filePath);
return false;
}
async Task<FfmpegExecutionResult> ExecuteFfmpegWithInputAsync(
string arguments,
string workingDirectory,
Stream inputStream,
string operationName,
CancellationToken cancellationToken)
try
{
using var process = BuildProcess(arguments, workingDirectory, redirectStandardInput: true);
process.Start();
logger.LogDebug("Validating audio file {FilePath}", filePath);
logger.LogDebug("[{Operation}] ffmpeg started (PID: {ProcessId} ) in {WorkingDirectory}", operationName, process.Id, workingDirectory);
var executionResult = await ExecuteFfmpegAsync(
BuildValidateAudioArguments(filePath),
Path.GetDirectoryName(filePath) ?? Environment.CurrentDirectory,
"ValidateAudioFile",
cancellationToken);
var outputTask = process.StandardOutput.ReadToEndAsync(cancellationToken);
var errorTask = process.StandardError.ReadToEndAsync(cancellationToken);
if (inputStream.CanSeek)
inputStream.Position = 0;
await inputStream.CopyToAsync(process.StandardInput.BaseStream, cancellationToken);
process.StandardInput.Close();
return await WaitForProcessResultAsync(process, outputTask, errorTask, operationName, cancellationToken);
}
async Task<FfmpegExecutionResult> ExecuteFfmpegAsync(
string arguments,
string workingDirectory,
string operationName,
CancellationToken cancellationToken)
{
using var process = BuildProcess(arguments, workingDirectory, redirectStandardInput: false);
process.Start();
logger.LogDebug("[{Operation}] ffmpeg started (PID: {ProcessId} ) in {WorkingDirectory}", operationName, process.Id, workingDirectory);
var outputTask = process.StandardOutput.ReadToEndAsync(cancellationToken);
var errorTask = process.StandardError.ReadToEndAsync(cancellationToken);
return await WaitForProcessResultAsync(process, outputTask, errorTask, operationName, cancellationToken);
}
Process BuildProcess(string arguments, string workingDirectory, bool redirectStandardInput)
=> new()
var isValid = executionResult.ExitCode == 0;
if (!isValid)
{
StartInfo = new ProcessStartInfo
{
FileName = audioConfiguration.Ffmpeg.ExecutableName,
WorkingDirectory = workingDirectory,
Arguments = arguments,
RedirectStandardInput = redirectStandardInput,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
async Task<FfmpegExecutionResult> WaitForProcessResultAsync(
Process process,
Task<string> outputTask,
Task<string> errorTask,
string operationName,
CancellationToken cancellationToken)
{
using var linkedCancellationTokens = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
linkedCancellationTokens.CancelAfter(audioConfiguration.TranscodingTimeout);
try
{
await process.WaitForExitAsync(linkedCancellationTokens.Token);
logger.LogWarning("Audio validation failed for {FilePath}: {StandardError}", filePath, executionResult.StandardError);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
else
{
logger.LogError("[{Operation}] ffmpeg timed out after {Timeout} (PID: {ProcessId} )",
operationName, audioConfiguration.TranscodingTimeout, process.Id);
TryKillProcess(process);
throw new TimeoutException($"ffmpeg execution exceeded timeout {audioConfiguration.TranscodingTimeout}.");
logger.LogDebug("Audio validation successful for {FilePath}", filePath);
}
var standardError = await errorTask;
var standardOutput = await outputTask;
logger.LogDebug("[{Operation}] ffmpeg finished (PID: {ProcessId} ). Exit code: {ExitCode}, Output: {OutputLength}B, Error: {ErrorLength}B",
operationName, process.Id, process.ExitCode, standardOutput.Length, standardError.Length);
return new FfmpegExecutionResult(process.ExitCode, standardOutput, standardError);
return isValid;
}
void TryKillProcess(Process process)
catch (TimeoutException timeoutException)
{
try
{
if (!process.HasExited)
process.Kill();
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to kill ffmpeg process (PID: {ProcessId} )", process.Id);
}
logger.LogError(timeoutException, "Audio validation timed out for {FilePath}", filePath);
}
static string BuildAudioFileArguments(string outputDirectory, FfmpegConfiguration ffmpegConfiguration)
catch (Exception exception)
{
var outputPath = Path.Combine(outputDirectory, ffmpegConfiguration.OutputFileName);
var additionalArguments = string.IsNullOrWhiteSpace(ffmpegConfiguration.AdditionalArguments)
? string.Empty
: $" {ffmpegConfiguration.AdditionalArguments.Trim()}";
return "-y -hide_banner -loglevel error " +
"-i pipe:0 " +
"-vn " +
"-map 0:a " +
$"-c:a {ffmpegConfiguration.AudioCodec} " +
$"-b:a {ffmpegConfiguration.AudioBitrate} " +
$"-ac {ffmpegConfiguration.AudioChannels} " +
$"-ar {ffmpegConfiguration.AudioSampleRate} " +
$"-profile:a {ffmpegConfiguration.AudioProfile} " +
"-movflags +faststart" +
additionalArguments +
$" \"{outputPath}\"";
logger.LogError(exception, "Failed to validate audio file {FilePath}", filePath);
}
static string BuildValidateAudioArguments(string filePath)
=> $"-v error -i \"{filePath}\" -map 0:a:0 -f null -";
static string BuildProbeDurationArguments(string filePath)
=> $"-hide_banner -i \"{filePath}\" -f null -";
return false;
}
}
private async Task<FfmpegExecutionResult> ExecuteFfmpegWithInputAsync(
string arguments,
string workingDirectory,
Stream inputStream,
string operationName,
CancellationToken cancellationToken)
{
using var process = BuildProcess(arguments, workingDirectory, redirectStandardInput: true);
process.Start();
logger.LogDebug("[{Operation}] ffmpeg started (PID: {ProcessId}) in {WorkingDirectory}", operationName, process.Id, workingDirectory);
var outputTask = process.StandardOutput.ReadToEndAsync(cancellationToken);
var errorTask = process.StandardError.ReadToEndAsync(cancellationToken);
if (inputStream.CanSeek)
inputStream.Position = 0;
await inputStream.CopyToAsync(process.StandardInput.BaseStream, cancellationToken);
process.StandardInput.Close();
return await WaitForProcessResultAsync(process, outputTask, errorTask, operationName, cancellationToken);
}
private async Task<FfmpegExecutionResult> ExecuteFfmpegAsync(
string arguments,
string workingDirectory,
string operationName,
CancellationToken cancellationToken)
{
using var process = BuildProcess(arguments, workingDirectory, redirectStandardInput: false);
process.Start();
logger.LogDebug("[{Operation}] ffmpeg started (PID: {ProcessId}) in {WorkingDirectory}", operationName, process.Id, workingDirectory);
var outputTask = process.StandardOutput.ReadToEndAsync(cancellationToken);
var errorTask = process.StandardError.ReadToEndAsync(cancellationToken);
return await WaitForProcessResultAsync(process, outputTask, errorTask, operationName, cancellationToken);
}
private Process BuildProcess(string arguments, string workingDirectory, bool redirectStandardInput)
=> new()
{
StartInfo = new ProcessStartInfo
{
FileName = audioConfiguration.Ffmpeg.ExecutableName,
WorkingDirectory = workingDirectory,
Arguments = arguments,
RedirectStandardInput = redirectStandardInput,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
private async Task<FfmpegExecutionResult> WaitForProcessResultAsync(
Process process,
Task<string> outputTask,
Task<string> errorTask,
string operationName,
CancellationToken cancellationToken)
{
using var linkedCancellationTokens = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
linkedCancellationTokens.CancelAfter(audioConfiguration.TranscodingTimeout);
try
{
await process.WaitForExitAsync(linkedCancellationTokens.Token);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
logger.LogError("[{Operation}] ffmpeg timed out after {Timeout} (PID: {ProcessId})",
operationName, audioConfiguration.TranscodingTimeout, process.Id);
TryKillProcess(process);
throw new TimeoutException($"ffmpeg execution exceeded timeout {audioConfiguration.TranscodingTimeout}.");
}
var standardError = await errorTask;
var standardOutput = await outputTask;
logger.LogDebug("[{Operation}] ffmpeg finished (PID: {ProcessId}). Exit code: {ExitCode}, Output: {OutputLength}B, Error: {ErrorLength}B",
operationName, process.Id, process.ExitCode, standardOutput.Length, standardError.Length);
return new FfmpegExecutionResult(process.ExitCode, standardOutput, standardError);
}
private void TryKillProcess(Process process)
{
try
{
if (!process.HasExited)
process.Kill();
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to kill ffmpeg process (PID: {ProcessId})", process.Id);
}
}
private static string BuildAudioFileArguments(string outputDirectory, FfmpegConfiguration ffmpegConfiguration)
{
var outputPath = Path.Combine(outputDirectory, ffmpegConfiguration.OutputFileName);
var additionalArguments = string.IsNullOrWhiteSpace(ffmpegConfiguration.AdditionalArguments)
? string.Empty
: $" {ffmpegConfiguration.AdditionalArguments.Trim()}";
return "-y -hide_banner -loglevel error " +
"-i pipe:0 " +
"-vn " +
"-map 0:a " +
$"-c:a {ffmpegConfiguration.AudioCodec} " +
$"-b:a {ffmpegConfiguration.AudioBitrate} " +
$"-ac {ffmpegConfiguration.AudioChannels} " +
$"-ar {ffmpegConfiguration.AudioSampleRate} " +
$"-profile:a {ffmpegConfiguration.AudioProfile} " +
"-movflags +faststart" +
additionalArguments +
$" \"{outputPath}\"";
}
private static string BuildValidateAudioArguments(string filePath)
=> $"-v error -i \"{filePath}\" -map 0:a:0 -f null -";
private static string BuildProbeDurationArguments(string filePath)
=> $"-hide_banner -i \"{filePath}\" -f null -";
}
@@ -3,38 +3,37 @@ using Musify.Application.Contracts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
namespace Musify.Infrastructure.Services
namespace Musify.Infrastructure.Services;
public class PictureService(ILogger<PictureService> logger)
: IPictureService
{
public class PictureService(ILogger<PictureService> logger)
: IPictureService
public async Task<Stream> ResizePictureAsWebpAsync(Stream pictureStream, int width, int height, CancellationToken cancellationToken)
{
public async Task<Stream> ResizePictureAsWebpAsync(Stream pictureStream, int width, int height, CancellationToken cancellationToken)
try
{
try
logger.LogDebug("Resizing picture to {Width}x{Height}", width, height);
if (pictureStream.CanSeek && pictureStream.Position > 0)
pictureStream.Position = 0;
using var picture = await Image.LoadAsync(pictureStream, cancellationToken);
picture.Mutate(options => options.Resize(new ResizeOptions
{
logger.LogDebug("Resizing picture to {Width}x{Height}", width, height);
if (pictureStream.CanSeek && pictureStream.Position > 0)
pictureStream.Position = 0;
Size = new Size(width, height),
Mode = ResizeMode.Max
}));
using var picture = await Image.LoadAsync(pictureStream, cancellationToken);
picture.Mutate(options => options.Resize(new ResizeOptions
{
Size = new Size(width, height),
Mode = ResizeMode.Max
} ));
var memoryStream = new MemoryStream();
await picture.SaveAsWebpAsync(memoryStream, cancellationToken);
memoryStream.Position = 0;
var memoryStream = new MemoryStream();
await picture.SaveAsWebpAsync(memoryStream, cancellationToken);
memoryStream.Position = 0;
logger.LogDebug("Picture resized to {Width}x{Height}, length: {Length}", width, height, memoryStream.Length);
return memoryStream;
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to resize picture to {Width}x{Height}", width, height);
throw;
}
logger.LogDebug("Picture resized to {Width}x{Height}, length: {Length}", width, height, memoryStream.Length);
return memoryStream;
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to resize picture to {Width}x{Height}", width, height);
throw;
}
}
}
}
@@ -3,108 +3,106 @@ using Hangfire;
using Hangfire.PostgreSql;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Musify.Application.Configuration;
using Musify.Application.Contracts;
using Musify.Infrastructure.Configuration;
using Musify.Infrastructure.Jobs;
using Musify.Application.Contracts;
namespace Musify.Infrastructure.Services
namespace Musify.Infrastructure.Services;
public static class ServicesDependencyInjection
{
public static class ServicesDependencyInjection
public static IServiceCollection AddStorageService(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
public static IServiceCollection AddStorageService(this IServiceCollection serviceDescriptors, IConfiguration configuration)
serviceDescriptors
.AddOptionsWithValidateOnStart<InfrastructureStorageConfiguration>()
.Bind(configuration.GetRequiredSection(InfrastructureStorageConfiguration.SectionName))
.ValidateDataAnnotations();
serviceDescriptors.AddSingleton(serviceProvider =>
serviceProvider.GetRequiredService<IOptions<InfrastructureStorageConfiguration>>().Value);
serviceDescriptors.AddSingleton<IAmazonS3>(serviceProvider =>
{
serviceDescriptors
.AddOptionsWithValidateOnStart<InfrastructureStorageConfiguration>()
.Bind(configuration.GetRequiredSection(InfrastructureStorageConfiguration.SectionName))
.ValidateDataAnnotations();
serviceDescriptors.AddSingleton(serviceProvider =>
serviceProvider.GetRequiredService<IOptions<InfrastructureStorageConfiguration>>().Value);
serviceDescriptors.AddSingleton<IAmazonS3>(serviceProvider =>
var configuration = serviceProvider.GetRequiredService<InfrastructureStorageConfiguration>();
var s3Configuration = new AmazonS3Config
{
var configuration = serviceProvider.GetRequiredService<InfrastructureStorageConfiguration>();
var s3Configuration = new AmazonS3Config
{
ServiceURL = configuration.Address,
ForcePathStyle = configuration.ForcePathStyle,
UseHttp = configuration.UseHttp,
};
return new AmazonS3Client(configuration.AccessKey, configuration.SecretAccessKey, s3Configuration);
} );
ServiceURL = configuration.Address,
ForcePathStyle = configuration.ForcePathStyle,
UseHttp = configuration.UseHttp,
};
return new AmazonS3Client(configuration.AccessKey, configuration.SecretAccessKey, s3Configuration);
});
serviceDescriptors.AddScoped<IStorageService, StorageService>();
return serviceDescriptors;
}
public static IServiceCollection AddPictureService(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors.AddScoped<IPictureService, PictureService>();
return serviceDescriptors;
}
public static IServiceCollection AddUploadIntentConfiguration(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors.AddValidatedOptions<UploadIntentConfiguration>(configuration, UploadIntentConfiguration.SectionName);
return serviceDescriptors;
}
public static IServiceCollection AddUploadIntentJobs(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors.AddUploadIntentConfiguration(configuration);
serviceDescriptors.AddHostedService<UploadIntentExpirationJob>();
serviceDescriptors.AddHostedService<TemporalUploadsCleanUpJob>();
return serviceDescriptors;
}
public static IServiceCollection AddDailyMixGenerationJob(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors.AddHangfire((serviceProvider, hangfireConfiguration) =>
{
var databaseConfiguration = serviceProvider.GetRequiredService<DatabaseConfiguration>();
hangfireConfiguration.UsePostgreSqlStorage(options =>
options.UseNpgsqlConnection(databaseConfiguration.ConnectionString));
});
serviceDescriptors.AddHangfireServer();
serviceDescriptors.AddScoped<DailyMixGenerationJob>();
serviceDescriptors.AddScoped<ListeningHistoryCleanupJob>();
return serviceDescriptors;
}
public static IServiceCollection AddStreamTicketService(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors
.AddOptionsWithValidateOnStart<StreamTicketConfiguration>()
.Bind(configuration.GetRequiredSection(StreamTicketConfiguration.SectionName))
.ValidateDataAnnotations();
serviceDescriptors.AddSingleton(serviceProvider =>
serviceProvider.GetRequiredService<IOptions<StreamTicketConfiguration>>().Value);
serviceDescriptors.AddSingleton<IStreamTicketService, StreamTicketService>();
return serviceDescriptors;
}
public static IServiceCollection AddAudioTranscoder(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors
.AddOptionsWithValidateOnStart<AudioConfiguration>()
.Bind(configuration.GetRequiredSection(AudioConfiguration.SectionName))
.ValidateDataAnnotations();
serviceDescriptors.AddSingleton(serviceProvider =>
serviceProvider.GetRequiredService<IOptions<AudioConfiguration>>().Value);
serviceDescriptors.AddScoped<IAudioTranscoderService, AudioService>();
return serviceDescriptors;
}
serviceDescriptors.AddScoped<IStorageService, StorageService>();
return serviceDescriptors;
}
}
public static IServiceCollection AddPictureService(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors.AddScoped<IPictureService, PictureService>();
return serviceDescriptors;
}
public static IServiceCollection AddUploadIntentConfiguration(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors.AddValidatedOptions<UploadIntentConfiguration>(configuration, UploadIntentConfiguration.SectionName);
return serviceDescriptors;
}
public static IServiceCollection AddUploadIntentJobs(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors.AddUploadIntentConfiguration(configuration);
serviceDescriptors.AddHostedService<UploadIntentExpirationJob>();
serviceDescriptors.AddHostedService<TemporalUploadsCleanUpJob>();
return serviceDescriptors;
}
public static IServiceCollection AddDailyMixGenerationJob(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors.AddHangfire((serviceProvider, hangfireConfiguration) =>
{
var databaseConfiguration = serviceProvider.GetRequiredService<DatabaseConfiguration>();
hangfireConfiguration.UsePostgreSqlStorage(options =>
options.UseNpgsqlConnection(databaseConfiguration.ConnectionString));
});
serviceDescriptors.AddHangfireServer();
serviceDescriptors.AddScoped<DailyMixGenerationJob>();
serviceDescriptors.AddScoped<ListeningHistoryCleanupJob>();
return serviceDescriptors;
}
public static IServiceCollection AddStreamTicketService(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors
.AddOptionsWithValidateOnStart<StreamTicketConfiguration>()
.Bind(configuration.GetRequiredSection(StreamTicketConfiguration.SectionName))
.ValidateDataAnnotations();
serviceDescriptors.AddSingleton(serviceProvider =>
serviceProvider.GetRequiredService<IOptions<StreamTicketConfiguration>>().Value);
serviceDescriptors.AddSingleton<IStreamTicketService, StreamTicketService>();
return serviceDescriptors;
}
public static IServiceCollection AddAudioTranscoder(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors
.AddOptionsWithValidateOnStart<AudioConfiguration>()
.Bind(configuration.GetRequiredSection(AudioConfiguration.SectionName))
.ValidateDataAnnotations();
serviceDescriptors.AddSingleton(serviceProvider =>
serviceProvider.GetRequiredService<IOptions<AudioConfiguration>>().Value);
serviceDescriptors.AddScoped<IAudioTranscoderService, AudioService>();
return serviceDescriptors;
}
}
@@ -2,40 +2,39 @@ using System.Collections.Concurrent;
using ErrorOr;
using Microsoft.Extensions.Caching.Memory;
namespace Musify.Infrastructure.Services
namespace Musify.Infrastructure.Services;
public sealed class SingleFlightCache(IMemoryCache cache)
{
public sealed class SingleFlightCache(IMemoryCache cache)
private readonly ConcurrentDictionary<string, object> inFlight = new();
public async Task<ErrorOr<TValue>> GetOrCreateAsync<TValue>(
string key,
TimeSpan duration,
Func<Task<ErrorOr<TValue>>> factory)
{
private readonly ConcurrentDictionary<string, object> inFlight = new();
if (duration <= TimeSpan.Zero)
return await factory();
public async Task<ErrorOr<TValue>> GetOrCreateAsync<TValue>(
string key,
TimeSpan duration,
Func<Task<ErrorOr<TValue>>> factory)
if (cache.TryGetValue(key, out TValue? cached) && cached != null)
return cached;
var pending = (Lazy<Task<ErrorOr<TValue>>>)inFlight.GetOrAdd(
key,
_ => new Lazy<Task<ErrorOr<TValue>>>(factory));
try
{
if (duration <= TimeSpan.Zero)
return await factory();
var result = await pending.Value;
if (cache.TryGetValue(key, out TValue? cached) && cached != null)
return cached;
if (!result.IsError)
cache.Set(key, result.Value, duration);
var pending = (Lazy<Task<ErrorOr<TValue>>>)inFlight.GetOrAdd(
key,
_ => new Lazy<Task<ErrorOr<TValue>>>(factory));
try
{
var result = await pending.Value;
if (!result.IsError)
cache.Set(key, result.Value, duration);
return result;
}
finally
{
inFlight.TryRemove(key, out _);
}
return result;
}
finally
{
inFlight.TryRemove(key, out _);
}
}
}
@@ -9,186 +9,121 @@ using Musify.Domain.ValueObjects;
using Musify.Infrastructure.Configuration;
using ObjectMetaData = Musify.Application.Contracts.ObjectMetaData;
namespace Musify.Infrastructure.Services
namespace Musify.Infrastructure.Services;
public class StorageService(IDatabase database, IAmazonS3 amazonS3, ILogger<StorageService> logger,
InfrastructureStorageConfiguration storageClientConfiguration)
: IStorageService
{
public class StorageService(IDatabase database, IAmazonS3 amazonS3, ILogger<StorageService> logger,
InfrastructureStorageConfiguration storageClientConfiguration)
: IStorageService
public async Task<Stream> GetFileAsync(string bucket, string key, CancellationToken cancellationToken)
{
public async Task<Stream> GetFileAsync(string bucket, string key, CancellationToken cancellationToken)
var request = new GetObjectRequest
{
var request = new GetObjectRequest
{
BucketName = bucket,
Key = key,
};
BucketName = bucket,
Key = key,
};
try
{
var response = await amazonS3.GetObjectAsync(request, cancellationToken);
logger.LogDebug("Retrieved file from S3 {Bucket}/{Key}", bucket, key);
return response.ResponseStream;
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to get file from S3 {Bucket}/{Key}", bucket, key);
throw;
}
try
{
var response = await amazonS3.GetObjectAsync(request, cancellationToken);
logger.LogDebug("Retrieved file from S3 {Bucket}/{Key}", bucket, key);
return response.ResponseStream;
}
public async Task<string> GetUrlAsync(string bucket, string key, TimeSpan expirationTime, CancellationToken cancellationToken)
catch (Exception exception)
{
var request = new GetPreSignedUrlRequest
{
BucketName = bucket,
Key = key,
Expires = DateTime.UtcNow + expirationTime,
Protocol = storageClientConfiguration.UseHttp ? Protocol.HTTP : Protocol.HTTPS
};
logger.LogDebug("Generating pre-signed URL for {Bucket}/{Key}", bucket, key);
return await amazonS3.GetPreSignedURLAsync(request);
logger.LogError(exception, "Failed to get file from S3 {Bucket}/{Key}", bucket, key);
throw;
}
}
public async Task<string> GetUploadUrlAsync(
string bucket,
string key,
string contentType,
TimeSpan expirationTime,
CancellationToken cancellationToken,
bool preventOverwrite = true)
public async Task<string> GetUrlAsync(string bucket, string key, TimeSpan expirationTime, CancellationToken cancellationToken)
{
var request = new GetPreSignedUrlRequest
{
var request = new GetPreSignedUrlRequest
{
BucketName = bucket,
Key = key,
Expires = DateTime.UtcNow + expirationTime,
Protocol = storageClientConfiguration.UseHttp ? Protocol.HTTP : Protocol.HTTPS,
Verb = HttpVerb.PUT,
ContentType = contentType
};
BucketName = bucket,
Key = key,
Expires = DateTime.UtcNow + expirationTime,
Protocol = storageClientConfiguration.UseHttp ? Protocol.HTTP : Protocol.HTTPS
};
if (preventOverwrite)
request.Headers["If-None-Match"] = "*";
logger.LogDebug("Generating pre-signed URL for {Bucket}/{Key}", bucket, key);
return await amazonS3.GetPreSignedURLAsync(request);
}
logger.LogDebug("Generating pre-signed upload URL for {Bucket}/{Key}", bucket, key);
return await amazonS3.GetPreSignedURLAsync(request);
public async Task<string> GetUploadUrlAsync(
string bucket,
string key,
string contentType,
TimeSpan expirationTime,
CancellationToken cancellationToken,
bool preventOverwrite = true)
{
var request = new GetPreSignedUrlRequest
{
BucketName = bucket,
Key = key,
Expires = DateTime.UtcNow + expirationTime,
Protocol = storageClientConfiguration.UseHttp ? Protocol.HTTP : Protocol.HTTPS,
Verb = HttpVerb.PUT,
ContentType = contentType
};
if (preventOverwrite)
request.Headers["If-None-Match"] = "*";
logger.LogDebug("Generating pre-signed upload URL for {Bucket}/{Key}", bucket, key);
return await amazonS3.GetPreSignedURLAsync(request);
}
public async Task<ObjectMetaData?> HeadObjectAsync(string bucket, string key, CancellationToken cancellationToken)
{
try
{
var response = await amazonS3.GetObjectMetadataAsync(bucket, key, cancellationToken);
return new ObjectMetaData(response.Headers.ContentType, response.ContentLength);
}
public async Task<ObjectMetaData?> HeadObjectAsync(string bucket, string key, CancellationToken cancellationToken)
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
try
{
var response = await amazonS3.GetObjectMetadataAsync(bucket, key, cancellationToken);
return new ObjectMetaData(response.Headers.ContentType, response.ContentLength);
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
catch (Exception exception)
{
logger.LogError(exception, "HEAD failed for {Bucket}/{Key}", bucket, key);
throw;
}
return null;
}
public async Task RemoveFileAsync(string bucket, string key, CancellationToken cancellationToken)
catch (Exception exception)
{
var request = new DeleteObjectRequest
{
BucketName = bucket,
Key = key,
};
logger.LogDebug("Removing file from S3 {Bucket}/{Key}", bucket, key);
await amazonS3.DeleteObjectAsync(request, cancellationToken);
logger.LogError(exception, "HEAD failed for {Bucket}/{Key}", bucket, key);
throw;
}
}
public async Task<IReadOnlyList<string>> TransferFilesAsync(string sourceDirectory, string bucket, string route, CancellationToken cancellationToken)
public async Task RemoveFileAsync(string bucket, string key, CancellationToken cancellationToken)
{
var request = new DeleteObjectRequest
{
var trasnsferUtility = new TransferUtility(amazonS3);
BucketName = bucket,
Key = key,
};
var files = Directory.GetFiles(sourceDirectory, "*");
logger.LogDebug("Removing file from S3 {Bucket}/{Key}", bucket, key);
await amazonS3.DeleteObjectAsync(request, cancellationToken);
}
var uploadedKeys = new List<string>();
var successCount = 0;
var failedCount = 0;
public async Task<IReadOnlyList<string>> TransferFilesAsync(string sourceDirectory, string bucket, string route, CancellationToken cancellationToken)
{
var trasnsferUtility = new TransferUtility(amazonS3);
foreach (var file in files)
{
string fileName = Path.GetFileName(file);
string filePath = Path.Combine(sourceDirectory, file);
var files = Directory.GetFiles(sourceDirectory, "*");
var key = string.Join('/', new[] { route, fileName }
.Where(static s => !string.IsNullOrWhiteSpace(s))
.Select(static s => s.Trim().Trim('/', '\\')));
var contentType = MimeUtility.GetMimeMapping(filePath);
var upload = new Upload
{
Id = Guid.NewGuid(),
Bucket = bucket,
Key = key,
ContentType = contentType
};
await database.Uploads.AddAsync(upload, cancellationToken);
var uploadedKeys = new List<string>();
var successCount = 0;
var failedCount = 0;
try
{
await trasnsferUtility.UploadAsync(
new TransferUtilityUploadRequest
{
FilePath = filePath,
BucketName = bucket,
Key = key,
ContentType = contentType
},
cancellationToken);
upload.State = UploadState.Successful;
uploadedKeys.Add(key);
successCount++;
logger.LogDebug("Transferred file to S3 {Bucket}/{Key}", bucket, key);
}
catch (Exception exception)
{
failedCount++;
upload.State = UploadState.Failed;
logger.LogError(exception, "Failed to transfer file to S3 {Bucket}/{Key}", bucket, key);
throw;
}
}
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("File transfer completed to {Bucket}/{Route}. Success: {SuccessCount}, Failed: {FailedCount}", bucket, route, successCount, failedCount);
return uploadedKeys;
}
public async Task UploadFileAsync(string filePath, string bucket, string key, CancellationToken cancellationToken)
foreach (var file in files)
{
try
{
using var fileStream = File.OpenRead(filePath);
var contentType = MimeUtility.GetMimeMapping(filePath);
await UploadFileAsync(fileStream, contentType, bucket, key, cancellationToken);
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to upload file to S3 {Bucket}/{Key}", bucket, key);
throw;
}
}
public async Task UploadFileAsync(Stream sourceStream, string contentType, string bucket, string key, CancellationToken cancellationToken)
{
var request = new PutObjectRequest
{
BucketName = bucket,
ContentType = contentType,
InputStream = sourceStream,
Key = key
};
string fileName = Path.GetFileName(file);
string filePath = Path.Combine(sourceDirectory, file);
var key = string.Join('/', new[] { route, fileName }
.Where(static s => !string.IsNullOrWhiteSpace(s))
.Select(static s => s.Trim().Trim('/', '\\')));
var contentType = MimeUtility.GetMimeMapping(filePath);
var upload = new Upload
{
Id = Guid.NewGuid(),
@@ -200,105 +135,169 @@ namespace Musify.Infrastructure.Services
try
{
var response = await amazonS3.PutObjectAsync(request, cancellationToken);
logger.LogDebug("Uploaded file to S3 {Bucket}/{Key}", bucket, key);
await trasnsferUtility.UploadAsync(
new TransferUtilityUploadRequest
{
FilePath = filePath,
BucketName = bucket,
Key = key,
ContentType = contentType
},
cancellationToken);
upload.State = UploadState.Successful;
uploadedKeys.Add(key);
successCount++;
logger.LogDebug("Transferred file to S3 {Bucket}/{Key}", bucket, key);
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to upload file to S3 {Bucket}/{Key}", bucket, key);
failedCount++;
upload.State = UploadState.Failed;
await database.SaveChangesAsync(cancellationToken);
throw;
}
upload.State = UploadState.Successful;
await database.SaveChangesAsync(cancellationToken);
logger.LogDebug("Saved upload record for {Bucket}/{Key}", bucket, key);
}
public async Task CopyFileAsync(string sourceBucket, string sourceKey, string destinationBucket, string destinationKey,
CancellationToken cancellationToken)
{
var request = new CopyObjectRequest
{
SourceBucket = sourceBucket,
SourceKey = sourceKey,
DestinationBucket = destinationBucket,
DestinationKey = destinationKey
};
try
{
var response = await amazonS3.CopyObjectAsync(request, cancellationToken);
logger.LogInformation("Copied file from {SourceBucket}/{SourceKey} to {DestinationBucket}/{DestinationKey}",
sourceBucket, sourceKey, destinationBucket, destinationKey);
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to copy file from {SourceBucket}/{SourceKey} to {DestinationBucket}/{DestinationKey}",
sourceBucket, sourceKey, destinationBucket, destinationKey);
logger.LogError(exception, "Failed to transfer file to S3 {Bucket}/{Key}", bucket, key);
throw;
}
}
public async IAsyncEnumerable<StorageObject> ListObjectsAsync(
string bucket, string prefix, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("File transfer completed to {Bucket}/{Route}. Success: {SuccessCount}, Failed: {FailedCount}", bucket, route, successCount, failedCount);
return uploadedKeys;
}
public async Task UploadFileAsync(string filePath, string bucket, string key, CancellationToken cancellationToken)
{
try
{
var listRequest = new ListObjectsV2Request
{
BucketName = bucket,
Prefix = prefix.EndsWith('/') ? prefix : $"{prefix}/"
};
ListObjectsV2Response listResponse;
do
{
listResponse = await amazonS3.ListObjectsV2Async(listRequest, cancellationToken);
foreach (var s3Object in listResponse.S3Objects ?? [] )
yield return new StorageObject(s3Object.Key, (s3Object.LastModified ?? DateTime.UtcNow).ToUniversalTime());
listRequest.ContinuationToken = listResponse.NextContinuationToken;
}
while (listResponse.IsTruncated.HasValue && listResponse.IsTruncated.Value);
using var fileStream = File.OpenRead(filePath);
var contentType = MimeUtility.GetMimeMapping(filePath);
await UploadFileAsync(fileStream, contentType, bucket, key, cancellationToken);
}
public async Task RemoveFolderAsync(string bucket, string folderKey, CancellationToken cancellationToken)
catch (Exception exception)
{
var prefix = folderKey.EndsWith('/') ? folderKey : $"{folderKey}/";
var listRequest = new ListObjectsV2Request
{
BucketName = bucket,
Prefix = prefix
};
ListObjectsV2Response listResponse;
do
{
listResponse = await amazonS3.ListObjectsV2Async(listRequest, cancellationToken);
if (listResponse.S3Objects == null|| listResponse.S3Objects.Count == 0)
break;
var deleteRequest = new DeleteObjectsRequest
{
BucketName = bucket,
Objects = listResponse.S3Objects
.Select(o => new KeyVersion { Key = o.Key } )
.ToList()
};
var deleteResponse = await amazonS3.DeleteObjectsAsync(deleteRequest, cancellationToken);
var deleteErrors = deleteResponse.DeleteErrors ?? [];
if (deleteErrors.Count > 0)
{
var errors = string.Join(", ", deleteErrors.Select(e => $"{e.Key}: {e.Message}"));
throw new InvalidOperationException($"Failed to delete some objects in folder {folderKey}: {errors}");
}
listRequest.ContinuationToken = listResponse.NextContinuationToken;
} while (listResponse.IsTruncated.HasValue && listResponse.IsTruncated.Value);
logger.LogError(exception, "Failed to upload file to S3 {Bucket}/{Key}", bucket, key);
throw;
}
}
}
public async Task UploadFileAsync(Stream sourceStream, string contentType, string bucket, string key, CancellationToken cancellationToken)
{
var request = new PutObjectRequest
{
BucketName = bucket,
ContentType = contentType,
InputStream = sourceStream,
Key = key
};
var upload = new Upload
{
Id = Guid.NewGuid(),
Bucket = bucket,
Key = key,
ContentType = contentType
};
await database.Uploads.AddAsync(upload, cancellationToken);
try
{
var response = await amazonS3.PutObjectAsync(request, cancellationToken);
logger.LogDebug("Uploaded file to S3 {Bucket}/{Key}", bucket, key);
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to upload file to S3 {Bucket}/{Key}", bucket, key);
upload.State = UploadState.Failed;
await database.SaveChangesAsync(cancellationToken);
throw;
}
upload.State = UploadState.Successful;
await database.SaveChangesAsync(cancellationToken);
logger.LogDebug("Saved upload record for {Bucket}/{Key}", bucket, key);
}
public async Task CopyFileAsync(string sourceBucket, string sourceKey, string destinationBucket, string destinationKey,
CancellationToken cancellationToken)
{
var request = new CopyObjectRequest
{
SourceBucket = sourceBucket,
SourceKey = sourceKey,
DestinationBucket = destinationBucket,
DestinationKey = destinationKey
};
try
{
var response = await amazonS3.CopyObjectAsync(request, cancellationToken);
logger.LogInformation("Copied file from {SourceBucket}/{SourceKey} to {DestinationBucket}/{DestinationKey}",
sourceBucket, sourceKey, destinationBucket, destinationKey);
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to copy file from {SourceBucket}/{SourceKey} to {DestinationBucket}/{DestinationKey}",
sourceBucket, sourceKey, destinationBucket, destinationKey);
throw;
}
}
public async IAsyncEnumerable<StorageObject> ListObjectsAsync(
string bucket, string prefix, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
{
var listRequest = new ListObjectsV2Request
{
BucketName = bucket,
Prefix = prefix.EndsWith('/') ? prefix : $"{prefix}/"
};
ListObjectsV2Response listResponse;
do
{
listResponse = await amazonS3.ListObjectsV2Async(listRequest, cancellationToken);
foreach (var s3Object in listResponse.S3Objects ?? [])
yield return new StorageObject(s3Object.Key, (s3Object.LastModified ?? DateTime.UtcNow).ToUniversalTime());
listRequest.ContinuationToken = listResponse.NextContinuationToken;
}
while (listResponse.IsTruncated.HasValue && listResponse.IsTruncated.Value);
}
public async Task RemoveFolderAsync(string bucket, string folderKey, CancellationToken cancellationToken)
{
var prefix = folderKey.EndsWith('/') ? folderKey : $"{folderKey}/";
var listRequest = new ListObjectsV2Request
{
BucketName = bucket,
Prefix = prefix
};
ListObjectsV2Response listResponse;
do
{
listResponse = await amazonS3.ListObjectsV2Async(listRequest, cancellationToken);
if (listResponse.S3Objects == null || listResponse.S3Objects.Count == 0)
break;
var deleteRequest = new DeleteObjectsRequest
{
BucketName = bucket,
Objects = listResponse.S3Objects
.Select(o => new KeyVersion { Key = o.Key })
.ToList()
};
var deleteResponse = await amazonS3.DeleteObjectsAsync(deleteRequest, cancellationToken);
var deleteErrors = deleteResponse.DeleteErrors ?? [];
if (deleteErrors.Count > 0)
{
var errors = string.Join(", ", deleteErrors.Select(e => $"{e.Key}: {e.Message}"));
throw new InvalidOperationException($"Failed to delete some objects in folder {folderKey}: {errors}");
}
listRequest.ContinuationToken = listResponse.NextContinuationToken;
} while (listResponse.IsTruncated.HasValue && listResponse.IsTruncated.Value);
}
}
@@ -4,51 +4,50 @@ using Microsoft.IdentityModel.Tokens;
using Musify.Application.Contracts;
using Musify.Infrastructure.Configuration;
namespace Musify.Infrastructure.Services
namespace Musify.Infrastructure.Services;
public sealed class StreamTicketService : IStreamTicketService, IDisposable
{
public sealed class StreamTicketService : IStreamTicketService, IDisposable
private readonly StreamTicketConfiguration configuration;
private readonly RSA rsa;
private readonly SigningCredentials signingCredentials;
private readonly JsonWebTokenHandler tokenHandler = new();
public StreamTicketService(StreamTicketConfiguration configuration)
{
private readonly StreamTicketConfiguration configuration;
private readonly RSA rsa;
private readonly SigningCredentials signingCredentials;
private readonly JsonWebTokenHandler tokenHandler = new();
this.configuration = configuration;
public StreamTicketService(StreamTicketConfiguration configuration)
{
this.configuration = configuration;
rsa = RSA.Create();
rsa.ImportFromPem(File.ReadAllText(configuration.PrivateKeyPath));
rsa = RSA.Create();
rsa.ImportFromPem(File.ReadAllText(configuration.PrivateKeyPath));
var key = new RsaSecurityKey(rsa);
signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
}
public StreamTicket IssueTicket(long? userId, string keyPrefix, long? maxBytes = null)
{
var now = DateTimeOffset.UtcNow;
var claims = new Dictionary<string, object> { ["prefix"] = keyPrefix };
if (userId != null)
claims["sub"] = userId.Value.ToString();
if (maxBytes != null)
claims["maxBytes"] = maxBytes.Value.ToString();
var descriptor = new SecurityTokenDescriptor
{
Issuer = configuration.Issuer,
Audience = configuration.Audience,
IssuedAt = now.UtcDateTime,
NotBefore = now.UtcDateTime,
Expires = now.AddSeconds(configuration.TicketTtlSeconds).UtcDateTime,
Claims = claims,
SigningCredentials = signingCredentials,
};
var token = tokenHandler.CreateToken(descriptor);
return new StreamTicket(token, configuration.TicketTtlSeconds);
}
public void Dispose() => rsa.Dispose();
var key = new RsaSecurityKey(rsa);
signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
}
public StreamTicket IssueTicket(long? userId, string keyPrefix, long? maxBytes = null)
{
var now = DateTimeOffset.UtcNow;
var claims = new Dictionary<string, object> { ["prefix"] = keyPrefix };
if (userId != null)
claims["sub"] = userId.Value.ToString();
if (maxBytes != null)
claims["maxBytes"] = maxBytes.Value.ToString();
var descriptor = new SecurityTokenDescriptor
{
Issuer = configuration.Issuer,
Audience = configuration.Audience,
IssuedAt = now.UtcDateTime,
NotBefore = now.UtcDateTime,
Expires = now.AddSeconds(configuration.TicketTtlSeconds).UtcDateTime,
Claims = claims,
SigningCredentials = signingCredentials,
};
var token = tokenHandler.CreateToken(descriptor);
return new StreamTicket(token, configuration.TicketTtlSeconds);
}
public void Dispose() => rsa.Dispose();
}