Code в C# Controller < /p>
Код: Выделить всё
[HttpPost("download")]
public async Task Download([FromBody] DownloadRequest request)
{
if (string.IsNullOrEmpty(request.Url))
return BadRequest("URL is required");
// Create download ID
string downloadId = Guid.NewGuid().ToString();
// Initialize download status
var downloadStatus = new DownloadStatus
{
Id = downloadId,
Url = request.Url,
State = "Initializing",
Progress = 0,
IsCompleted = false
};
// Store the download status
_downloads[downloadId] = downloadStatus;
// Start download process asynchronously
await Task.Run(async () =>
{
try
{
// Set up progress tracking
var progress = new Progress(p =>
{
downloadStatus.State = p.State.ToString();
downloadStatus.Progress = p.Progress;
downloadStatus.DownloadSpeed = p.DownloadSpeed;
downloadStatus.ETA = p.ETA;
});
var output = new Progress(s =>
{
downloadStatus.Output.Add(s);
});
// Parse custom options
OptionSet? custom = null;
if (!string.IsNullOrEmpty(request.Options))
{
custom = OptionSet.FromString(request.Options.Split('\n'));
}
// Start download
RunResult result;
if (request.AudioOnly)
{
result = await _youtubeDL.RunAudioDownload(
request.Url,
AudioConversionFormat.Mp3,
progress: progress,
output: output,
overrideOptions: custom
);
}
else
{
result = await _youtubeDL.RunVideoDownload(
request.Url,
progress: progress,
output: output,
overrideOptions: custom
);
}
// Update download status after completion
downloadStatus.IsCompleted = true;
downloadStatus.IsSuccessful = result.Success;
if (result.Success)
{
downloadStatus.FilePath = result.Data;
}
else
{
downloadStatus.ErrorMessage = string.Join("\n", result.ErrorOutput);
}
}
catch (Exception ex)
{
downloadStatus.IsCompleted = true;
downloadStatus.IsSuccessful = false;
downloadStatus.ErrorMessage = ex.Message;
}
});
// Return the download ID for status tracking
return Ok(new { DownloadId = downloadId });
}
// this is the process return status back to client run every second.
[HttpGet("status/{id}")]
public Task GetDownloadStatus(string id)
{
if (!_downloads.TryGetValue(id, out var status))
{
return Task.FromResult(NotFound("Download not found"));
}
return Task.FromResult(Ok(status));
}
< /code>
На угловой службе клиента < /p>
downloadVideo(request: DownloadRequest): Observable {
return this.http.post(`${this.apiUrl}/download`, request);
}
getDownloadStatus(id: string): Observable {
return this.http.get(`${this.apiUrl}/status/${id}`);
}
< /code>
component.ts Попробуйте вытащить статус каждую секунду. < /p>
this.statusSubscription = interval(1000)
.pipe(
switchMap(() => this.youtubeDlService.getDownloadStatus(this.currentDownloadId!))
)
.subscribe({
next: (status) => {
this.downloadStatus = status;
// Update UI with latest output
if (status.output && status.output.length > this.output.length) {
this.output = [...status.output];
}
// Check if download is completed
if (status.isCompleted) {
this.isDownloading = false;
this.statusSubscription?.unsubscribe();
if (status.isSuccessful) {
this.showSuccessMessage(status.filePath);
} else {
this.showErrorMessage('Download failed', status.errorMessage);
}
}
},
error: (error) => {
console.error('Error polling status:', error);
this.isDownloading = false;
this.statusSubscription?.unsubscribe();
}
});
githup -исходный код для этого https://github.com/d052057/ytsharp
Подробнее здесь: https://stackoverflow.com/questions/794 ... lar-client