Skip to content

Commit

Permalink
Merge pull request shaked6540#239 from cristianst85/fix-download-sing…
Browse files Browse the repository at this point in the history
…le-video-files

Fixed an issue with downloading single video files
  • Loading branch information
shaked6540 authored Mar 9, 2024
2 parents 7810369 + 321165a commit 46884b5
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 36 deletions.
52 changes: 33 additions & 19 deletions YoutubePlaylistDownloader/DownloadPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ public partial class DownloadPage : UserControl, IDisposable, IDownload
private readonly CancellationTokenSource cts;
private readonly VideoQuality Quality;
private string Bitrate;
private List<Tuple<PlaylistVideo, string>> NotDownloaded;
private IEnumerable<PlaylistVideo> Videos;
private List<Tuple<IVideo, string>> NotDownloaded;
private IEnumerable<IVideo> Videos;
private readonly bool AudioOnly;
private readonly bool PreferHighestFPS;
private bool DownloadCaptions;
Expand All @@ -28,7 +28,7 @@ public partial class DownloadPage : UserControl, IDisposable, IDownload
const int megaBytes = 1 << 20;
private readonly bool silent;
private FixedQueue<double> downloadSpeeds;
private readonly Dictionary<PlaylistVideo, int> indexes = [];
private readonly Dictionary<IVideo, int> indexes = [];
private readonly List<Task> convertionTasks = [];

public bool StillDownloading;
Expand Down Expand Up @@ -106,7 +106,7 @@ public string CurrentStatus
}


