Skip to content

Commit

Permalink
feat: implement "stop" function
Browse files Browse the repository at this point in the history
Signed-off-by: 陳鈞 <[email protected]>
  • Loading branch information
jim60105 committed Mar 21, 2024
1 parent 3d56e46 commit 4743ab8
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 44 deletions.
32 changes: 22 additions & 10 deletions Download.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ internal partial class Download(string id,
public bool Succeeded;
public string? OutputFilePath;

public async Task Start()
public async Task Start(CancellationToken? cancellationToken = default)
{
cancellationToken ??= CancellationToken.None;
Log.Information("Start the download process...");
Succeeded = false;
Finished = false;
Expand All @@ -51,7 +52,7 @@ public async Task Start()
IgnoreDownloadErrors = true
};

var videoData = await FetchVideoInfoAsync(ytdl, optionSet);
var videoData = await FetchVideoInfoAsync(ytdl, optionSet, cancellationToken);
if (null == videoData) return;

OutputFilePath = CalculatePath(videoData.Title,
Expand All @@ -60,7 +61,7 @@ public async Task Start()
CultureInfo.InvariantCulture),
videoData.Id);

var downloadSuccess = await DownloadVideoAsync(ytdl, optionSet);
var downloadSuccess = await DownloadVideoAsync(ytdl, optionSet, cancellationToken);
if (!downloadSuccess) return;

if (end == 0)
Expand All @@ -70,7 +71,7 @@ public async Task Start()
}
else
{
_ = await CutWithFFmpegAsync(tempFilePath1, tempFilePath2);
_ = await CutWithFFmpegAsync(tempFilePath1, tempFilePath2, cancellationToken);
File.Move(tempFilePath2, OutputFilePath, true);
}

Expand All @@ -80,12 +81,18 @@ public async Task Start()
}
catch (Exception e)
{
if (e is TaskCanceledException or OperationCanceledException)
throw;

Log.Error("vvvvvvvvvvvvvvvvvvvvv");
Log.Error(e.Message);
Log.Error("^^^^^^^^^^^^^^^^^^^^^");
}
finally
{
// Wait 500 ms to ensure the file is released
await Task.Delay(500);

File.Delete(tempFilePath1);
File.Delete(tempFilePath2);
File.Delete(Path.ChangeExtension(tempFilePath1, "tmp"));
Expand Down Expand Up @@ -134,11 +141,13 @@ private OptionSet CreateOptionSet()
/// </summary>
/// <param name="ytdl"></param>
/// <param name="optionSet"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<YtdlpVideoData?> FetchVideoInfoAsync(YoutubeDL ytdl, OptionSet optionSet)
private async Task<YtdlpVideoData?> FetchVideoInfoAsync(YoutubeDL ytdl, OptionSet optionSet, CancellationToken? cancellationToken = default)
{
Log.Information("Start getting video information...");
RunResult<YtdlpVideoData> result = await ytdl.RunVideoDataFetch_Alt(Link, overrideOptions: optionSet);
RunResult<YtdlpVideoData> result =
await ytdl.RunVideoDataFetch_Alt(Link, overrideOptions: optionSet, ct: cancellationToken ?? CancellationToken.None);

if (!result.Success)
{
Expand Down Expand Up @@ -172,8 +181,9 @@ private OptionSet CreateOptionSet()
/// </summary>
/// <param name="ytdl"></param>
/// <param name="optionSet"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<bool> DownloadVideoAsync(YoutubeDL ytdl, OptionSet optionSet)
private async Task<bool> DownloadVideoAsync(YoutubeDL ytdl, OptionSet optionSet, CancellationToken? cancellationToken = default)
{
Log.Information("Start downloading video...");
var lastProgress = 0.0f;
Expand All @@ -198,7 +208,8 @@ private async Task<bool> DownloadVideoAsync(YoutubeDL ytdl, OptionSet optionSet)
lastProgress = currentProgress;
Log.Verbose(rawProgress);
}),
overrideOptions: optionSet);
overrideOptions: optionSet,
ct: cancellationToken ?? CancellationToken.None);

