Skip to content

Commit

Permalink
Refactor with C# 12 features
Browse files Browse the repository at this point in the history
  • Loading branch information
Tyrrrz committed Dec 10, 2023
1 parent 3cb3f54 commit eab9329
Show file tree
Hide file tree
Showing 16 changed files with 95 additions and 148 deletions.
8 changes: 3 additions & 5 deletions YoutubeDownloader.Core/Downloading/VideoDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,10 @@

namespace YoutubeDownloader.Core.Downloading;

public class VideoDownloader
public class VideoDownloader(IReadOnlyList<Cookie>? initialCookies = null)
{
private readonly YoutubeClient _youtube;

public VideoDownloader(IReadOnlyList<Cookie>? initialCookies = null) =>
_youtube = new YoutubeClient(Http.Client, initialCookies ?? Array.Empty<Cookie>());
private readonly YoutubeClient _youtube =
new(Http.Client, initialCookies ?? Array.Empty<Cookie>());

public async Task<IReadOnlyList<VideoDownloadOption>> GetDownloadOptionsAsync(
VideoId videoId,
Expand Down
8 changes: 3 additions & 5 deletions YoutubeDownloader.Core/Resolving/QueryResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@

namespace YoutubeDownloader.Core.Resolving;

public class QueryResolver
public class QueryResolver(IReadOnlyList<Cookie>? initialCookies = null)
{
private readonly YoutubeClient _youtube;

public QueryResolver(IReadOnlyList<Cookie>? initialCookies = null) =>
_youtube = new YoutubeClient(Http.Client, initialCookies ?? Array.Empty<Cookie>());
private readonly YoutubeClient _youtube =
new(Http.Client, initialCookies ?? Array.Empty<Cookie>());

public async Task<QueryResult> ResolveAsync(
string query,
Expand Down
26 changes: 11 additions & 15 deletions YoutubeDownloader.Core/Tagging/MediaFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,28 @@

namespace YoutubeDownloader.Core.Tagging;

internal partial class MediaFile : IDisposable
internal partial class MediaFile(TagFile file) : IDisposable
{
private readonly TagFile _file;

public MediaFile(TagFile file) => _file = file;

public void SetThumbnail(byte[] thumbnailData) =>
_file.Tag.Pictures = new IPicture[] { new Picture(thumbnailData) };
file.Tag.Pictures = new IPicture[] { new Picture(thumbnailData) };

public void SetArtist(string artist) => _file.Tag.Performers = new[] { artist };
public void SetArtist(string artist) => file.Tag.Performers = new[] { artist };

public void SetArtistSort(string artistSort) => _file.Tag.PerformersSort = new[] { artistSort };
public void SetArtistSort(string artistSort) => file.Tag.PerformersSort = new[] { artistSort };

public void SetTitle(string title) => _file.Tag.Title = title;
public void SetTitle(string title) => file.Tag.Title = title;

public void SetAlbum(string album) => _file.Tag.Album = album;
public void SetAlbum(string album) => file.Tag.Album = album;

public void SetDescription(string description) => _file.Tag.Description = description;
public void SetDescription(string description) => file.Tag.Description = description;

public void SetComment(string comment) => _file.Tag.Comment = comment;
public void SetComment(string comment) => file.Tag.Comment = comment;

public void Dispose()
{
_file.Tag.DateTagged = DateTime.Now;
_file.Save();
_file.Dispose();
file.Tag.DateTagged = DateTime.Now;
file.Save();
file.Dispose();
}
}

Expand Down
7 changes: 2 additions & 5 deletions YoutubeDownloader.Core/Utils/ThrottleLock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@

namespace YoutubeDownloader.Core.Utils;

public class ThrottleLock : IDisposable
public class ThrottleLock(TimeSpan interval) : IDisposable
{
private readonly SemaphoreSlim _semaphore = new(1, 1);
private readonly TimeSpan _interval;
private DateTimeOffset _lastRequestInstant = DateTimeOffset.MinValue;

public ThrottleLock(TimeSpan interval) => _interval = interval;

public async Task WaitAsync(CancellationToken cancellationToken = default)
{
await _semaphore.WaitAsync(cancellationToken);
Expand All @@ -20,7 +17,7 @@ public async Task WaitAsync(CancellationToken cancellationToken = default)
{
var timePassedSinceLastRequest = DateTimeOffset.Now - _lastRequestInstant;

var remainingTime = _interval - timePassedSinceLastRequest;
var remainingTime = interval - timePassedSinceLastRequest;
if (remainingTime > TimeSpan.Zero)
await Task.Delay(remainingTime, cancellationToken);

Expand Down
24 changes: 9 additions & 15 deletions YoutubeDownloader/Converters/BoolToVisibilityConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,22 @@
namespace YoutubeDownloader.Converters;

[ValueConversion(typeof(bool), typeof(Visibility))]
public partial class BoolToVisibilityConverter : IValueConverter
public partial class BoolToVisibilityConverter(
Visibility trueVisibility,
Visibility falseVisibility
) : IValueConverter
{
private readonly Visibility _trueVisibility;
private readonly Visibility _falseVisibility;

public BoolToVisibilityConverter(Visibility trueVisibility, Visibility falseVisibility)
{
_trueVisibility = trueVisibility;
_falseVisibility = falseVisibility;
}

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value is true ? _trueVisibility : _falseVisibility;
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is true ? trueVisibility : falseVisibility;

public object ConvertBack(
object value,
object? value,
Type targetType,
object parameter,
object? parameter,
CultureInfo culture
) =>
value is Visibility visibility
? visibility == _trueVisibility
? visibility == trueVisibility
: throw new NotSupportedException();
}

Expand Down
4 changes: 2 additions & 2 deletions YoutubeDownloader/Converters/InverseBoolConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ public class InverseBoolConverter : IValueConverter
{
public static InverseBoolConverter Instance { get; } = new();

public object Convert(object? value, Type targetType, object parameter, CultureInfo culture) =>
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is false;

public object ConvertBack(
object? value,
Type targetType,
object parameter,
object? parameter,
CultureInfo culture
) => value is false;
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class VideoQualityPreferenceToStringConverter : IValueConverter
{
public static VideoQualityPreferenceToStringConverter Instance { get; } = new();

public object? Convert(object? value, Type targetType, object parameter, CultureInfo culture)
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is VideoQualityPreference preference)
return preference.GetDisplayName();
Expand All @@ -21,7 +21,7 @@ public class VideoQualityPreferenceToStringConverter : IValueConverter
public object ConvertBack(
object? value,
Type targetType,
object parameter,
object? parameter,
CultureInfo culture
) => throw new NotSupportedException();
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,17 @@ public class VideoToHighestQualityThumbnailUrlConverter : IValueConverter
{
public static VideoToHighestQualityThumbnailUrlConverter Instance { get; } = new();

public object? Convert(object? value, Type targetType, object parameter, CultureInfo culture) =>
value is IVideo video ? video.Thumbnails.TryGetWithHighestResolution()?.Url : null;
public object? Convert(
object? value,
Type targetType,
object? parameter,
CultureInfo culture
) => value is IVideo video ? video.Thumbnails.TryGetWithHighestResolution()?.Url : null;

public object ConvertBack(
object? value,
Type targetType,
object parameter,
object? parameter,
CultureInfo culture
) => throw new NotSupportedException();
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,17 @@ public class VideoToLowestQualityThumbnailUrlConverter : IValueConverter
{
public static VideoToLowestQualityThumbnailUrlConverter Instance { get; } = new();

public object? Convert(object? value, Type targetType, object parameter, CultureInfo culture) =>
value is IVideo video ? video.Thumbnails.MinBy(t => t.Resolution.Area)?.Url : null;
public object? Convert(
object? value,
Type targetType,
object? parameter,
CultureInfo culture
) => value is IVideo video ? video.Thumbnails.MinBy(t => t.Resolution.Area)?.Url : null;

public object ConvertBack(
object? value,
Type targetType,
object parameter,
object? parameter,
CultureInfo culture
) => throw new NotSupportedException();
}
7 changes: 3 additions & 4 deletions YoutubeDownloader/Services/SettingsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
namespace YoutubeDownloader.Services;

[AddINotifyPropertyChangedInterface]
public partial class SettingsService : SettingsBase, INotifyPropertyChanged
public partial class SettingsService()
: SettingsBase(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings.dat")),
INotifyPropertyChanged
{
public bool IsUkraineSupportMessageEnabled { get; set; } = true;

Expand Down Expand Up @@ -43,9 +45,6 @@ public partial class SettingsService : SettingsBase, INotifyPropertyChanged
public VideoQualityPreference LastVideoQualityPreference { get; set; } =
VideoQualityPreference.Highest;

public SettingsService()
: base(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings.dat")) { }

public override void Save()
{
// Clear the cookies if they are not supposed to be persisted
Expand Down
15 changes: 4 additions & 11 deletions YoutubeDownloader/Services/UpdateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,20 @@

namespace YoutubeDownloader.Services;

public class UpdateService : IDisposable
public class UpdateService(SettingsService settingsService) : IDisposable
{
private readonly IUpdateManager _updateManager = new UpdateManager(
new GithubPackageResolver("Tyrrrz", "YoutubeDownloader", "YoutubeDownloader.zip"),
new ZipPackageExtractor()
);

private readonly SettingsService _settingsService;

private Version? _updateVersion;
private bool _updatePrepared;
private bool _updaterLaunched;

public UpdateService(SettingsService settingsService)
{
_settingsService = settingsService;
}

public async Task<Version?> CheckForUpdatesAsync()
{
if (!_settingsService.IsAutoUpdateEnabled)
if (!settingsService.IsAutoUpdateEnabled)
return null;

var check = await _updateManager.CheckForUpdatesAsync();
Expand All @@ -35,7 +28,7 @@ public UpdateService(SettingsService settingsService)

public async Task PrepareUpdateAsync(Version version)
{
if (!_settingsService.IsAutoUpdateEnabled)
if (!settingsService.IsAutoUpdateEnabled)
return;

try
Expand All @@ -55,7 +48,7 @@ public async Task PrepareUpdateAsync(Version version)

public void FinalizeUpdate(bool needRestart)
{
if (!_settingsService.IsAutoUpdateEnabled)
if (!settingsService.IsAutoUpdateEnabled)
return;

if (_updateVersion is null || !_updatePrepared || _updaterLaunched)
Expand Down
8 changes: 2 additions & 6 deletions YoutubeDownloader/Utils/ResizableSemaphore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,8 @@ public void Dispose()

internal partial class ResizableSemaphore
{
private class AcquiredAccess : IDisposable
private class AcquiredAccess(ResizableSemaphore semaphore) : IDisposable
{
private readonly ResizableSemaphore _semaphore;

public AcquiredAccess(ResizableSemaphore semaphore) => _semaphore = semaphore;

public void Dispose() => _semaphore.Release();
public void Dispose() => semaphore.Release();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@

namespace YoutubeDownloader.ViewModels.Dialogs;

public class DownloadMultipleSetupViewModel : DialogScreen<IReadOnlyList<DownloadViewModel>>
public class DownloadMultipleSetupViewModel(
IViewModelFactory viewModelFactory,
DialogManager dialogManager,
SettingsService settingsService
) : DialogScreen<IReadOnlyList<DownloadViewModel>>
{
private readonly IViewModelFactory _viewModelFactory;
private readonly DialogManager _dialogManager;
private readonly SettingsService _settingsService;

public string? Title { get; set; }

public IReadOnlyList<IVideo>? AvailableVideos { get; set; }
Expand All @@ -36,21 +36,10 @@ public class DownloadMultipleSetupViewModel : DialogScreen<IReadOnlyList<Downloa
public VideoQualityPreference SelectedVideoQualityPreference { get; set; } =
VideoQualityPreference.Highest;

public DownloadMultipleSetupViewModel(
IViewModelFactory viewModelFactory,
DialogManager dialogManager,
SettingsService settingsService
)
{
_viewModelFactory = viewModelFactory;
_dialogManager = dialogManager;
_settingsService = settingsService;
}

public void OnViewLoaded()
{
SelectedContainer = _settingsService.LastContainer;
SelectedVideoQualityPreference = _settingsService.LastVideoQualityPreference;
SelectedContainer = settingsService.LastContainer;
SelectedVideoQualityPreference = settingsService.LastVideoQualityPreference;
}

public void CopyTitle() => Clipboard.SetText(Title!);
Expand All @@ -59,7 +48,7 @@ public void OnViewLoaded()

public void Confirm()
{
var dirPath = _dialogManager.PromptDirectoryPath();
var dirPath = dialogManager.PromptDirectoryPath();
if (string.IsNullOrWhiteSpace(dirPath))
return;

Expand All @@ -71,14 +60,14 @@ public void Confirm()
var baseFilePath = Path.Combine(
dirPath,
FileNameTemplate.Apply(
_settingsService.FileNameTemplate,
settingsService.FileNameTemplate,
video,
SelectedContainer,
(i + 1).ToString().PadLeft(SelectedVideos.Count.ToString().Length, '0')
)
);

if (_settingsService.ShouldSkipExistingFiles && File.Exists(baseFilePath))
if (settingsService.ShouldSkipExistingFiles && File.Exists(baseFilePath))
continue;

var filePath = PathEx.EnsureUniquePath(baseFilePath);
Expand All @@ -88,16 +77,16 @@ public void Confirm()
File.WriteAllBytes(filePath, Array.Empty<byte>());

downloads.Add(
_viewModelFactory.CreateDownloadViewModel(
viewModelFactory.CreateDownloadViewModel(
video,
new VideoDownloadPreference(SelectedContainer, SelectedVideoQualityPreference),
filePath
)
);
}

_settingsService.LastContainer = SelectedContainer;
_settingsService.LastVideoQualityPreference = SelectedVideoQualityPreference;
settingsService.LastContainer = SelectedContainer;
settingsService.LastVideoQualityPreference = SelectedVideoQualityPreference;

Close(downloads);
}
Expand Down
Loading

0 comments on commit eab9329

Please # to comment.