94 lines
2.7 KiB
C#
94 lines
2.7 KiB
C#
using System.Collections;
|
|
using Microsoft.AspNetCore.Http.HttpResults;
|
|
Queue<EncodingJob> JobQueue = new();
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
//Settings
|
|
string tmpFilePath = builder.Configuration.GetValue<string>("TempFilePath") ?? Path.GetTempPath();
|
|
|
|
//Services
|
|
builder.Services.AddOpenApi();
|
|
var app = builder.Build();
|
|
|
|
if (app.Environment.IsDevelopment()) { app.MapOpenApi(); }
|
|
|
|
app.UseHttpsRedirection();
|
|
|
|
// Get a video file as multipart form data and schedule it for encoding
|
|
// Get video encoding settings from query parameters
|
|
// Returns the ID of the job handling the encoding
|
|
app.MapPost("encode", context =>
|
|
{
|
|
var request = context.Request;
|
|
if (!request.HasFormContentType) {
|
|
context.Response.StatusCode = 400;
|
|
return context.Response.WriteAsync("Invalid content type. Expected multipart/form-data.");
|
|
}
|
|
|
|
var form = request.Form;
|
|
var file = form.Files.GetFile("video");
|
|
|
|
if (file == null) {
|
|
context.Response.StatusCode = 400;
|
|
return context.Response.WriteAsync("No video file provided.");
|
|
}
|
|
|
|
var Job = new EncodingJob(Guid.NewGuid());
|
|
JobQueue.Enqueue(Job);
|
|
|
|
return context.Response.WriteAsJsonAsync(new { JobId = Job.Id });
|
|
});
|
|
|
|
// Check the status of an encoding job by its ID
|
|
app.MapGet("status/{jobId:guid}", (Guid jobId) =>
|
|
{
|
|
var job = JobQueue.FirstOrDefault(j => j.Id == jobId);
|
|
if (job == null) {
|
|
return Results.NotFound(new { Message = "Job not found." });
|
|
}
|
|
|
|
return Results.Ok(new {
|
|
JobId = job.Id,
|
|
Status = job.Status.ToString(),
|
|
CreatedAt = job.CreatedAt,
|
|
CompletedAt = job.CompletedAt
|
|
});
|
|
});
|
|
|
|
app.MapGet("file/{jobId:guid}", (Guid jobId) =>
|
|
{
|
|
var job = JobQueue.FirstOrDefault(j => j.Id == jobId);
|
|
if (job == null) {
|
|
return Results.NotFound(new { Message = "Job not found." });
|
|
}
|
|
|
|
if (job.Status != JobStatus.Completed) {
|
|
return Results.BadRequest(new { Message = "Job is not completed yet." });
|
|
}
|
|
|
|
var filePath = job.EncodedFilePath;
|
|
if (!File.Exists(filePath)) {
|
|
return Results.NotFound(new { Message = "Encoded file not found." });
|
|
}
|
|
|
|
var fileBytes = File.ReadAllBytes(filePath);
|
|
return Results.File(fileBytes, "video/mp4", Path.GetFileName(filePath), enableRangeProcessing:true);
|
|
});
|
|
|
|
app.Run();
|
|
|
|
public enum JobStatus {
|
|
Pending,
|
|
InProgress,
|
|
Completed,
|
|
Failed
|
|
}
|
|
|
|
public record EncodingJob(Guid Id) {
|
|
public JobStatus Status { get; set; } = JobStatus.Pending;
|
|
public DateTime CreatedAt { get; init; } = DateTime.Now;
|
|
public DateTime? CompletedAt { get; set; } = null;
|
|
public string OrigFilePath { get; init; } = string.Empty;
|
|
public string EncodedFilePath { get; set; } = string.Empty;
|
|
} |