if (!result.Success)
{
Expand All @@ -224,8 +235,9 @@ static bool isProgressEqualOrMinorChange(float currentProgress, float lastProgre
/// </summary>
/// <param name="inputPath"></param>
/// <param name="outputPath"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<IConversionResult> CutWithFFmpegAsync(string inputPath, string outputPath)
private async Task<IConversionResult> CutWithFFmpegAsync(string inputPath, string outputPath, CancellationToken? cancellationToken = default)
{
Log.Information("Start cutting video with FFmpeg...");

Expand All @@ -247,7 +259,7 @@ private async Task<IConversionResult> CutWithFFmpegAsync(string inputPath, strin
if (e.Data != null) Log.Verbose(e.Data);
};
Log.Debug("FFmpeg arguments: {arguments}", conversion.Build());
return await conversion.Start();
return await conversion.Start(cancellationToken: cancellationToken ?? CancellationToken.None);
}

/// <summary>
Expand Down
10 changes: 9 additions & 1 deletion Form1.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

97 changes: 72 additions & 25 deletions Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,19 @@ namespace YoutubeSegmentDownloader;

public partial class Form1 : Form
{
readonly ComponentResourceManager resources = new(typeof(Form1));
private readonly ComponentResourceManager _resources = new(typeof(Form1));

public Form1()
{
InitializeComponent();
Shown += Form1_Shown;
Closing += (_, _) =>
{
_cancellationTokenSource.Cancel();

// Wait 1 second for the download process to terminate and files clean up
Thread.Sleep(1000);
};
}

private void Form1_Shown(object? sender, EventArgs e)
Expand Down Expand Up @@ -67,6 +74,7 @@ private async Task PrepareYtdlpAndFFmpegAsync(bool forceUpdate = false)
DependencyStatus.Failed => "😕",
_ => throw new NotImplementedException()
};

label_checking_ffmpeg.Text =
FFmpegStatus switch
{
Expand All @@ -87,36 +95,55 @@ private async Task PrepareYtdlpAndFFmpegAsync(bool forceUpdate = false)
private void checkBox_segment_CheckedChanged(object sender, EventArgs e)
=> tableLayoutPanel_segment.Enabled = checkBox_segment.Checked;

private bool _isDownloading;
private CancellationTokenSource _cancellationTokenSource = new();

private void button_start_Click(object sender, EventArgs e)
{
if (_isDownloading)
{
_isDownloading = false;

if (!_cancellationTokenSource.Token.CanBeCanceled) return;

Log.Information("Terminate download process.");
_cancellationTokenSource.Cancel();

return;
}

_cancellationTokenSource = new CancellationTokenSource();

Settings.Default.Directory = textBox_outputDirectory.Text;

var id = TryPrepareVideoId(textBox_youtube.Text);

if (!TryPrepareStartEndTime(textBox_start.Text, textBox_end.Text, checkBox_segment.Checked, out var start, out var end))
{
return;
}

if (!TryPrepareDirectory(textBox_outputDirectory.Text, out var directory))
{
return;
}

var format = textBox_format.Text;
Settings.Default.Format = format;

var browser = comboBox_browser.Text;
if (string.IsNullOrEmpty(browser)
|| browser == resources.GetString("comboBox_browser.Items"))
|| browser == _resources.GetString("comboBox_browser.Items"))
{
browser = "";
}

Settings.Default.Browser = browser;
Settings.Default.Save();

_ = DownloadAsync(id, start, end, directory!, format, browser).ConfigureAwait(true);
_ = DownloadAsync(id: id,
start: start,
end: end,
directory: directory!,
format: format,
browser: browser,
cancellationToken: _cancellationTokenSource.Token).ConfigureAwait(false);
}

private string TryPrepareVideoId(string text)
Expand All @@ -132,8 +159,8 @@ private string TryPrepareVideoId(string text)
}
else
{
Log.Error(resources.GetString("hiddenlabel1.Text", new CultureInfo("en-us"))!);
MessageBox.Show(resources.GetString("hiddenlabel1.Text"), "Warning!");
Log.Error(_resources.GetString("hiddenlabel1.Text", new CultureInfo("en-us"))!);
MessageBox.Show(_resources.GetString("hiddenlabel1.Text"), "Warning!");
}

return text;
Expand Down Expand Up @@ -172,6 +199,7 @@ private static bool TryPrepareDirectory(string directoryPath, out DirectoryInfo?
var path = directoryPath.Contains('%')
? Environment.ExpandEnvironmentVariables(directoryPath)
: directoryPath;

directory = new DirectoryInfo(path);
directory.Create();
Log.Information("Output directory:");
Expand All @@ -187,18 +215,29 @@ private static bool TryPrepareDirectory(string directoryPath, out DirectoryInfo?
}
}

private async Task DownloadAsync(string id, float start, float end, DirectoryInfo directory, string format, string browser)
private async Task DownloadAsync(string id,
float start,
float end,
DirectoryInfo directory,
string format,
string browser,
CancellationToken? cancellationToken = default)
{
var oldText = button_start.Text;
button_start.Text = _resources.GetString("hiddenlabel2.Text");
try
{
_isDownloading = true;

tableLayoutPanel_main.Enabled
= tableLayoutPanel_segment.Enabled
= button_start.Enabled
= groupBox1.Enabled
= groupBox2.Enabled
= groupBox3.Enabled
= button_redownloadDependencies.Enabled
= false;
= tableLayoutPanel_segment.Enabled
//= button_start.Enabled
= groupBox1.Enabled
= groupBox2.Enabled
= groupBox3.Enabled
= button_redownloadDependencies.Enabled
= false;

Application.DoEvents();

Download download = new(id: id,
Expand All @@ -207,7 +246,8 @@ private async Task DownloadAsync(string id, float start, float end, DirectoryInf
outputDirectory: directory,
format: format,
browser: browser);
await download.Start();

await download.Start(cancellationToken);

if (!download.Succeeded)
{
Expand All @@ -224,6 +264,9 @@ private async Task DownloadAsync(string id, float start, float end, DirectoryInf
}
catch (Exception e)
{
if (e is TaskCanceledException or OperationCanceledException)
return;

Log.Logger.Error(e.Message);
MessageBox.Show("Download not successful!", "Failed!!!");
Log.Logger.Error("!!!! FAILED !!!!");
Expand All @@ -233,15 +276,19 @@ private async Task DownloadAsync(string id, float start, float end, DirectoryInf
finally
{
tableLayoutPanel_main.Enabled
//= tableLayoutPanel_segment.Enabled
= button_start.Enabled
= groupBox1.Enabled
= groupBox2.Enabled
= groupBox3.Enabled
= button_redownloadDependencies.Enabled
= true;
//= tableLayoutPanel_segment.Enabled
//= button_start.Enabled
= groupBox1.Enabled
= groupBox2.Enabled
= groupBox3.Enabled
= button_redownloadDependencies.Enabled
= true;

tableLayoutPanel_segment.Enabled = checkBox_segment.Checked;
button_start.Text = oldText;
Application.DoEvents();

_isDownloading = false;
}
}

Expand Down
Loading

0 comments on commit 4743ab8

Please sign in to comment.