Add download worker and download service

This commit is contained in:
Misaki
2024-06-05 19:24:57 +09:00
parent 307701c6c5
commit 150cd3cb26
8 changed files with 278 additions and 65 deletions

View File

@@ -0,0 +1,98 @@
using Downloader;
using DownloadManager.Models;
using System.ComponentModel;
namespace DownloadManager.DownloaderCore;
public class DownloadWorker(DownloadItemData itemData)
{
IDownload? _worker;
DownloadItemData _downloadData = itemData;
public Action<DownloadWorker> OnDownloadStarted;
public Action<DownloadWorker> OnDownloadFileCompleted;
public Action<DownloadWorker> OnDownloadStop;
public bool BuildDownloadRequest()
{
try
{
_worker = new DownloadBuilder()
.WithUrl(_downloadData.Url)
.WithDirectory(_downloadData.FilePath)
.WithFileName(_downloadData.FileName)
.WithConfiguration(_downloadData.downloadConfiguration)
.Build();
_worker.DownloadStarted += DownloadStarted;
_worker.DownloadProgressChanged += DownloadProgressChanged;
_worker.DownloadFileCompleted += DownloadFileCompleted;
return true;
}
catch (Exception)
{
return false;
throw;
}
}
private void DownloadStarted(object? sender, DownloadStartedEventArgs e)
{
_downloadData.Status = DownloadStatus.Running;
OnDownloadStarted?.Invoke(this);
}
private void DownloadProgressChanged(object? sender, DownloadProgressChangedEventArgs e)
{
_downloadData.Progress = (int)e.ProgressPercentage;
_downloadData.Speed = e.BytesPerSecondSpeed;
}
private void DownloadFileCompleted(object? sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
_downloadData.Status = DownloadStatus.Failed;
}
else
{
_downloadData.Status = DownloadStatus.Completed;
}
OnDownloadFileCompleted?.Invoke(this);
}
public void StartDownload()
{
if (_worker == null)
return;
_worker.StartAsync();
}
public void PauseDownload()
{
if (_worker == null)
return;
_worker.Pause();
OnDownloadStop?.Invoke(this);
}
public void ResumeDownload()
{
if (_worker == null)
return;
_worker.Resume();
}
public void StopDownload()
{
if (_worker == null)
return;
_worker.Stop();
OnDownloadStop?.Invoke(this);
}
}