public DownloadPage(FullPlaylist playlist, DownloadSettings settings, string savePath = "", IEnumerable<PlaylistVideo> videos = null,
public DownloadPage(FullPlaylist playlist, DownloadSettings settings, string savePath = "", IEnumerable<IVideo> videos = null,
bool silent = false, CancellationTokenSource cancellationToken = null)
{
InitializeComponent();
Expand Down Expand Up @@ -185,7 +185,7 @@ public DownloadPage(FullPlaylist playlist, DownloadSettings settings, string sav
CurrentDownloadSpeed = $"{FindResource("DownloadSpeed")}: 0 MiB/s";

if (settings.Convert || settings.AudioOnly)
StartDownloadingWithConverting(playlist.BasePlaylist.Id, cts.Token).ConfigureAwait(false);
StartDownloadingWithConverting(playlist.BasePlaylist?.Id, cts.Token).ConfigureAwait(false);
else
StartDownloading(cts.Token).ConfigureAwait(false);

Expand All @@ -198,11 +198,11 @@ public static async Task SequenceDownload(IEnumerable<string> links, DownloadSet
Playlist basePlaylist;
FullPlaylist fullPlaylist;
Channel channel;
IEnumerable<PlaylistVideo> videos = new List<PlaylistVideo>();
IEnumerable<IVideo> videos = new List<IVideo>();
var notDownloaded = new List<(string, string)>();
foreach (var link in links)
{
async Task Download(FullPlaylist playlistD, IEnumerable<PlaylistVideo> videosD)
async Task Download(FullPlaylist playlistD, IEnumerable<IVideo> videosD)
{
await Application.Current.Dispatcher.InvokeAsync(() =>
{
Expand All @@ -213,9 +213,9 @@ await Application.Current.Dispatcher.InvokeAsync(() =>
{
if (YoutubeHelpers.TryParsePlaylistId(link, out var playlistId))
{
basePlaylist = await client.Playlists.GetAsync(playlistId).ConfigureAwait(false);
basePlaylist = await client.Playlists.GetAsync(playlistId.Value).ConfigureAwait(false);
fullPlaylist = new FullPlaylist(basePlaylist, await client.Playlists.GetVideosAsync(basePlaylist.Id).CollectAsync().ConfigureAwait(false));
await Download(fullPlaylist, new List<PlaylistVideo>());
await Download(fullPlaylist, new List<IVideo>());
}
else if (YoutubeHelpers.TryParseChannelId(link, out var channelId))
{
Expand All @@ -233,8 +233,14 @@ await Application.Current.Dispatcher.InvokeAsync(() =>
}
else if (YoutubeHelpers.TryParseVideoId(link, out var videoId))
{
var video = await client.Videos.GetAsync(videoId);
await Download(null, new[] { new PlaylistVideo(playlistId, video.Id, video.Title, video.Author, video.Duration, video.Thumbnails) });
IVideo video = await client.Videos.GetAsync(videoId);

if (playlistId.HasValue)
{
video = new PlaylistVideo(playlistId.Value, video.Id, video.Title, video.Author, video.Duration, video.Thumbnails);
}

await Download(null, new[] { video });
}
else
{
Expand All @@ -261,7 +267,7 @@ await GlobalConsts.ShowSelectableDialog($"{Application.Current.FindResource("Cou
}
}

public async Task StartDownloadingWithConverting(PlaylistId playlistId, CancellationToken token)
public async Task StartDownloadingWithConverting(PlaylistId? playlistId, CancellationToken token)
{
try
{
Expand All @@ -279,7 +285,7 @@ public async Task StartDownloadingWithConverting(PlaylistId playlistId, Cancella
{
var video = Videos.ElementAtOrDefault(i);

if (video == default(PlaylistVideo))
if (video == default(IVideo))
goto exit;

indexes.Add(video, i + 1);
Expand Down Expand Up @@ -414,7 +420,11 @@ await Dispatcher.InvokeAsync(() =>
FileType = new string(copyFileLoc.Skip(copyFileLoc.LastIndexOf('.') + 1).ToArray());
if (afterTagName != outputFileLoc)
{
video = new PlaylistVideo(playlistId, video.Id, afterTagName, video.Author, video.Duration, video.Thumbnails);
if (playlistId.HasValue)
{
video = new PlaylistVideo(playlistId.Value, video.Id, afterTagName, video.Author, video.Duration, video.Thumbnails);
}

cleanFileName = GlobalConsts.CleanFileName(downloadSettings.GetFilenameByPattern(video, i, title, Playlist));
copyFileLoc = $"{SavePath}\\{cleanFileName}.{FileType}";
}
Expand Down Expand Up @@ -475,7 +485,11 @@ await Dispatcher.InvokeAsync(() =>
var afterTagName = await GlobalConsts.TagFile(video, i + 1, copyFileLoc, Playlist);
if (afterTagName != outputFileLoc)
{
video = new PlaylistVideo(playlistId, video.Id, afterTagName, video.Author, video.Duration, video.Thumbnails);
if (playlistId.HasValue)
{
video = new PlaylistVideo(playlistId.Value, video.Id, afterTagName, video.Author, video.Duration, video.Thumbnails);
}

cleanFileName = GlobalConsts.CleanFileName(downloadSettings.GetFilenameByPattern(video, i, title, Playlist));
copyFileLoc = $"{SavePath}\\{cleanFileName}.{FileType}";
}
Expand All @@ -498,7 +512,7 @@ await Dispatcher.InvokeAsync(() =>
catch (Exception ex)
{
await GlobalConsts.Log(ex.ToString(), "DownloadPage DownlaodWithConvert");
NotDownloaded.Add(new Tuple<PlaylistVideo, string>(video, ex.Message));
NotDownloaded.Add(new Tuple<IVideo, string>(video, ex.Message));
}
}

Expand Down Expand Up @@ -589,7 +603,7 @@ public async Task StartDownloading(CancellationToken token)
{
var video = Videos.ElementAtOrDefault(i);

if (video == default(PlaylistVideo))
if (video == default(IVideo))
goto exit;

try
Expand Down Expand Up @@ -812,7 +826,7 @@ await Dispatcher.InvokeAsync(() =>
catch (Exception ex)
{
await GlobalConsts.Log(ex.ToString(), "DownloadPage DownlaodWithConvert");
NotDownloaded.Add(new Tuple<PlaylistVideo, string>(video, ex.Message));
NotDownloaded.Add(new Tuple<IVideo, string>(video, ex.Message));
}
}

Expand Down Expand Up @@ -884,7 +898,7 @@ private void Background_Exit(object sender, RoutedEventArgs e)
GlobalConsts.LoadPage(GlobalConsts.MainPage.Load());
}

private void Update(int percent, PlaylistVideo video)
private void Update(int percent, IVideo video)
{
CurrentDownloadProgressBar.Value = percent;
HeadlineTextBlock.Text = (string)FindResource("CurrentlyDownlading") + video.Title;
Expand Down
4 changes: 2 additions & 2 deletions YoutubePlaylistDownloader/GlobalConsts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ static async Task<string> TagMusicFile(Video fullVideo, string file, int vIndex)
return $"{string.Join(", ", artists)} - {title}";
}

public static async Task<string> TagFileBasedOnTitle(PlaylistVideo video, int vIndex, string file, FullPlaylist playlist = null)
public static async Task<string> TagFileBasedOnTitle(IVideo video, int vIndex, string file, FullPlaylist playlist = null)
{
var genre = video.Title.Split('[', ']').ElementAtOrDefault(1);
if (genre == null)
Expand Down Expand Up @@ -450,7 +450,7 @@ public static async Task<string> TagFileBasedOnTitle(PlaylistVideo video, int vI
return file;
}

public static async Task<string> TagFile(PlaylistVideo video, int vIndex, string file, FullPlaylist playlist = null)
public static async Task<string> TagFile(IVideo video, int vIndex, string file, FullPlaylist playlist = null)
{
ArgumentNullException.ThrowIfNull(video);

Expand Down
12 changes: 6 additions & 6 deletions YoutubePlaylistDownloader/MainPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public partial class MainPage : UserControl
{
private readonly YoutubeClient client;
private FullPlaylist list = null;
private IEnumerable<PlaylistVideo> VideoList;
private IEnumerable<IVideo> VideoList;
private Channel channel = null;
private readonly Dictionary<string, VideoQuality> Resolutions = new()
{
Expand Down Expand Up @@ -32,7 +32,7 @@ public MainPage()
GlobalConsts.ShowSettingsButton();
GlobalConsts.ShowAboutButton();
GlobalConsts.ShowHelpButton();
VideoList = new List<PlaylistVideo>();
VideoList = new List<IVideo>();
client = GlobalConsts.YoutubeClient;

GlobalConsts.MainPage = this;
Expand All @@ -55,7 +55,7 @@ private async void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
_ = Task.Run(async () =>
{
var basePlaylist = await client.Playlists.GetAsync(playlistId).ConfigureAwait(false);
var basePlaylist = await client.Playlists.GetAsync(playlistId.Value).ConfigureAwait(false);
list = new FullPlaylist(basePlaylist, await client.Playlists.GetVideosAsync(basePlaylist.Id).CollectAsync().ConfigureAwait(false));
VideoList = new List<PlaylistVideo>();
await UpdatePlaylistInfo(Visibility.Visible, list.BasePlaylist.Title, list.BasePlaylist.Author?.ChannelTitle ?? "", "", list.Videos.Count().ToString(), $"https://img.youtube.com/vi/{list?.Videos?.FirstOrDefault()?.Id}/maxresdefault.jpg", true, true);
Expand Down Expand Up @@ -96,7 +96,7 @@ private async void TextBox_TextChanged(object sender, TextChangedEventArgs e)
_ = Task.Run(async () =>
{
var video = await client.Videos.GetAsync(videoId);
VideoList = new List<PlaylistVideo> { new(playlistId, video.Id, video.Title, video.Author, video.Duration, video.Thumbnails) };
VideoList = new List<Video> { video };
list = new FullPlaylist(null, null);
await UpdatePlaylistInfo(Visibility.Visible, video.Title, video.Author.ChannelTitle, video.Engagement.ViewCount.ToString(), string.Empty, $"https://img.youtube.com/vi/{video.Id}/maxresdefault.jpg", true, false);

Expand Down Expand Up @@ -126,7 +126,7 @@ private void DownloadButton_Click(object sender, RoutedEventArgs e)
}

GlobalConsts.LoadPage(new DownloadPage(list, GlobalConsts.DownloadSettings.Clone(), videos: VideoList));
VideoList = new List<PlaylistVideo>();
VideoList = new List<IVideo>();
PlaylistLinkTextBox.Text = string.Empty;
}
}
Expand Down Expand Up @@ -175,7 +175,7 @@ private void DownloadInBackgroundButton_Click(object sender, RoutedEventArgs e)
}

_ = new DownloadPage(list, GlobalConsts.DownloadSettings.Clone(), silent: true, videos: VideoList);
VideoList = new List<PlaylistVideo>();
VideoList = new List<IVideo>();
PlaylistLinkTextBox.Text = string.Empty;
}
}
Expand Down
2 changes: 1 addition & 1 deletion YoutubePlaylistDownloader/Objects/DownloadSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public DownloadSettings(DownloadSettings settings)
VideoSaveFormat = settings.VideoSaveFormat;
}

public string GetFilenameByPattern(PlaylistVideo video, int vIndex, string file, FullPlaylist playlist = null)
public string GetFilenameByPattern(IVideo video, int vIndex, string file, FullPlaylist playlist = null)
{
if (video == null)
return file;
Expand Down
4 changes: 2 additions & 2 deletions YoutubePlaylistDownloader/Objects/FullPlaylist.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
namespace YoutubePlaylistDownloader.Objects;

public class FullPlaylist(Playlist basePlaylist, IEnumerable<PlaylistVideo> videos, string title = null)
public class FullPlaylist(Playlist basePlaylist, IEnumerable<IVideo> videos, string title = null)
{
public Playlist BasePlaylist { get; private set; } = basePlaylist;
public IEnumerable<PlaylistVideo> Videos { get; private set; } = videos;
public IEnumerable<IVideo> Videos { get; private set; } = videos;

public string Title { get; private set; } = basePlaylist?.Title ?? title;
}
10 changes: 5 additions & 5 deletions YoutubePlaylistDownloader/Utilities/YoutubeHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public static bool ValidatePlaylistId(string playlistId)
/// <summary>
/// Tries to parse playlist ID from a YouTube playlist URL.
/// </summary>
public static bool TryParsePlaylistId(string playlistUrl, out string playlistId)
public static bool TryParsePlaylistId(string playlistUrl, out PlaylistId? playlistId)
{
playlistId = default;

Expand All @@ -72,31 +72,31 @@ public static bool TryParsePlaylistId(string playlistUrl, out string playlistId)
var regularMatch = RegularRegex().Match(playlistUrl).Groups[1].Value;
if (!string.IsNullOrWhiteSpace(regularMatch) && ValidatePlaylistId(regularMatch))
{
playlistId = regularMatch;
playlistId = PlaylistId.Parse(regularMatch);
return true;
}

// https://www.youtube.com/watch?v=b8m9zhNAgKs&list=PL9tY0BWXOZFuFEG_GtOBZ8-8wbkH-NVAr
var compositeMatch = CompositeRegex().Match(playlistUrl).Groups[1].Value;
if (!string.IsNullOrWhiteSpace(compositeMatch) && ValidatePlaylistId(compositeMatch))
{
playlistId = compositeMatch;
playlistId = PlaylistId.Parse(compositeMatch);
return true;
}

// https://youtu.be/b8m9zhNAgKs/?list=PL9tY0BWXOZFuFEG_GtOBZ8-8wbkH-NVAr
var shortCompositeMatch = ShortLinkRegex().Match(playlistUrl).Groups[1].Value;
if (!string.IsNullOrWhiteSpace(shortCompositeMatch) && ValidatePlaylistId(shortCompositeMatch))
{
playlistId = shortCompositeMatch;
playlistId = PlaylistId.Parse(shortCompositeMatch);
return true;
}

// https://www.youtube.com/embed/b8m9zhNAgKs/?list=PL9tY0BWXOZFuFEG_GtOBZ8-8wbkH-NVAr
var embedCompositeMatch = EmbedRegex().Match(playlistUrl).Groups[1].Value;
if (!string.IsNullOrWhiteSpace(embedCompositeMatch) && ValidatePlaylistId(embedCompositeMatch))
{
playlistId = embedCompositeMatch;
playlistId = PlaylistId.Parse(embedCompositeMatch);
return true;
}

Expand Down
2 changes: 1 addition & 1 deletion YoutubePlaylistDownloader/YoutubePlaylistDownloader.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
</PackageReference>
<PackageReference Include="MahApps.Metro" Version="2.4.9" />
<PackageReference Include="MahApps.Metro.IconPacks" Version="4.11.0" />
<PackageReference Include="YoutubeExplode" Version="6.3.12" />
<PackageReference Include="YoutubeExplode" Version="6.3.13" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Windows.Compatibility" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
Expand Down

0 comments on commit 46884b5

Please sign in to comment.