1.0-dev16 (GUI code cleaning, media not found exception handling added)

This commit is contained in:
2022-03-09 23:43:51 +01:00
Unverified
parent 51389c4df1
commit b4347f2b5c
40 changed files with 1312 additions and 1412 deletions

View File

@@ -1,8 +0,0 @@
namespace VDownload.Core.EventArgs
{
public class PlaylistSearchEventArgs : System.EventArgs
{
public string Url { get; set; }
public int VideosCount { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using VDownload.Core.Interfaces;
namespace VDownload.Core.EventArgs
{
public class PlaylistSearchSuccessedEventArgs : System.EventArgs
{
public IPlaylistService PlaylistService { get; set; }
}
}

View File

@@ -1,7 +0,0 @@
namespace VDownload.Core.EventArgs
{
public class VideoSearchEventArgs : System.EventArgs
{
public string Url { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using VDownload.Core.Interfaces;
namespace VDownload.Core.EventArgs
{
public class VideoSearchSuccessedEventArgs : System.EventArgs
{
public IVideoService VideoService { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VDownload.Core.Exceptions
{
public class MediaNotFoundException : Exception
{
public MediaNotFoundException() { }
public MediaNotFoundException(string message) : base(message) { }
public MediaNotFoundException(string message, Exception inner) : base(message, inner) { }
}
}

View File

@@ -18,7 +18,7 @@ namespace VDownload.Core.Services
// PLAYLIST SOURCES REGULAR EXPRESSIONS // PLAYLIST SOURCES REGULAR EXPRESSIONS
private static readonly (Regex Regex, PlaylistSource Type)[] PlaylistSources = new (Regex Regex, PlaylistSource Type)[] private static readonly (Regex Regex, PlaylistSource Type)[] PlaylistSources = new (Regex Regex, PlaylistSource Type)[]
{ {
(new Regex(@"^https://www.twitch.tv/(?<id>[^?]+)"), PlaylistSource.TwitchChannel), (new Regex(@"^https://www.twitch.tv/(?<id>[^?/]+)"), PlaylistSource.TwitchChannel),
}; };
#endregion #endregion

View File

@@ -49,7 +49,9 @@ namespace VDownload.Core.Services.Sources.Twitch
using (WebClient client = await Client.Helix()) using (WebClient client = await Client.Helix())
{ {
client.QueryString.Add("login", ID); client.QueryString.Add("login", ID);
response = JObject.Parse(await client.DownloadStringTaskAsync("https://api.twitch.tv/helix/users"))["data"][0]; response = JObject.Parse(await client.DownloadStringTaskAsync("https://api.twitch.tv/helix/users"))["data"];
if (((JArray)response).Count > 0) response = response[0];
else throw new MediaNotFoundException($"Twitch Channel (ID: {ID}) was not found");
} }
// Create unified playlist url // Create unified playlist url

View File

@@ -54,7 +54,9 @@ namespace VDownload.Core.Services.Sources.Twitch
using (WebClient client = await Client.Helix()) using (WebClient client = await Client.Helix())
{ {
client.QueryString.Add("id", ID); client.QueryString.Add("id", ID);
response = JObject.Parse(await client.DownloadStringTaskAsync("https://api.twitch.tv/helix/clips")).GetValue("data")[0]; response = JObject.Parse(await client.DownloadStringTaskAsync("https://api.twitch.tv/helix/clips")).GetValue("data");
if (((JArray)response).Count > 0) response = response[0];
else throw new MediaNotFoundException($"Twitch Clip (ID: {ID}) was not found");
} }
// Create unified video url // Create unified video url

View File

@@ -2,12 +2,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using VDownload.Core.Enums; using VDownload.Core.Enums;
using VDownload.Core.Exceptions;
using VDownload.Core.Interfaces; using VDownload.Core.Interfaces;
using VDownload.Core.Services.Sources.Twitch.Helpers; using VDownload.Core.Services.Sources.Twitch.Helpers;
using VDownload.Core.Structs; using VDownload.Core.Structs;
@@ -52,7 +54,16 @@ namespace VDownload.Core.Services.Sources.Twitch
{ {
client.QueryString.Add("id", ID); client.QueryString.Add("id", ID);
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
response = JObject.Parse(await client.DownloadStringTaskAsync("https://api.twitch.tv/helix/videos")).GetValue("data")[0]; try
{
response = JObject.Parse(await client.DownloadStringTaskAsync("https://api.twitch.tv/helix/videos")).GetValue("data")[0];
}
catch (WebException ex)
{
if (ex.Response != null && new StreamReader(ex.Response.GetResponseStream()).ReadToEnd().Contains("Not Found")) throw new MediaNotFoundException($"Twitch VOD (ID: {ID}) was not found");
else if (ex.Response != null && new StreamReader(ex.Response.GetResponseStream()).ReadToEnd() == string.Empty && ex.Message.Contains("400")) throw new MediaNotFoundException($"Twitch VOD (ID: {ID}) was not found");
else throw;
}
} }
// Set parameters // Set parameters

View File

@@ -1,9 +1,6 @@
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VDownload.Core.Services namespace VDownload.Core.Services
{ {
@@ -15,17 +12,15 @@ namespace VDownload.Core.Services
string formattedTimeSpan = string.Empty; string formattedTimeSpan = string.Empty;
int maxTHLength = 0; int maxTHLength = 0;
if (Math.Floor(timeSpan.TotalHours) > 0) foreach (TimeSpan format in formatBase.Concat(new TimeSpan[] { timeSpan }))
{ {
maxTHLength = Math.Floor(timeSpan.TotalHours).ToString().Length; int THLength = Math.Floor(format.TotalHours) > 0 ? Math.Floor(timeSpan.TotalHours).ToString().Length : 0;
foreach (TimeSpan format in formatBase) if (THLength > maxTHLength) maxTHLength = THLength;
{
int THLength = Math.Floor(format.TotalHours) > 0 ? Math.Floor(timeSpan.TotalHours).ToString().Length : 0;
if (THLength > maxTHLength) maxTHLength = THLength;
}
formattedTimeSpan += $"{((int)Math.Floor(timeSpan.TotalHours)).ToString($"D{maxTHLength}")}:";
} }
formattedTimeSpan += $"{((int)Math.Floor(timeSpan.TotalHours)).ToString($"D{maxTHLength}")}:";
formattedTimeSpan += maxTHLength == 0 ? $"{timeSpan.Minutes}:" : $"{timeSpan.Minutes:00}:"; formattedTimeSpan += maxTHLength == 0 ? $"{timeSpan.Minutes}:" : $"{timeSpan.Minutes:00}:";
formattedTimeSpan += $"{timeSpan.Seconds:00}"; formattedTimeSpan += $"{timeSpan.Seconds:00}";
return formattedTimeSpan; return formattedTimeSpan;
@@ -37,22 +32,20 @@ namespace VDownload.Core.Services
string formattedTimeSpan = string.Empty; string formattedTimeSpan = string.Empty;
int maxTHLength = 0; int maxTHLength = 0;
if (Math.Floor(timeSpan.TotalHours) > 0) foreach (TimeSpan format in formatBase.Concat(new TimeSpan[] { timeSpan }))
{ {
maxTHLength = Math.Floor(timeSpan.TotalHours).ToString().Length; int THLength = Math.Floor(format.TotalHours) > 0 ? Math.Floor(timeSpan.TotalHours).ToString().Length : 0;
foreach (TimeSpan format in formatBase) if (THLength > maxTHLength) maxTHLength = THLength;
{
int THLength = Math.Floor(format.TotalHours) > 0 ? Math.Floor(timeSpan.TotalHours).ToString().Length : 0;
if (THLength > maxTHLength) maxTHLength = THLength;
}
formattedTimeSpan += $"{((int)Math.Floor(timeSpan.TotalHours)).ToString($"D{maxTHLength}")}:";
} }
formattedTimeSpan += $"{((int)Math.Floor(timeSpan.TotalHours)).ToString($"D{maxTHLength}")}:";
bool MM = false; bool MM = false;
if (Math.Floor(timeSpan.TotalMinutes) > 0) if (Math.Floor(timeSpan.TotalMinutes) > 0 || maxTHLength > 0)
{ {
formattedTimeSpan += maxTHLength > 0 ? $"{timeSpan.Minutes:00}:" : $"{timeSpan.Minutes}:"; formattedTimeSpan += maxTHLength > 0 ? $"{timeSpan.Minutes:00}:" : $"{timeSpan.Minutes}:";
MM = true; MM = true;
} }
formattedTimeSpan += MM ? $"{timeSpan.Seconds:00}:" : $"{timeSpan.Seconds}:"; formattedTimeSpan += MM ? $"{timeSpan.Seconds:00}:" : $"{timeSpan.Seconds}:";
return formattedTimeSpan; return formattedTimeSpan;

View File

@@ -8,13 +8,6 @@ namespace VDownload.Core.Structs
public struct TaskData public struct TaskData
{ {
public IVideoService VideoService { get; set; } public IVideoService VideoService { get; set; }
public MediaType MediaType { get; set; } public TaskOptions TaskOptions { get; set; }
public BaseStream Stream { get; set; }
public TimeSpan TrimStart { get; set; }
public TimeSpan TrimEnd { get; set; }
public string Filename { get; set; }
public MediaFileExtension Extension { get; set; }
public StorageFolder Location { get; set; }
public double Schedule { get; set; }
} }
} }

View File

@@ -0,0 +1,18 @@
using System;
using VDownload.Core.Enums;
using Windows.Storage;
namespace VDownload.Core.Structs
{
public struct TaskOptions
{
public MediaType MediaType { get; set; }
public BaseStream Stream { get; set; }
public TimeSpan TrimStart { get; set; }
public TimeSpan TrimEnd { get; set; }
public string Filename { get; set; }
public MediaFileExtension Extension { get; set; }
public StorageFolder Location { get; set; }
public double Schedule { get; set; }
}
}

View File

@@ -130,8 +130,9 @@
<Compile Include="Enums\TaskStatus.cs" /> <Compile Include="Enums\TaskStatus.cs" />
<Compile Include="EventArgs\ProgressChangedEventArgs.cs" /> <Compile Include="EventArgs\ProgressChangedEventArgs.cs" />
<Compile Include="EventArgs\TasksAddingRequestedEventArgs.cs" /> <Compile Include="EventArgs\TasksAddingRequestedEventArgs.cs" />
<Compile Include="EventArgs\VideoSearchEventArgs.cs" /> <Compile Include="EventArgs\PlaylistSearchSuccessedEventArgs.cs" />
<Compile Include="EventArgs\PlaylistSearchEventArgs.cs" /> <Compile Include="EventArgs\VideoSearchSuccessedEventArgs.cs" />
<Compile Include="Exceptions\MediaNotFoundException.cs" />
<Compile Include="Exceptions\TwitchAccessTokenNotFoundException.cs" /> <Compile Include="Exceptions\TwitchAccessTokenNotFoundException.cs" />
<Compile Include="Exceptions\TwitchAccessTokenNotValidException.cs" /> <Compile Include="Exceptions\TwitchAccessTokenNotValidException.cs" />
<Compile Include="Interfaces\IPlaylistService.cs" /> <Compile Include="Interfaces\IPlaylistService.cs" />
@@ -149,6 +150,7 @@
<Compile Include="Services\Sources\Twitch\Clip.cs" /> <Compile Include="Services\Sources\Twitch\Clip.cs" />
<Compile Include="Services\Sources\Twitch\Vod.cs" /> <Compile Include="Services\Sources\Twitch\Vod.cs" />
<Compile Include="Services\TaskId.cs" /> <Compile Include="Services\TaskId.cs" />
<Compile Include="Structs\TaskOptions.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform"> <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">

View File

@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1600px" height="1600px"><g fill="#f44336"><path d="m20.132 17.303-13.435-13.435c-.586-.586-1.536-.586-2.121 0l-.708.707c-.586.586-.586 1.536 0 2.121l13.435 13.435c.586.586 1.536.586 2.121 0l.707-.707c.587-.585.587-1.535.001-2.121z"/><path d="m17.303 3.868-13.435 13.435c-.586.586-.586 1.536 0 2.121l.707.707c.586.586 1.536.586 2.121 0l13.436-13.434c.586-.586.586-1.536 0-2.121l-.707-.707c-.586-.587-1.536-.587-2.122-.001z"/></g></svg> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><g fill="#f44336"><path d="m20.132 17.303-13.435-13.435c-.586-.586-1.536-.586-2.121 0l-.708.707c-.586.586-.586 1.536 0 2.121l13.435 13.435c.586.586 1.536.586 2.121 0l.707-.707c.587-.585.587-1.535.001-2.121z"/><path d="m17.303 3.868-13.435 13.435c-.586.586-.586 1.536 0 2.121l.707.707c.586.586 1.536.586 2.121 0l13.436-13.434c.586-.586.586-1.536 0-2.121l-.707-.707c-.586-.587-1.536-.587-2.122-.001z"/></g></svg>

Before

Width:  |  Height:  |  Size: 502 B

After

Width:  |  Height:  |  Size: 471 B

View File

@@ -120,6 +120,39 @@
<data name="CloseErrorDialogButtonText" xml:space="preserve"> <data name="CloseErrorDialogButtonText" xml:space="preserve">
<value>OK</value> <value>OK</value>
</data> </data>
<data name="HomeAddingDownloadingOptionsHeaderTextBlock.Text" xml:space="preserve">
<value>Downloading options</value>
</data>
<data name="HomeAddingFileOptionsHeaderTextBlock.Text" xml:space="preserve">
<value>File options</value>
</data>
<data name="HomeAddingFileSettingControl.Title" xml:space="preserve">
<value>File</value>
</data>
<data name="HomeAddingLocationBrowseButton.Content" xml:space="preserve">
<value>Browse</value>
</data>
<data name="HomeAddingLocationSettingControl.Title" xml:space="preserve">
<value>Location</value>
</data>
<data name="HomeAddingMediaTypeSettingControl.Title" xml:space="preserve">
<value>Media type</value>
</data>
<data name="HomeAddingQualitySettingControl.Title" xml:space="preserve">
<value>Quality</value>
</data>
<data name="HomeAddingScheduleSettingControl.Description" xml:space="preserve">
<value>Number of minutes to start the task (after clicking downloading button).</value>
</data>
<data name="HomeAddingScheduleSettingControl.Title" xml:space="preserve">
<value>Schedule</value>
</data>
<data name="HomeAddingTaskOptionsHeaderTextBlock.Text" xml:space="preserve">
<value>Task options</value>
</data>
<data name="HomeAddingTrimSettingControl.Title" xml:space="preserve">
<value>Trim</value>
</data>
<data name="HomeDownloadAllButtonMeteredConnectionDialogCancel" xml:space="preserve"> <data name="HomeDownloadAllButtonMeteredConnectionDialogCancel" xml:space="preserve">
<value>No</value> <value>No</value>
</data> </data>
@@ -135,46 +168,6 @@
<data name="HomeDownloadAllButtonMeteredConnectionDialogTitle" xml:space="preserve"> <data name="HomeDownloadAllButtonMeteredConnectionDialogTitle" xml:space="preserve">
<value>Metered connection detected</value> <value>Metered connection detected</value>
</data> </data>
<data name="HomeOptionsBarAddPlaylistButton.Label" xml:space="preserve">
<value>Add playlist</value>
</data>
<data name="HomeOptionsBarAddPlaylistButton.Width" xml:space="preserve">
<value>85</value>
</data>
<data name="HomeOptionsBarAddPlaylistControlInfoBox.Subtitle" xml:space="preserve">
<value>- Twitch (Channel)
Number of videos got from playlist
The number in the numberbox indicades how many videos will be got from playlist. 0 = all.
</value>
</data>
<data name="HomeOptionsBarAddPlaylistControlInfoBox.Title" xml:space="preserve">
<value>Supported sources</value>
</data>
<data name="HomeOptionsBarAddPlaylistControlSearchButton.Content" xml:space="preserve">
<value>Search</value>
</data>
<data name="HomeOptionsBarAddPlaylistControlUrlTextBox.PlaceholderText" xml:space="preserve">
<value>Playlist URL</value>
</data>
<data name="HomeOptionsBarAddVideoButton.Label" xml:space="preserve">
<value>Add video</value>
</data>
<data name="HomeOptionsBarAddVideoButton.Width" xml:space="preserve">
<value>75</value>
</data>
<data name="HomeOptionsBarAddVideoControlInfoBox.Subtitle" xml:space="preserve">
<value>- Twitch (VODs, Clips)</value>
</data>
<data name="HomeOptionsBarAddVideoControlInfoBox.Title" xml:space="preserve">
<value>Supported sources</value>
</data>
<data name="HomeOptionsBarAddVideoControlSearchButton.Content" xml:space="preserve">
<value>Search</value>
</data>
<data name="HomeOptionsBarAddVideoControlUrlTextBox.PlaceholderText" xml:space="preserve">
<value>Video URL</value>
</data>
<data name="HomeOptionsBarDownloadAllButton.Label" xml:space="preserve"> <data name="HomeOptionsBarDownloadAllButton.Label" xml:space="preserve">
<value>Download all</value> <value>Download all</value>
</data> </data>
@@ -187,6 +180,28 @@ The number in the numberbox indicades how many videos will be got from playlist.
<data name="HomeOptionsBarLoadSubscripionsButton.Width" xml:space="preserve"> <data name="HomeOptionsBarLoadSubscripionsButton.Width" xml:space="preserve">
<value>120</value> <value>120</value>
</data> </data>
<data name="HomeOptionsBarPlaylistSearchButton.Label" xml:space="preserve">
<value>Playlist search</value>
</data>
<data name="HomeOptionsBarPlaylistSearchButton.Width" xml:space="preserve">
<value>95</value>
</data>
<data name="HomeOptionsBarPlaylistSearchControlInfoBox.Subtitle" xml:space="preserve">
<value>- Twitch (Channel)
Number of videos got from playlist
The number in the numberbox indicades how many videos will be got from playlist. 0 = all.
</value>
</data>
<data name="HomeOptionsBarPlaylistSearchControlInfoBox.Title" xml:space="preserve">
<value>Supported sources</value>
</data>
<data name="HomeOptionsBarPlaylistSearchControlSearchButton.Content" xml:space="preserve">
<value>Search</value>
</data>
<data name="HomeOptionsBarPlaylistSearchControlUrlTextBox.PlaceholderText" xml:space="preserve">
<value>Playlist URL</value>
</data>
<data name="HomeOptionsBarPlaylistSearchingErrorDialogTitle" xml:space="preserve"> <data name="HomeOptionsBarPlaylistSearchingErrorDialogTitle" xml:space="preserve">
<value>Playlist search error</value> <value>Playlist search error</value>
</data> </data>
@@ -199,6 +214,24 @@ The number in the numberbox indicades how many videos will be got from playlist.
<data name="HomeOptionsBarPlaylistSearchingTwitchAccessTokenNotValidErrorDialogDescription" xml:space="preserve"> <data name="HomeOptionsBarPlaylistSearchingTwitchAccessTokenNotValidErrorDialogDescription" xml:space="preserve">
<value>There is a problem with linked Twitch account. Check Twitch login status in Sources page.</value> <value>There is a problem with linked Twitch account. Check Twitch login status in Sources page.</value>
</data> </data>
<data name="HomeOptionsBarVideoSearchButton.Label" xml:space="preserve">
<value>Video search</value>
</data>
<data name="HomeOptionsBarVideoSearchButton.Width" xml:space="preserve">
<value>90</value>
</data>
<data name="HomeOptionsBarVideoSearchControlInfoBox.Subtitle" xml:space="preserve">
<value>- Twitch (VODs, Clips)</value>
</data>
<data name="HomeOptionsBarVideoSearchControlInfoBox.Title" xml:space="preserve">
<value>Supported sources</value>
</data>
<data name="HomeOptionsBarVideoSearchControlSearchButton.Content" xml:space="preserve">
<value>Search</value>
</data>
<data name="HomeOptionsBarVideoSearchControlUrlTextBox.PlaceholderText" xml:space="preserve">
<value>Video URL</value>
</data>
<data name="HomeOptionsBarVideoSearchingErrorDialogTitle" xml:space="preserve"> <data name="HomeOptionsBarVideoSearchingErrorDialogTitle" xml:space="preserve">
<value>Video search error</value> <value>Video search error</value>
</data> </data>
@@ -341,40 +374,7 @@ The number in the numberbox indicades how many videos will be got from playlist.
<value>Metered connection detected</value> <value>Metered connection detected</value>
</data> </data>
<data name="HomeTasksListPlaceholderTextBlock.Text" xml:space="preserve"> <data name="HomeTasksListPlaceholderTextBlock.Text" xml:space="preserve">
<value>Click "Add video/playlist" button to start</value> <value>Click "Video/Playlist search" button to start</value>
</data>
<data name="HomeVideoAddingDownloadingOptionsHeaderTextBlock.Text" xml:space="preserve">
<value>Downloading options</value>
</data>
<data name="HomeVideoAddingFileOptionsHeaderTextBlock.Text" xml:space="preserve">
<value>File options</value>
</data>
<data name="HomeVideoAddingFileSettingControl.Title" xml:space="preserve">
<value>File</value>
</data>
<data name="HomeVideoAddingLocationBrowseButton.Content" xml:space="preserve">
<value>Browse</value>
</data>
<data name="HomeVideoAddingLocationSettingControl.Title" xml:space="preserve">
<value>Location</value>
</data>
<data name="HomeVideoAddingMediaTypeSettingControl.Title" xml:space="preserve">
<value>Media type</value>
</data>
<data name="HomeVideoAddingQualitySettingControl.Title" xml:space="preserve">
<value>Quality</value>
</data>
<data name="HomeVideoAddingScheduleSettingControl.Description" xml:space="preserve">
<value>Number of minutes to start the task (after clicking downloading button).</value>
</data>
<data name="HomeVideoAddingScheduleSettingControl.Title" xml:space="preserve">
<value>Schedule</value>
</data>
<data name="HomeVideoAddingTaskOptionsHeaderTextBlock.Text" xml:space="preserve">
<value>Task options</value>
</data>
<data name="HomeVideoAddingTrimSettingControl.Title" xml:space="preserve">
<value>Trim</value>
</data> </data>
<data name="MainPageNavigationPanelHomeItem.Content" xml:space="preserve"> <data name="MainPageNavigationPanelHomeItem.Content" xml:space="preserve">
<value>Home</value> <value>Home</value>

View File

@@ -125,11 +125,14 @@
<Compile Include="Views\About\AboutMain.xaml.cs"> <Compile Include="Views\About\AboutMain.xaml.cs">
<DependentUpon>AboutMain.xaml</DependentUpon> <DependentUpon>AboutMain.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Views\Home\HomeOptionsBarAddPlaylistControl.xaml.cs"> <Compile Include="Views\Home\Controls\HomeAddingVideoOptions.xaml.cs">
<DependentUpon>HomeOptionsBarAddPlaylistControl.xaml</DependentUpon> <DependentUpon>HomeAddingVideoOptions.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Views\Home\HomeOptionsBarAddVideoControl.xaml.cs"> <Compile Include="Views\Home\Controls\HomeOptionsBarPlaylistSearch.xaml.cs">
<DependentUpon>HomeOptionsBarAddVideoControl.xaml</DependentUpon> <DependentUpon>HomeOptionsBarPlaylistSearch.xaml</DependentUpon>
</Compile>
<Compile Include="Views\Home\Controls\HomeOptionsBarVideoSearch.xaml.cs">
<DependentUpon>HomeOptionsBarVideoSearch.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Controls\SettingControl.xaml.cs"> <Compile Include="Controls\SettingControl.xaml.cs">
<DependentUpon>SettingControl.xaml</DependentUpon> <DependentUpon>SettingControl.xaml</DependentUpon>
@@ -140,16 +143,16 @@
<Compile Include="Views\Home\HomePlaylistAddingPanel.xaml.cs"> <Compile Include="Views\Home\HomePlaylistAddingPanel.xaml.cs">
<DependentUpon>HomePlaylistAddingPanel.xaml</DependentUpon> <DependentUpon>HomePlaylistAddingPanel.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Views\Home\HomePlaylistAddingPanelVideoPanel.xaml.cs"> <Compile Include="Views\Home\Controls\HomeSerialAddingVideoPanel.xaml.cs">
<DependentUpon>HomePlaylistAddingPanelVideoPanel.xaml</DependentUpon> <DependentUpon>HomeSerialAddingVideoPanel.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Views\Home\HomeTasksListPlaceholder.xaml.cs"> <Compile Include="Views\Home\Controls\HomeTasksListPlaceholder.xaml.cs">
<DependentUpon>HomeTasksListPlaceholder.xaml</DependentUpon> <DependentUpon>HomeTasksListPlaceholder.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Views\Home\HomeVideoAddingPanel.xaml.cs"> <Compile Include="Views\Home\HomeVideoAddingPanel.xaml.cs">
<DependentUpon>HomeVideoAddingPanel.xaml</DependentUpon> <DependentUpon>HomeVideoAddingPanel.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Views\Home\HomeTaskPanel.xaml.cs"> <Compile Include="Views\Home\Controls\HomeTaskPanel.xaml.cs">
<DependentUpon>HomeTaskPanel.xaml</DependentUpon> <DependentUpon>HomeTaskPanel.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Views\MainPage.xaml.cs"> <Compile Include="Views\MainPage.xaml.cs">
@@ -295,11 +298,15 @@
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</Page> </Page>
<Page Include="Views\Home\HomeOptionsBarAddPlaylistControl.xaml"> <Page Include="Views\Home\Controls\HomeAddingVideoOptions.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Views\Home\Controls\HomeOptionsBarPlaylistSearch.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType> <SubType>Designer</SubType>
</Page> </Page>
<Page Include="Views\Home\HomeOptionsBarAddVideoControl.xaml"> <Page Include="Views\Home\Controls\HomeOptionsBarVideoSearch.xaml">
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</Page> </Page>
@@ -315,11 +322,11 @@
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</Page> </Page>
<Page Include="Views\Home\HomePlaylistAddingPanelVideoPanel.xaml"> <Page Include="Views\Home\Controls\HomeSerialAddingVideoPanel.xaml">
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</Page> </Page>
<Page Include="Views\Home\HomeTasksListPlaceholder.xaml"> <Page Include="Views\Home\Controls\HomeTasksListPlaceholder.xaml">
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</Page> </Page>
@@ -327,7 +334,7 @@
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</Page> </Page>
<Page Include="Views\Home\HomeTaskPanel.xaml"> <Page Include="Views\Home\Controls\HomeTaskPanel.xaml">
<SubType>Designer</SubType> <SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>
</Page> </Page>

View File

@@ -0,0 +1,76 @@
<UserControl
x:Class="VDownload.Views.Home.Controls.HomeAddingVideoOptions"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VDownload.Views.Home.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
xmlns:ex="using:Microsoft.Toolkit.Uwp.UI"
xmlns:cc="using:VDownload.Controls"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ms-appx:///Resources/Icons.xaml"/>
<ResourceDictionary Source="ms-appx:///Resources/Converters.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<StackPanel Spacing="30">
<StackPanel>
<TextBlock x:Uid="HomeAddingDownloadingOptionsHeaderTextBlock" Margin="0,0,0,10" FontWeight="SemiBold"/>
<cc:SettingControl x:Uid="HomeAddingMediaTypeSettingControl" Margin="0,0,0,10" Icon="{ThemeResource MediaTypeIcon}">
<cc:SettingControl.SettingContent>
<ComboBox x:Name="HomeAddingMediaTypeSettingControlComboBox" Width="150" SelectionChanged="HomeAddingMediaTypeSettingControlComboBox_SelectionChanged"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
<cc:SettingControl x:Name="HomeAddingQualitySettingControl" Margin="0,0,0,10" x:Uid="HomeAddingQualitySettingControl" Icon="{ThemeResource QualityIcon}">
<cc:SettingControl.SettingContent>
<ComboBox x:Name="HomeAddingQualitySettingControlComboBox" Width="150" SelectionChanged="HomeAddingQualitySettingControlComboBox_SelectionChanged"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
<cc:SettingControl x:Uid="HomeAddingTrimSettingControl" Icon="{ThemeResource TrimIcon}">
<cc:SettingControl.SettingContent>
<StackPanel Orientation="Horizontal" Spacing="5">
<TextBox x:Name="HomeAddingTrimStartTextBox" ex:TextBoxExtensions.CustomMask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskElementsConverter}}" ex:TextBoxExtensions.Mask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskConverter}}" LostFocus="HomeAddingTrimStartTextBox_LostFocus"/>
<TextBlock VerticalAlignment="Center" Text="-"/>
<TextBox x:Name="HomeAddingTrimEndTextBox" ex:TextBoxExtensions.CustomMask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskElementsConverter}}" ex:TextBoxExtensions.Mask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskConverter}}" LostFocus="HomeAddingTrimEndTextBox_LostFocus"/>
</StackPanel>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
</StackPanel>
<StackPanel Spacing="10">
<TextBlock x:Uid="HomeAddingFileOptionsHeaderTextBlock" FontWeight="SemiBold"/>
<cc:SettingControl x:Uid="HomeAddingFileSettingControl" Icon="{ThemeResource FileIcon}">
<cc:SettingControl.SettingContent>
<Grid ColumnSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="HomeAddingFilenameTextBox" Grid.Column="0" MaxWidth="300" HorizontalAlignment="Right" IsSpellCheckEnabled="False" LostFocus="HomeAddingFilenameTextBox_LostFocus"/>
<ComboBox x:Name="HomeAddingExtensionComboBox" Grid.Column="1" HorizontalAlignment="Stretch" SelectionChanged="HomeAddingExtensionComboBox_SelectionChanged"/>
</Grid>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
<cc:SettingControl x:Name="HomeAddingLocationSettingControl" x:Uid="HomeAddingLocationSettingControl" Icon="{ThemeResource LocationIcon}">
<cc:SettingControl.SettingContent>
<Button x:Uid="HomeAddingLocationBrowseButton" Click="HomeAddingLocationBrowseButton_Click"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
</StackPanel>
<StackPanel Spacing="10">
<TextBlock x:Uid="HomeAddingTaskOptionsHeaderTextBlock" FontWeight="SemiBold"/>
<cc:SettingControl x:Uid="HomeAddingScheduleSettingControl" Icon="{ThemeResource ScheduleIcon}">
<cc:SettingControl.SettingContent>
<muxc:NumberBox x:Name="HomeAddingScheduleNumberBox" MaxWidth="100" Value="0" Minimum="0" SpinButtonPlacementMode="Compact" LostFocus="HomeAddingScheduleNumberBox_LostFocus"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
</StackPanel>
</StackPanel>
</UserControl>

View File

@@ -0,0 +1,279 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using VDownload.Core.Enums;
using VDownload.Core.Interfaces;
using VDownload.Core.Services;
using VDownload.Core.Structs;
using Windows.ApplicationModel.Resources;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace VDownload.Views.Home.Controls
{
public sealed partial class HomeAddingVideoOptions : UserControl
{
#region CONSTRUCTORS
public HomeAddingVideoOptions(IVideoService videoService)
{
this.InitializeComponent();
// Set video service
VideoService = videoService;
}
// INIT CONTROL
public async Task Init()
{
// Set media type
foreach (string mediaType in Enum.GetNames(typeof(MediaType)))
{
HomeAddingMediaTypeSettingControlComboBox.Items.Add(ResourceLoader.GetForCurrentView().GetString($"MediaType{mediaType}Text"));
}
HomeAddingMediaTypeSettingControlComboBox.SelectedIndex = (int)Config.GetValue("default_media_type");
// Set quality
foreach (BaseStream stream in VideoService.BaseStreams)
{
HomeAddingQualitySettingControlComboBox.Items.Add($"{stream.Height}p{(stream.FrameRate > 0 ? stream.FrameRate.ToString() : "N/A")}");
}
HomeAddingQualitySettingControlComboBox.SelectedIndex = 0;
// Set trim start
TrimStart = TimeSpan.Zero;
HomeAddingTrimStartTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(TrimStart, VideoService.Metadata.Duration);
// Set trim end
TrimEnd = VideoService.Metadata.Duration;
HomeAddingTrimEndTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(TrimEnd);
// Set filename
string temporaryFilename = (string)Config.GetValue("default_filename");
Dictionary<string, string> filenameStandardTemplates = new Dictionary<string, string>()
{
{ "<title>", VideoService.Metadata.Title },
{ "<author>", VideoService.Metadata.Author },
{ "<views>", VideoService.Metadata.Views.ToString() },
{ "<id>", VideoService.ID },
};
foreach (KeyValuePair<string, string> template in filenameStandardTemplates) temporaryFilename = temporaryFilename.Replace(template.Key, template.Value);
Dictionary<Regex, IFormattable> filenameFormatTemplates = new Dictionary<Regex, IFormattable>()
{
{ new Regex(@"<date_pub:(?<format>.*)>"), VideoService.Metadata.Date },
{ new Regex(@"<date_now:(?<format>.*)>"), DateTime.Now },
{ new Regex(@"<duration:(?<format>.*)>"), VideoService.Metadata.Duration },
};
foreach (KeyValuePair<Regex, IFormattable> template in filenameFormatTemplates) foreach (Match templateMatch in template.Key.Matches(temporaryFilename)) temporaryFilename = temporaryFilename.Replace(templateMatch.Value, template.Value.ToString(templateMatch.Groups["format"].Value, null));
foreach (char c in Path.GetInvalidFileNameChars()) temporaryFilename = temporaryFilename.Replace(c, ' ');
Filename = temporaryFilename;
HomeAddingFilenameTextBox.Text = Filename;
// Set location
if (!(bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("last_media_location"))
{
Location = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("last_media_location");
HomeAddingLocationSettingControl.Description = Location.Path;
}
else if ((bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("custom_media_location"))
{
Location = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("selected_media_location");
HomeAddingLocationSettingControl.Description = Location.Path;
}
else
{
Location = null;
HomeAddingLocationSettingControl.Description = $@"{UserDataPaths.GetDefault().Downloads}\VDownload";
}
// Set schedule
Schedule = 0;
}
#endregion
#region PROPERTIES
// VIDEO SERVICE
private IVideoService VideoService { get; set; }
// TASK OPTIONS
public MediaType MediaType { get; private set; }
public BaseStream Stream { get; private set; }
public TimeSpan TrimStart { get; private set; }
public TimeSpan TrimEnd { get; private set; }
public string Filename { get; private set; }
public MediaFileExtension Extension { get; private set; }
public StorageFolder Location { get; private set; }
public double Schedule { get; private set; }
#endregion
#region CHANGE PROPERTIES FROM PARENT VOIDS
// LOCATION
public void ChangeLocation(StorageFolder location)
{
Location = location;
HomeAddingLocationSettingControl.Description = Location.Path ?? $@"{UserDataPaths.GetDefault().Downloads}\VDownload";
}
// SCHEDULE
public void ChangeSchedule(double schedule)
{
Schedule = schedule;
HomeAddingScheduleNumberBox.Value = Schedule;
}
#endregion
#region EVENT HANDLERS VOIDS
// MEDIA TYPE COMBOBOX SELECTION CHANGED
private void HomeAddingMediaTypeSettingControlComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MediaType = (MediaType)HomeAddingMediaTypeSettingControlComboBox.SelectedIndex;
if (HomeAddingMediaTypeSettingControlComboBox.SelectedIndex == (int)MediaType.OnlyAudio)
{
HomeAddingQualitySettingControl.Visibility = Visibility.Collapsed;
HomeAddingQualitySettingControlComboBox.SelectedIndex = VideoService.BaseStreams.Count() - 1;
HomeAddingExtensionComboBox.Items.Clear();
foreach (AudioFileExtension extension in Enum.GetValues(typeof(AudioFileExtension)))
{
HomeAddingExtensionComboBox.Items.Add(extension);
}
HomeAddingExtensionComboBox.SelectedIndex = (int)Config.GetValue("default_audio_extension") - 3;
}
else
{
HomeAddingQualitySettingControl.Visibility = Visibility.Visible;
HomeAddingQualitySettingControlComboBox.SelectedIndex = 0;
HomeAddingExtensionComboBox.Items.Clear();
foreach (VideoFileExtension extension in Enum.GetValues(typeof(VideoFileExtension)))
{
HomeAddingExtensionComboBox.Items.Add(extension);
}
HomeAddingExtensionComboBox.SelectedIndex = (int)Config.GetValue("default_video_extension");
}
}
// QUALITY COMBOBOX SELECTION CHANGED
private void HomeAddingQualitySettingControlComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Stream = VideoService.BaseStreams[HomeAddingQualitySettingControlComboBox.SelectedIndex];
}
// TRIM START TEXTBOX LOST FOCUS
private void HomeAddingTrimStartTextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (!HomeAddingTrimStartTextBox.Text.Contains('_'))
{
string[] segments = HomeAddingTrimStartTextBox.Text.Split(':').Reverse().ToArray();
int.TryParse(segments.ElementAtOrDefault(0), out int seconds);
int.TryParse(segments.ElementAtOrDefault(1), out int minutes);
int.TryParse(segments.ElementAtOrDefault(2), out int hours);
TimeSpan parsedTimeSpan = new TimeSpan(hours, minutes, seconds);
if (parsedTimeSpan < VideoService.Metadata.Duration && parsedTimeSpan > TimeSpan.Zero) TrimStart = parsedTimeSpan;
else
{
TrimStart = TimeSpan.Zero;
HomeAddingTrimStartTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(TrimStart, VideoService.Metadata.Duration);
}
}
}
// TRIM END TEXTBOX LOST FOCUS
private void HomeAddingTrimEndTextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (!HomeAddingTrimEndTextBox.Text.Contains('_'))
{
string[] segments = HomeAddingTrimEndTextBox.Text.Split(':').Reverse().ToArray();
int.TryParse(segments.ElementAtOrDefault(0), out int seconds);
int.TryParse(segments.ElementAtOrDefault(1), out int minutes);
int.TryParse(segments.ElementAtOrDefault(2), out int hours);
TimeSpan parsedTimeSpan = new TimeSpan(hours, minutes, seconds);
if (parsedTimeSpan < VideoService.Metadata.Duration && parsedTimeSpan > TimeSpan.Zero) TrimEnd = parsedTimeSpan;
else
{
TrimEnd = VideoService.Metadata.Duration;
HomeAddingTrimEndTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(TrimEnd);
}
}
}
// FILENAME TEXTBOX LOST FOCUS
private void HomeAddingFilenameTextBox_LostFocus(object sender, RoutedEventArgs e)
{
foreach (char c in Path.GetInvalidFileNameChars()) HomeAddingFilenameTextBox.Text = HomeAddingFilenameTextBox.Text.Replace(c, ' ');
Filename = HomeAddingFilenameTextBox.Text;
}
// EXTENSION COMBOBOX SELECTION CHANGED
private void HomeAddingExtensionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Extension = (MediaFileExtension)HomeAddingExtensionComboBox.SelectedIndex + (MediaType == MediaType.OnlyAudio ? 3 : 0);
}
// SCHEDULE NUMBERBOX LOST FOCUS
private void HomeAddingScheduleNumberBox_LostFocus(object sender, RoutedEventArgs e)
{
if (HomeAddingScheduleNumberBox.Value == double.NaN) HomeAddingScheduleNumberBox.Value = 0;
Schedule = HomeAddingScheduleNumberBox.Value;
}
// LOCATION BROWSE BUTTON CLICKED
private async void HomeAddingLocationBrowseButton_Click(object sender, RoutedEventArgs e)
{
// Create location picker
FolderPicker picker = new FolderPicker
{
SuggestedStartLocation = PickerLocationId.Downloads
};
picker.FileTypeFilter.Add("*");
// Select location
StorageFolder selectedFolder = await picker.PickSingleFolderAsync();
if (selectedFolder != null)
{
try
{
await(await selectedFolder.CreateFileAsync("VDownloadLocationAccessTest")).DeleteAsync();
StorageApplicationPermissions.FutureAccessList.AddOrReplace("last_media_location", selectedFolder);
Location = selectedFolder;
HomeAddingLocationSettingControl.Description = Location.Path;
}
catch (UnauthorizedAccessException) { }
}
}
#endregion
}
}

View File

@@ -0,0 +1,42 @@
<UserControl
x:Class="VDownload.Views.Home.HomeOptionsBarPlaylistSearch"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VDownload.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
mc:Ignorable="d"
d:DesignHeight="100"
d:DesignWidth="400">
<Grid x:Name="HomeOptionsBarPlaylistSearchControlGrid" Margin="10" ColumnSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!-- URL TEXTBOX -->
<TextBox x:Name="HomeOptionsBarPlaylistSearchControlUrlTextBox" x:Uid="HomeOptionsBarPlaylistSearchControlUrlTextBox" Grid.Column="0" VerticalAlignment="Center"/>
<!-- MAX VIDEOS NUMBERBOX -->
<muxc:NumberBox x:Name="HomeOptionsBarPlaylistSearchControlMaxVideosNumberBox" Grid.Column="1" VerticalAlignment="Center" SpinButtonPlacementMode="Compact" Minimum="0" LostFocus="HomeOptionsBarPlaylistSearchControlMaxVideosNumberBox_LostFocus"/>
<!-- SEARCH BUTTON-->
<Button x:Name="HomeOptionsBarPlaylistSearchControlSearchButton" x:Uid="HomeOptionsBarPlaylistSearchControlSearchButton" Grid.Column="2" Click="HomeOptionsBarPlaylistSearchControlSearchButton_Click"/>
<!-- HELP BUTTON -->
<Button x:Name="HomeOptionsBarPlaylistSearchControlHelpButton" Grid.Column="3" Content="?" Click="HomeOptionsBarPlaylistSearchControlHelpButton_Click">
<Button.Resources>
<muxc:TeachingTip x:Name="HomeOptionsBarPlaylistSearchControlInfoBox" x:Uid="HomeOptionsBarPlaylistSearchControlInfoBox" Target="{x:Bind HomeOptionsBarPlaylistSearchControlGrid}"/>
</Button.Resources>
</Button>
<!-- STATUS CONTROL -->
<ContentPresenter x:Name="HomeOptionsBarPlaylistSearchControlStatusControl" Margin="-10,0,0,0" Grid.Column="4"/>
</Grid>
</UserControl>

View File

@@ -0,0 +1,175 @@
using Microsoft.Toolkit.Uwp.Connectivity;
using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using VDownload.Core.Enums;
using VDownload.Core.EventArgs;
using VDownload.Core.Exceptions;
using VDownload.Core.Interfaces;
using VDownload.Core.Services;
using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
namespace VDownload.Views.Home
{
public sealed partial class HomeOptionsBarPlaylistSearch : UserControl
{
#region CONSTANTS
// RESOURCES
private static readonly ResourceDictionary IconRes = new ResourceDictionary { Source = new Uri("ms-appx:///Resources/Icons.xaml") };
// SEARCHING STATUS CONTROLS
private static readonly Microsoft.UI.Xaml.Controls.ProgressRing HomeOptionsBarPlaylistSearchStatusProgressRing = new Microsoft.UI.Xaml.Controls.ProgressRing { Width = 15, Height = 15, Margin = new Thickness(15, 5, 5, 5), IsActive = true };
private static readonly Image HomeOptionsBarPlaylistSearchStatusErrorImage = new Image { Width = 15, Height = 15, Margin = new Thickness(15, 5, 5, 5), Source = (SvgImageSource)IconRes["ErrorIcon"] };
#endregion
#region CONSTRUCTORS
public HomeOptionsBarPlaylistSearch()
{
this.InitializeComponent();
// Set default max videos
HomeOptionsBarPlaylistSearchControlMaxVideosNumberBox.Value = (int)Config.GetValue("default_max_playlist_videos");
}
#endregion
#region PROPERTIES
public CancellationToken CancellationToken { get; set; }
#endregion
#region EVENT HANDLERS
// NUMBERBOX FOCUS LOST
private void HomeOptionsBarPlaylistSearchControlMaxVideosNumberBox_LostFocus(object sender, RoutedEventArgs e)
{
if (double.IsNaN(HomeOptionsBarPlaylistSearchControlMaxVideosNumberBox.Value)) HomeOptionsBarPlaylistSearchControlMaxVideosNumberBox.Value = (int)Config.GetValue("default_max_playlist_videos");
}
// SEARCH BUTTON CLICKED
private async void HomeOptionsBarPlaylistSearchControlSearchButton_Click(object sender, RoutedEventArgs e)
{
// Invoke search button click event
SearchButtonClick?.Invoke(this, EventArgs.Empty);
// Close info box
HomeOptionsBarPlaylistSearchControlInfoBox.IsOpen = false;
// Set SearchingStatusControl
HomeOptionsBarPlaylistSearchControlStatusControl.Content = HomeOptionsBarPlaylistSearchStatusProgressRing;
// Parse url
(PlaylistSource Type, string ID) source = Source.GetPlaylistSource(HomeOptionsBarPlaylistSearchControlUrlTextBox.Text);
// Check url
if (source.Type == PlaylistSource.Null)
{
HomeOptionsBarPlaylistSearchControlStatusControl.Content = HomeOptionsBarPlaylistSearchStatusErrorImage;
}
else
{
// Select video service
IPlaylistService playlistService = null;
switch (source.Type)
{
case PlaylistSource.TwitchChannel: playlistService = new Core.Services.Sources.Twitch.Channel(source.ID); break;
}
// Get metadata and streams
try
{
await playlistService.GetMetadataAsync(CancellationToken);
await playlistService.GetVideosAsync((int)Math.Round(HomeOptionsBarPlaylistSearchControlMaxVideosNumberBox.Value), CancellationToken);
}
catch (OperationCanceledException)
{
HomeOptionsBarPlaylistSearchControlStatusControl.Content = null;
return;
}
catch (MediaNotFoundException)
{
HomeOptionsBarPlaylistSearchControlStatusControl.Content = HomeOptionsBarPlaylistSearchStatusErrorImage;
return;
}
catch (TwitchAccessTokenNotFoundException)
{
HomeOptionsBarPlaylistSearchControlStatusControl.Content = HomeOptionsBarPlaylistSearchStatusErrorImage;
ContentDialog twitchAccessTokenNotFoundErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingTwitchAccessTokenNotFoundErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await twitchAccessTokenNotFoundErrorDialog.ShowAsync();
return;
}
catch (TwitchAccessTokenNotValidException)
{
HomeOptionsBarPlaylistSearchControlStatusControl.Content = HomeOptionsBarPlaylistSearchStatusErrorImage;
ContentDialog twitchAccessTokenNotValidErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingTwitchAccessTokenNotValidErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await twitchAccessTokenNotValidErrorDialog.ShowAsync();
return;
}
catch (WebException ex)
{
HomeOptionsBarPlaylistSearchControlStatusControl.Content = HomeOptionsBarPlaylistSearchStatusErrorImage;
if (!NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable)
{
ContentDialog internetAccessErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingInternetConnectionErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await internetAccessErrorDialog.ShowAsync();
return;
}
else throw;
}
// Set searching status control to done (null)
HomeOptionsBarPlaylistSearchControlStatusControl.Content = null;
// Invoke search successed event
PlaylistSearchSuccessed?.Invoke(this, new PlaylistSearchSuccessedEventArgs { PlaylistService = playlistService });
}
}
// HELP BUTTON CLICKED
private void HomeOptionsBarPlaylistSearchControlHelpButton_Click(object sender, RoutedEventArgs e)
{
// Switch info box
HomeOptionsBarPlaylistSearchControlInfoBox.IsOpen = !HomeOptionsBarPlaylistSearchControlInfoBox.IsOpen;
}
#endregion
#region EVENT HANDLERS
public event EventHandler<PlaylistSearchSuccessedEventArgs> PlaylistSearchSuccessed;
public event EventHandler SearchButtonClick;
#endregion
}
}

View File

@@ -0,0 +1,38 @@
<UserControl
x:Class="VDownload.Views.Home.HomeOptionsBarVideoSearch"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VDownload.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
mc:Ignorable="d"
d:DesignHeight="100"
d:DesignWidth="400">
<Grid x:Name="HomeOptionsBarVideoSearchControlGrid" Margin="10" ColumnSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!-- URL TEXTBOX -->
<TextBox x:Name="HomeOptionsBarVideoSearchControlUrlTextBox" x:Uid="HomeOptionsBarVideoSearchControlUrlTextBox" Grid.Column="0" VerticalAlignment="Center"/>
<!-- SEARCH BUTTON -->
<Button x:Name="HomeOptionsBarVideoSearchControlSearchButton" x:Uid="HomeOptionsBarVideoSearchControlSearchButton" Grid.Column="1" Click="HomeOptionsBarVideoSearchControlSearchButton_Click"/>
<!-- INFO BUTTON -->
<Button x:Name="HomeOptionsBarVideoSearchControlHelpButton" x:Uid="HomeOptionsBarVideoSearchControlHelpButton" Grid.Column="2" Content="?" Click="HomeOptionsBarVideoSearchControlHelpButton_Click">
<Button.Resources>
<muxc:TeachingTip x:Name="HomeOptionsBarVideoSearchControlInfoBox" x:Uid="HomeOptionsBarAddVideoControlInfoBox" Target="{x:Bind HomeOptionsBarVideoSearchControlGrid}"/>
</Button.Resources>
</Button>
<!-- STATUS CONTROL -->
<ContentPresenter x:Name="HomeOptionBarVideoSearchControlStatusControl" Margin="-10,0,0,0" Grid.Column="3"/>
</Grid>
</UserControl>

View File

@@ -0,0 +1,166 @@
using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using VDownload.Core.Enums;
using VDownload.Core.EventArgs;
using VDownload.Core.Exceptions;
using VDownload.Core.Interfaces;
using VDownload.Core.Services;
using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
namespace VDownload.Views.Home
{
public sealed partial class HomeOptionsBarVideoSearch : UserControl
{
#region CONSTANTS
// RESOURCES
private static readonly ResourceDictionary IconRes = new ResourceDictionary { Source = new Uri("ms-appx:///Resources/Icons.xaml") };
// SEARCHING STATUS CONTROLS
private static readonly Microsoft.UI.Xaml.Controls.ProgressRing HomeOptionsBarVideoSearchStatusProgressRing = new Microsoft.UI.Xaml.Controls.ProgressRing { Width = 15, Height = 15, Margin = new Thickness(15, 5, 5, 5), IsActive = true };
private static readonly Image HomeOptionsBarVideoSearchStatusErrorImage = new Image { Width = 15, Height = 15, Margin = new Thickness(15, 5, 5, 5), Source = (SvgImageSource)IconRes["ErrorIcon"] };
#endregion
#region CONSTRUCTORS
public HomeOptionsBarVideoSearch()
{
this.InitializeComponent();
}
#endregion
#region PROPERTIES
public CancellationToken CancellationToken { get; set; }
#endregion
#region EVENT HANDLERS VOIDS
// SEARCH BUTTON CLICKED
private async void HomeOptionsBarVideoSearchControlSearchButton_Click(object sender, RoutedEventArgs e)
{
// Invoke search button click event
SearchButtonClick?.Invoke(this, EventArgs.Empty);
// Close info box
HomeOptionsBarVideoSearchControlInfoBox.IsOpen = false;
// Set SearchingStatusControl
HomeOptionBarVideoSearchControlStatusControl.Content = HomeOptionsBarVideoSearchStatusProgressRing;
// Parse url
(VideoSource Type, string ID) source = Source.GetVideoSource(HomeOptionsBarVideoSearchControlUrlTextBox.Text);
// Check url
if (source.Type == VideoSource.Null)
{
HomeOptionBarVideoSearchControlStatusControl.Content = HomeOptionsBarVideoSearchStatusErrorImage;
}
else
{
// Select video service
IVideoService videoService = null;
switch (source.Type)
{
case VideoSource.TwitchVod: videoService = new Core.Services.Sources.Twitch.Vod(source.ID); break;
case VideoSource.TwitchClip: videoService = new Core.Services.Sources.Twitch.Clip(source.ID); break;
}
// Get metadata and streams
try
{
await videoService.GetMetadataAsync(CancellationToken);
await videoService.GetStreamsAsync(CancellationToken);
}
catch (OperationCanceledException)
{
HomeOptionBarVideoSearchControlStatusControl.Content = null;
return;
}
catch (MediaNotFoundException)
{
HomeOptionBarVideoSearchControlStatusControl.Content = HomeOptionsBarVideoSearchStatusErrorImage;
return;
}
catch (TwitchAccessTokenNotFoundException)
{
HomeOptionBarVideoSearchControlStatusControl.Content = HomeOptionsBarVideoSearchStatusErrorImage;
ContentDialog twitchAccessTokenNotFoundErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingTwitchAccessTokenNotFoundErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await twitchAccessTokenNotFoundErrorDialog.ShowAsync();
return;
}
catch (TwitchAccessTokenNotValidException)
{
HomeOptionBarVideoSearchControlStatusControl.Content = HomeOptionsBarVideoSearchStatusErrorImage;
ContentDialog twitchAccessTokenNotValidErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingTwitchAccessTokenNotValidErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await twitchAccessTokenNotValidErrorDialog.ShowAsync();
return;
}
catch (WebException wex)
{
HomeOptionBarVideoSearchControlStatusControl.Content = HomeOptionsBarVideoSearchStatusErrorImage;
if (wex.Response is null)
{
ContentDialog internetAccessErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingInternetConnectionErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await internetAccessErrorDialog.ShowAsync();
return;
}
else throw;
}
// Set searching status control to done (null)
HomeOptionBarVideoSearchControlStatusControl.Content = null;
// Invoke search successed event
VideoSearchSuccessed?.Invoke(this, new VideoSearchSuccessedEventArgs { VideoService = videoService });
}
}
// HELP BUTTON CLICKED
private void HomeOptionsBarVideoSearchControlHelpButton_Click(object sender, RoutedEventArgs e)
{
// Switch info box
HomeOptionsBarVideoSearchControlInfoBox.IsOpen = !HomeOptionsBarVideoSearchControlInfoBox.IsOpen;
}
#endregion
#region EVENT HANDLERS
public event EventHandler<VideoSearchSuccessedEventArgs> VideoSearchSuccessed;
public event EventHandler SearchButtonClick;
#endregion
}
}

View File

@@ -0,0 +1,75 @@
<UserControl
x:Class="VDownload.Views.Home.Controls.HomeSerialAddingVideoPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VDownload.Views.Home"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
xmlns:cc="using:VDownload.Controls"
xmlns:ex="using:Microsoft.Toolkit.Uwp.UI"
Loading="HomeSerialAddingVideoPanel_Loading"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ms-appx:///Resources/Colors.xaml"/>
<ResourceDictionary Source="ms-appx:///Resources/Icons.xaml"/>
<ResourceDictionary Source="ms-appx:///Resources/Converters.xaml"/>
</ResourceDictionary.MergedDictionaries>
<x:String x:Key="MetadataIconSize">14</x:String>
<x:String x:Key="MetadataTextSize">11</x:String>
</ResourceDictionary>
</UserControl.Resources>
<muxc:Expander x:Name="HomeSerialAddingVideoExpander" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" Background="{ThemeResource HomePlaylistAddingVideoPanelContentBackgroundColor}">
<muxc:Expander.Header>
<Grid Margin="-5,10,-15,10" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" Height="80" Source="{x:Bind ThumbnailImage}"/>
<Grid Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Spacing="5" Orientation="Horizontal">
<Image Width="{StaticResource MetadataIconSize}" Source="{ThemeResource AuthorIcon}"/>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{StaticResource MetadataTextSize}" Text="{x:Bind Author}"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="0" Spacing="5" Orientation="Horizontal">
<Image Width="{StaticResource MetadataIconSize}" Source="{ThemeResource ViewsIcon}"/>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{StaticResource MetadataTextSize}" Text="{x:Bind Views}"/>
</StackPanel>
<StackPanel Grid.Row="0" Grid.Column="1" Spacing="5" Orientation="Horizontal">
<Image Width="{StaticResource MetadataIconSize}" Source="{ThemeResource DateIcon}"/>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{StaticResource MetadataTextSize}" Text="{x:Bind Date}"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="1" Spacing="5" Orientation="Horizontal">
<Image Width="{StaticResource MetadataIconSize}" Source="{ThemeResource DurationIcon}"/>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{StaticResource MetadataTextSize}" Text="{x:Bind Duration}"/>
</StackPanel>
</Grid>
<TextBlock Grid.Row="0" Grid.Column="1" FontSize="15" VerticalAlignment="Center" FontWeight="SemiBold" Text="{x:Bind Title}"/>
<AppBarButton Grid.Row="0" Grid.Column="2" Margin="0,-4,0,-4" Width="40" Height="48" Icon="{x:Bind SourceImage}" Click="HomeSerialAddingVideoPanelSourceButton_Click"/>
<AppBarButton Grid.Row="1" Grid.Column="2" Margin="0,-4,0,-4" Width="40" Height="48" Icon="Delete" Click="HomeSerialAddingVideoPanelDeleteButton_Click"/>
</Grid>
</muxc:Expander.Header>
</muxc:Expander>
</UserControl>

View File

@@ -0,0 +1,103 @@
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using VDownload.Core.Interfaces;
using VDownload.Core.Services;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
namespace VDownload.Views.Home.Controls
{
public sealed partial class HomeSerialAddingVideoPanel : UserControl
{
#region CONSTANTS
private readonly ResourceDictionary ImagesRes = new ResourceDictionary { Source = new Uri("ms-appx:///Resources/Images.xaml") };
#endregion
#region CONSTRUCTORS
public HomeSerialAddingVideoPanel(IVideoService videoService)
{
this.InitializeComponent();
// Set video service object
VideoService = videoService;
// Set metadata
ThumbnailImage = VideoService.Metadata.Thumbnail != null ? new BitmapImage { UriSource = VideoService.Metadata.Thumbnail } : (BitmapImage)ImagesRes["UnknownThumbnailImage"];
SourceImage = new BitmapIcon { UriSource = new Uri($"ms-appx:///Assets/Sources/{VideoService.GetType().Namespace.Split(".").Last()}.png"), ShowAsMonochrome = false };
Title = VideoService.Metadata.Title;
Author = VideoService.Metadata.Author;
Views = VideoService.Metadata.Views.ToString();
Date = VideoService.Metadata.Date.ToString(CultureInfo.InstalledUICulture.DateTimeFormat.ShortDatePattern);
Duration = TimeSpanCustomFormat.ToOptTHBaseMMSS(VideoService.Metadata.Duration);
// Set video options control
HomeVideoAddingOptionsControl = new HomeAddingVideoOptions(VideoService);
}
#endregion
#region PROPERTIES
// BASE VIDEO DATA
public IVideoService VideoService { get; set; }
// VIDEO DATA
private ImageSource ThumbnailImage { get; set; }
private IconElement SourceImage { get; set; }
private string Title { get; set; }
private string Author { get; set; }
private string Views { get; set; }
private string Date { get; set; }
private string Duration { get; set; }
// OPTIONS CONTROL
public HomeAddingVideoOptions HomeVideoAddingOptionsControl { get; private set; }
#endregion
#region EVENT HANDLERS VOIDS
// ON CONTROL LOADING
private async void HomeSerialAddingVideoPanel_Loading(FrameworkElement sender, object args)
{
await HomeVideoAddingOptionsControl.Init();
HomeSerialAddingVideoExpander.Content = HomeVideoAddingOptionsControl;
}
// SOURCE BUTTON CLICKED
private async void HomeSerialAddingVideoPanelSourceButton_Click(object sender, RoutedEventArgs e)
{
// Launch the website
await Windows.System.Launcher.LaunchUriAsync(VideoService.VideoUrl);
}
// DELETE BUTTON CLICKED
private void HomeSerialAddingVideoPanelDeleteButton_Click(object sender, RoutedEventArgs e)
{
DeleteRequested?.Invoke(this, EventArgs.Empty);
}
#endregion
#region EVENT HANDLERS
public event EventHandler DeleteRequested;
#endregion
}
}

View File

@@ -1,5 +1,5 @@
<UserControl <UserControl
x:Class="VDownload.Views.Home.HomeTaskPanel" x:Class="VDownload.Views.Home.Controls.HomeTaskPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VDownload.Views.Home" xmlns:local="using:VDownload.Views.Home"

View File

@@ -19,7 +19,7 @@ using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Media.Imaging;
namespace VDownload.Views.Home namespace VDownload.Views.Home.Controls
{ {
public sealed partial class HomeTaskPanel : UserControl public sealed partial class HomeTaskPanel : UserControl
{ {
@@ -54,16 +54,16 @@ namespace VDownload.Views.Home
SourceImage = new BitmapIcon { UriSource = new Uri($"ms-appx:///Assets/Sources/{Data.VideoService.GetType().Namespace.Split(".").Last()}.png"), ShowAsMonochrome = false }; SourceImage = new BitmapIcon { UriSource = new Uri($"ms-appx:///Assets/Sources/{Data.VideoService.GetType().Namespace.Split(".").Last()}.png"), ShowAsMonochrome = false };
// Set duration // Set duration
TimeSpan newDuration = Data.TrimEnd.Subtract(Data.TrimStart); TimeSpan newDuration = Data.TaskOptions.TrimEnd.Subtract(Data.TaskOptions.TrimStart);
Duration = TimeSpanCustomFormat.ToOptTHBaseMMSS(newDuration); Duration = TimeSpanCustomFormat.ToOptTHBaseMMSS(newDuration);
if (Data.VideoService.Metadata.Duration > newDuration) Duration += $" ({TimeSpanCustomFormat.ToOptTHBaseMMSS(Data.TrimStart, Data.TrimEnd)} - {TimeSpanCustomFormat.ToOptTHBaseMMSS(Data.TrimEnd, Data.TrimStart)})"; if (Data.VideoService.Metadata.Duration > newDuration) Duration += $" ({TimeSpanCustomFormat.ToOptTHBaseMMSS(Data.TaskOptions.TrimStart, Data.TaskOptions.TrimEnd)} - {TimeSpanCustomFormat.ToOptTHBaseMMSS(Data.TaskOptions.TrimEnd, Data.TaskOptions.TrimStart)})";
// Set media type // Set media type
MediaTypeQuality += ResourceLoader.GetForCurrentView().GetString($"MediaType{Data.MediaType}Text"); MediaTypeQuality += ResourceLoader.GetForCurrentView().GetString($"MediaType{Data.TaskOptions.MediaType}Text");
if (Data.MediaType != MediaType.OnlyAudio) MediaTypeQuality += $" ({Data.Stream.Height}p{(Data.Stream.FrameRate > 0 ? Data.Stream.FrameRate.ToString() : "N/A")})"; if (Data.TaskOptions.MediaType != MediaType.OnlyAudio) MediaTypeQuality += $" ({Data.TaskOptions.Stream.Height}p{(Data.TaskOptions.Stream.FrameRate > 0 ? Data.TaskOptions.Stream.FrameRate.ToString() : "N/A")})";
// Set file // Set file
File += $@"{(Data.Location != null ? Data.Location.Path : $@"{UserDataPaths.GetDefault().Downloads}\VDownload")}\{Data.Filename}.{Data.Extension.ToString().ToLower()}"; File += $@"{(Data.TaskOptions.Location != null ? Data.TaskOptions.Location.Path : $@"{UserDataPaths.GetDefault().Downloads}\VDownload")}\{Data.TaskOptions.Filename}.{Data.TaskOptions.Extension.ToString().ToLower()}";
// Set state controls // Set state controls
HomeTaskPanelStateIcon.Source = (SvgImageSource)IconsRes["StateIdleIcon"]; HomeTaskPanelStateIcon.Source = (SvgImageSource)IconsRes["StateIdleIcon"];
@@ -110,9 +110,9 @@ namespace VDownload.Views.Home
CancellationTokenSource = new CancellationTokenSource(); CancellationTokenSource = new CancellationTokenSource();
// Scheduling // Scheduling
if (Data.Schedule > 0) if (Data.TaskOptions.Schedule > 0)
{ {
DateTime ScheduledDateTime = DateTime.Now.AddMinutes(Data.Schedule); DateTime ScheduledDateTime = DateTime.Now.AddMinutes(Data.TaskOptions.Schedule);
// Set task status // Set task status
Status = Core.Enums.TaskStatus.Scheduled; Status = Core.Enums.TaskStatus.Scheduled;
@@ -181,7 +181,7 @@ namespace VDownload.Views.Home
// Start task // Start task
CancellationTokenSource.Token.ThrowIfCancellationRequested(); CancellationTokenSource.Token.ThrowIfCancellationRequested();
StorageFile tempOutputFile = await Data.VideoService.DownloadAndTranscodeAsync(tempFolder, Data.Stream, Data.Extension, Data.MediaType, Data.TrimStart, Data.TrimEnd, CancellationTokenSource.Token); StorageFile tempOutputFile = await Data.VideoService.DownloadAndTranscodeAsync(tempFolder, Data.TaskOptions.Stream, Data.TaskOptions.Extension, Data.TaskOptions.MediaType, Data.TaskOptions.TrimStart, Data.TaskOptions.TrimEnd, CancellationTokenSource.Token);
// Dispose session // Dispose session
session.Dispose(); session.Dispose();
@@ -195,9 +195,9 @@ namespace VDownload.Views.Home
HomeTaskPanelStateProgressBar.IsIndeterminate = true; HomeTaskPanelStateProgressBar.IsIndeterminate = true;
// Move to output location // Move to output location
string filename = $"{Data.Filename}.{Data.Extension.ToString().ToLower()}"; string filename = $"{Data.TaskOptions.Filename}.{Data.TaskOptions.Extension.ToString().ToLower()}";
CreationCollisionOption collisionOption = (bool)Config.GetValue("replace_output_file_if_exists") ? CreationCollisionOption.ReplaceExisting : CreationCollisionOption.GenerateUniqueName; CreationCollisionOption collisionOption = (bool)Config.GetValue("replace_output_file_if_exists") ? CreationCollisionOption.ReplaceExisting : CreationCollisionOption.GenerateUniqueName;
StorageFile outputFile = await (Data.Location != null ? Data.Location.CreateFileAsync(filename, collisionOption): DownloadsFolder.CreateFileAsync(filename, collisionOption)); StorageFile outputFile = await (Data.TaskOptions.Location != null ? Data.TaskOptions.Location.CreateFileAsync(filename, collisionOption): DownloadsFolder.CreateFileAsync(filename, collisionOption));
await tempOutputFile.MoveAndReplaceAsync(outputFile); await tempOutputFile.MoveAndReplaceAsync(outputFile);
// Stop stopwatch // Stop stopwatch

View File

@@ -1,5 +1,5 @@
<UserControl <UserControl
x:Class="VDownload.Views.Home.HomeTasksListPlaceholder" x:Class="VDownload.Views.Home.Controls.HomeTasksListPlaceholder"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VDownload.Views.Home" xmlns:local="using:VDownload.Views.Home"

View File

@@ -1,6 +1,6 @@
using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls;
namespace VDownload.Views.Home namespace VDownload.Views.Home.Controls
{ {
public sealed partial class HomeTasksListPlaceholder : UserControl public sealed partial class HomeTasksListPlaceholder : UserControl
{ {

View File

@@ -84,12 +84,12 @@
<ContentPresenter x:Name="HomeOptionsBarAddingControl" Grid.Row="1" Grid.Column="0"/> <ContentPresenter x:Name="HomeOptionsBarAddingControl" Grid.Row="1" Grid.Column="0"/>
<ContentPresenter x:Name="HomeOptionsBarSearchingStatusControl" Grid.Row="1" Grid.Column="1"/> <ContentPresenter x:Name="HomeOptionsBarSearchingStatusControl" Grid.Row="1" Grid.Column="1"/>
<StackPanel x:Name="HomeOptionBarButtonsStackPanel" Grid.Row="1" Grid.Column="3" Margin="3,0,3,0" HorizontalAlignment="Center" Orientation="Horizontal"> <StackPanel x:Name="HomeOptionBarButtonsStackPanel" Grid.Row="1" Grid.Column="3" Margin="3,0,3,0" HorizontalAlignment="Center" Orientation="Horizontal">
<AppBarButton x:Name="HomeOptionsBarLoadSubscripionsButton" x:Uid="HomeOptionsBarLoadSubscripionsButton" Icon="Favorite" Label="Load subscriptions" Width="120"/> <AppBarButton x:Name="HomeOptionsBarLoadSubscripionsButton" x:Uid="HomeOptionsBarLoadSubscripionsButton" Icon="Favorite" Width="120"/>
<AppBarSeparator VerticalAlignment="Center" Height="50"/> <AppBarSeparator VerticalAlignment="Center" Height="50"/>
<AppBarToggleButton x:Name="HomeOptionsBarAddPlaylistButton" x:Uid="HomeOptionsBarAddPlaylistButton" Icon="List" Label="Add playlist" Width="85" Checked="HomeOptionsBarAddPlaylistButton_Checked" Unchecked="HomeOptionsBarAddingButtons_Unchecked"/> <AppBarToggleButton x:Name="HomeOptionsBarPlaylistSearchButton" x:Uid="HomeOptionsBarPlaylistSearchButton" Icon="List" Width="85" Checked="HomeOptionsBarPlaylistSearchButton_Checked" Unchecked="HomeOptionsBarAddingButtons_Unchecked"/>
<AppBarToggleButton x:Name="HomeOptionsBarAddVideoButton" x:Uid="HomeOptionsBarAddVideoButton" Icon="Video" Label="Add video" Width="75" Checked="HomeOptionsBarAddVideoButton_Checked" Unchecked="HomeOptionsBarAddingButtons_Unchecked"/> <AppBarToggleButton x:Name="HomeOptionsBarVideoSearchButton" x:Uid="HomeOptionsBarVideoSearchButton" Icon="Video" Width="75" Checked="HomeOptionsBarVideoSearchButton_Checked" Unchecked="HomeOptionsBarAddingButtons_Unchecked"/>
<AppBarSeparator VerticalAlignment="Center" Height="50"/> <AppBarSeparator VerticalAlignment="Center" Height="50"/>
<AppBarButton x:Name="HomeOptionsBarDownloadAllButton" x:Uid="HomeOptionsBarDownloadAllButton" Icon="Download" Label="Download All" Width="90" Click="HomeOptionsBarDownloadAllButton_Click"/> <AppBarButton x:Name="HomeOptionsBarDownloadAllButton" x:Uid="HomeOptionsBarDownloadAllButton" Icon="Download" Width="90" Click="HomeOptionsBarDownloadAllButton_Click"/>
</StackPanel> </StackPanel>
</Grid> </Grid>
</Grid> </Grid>

View File

@@ -12,6 +12,7 @@ using VDownload.Core.Exceptions;
using VDownload.Core.Interfaces; using VDownload.Core.Interfaces;
using VDownload.Core.Services; using VDownload.Core.Services;
using VDownload.Core.Structs; using VDownload.Core.Structs;
using VDownload.Views.Home.Controls;
using Windows.ApplicationModel.Resources; using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml; using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls;
@@ -22,21 +23,6 @@ namespace VDownload.Views.Home
{ {
public sealed partial class HomeMain : Page public sealed partial class HomeMain : Page
{ {
#region CONSTANTS
// RESOURCES
private static readonly ResourceDictionary ImageRes = new ResourceDictionary { Source = new Uri("ms-appx:///Resources/Icons.xaml") };
// SEARCHING STATUS CONTROLS
private static readonly Microsoft.UI.Xaml.Controls.ProgressRing HomeOptionsBarSearchingStatusProgressRing = new Microsoft.UI.Xaml.Controls.ProgressRing { Width = 15, Height = 15, Margin = new Thickness(5), IsActive = true };
private static readonly Image HomeOptionsBarSearchingStatusErrorImage = new Image { Width = 15, Height = 15, Margin = new Thickness(5), Source = (SvgImageSource)ImageRes["ErrorIcon"] };
// TASKS LIST PLACEHOLDER
private static readonly HomeTasksListPlaceholder HomeTasksListPlaceholder = new HomeTasksListPlaceholder();
#endregion
#region CONSTRUCTORS #region CONSTRUCTORS
public HomeMain() public HomeMain()
@@ -87,231 +73,72 @@ namespace VDownload.Views.Home
} }
else else
{ {
HomeTasksListCurrentParent.Content = HomeTasksListPlaceholder; HomeTasksListCurrentParent.Content = new HomeTasksListPlaceholder();
} }
} }
// ADD VIDEO BUTTON CHECKED // SEARCH VIDEO BUTTON CHECKED
private void HomeOptionsBarAddVideoButton_Checked(object sender, RoutedEventArgs e) private void HomeOptionsBarVideoSearchButton_Checked(object sender, RoutedEventArgs e)
{ {
// Uncheck playlist button // Uncheck playlist button
HomeOptionsBarAddPlaylistButton.IsChecked = false; HomeOptionsBarPlaylistSearchButton.IsChecked = false;
// Create video adding control // Create video adding control
HomeOptionsBarAddVideoControl homeOptionsBarAddVideoControl = new HomeOptionsBarAddVideoControl(); HomeOptionsBarVideoSearch homeOptionsBarSearchVideoControl = new HomeOptionsBarVideoSearch();
homeOptionsBarAddVideoControl.SearchButtonClicked += HomeOptionsBarAddVideoControl_SearchButtonClicked; homeOptionsBarSearchVideoControl.VideoSearchSuccessed += HomeOptionsBarVideoSearchControl_VideoSearchSuccessed;
HomeOptionsBarAddingControl.Content = homeOptionsBarAddVideoControl; homeOptionsBarSearchVideoControl.SearchButtonClick += (s, a) =>
{
SearchingCancellationToken.Cancel();
SearchingCancellationToken = new CancellationTokenSource();
homeOptionsBarSearchVideoControl.CancellationToken = SearchingCancellationToken.Token;
};
HomeOptionsBarAddingControl.Content = homeOptionsBarSearchVideoControl;
} }
// ADD VIDEO SEARCH BUTTON CLICKED // VIDEO SEARCH SUCCESSED
private async void HomeOptionsBarAddVideoControl_SearchButtonClicked(object sender, VideoSearchEventArgs e) private void HomeOptionsBarVideoSearchControl_VideoSearchSuccessed(object sender, VideoSearchSuccessedEventArgs e)
{ {
// Set UI // Set UI
HomeOptionBarAndAddingPanelRow.Height = GridLength.Auto; HomeOptionBarAndAddingPanelRow.Height = new GridLength(1, GridUnitType.Star);
HomeTasksListRow.Height = new GridLength(1, GridUnitType.Star); HomeTasksListRow.Height = new GridLength(0);
HomeAddingPanel.Content = null;
// Cancel previous operations // Open adding panel
SearchingCancellationToken.Cancel(); HomeVideoAddingPanel addingPanel = new HomeVideoAddingPanel(e.VideoService);
SearchingCancellationToken = new CancellationTokenSource(); addingPanel.TasksAddingRequested += HomeTasksAddingRequest;
HomeAddingPanel.Content = addingPanel;
// Set SearchingStatusControl
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusProgressRing;
// Parse url
(VideoSource Type, string ID) source = Source.GetVideoSource(e.Url);
// Check url
if (source.Type == VideoSource.Null)
{
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusErrorImage;
}
else
{
// Select video service
IVideoService videoService = null;
switch (source.Type)
{
case VideoSource.TwitchVod: videoService = new Core.Services.Sources.Twitch.Vod(source.ID); break;
case VideoSource.TwitchClip: videoService = new Core.Services.Sources.Twitch.Clip(source.ID); break;
}
// Get metadata and streams
try
{
await videoService.GetMetadataAsync(SearchingCancellationToken.Token);
await videoService.GetStreamsAsync(SearchingCancellationToken.Token);
}
catch (OperationCanceledException)
{
HomeOptionsBarSearchingStatusControl.Content = null;
return;
}
catch (TwitchAccessTokenNotFoundException)
{
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusErrorImage;
ContentDialog twitchAccessTokenNotFoundErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingTwitchAccessTokenNotFoundErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await twitchAccessTokenNotFoundErrorDialog.ShowAsync();
return;
}
catch (TwitchAccessTokenNotValidException)
{
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusErrorImage;
ContentDialog twitchAccessTokenNotValidErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingTwitchAccessTokenNotValidErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await twitchAccessTokenNotValidErrorDialog.ShowAsync();
return;
}
catch (WebException wex)
{
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusErrorImage;
if (wex.Response is null)
{
ContentDialog internetAccessErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarVideoSearchingInternetConnectionErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await internetAccessErrorDialog.ShowAsync();
return;
}
else throw;
}
// Set searching status control to done (null)
HomeOptionsBarSearchingStatusControl.Content = null;
// Set UI
HomeOptionBarAndAddingPanelRow.Height = new GridLength(1, GridUnitType.Star);
HomeTasksListRow.Height = new GridLength(0);
// Open adding panel
HomeVideoAddingPanel addingPanel = new HomeVideoAddingPanel(videoService);
addingPanel.TasksAddingRequested += HomeTasksAddingRequest;
HomeAddingPanel.Content = addingPanel;
}
} }
// ADD PLAYLIST BUTTON CHECKED // SEARCH PLAYLIST BUTTON CHECKED
private void HomeOptionsBarAddPlaylistButton_Checked(object sender, RoutedEventArgs e) private void HomeOptionsBarPlaylistSearchButton_Checked(object sender, RoutedEventArgs e)
{ {
// Uncheck video button // Uncheck video button
HomeOptionsBarAddVideoButton.IsChecked = false; HomeOptionsBarVideoSearchButton.IsChecked = false;
// Create playlist adding control // Create playlist adding control
HomeOptionsBarAddPlaylistControl homeOptionsBarAddPlaylistControl = new HomeOptionsBarAddPlaylistControl(); HomeOptionsBarPlaylistSearch homeOptionsBarPlaylistSearchControl = new HomeOptionsBarPlaylistSearch();
homeOptionsBarAddPlaylistControl.SearchButtonClicked += HomeOptionsBarAddPlaylistControl_SearchButtonClicked; homeOptionsBarPlaylistSearchControl.PlaylistSearchSuccessed += HomeOptionsBarPlaylistSearchControl_PlaylistSearchSuccessed;
HomeOptionsBarAddingControl.Content = homeOptionsBarAddPlaylistControl; homeOptionsBarPlaylistSearchControl.SearchButtonClick += (s, a) =>
{
SearchingCancellationToken.Cancel();
SearchingCancellationToken = new CancellationTokenSource();
homeOptionsBarPlaylistSearchControl.CancellationToken = SearchingCancellationToken.Token;
};
HomeOptionsBarAddingControl.Content = homeOptionsBarPlaylistSearchControl;
} }
// ADD PLAYLIST SEARCH BUTTON CLICKED // PLAYLIST SEARCH SUCCESSED
private async void HomeOptionsBarAddPlaylistControl_SearchButtonClicked(object sender, PlaylistSearchEventArgs e) private void HomeOptionsBarPlaylistSearchControl_PlaylistSearchSuccessed(object sender, PlaylistSearchSuccessedEventArgs e)
{ {
// Set UI // Set UI
HomeOptionBarAndAddingPanelRow.Height = GridLength.Auto; HomeOptionBarAndAddingPanelRow.Height = new GridLength(1, GridUnitType.Star);
HomeTasksListRow.Height = new GridLength(1, GridUnitType.Star); HomeTasksListRow.Height = new GridLength(0);
HomeAddingPanel.Content = null;
// Cancel previous operations // Open adding panel
SearchingCancellationToken.Cancel(); HomePlaylistAddingPanel addingPanel = new HomePlaylistAddingPanel(e.PlaylistService);
SearchingCancellationToken = new CancellationTokenSource(); addingPanel.TasksAddingRequested += HomeTasksAddingRequest;
HomeAddingPanel.Content = addingPanel;
// Set SearchingStatusControl
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusProgressRing;
// Parse url
(PlaylistSource Type, string ID) source = Source.GetPlaylistSource(e.Url);
// Check url
if (source.Type == PlaylistSource.Null)
{
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusErrorImage;
}
else
{
// Select video service
IPlaylistService playlistService = null;
switch (source.Type)
{
case PlaylistSource.TwitchChannel: playlistService = new Core.Services.Sources.Twitch.Channel(source.ID); break;
}
// Get metadata and streams
try
{
await playlistService.GetMetadataAsync(SearchingCancellationToken.Token);
await playlistService.GetVideosAsync(e.VideosCount, SearchingCancellationToken.Token);
}
catch (OperationCanceledException)
{
HomeOptionsBarSearchingStatusControl.Content = null;
return;
}
catch (TwitchAccessTokenNotFoundException)
{
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusErrorImage;
ContentDialog twitchAccessTokenNotFoundErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingTwitchAccessTokenNotFoundErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await twitchAccessTokenNotFoundErrorDialog.ShowAsync();
return;
}
catch (TwitchAccessTokenNotValidException)
{
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusErrorImage;
ContentDialog twitchAccessTokenNotValidErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingTwitchAccessTokenNotValidErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await twitchAccessTokenNotValidErrorDialog.ShowAsync();
return;
}
catch (WebException wex)
{
HomeOptionsBarSearchingStatusControl.Content = HomeOptionsBarSearchingStatusErrorImage;
if (!NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable)
{
ContentDialog internetAccessErrorDialog = new ContentDialog
{
Title = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingErrorDialogTitle"),
Content = ResourceLoader.GetForCurrentView().GetString("HomeOptionsBarPlaylistSearchingInternetConnectionErrorDialogDescription"),
CloseButtonText = ResourceLoader.GetForCurrentView().GetString("CloseErrorDialogButtonText"),
};
await internetAccessErrorDialog.ShowAsync();
return;
}
else throw;
}
// Set searching status control to done (null)
HomeOptionsBarSearchingStatusControl.Content = null;
// Set UI
HomeOptionBarAndAddingPanelRow.Height = new GridLength(1, GridUnitType.Star);
HomeTasksListRow.Height = new GridLength(0);
// Open adding panel
HomePlaylistAddingPanel addingPanel = new HomePlaylistAddingPanel(playlistService);
addingPanel.TasksAddingRequested += HomeTasksAddingRequest;
HomeAddingPanel.Content = addingPanel;
}
} }
@@ -324,8 +151,8 @@ namespace VDownload.Views.Home
// Uncheck button // Uncheck button
switch (e.RequestSource) switch (e.RequestSource)
{ {
case TaskAddingRequestSource.Video: HomeOptionsBarAddVideoButton.IsChecked = false; break; case TaskAddingRequestSource.Video: HomeOptionsBarVideoSearchButton.IsChecked = false; break;
case TaskAddingRequestSource.Playlist: HomeOptionsBarAddPlaylistButton.IsChecked = false; break; case TaskAddingRequestSource.Playlist: HomeOptionsBarPlaylistSearchButton.IsChecked = false; break;
} }
// Create video tasks // Create video tasks
@@ -338,7 +165,7 @@ namespace VDownload.Views.Home
// Remove task from tasks lists // Remove task from tasks lists
TasksList.Remove(taskPanel); TasksList.Remove(taskPanel);
HomeTasksList.Children.Remove(taskPanel); HomeTasksList.Children.Remove(taskPanel);
if (TasksList.Count <= 0) HomeTasksListCurrentParent.Content = HomeTasksListPlaceholder; if (TasksList.Count <= 0) HomeTasksListCurrentParent.Content = new HomeTasksListPlaceholder();
}; };
// Add task to tasks lists // Add task to tasks lists
@@ -400,7 +227,7 @@ namespace VDownload.Views.Home
foreach (HomeTaskPanel videoPanel in idleTasks) foreach (HomeTaskPanel videoPanel in idleTasks)
{ {
await Task.Delay(10); await Task.Delay(1);
#pragma warning disable CS4014 #pragma warning disable CS4014
videoPanel.Start(delay); videoPanel.Start(delay);

View File

@@ -1,38 +0,0 @@
<UserControl
x:Class="VDownload.Views.Home.HomeOptionsBarAddPlaylistControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VDownload.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
mc:Ignorable="d"
d:DesignHeight="100"
d:DesignWidth="400">
<Grid x:Name="HomeOptionsBarAddPlaylistControlGrid" Margin="10" ColumnSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!-- URL TEXTBOX -->
<TextBox x:Name="HomeOptionsBarAddPlaylistControlUrlTextBox" x:Uid="HomeOptionsBarAddPlaylistControlUrlTextBox" Grid.Column="0" VerticalAlignment="Center"/>
<!-- MAX VIDEOS NUMBERBOX -->
<muxc:NumberBox x:Name="HomeOptionsBarAddPlaylistControlMaxVideosNumberBox" Grid.Column="1" VerticalAlignment="Center" SpinButtonPlacementMode="Compact" Minimum="0" Value="{x:Bind DefaultMaxPlaylistVideos}" LostFocus="HomeOptionsBarAddPlaylistControlMaxVideosNumberBox_LostFocus"/>
<!-- SEARCH BUTTON-->
<Button x:Name="HomeOptionsBarAddPlaylistControlSearchButton" x:Uid="HomeOptionsBarAddPlaylistControlSearchButton" Grid.Column="2" Click="HomeOptionsBarAddPlaylistControlSearchButton_Click"/>
<!-- HELP BUTTON -->
<Button x:Name="HomeOptionsBarAddPlaylistControlHelpButton" Grid.Column="3" Content="?" Click="HomeOptionsBarAddPlaylistControlHelpButton_Click">
<Button.Resources>
<muxc:TeachingTip x:Name="HomeOptionsBarAddPlaylistControlInfoBox" x:Uid="HomeOptionsBarAddPlaylistControlInfoBox" Target="{x:Bind HomeOptionsBarAddPlaylistControlGrid}"/>
</Button.Resources>
</Button>
</Grid>
</UserControl>

View File

@@ -1,71 +0,0 @@
using System;
using VDownload.Core.EventArgs;
using VDownload.Core.Services;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace VDownload.Views.Home
{
public sealed partial class HomeOptionsBarAddPlaylistControl : UserControl
{
#region CONSTRUCTORS
public HomeOptionsBarAddPlaylistControl()
{
this.InitializeComponent();
}
#endregion
#region PROPERTIES
// MAX VIDEOS NUMBERBOX DEFAULT VALUE
public int DefaultMaxPlaylistVideos = (int)Config.GetValue("default_max_playlist_videos");
#endregion
#region EVENT HANDLERS
// NUMBERBOX FOCUS LOST
private void HomeOptionsBarAddPlaylistControlMaxVideosNumberBox_LostFocus(object sender, RoutedEventArgs e)
{
if (double.IsNaN(HomeOptionsBarAddPlaylistControlMaxVideosNumberBox.Value)) HomeOptionsBarAddPlaylistControlMaxVideosNumberBox.Value = DefaultMaxPlaylistVideos;
}
// SEARCH BUTTON CLICKED
private void HomeOptionsBarAddPlaylistControlSearchButton_Click(object sender, RoutedEventArgs e)
{
// Close info box
HomeOptionsBarAddPlaylistControlInfoBox.IsOpen = false;
// Invoke search button event handlers
PlaylistSearchEventArgs args = new PlaylistSearchEventArgs
{
Url = HomeOptionsBarAddPlaylistControlUrlTextBox.Text,
VideosCount = int.Parse(HomeOptionsBarAddPlaylistControlMaxVideosNumberBox.Text),
};
SearchButtonClicked?.Invoke(this, args);
}
// HELP BUTTON CLICKED
private void HomeOptionsBarAddPlaylistControlHelpButton_Click(object sender, RoutedEventArgs e)
{
// Switch info box
HomeOptionsBarAddPlaylistControlInfoBox.IsOpen = !HomeOptionsBarAddPlaylistControlInfoBox.IsOpen;
}
#endregion
#region EVENT HANDLERS
public event EventHandler<PlaylistSearchEventArgs> SearchButtonClicked;
#endregion
}
}

View File

@@ -1,34 +0,0 @@
<UserControl
x:Class="VDownload.Views.Home.HomeOptionsBarAddVideoControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VDownload.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
mc:Ignorable="d"
d:DesignHeight="100"
d:DesignWidth="400">
<Grid x:Name="HomeOptionsBarAddVideoControlGrid" Margin="10" ColumnSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!-- URL TEXTBOX -->
<TextBox x:Name="HomeOptionsBarAddVideoControlUrlTextBox" x:Uid="HomeOptionsBarAddVideoControlUrlTextBox" Grid.Column="0" VerticalAlignment="Center"/>
<!-- SEARCH BUTTON -->
<Button x:Name="HomeOptionsBarAddVideoControlSearchButton" x:Uid="HomeOptionsBarAddVideoControlSearchButton" Grid.Column="1" Click="HomeOptionsBarAddVideoControlSearchButton_Click"/>
<!-- INFO BUTTON -->
<Button x:Name="HomeOptionsBarAddVideoControlHelpButton" x:Uid="HomeOptionsBarAddVideoControlHelpButton" Grid.Column="2" Content="?" Click="HomeOptionsBarAddVideoControlHelpButton_Click">
<Button.Resources>
<muxc:TeachingTip x:Name="HomeOptionsBarAddVideoControlInfoBox" x:Uid="HomeOptionsBarAddVideoControlInfoBox" Target="{x:Bind HomeOptionsBarAddVideoControlGrid}"/>
</Button.Resources>
</Button>
</Grid>
</UserControl>

View File

@@ -1,54 +0,0 @@
using System;
using VDownload.Core.EventArgs;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace VDownload.Views.Home
{
public sealed partial class HomeOptionsBarAddVideoControl : UserControl
{
#region CONSTRUCTORS
public HomeOptionsBarAddVideoControl()
{
this.InitializeComponent();
}
#endregion
#region EVENT HANDLERS VOIDS
// SEARCH BUTTON CLICKED
private void HomeOptionsBarAddVideoControlSearchButton_Click(object sender, RoutedEventArgs e)
{
// Close info box
HomeOptionsBarAddVideoControlInfoBox.IsOpen = false;
// Invoke search button event handlers
VideoSearchEventArgs args = new VideoSearchEventArgs
{
Url = HomeOptionsBarAddVideoControlUrlTextBox.Text
};
SearchButtonClicked?.Invoke(this, args);
}
// HELP BUTTON CLICKED
private void HomeOptionsBarAddVideoControlHelpButton_Click(object sender, RoutedEventArgs e)
{
// Switch info box
HomeOptionsBarAddVideoControlInfoBox.IsOpen = !HomeOptionsBarAddVideoControlInfoBox.IsOpen;
}
#endregion
#region EVENT HANDLERS
public event EventHandler<VideoSearchEventArgs> SearchButtonClicked;
#endregion
}
}

View File

@@ -7,6 +7,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls" xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
xmlns:cc="using:VDownload.Controls" xmlns:cc="using:VDownload.Controls"
Loading="HomePlaylistAddingPanel_Loading"
mc:Ignorable="d"> mc:Ignorable="d">
@@ -69,7 +70,7 @@
<cc:SettingControl x:Uid="HomePlaylistAddingApplyToAllScheduleSettingControl" Icon="{ThemeResource ScheduleIcon}"> <cc:SettingControl x:Uid="HomePlaylistAddingApplyToAllScheduleSettingControl" Icon="{ThemeResource ScheduleIcon}">
<cc:SettingControl.SettingContent> <cc:SettingControl.SettingContent>
<StackPanel Spacing="10" Orientation="Horizontal"> <StackPanel Spacing="10" Orientation="Horizontal">
<muxc:NumberBox x:Name="HomePlaylistAddingApplyToAllScheduleNumberBox" MaxWidth="100" Value="0" Minimum="0" SpinButtonPlacementMode="Compact" ValueChanged="HomePlaylistAddingApplyToAllScheduleNumberBox_ValueChanged"/> <muxc:NumberBox x:Name="HomePlaylistAddingApplyToAllScheduleNumberBox" MaxWidth="100" Value="0" Minimum="0" SpinButtonPlacementMode="Compact" LostFocus="HomePlaylistAddingApplyToAllScheduleNumberBox_LostFocus"/>
<Button x:Uid="HomePlaylistAddingApplyToAllApplyButton" Click="HomePlaylistAddingApplyToAllApplyScheduleButton_Click"/> <Button x:Uid="HomePlaylistAddingApplyToAllApplyButton" Click="HomePlaylistAddingApplyToAllApplyScheduleButton_Click"/>
</StackPanel> </StackPanel>
</cc:SettingControl.SettingContent> </cc:SettingControl.SettingContent>

View File

@@ -2,7 +2,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices.WindowsRuntime;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@@ -13,19 +12,13 @@ using VDownload.Core.EventArgs;
using VDownload.Core.Interfaces; using VDownload.Core.Interfaces;
using VDownload.Core.Services; using VDownload.Core.Services;
using VDownload.Core.Structs; using VDownload.Core.Structs;
using VDownload.Views.Home.Controls;
using Windows.ApplicationModel.Resources; using Windows.ApplicationModel.Resources;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage; using Windows.Storage;
using Windows.Storage.AccessCache; using Windows.Storage.AccessCache;
using Windows.Storage.Pickers; using Windows.Storage.Pickers;
using Windows.UI.Xaml; using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace VDownload.Views.Home namespace VDownload.Views.Home
{ {
@@ -39,7 +32,47 @@ namespace VDownload.Views.Home
// Set playlist service object // Set playlist service object
PlaylistService = playlistService; PlaylistService = playlistService;
}
#endregion
#region PROPERTIES
// BASE PLAYLIST DATA
private IPlaylistService PlaylistService { get; set; }
// PLAYLIST DATA
private IconElement SourceImage { get; set; }
private string Name { get; set; }
// APPLY TO ALL OPTIONS
public StorageFolder ATLLocation { get; set; }
public double ATLSchedule { get; set; }
// DELETED VIDEOS
public List<HomeSerialAddingVideoPanel> DeletedVideos = new List<HomeSerialAddingVideoPanel>();
public List<HomeSerialAddingVideoPanel> HiddenVideos = new List<HomeSerialAddingVideoPanel>();
// FILTER MIN MAX
private long MinViews { get; set; }
private long MaxViews { get; set; }
private DateTime MinDate { get; set; }
private DateTime MaxDate { get; set; }
private TimeSpan MinDuration { get; set; }
private TimeSpan MaxDuration { get; set; }
#endregion
#region EVENT HANDLERS VOIDS
// ON CONTROL LOADING
private async void HomePlaylistAddingPanel_Loading(FrameworkElement sender, object args)
{
// Set metadata // Set metadata
SourceImage = new BitmapIcon { UriSource = new Uri($"ms-appx:///Assets/Sources/{PlaylistService.GetType().Namespace.Split(".").Last()}.png"), ShowAsMonochrome = false }; SourceImage = new BitmapIcon { UriSource = new Uri($"ms-appx:///Assets/Sources/{PlaylistService.GetType().Namespace.Split(".").Last()}.png"), ShowAsMonochrome = false };
Name = PlaylistService.Name; Name = PlaylistService.Name;
@@ -53,13 +86,16 @@ namespace VDownload.Views.Home
MaxDuration = PlaylistService.Videos[0].Metadata.Duration; MaxDuration = PlaylistService.Videos[0].Metadata.Duration;
foreach (IVideoService video in PlaylistService.Videos) foreach (IVideoService video in PlaylistService.Videos)
{ {
// Set mins and maxes
if (video.Metadata.Views < MinViews) MinViews = video.Metadata.Views; if (video.Metadata.Views < MinViews) MinViews = video.Metadata.Views;
if (video.Metadata.Views > MaxViews) MaxViews = video.Metadata.Views; if (video.Metadata.Views > MaxViews) MaxViews = video.Metadata.Views;
if (video.Metadata.Date < MinDate) MinDate = video.Metadata.Date; if (video.Metadata.Date < MinDate) MinDate = video.Metadata.Date;
if (video.Metadata.Date > MaxDate) MaxDate = video.Metadata.Date; if (video.Metadata.Date > MaxDate) MaxDate = video.Metadata.Date;
if (video.Metadata.Duration < MinDuration) MinDuration = video.Metadata.Duration; if (video.Metadata.Duration < MinDuration) MinDuration = video.Metadata.Duration;
if (video.Metadata.Duration > MaxDuration) MaxDuration = video.Metadata.Duration; if (video.Metadata.Duration > MaxDuration) MaxDuration = video.Metadata.Duration;
HomePlaylistAddingPanelVideoPanel videoPanel = new HomePlaylistAddingPanelVideoPanel(video);
// Add videos to list
HomeSerialAddingVideoPanel videoPanel = new HomeSerialAddingVideoPanel(video);
videoPanel.DeleteRequested += (s, a) => videoPanel.DeleteRequested += (s, a) =>
{ {
DeletedVideos.Add(videoPanel); DeletedVideos.Add(videoPanel);
@@ -70,21 +106,18 @@ namespace VDownload.Views.Home
HomePlaylistAddingPanelFilterHeaderCountTextBlock.Text = HiddenVideos.Count + DeletedVideos.Count > 0 ? $"{ResourceLoader.GetForCurrentView().GetString("HomePlaylistAddingPanelFilterHeaderCountTextBlockPrefix")}: {HiddenVideos.Count + DeletedVideos.Count}" : ""; HomePlaylistAddingPanelFilterHeaderCountTextBlock.Text = HiddenVideos.Count + DeletedVideos.Count > 0 ? $"{ResourceLoader.GetForCurrentView().GetString("HomePlaylistAddingPanelFilterHeaderCountTextBlockPrefix")}: {HiddenVideos.Count + DeletedVideos.Count}" : "";
HomePlaylistAddingPanelVideosList.Children.Remove(videoPanel); HomePlaylistAddingPanelVideosList.Children.Remove(videoPanel);
}; };
HomePlaylistAddingPanelVideosList.Children.Add(videoPanel); HomePlaylistAddingPanelVideosList.Children.Add(videoPanel);
} }
// Set apply to all location option // Set apply to all location option
if (!(bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("last_media_location")) if (!(bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("last_media_location"))
{ {
Task<StorageFolder> task = StorageApplicationPermissions.FutureAccessList.GetFolderAsync("last_media_location").AsTask(); ATLLocation = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("last_media_location");
ATLLocation = task.Result;
HomePlaylistAddingApplyToAllLocationSettingControl.Description = ATLLocation.Path; HomePlaylistAddingApplyToAllLocationSettingControl.Description = ATLLocation.Path;
} }
else if ((bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("custom_media_location")) else if ((bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("custom_media_location"))
{ {
Task<StorageFolder> task = StorageApplicationPermissions.FutureAccessList.GetFolderAsync("selected_media_location").AsTask(); ATLLocation = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("selected_media_location");
ATLLocation = task.Result;
HomePlaylistAddingApplyToAllLocationSettingControl.Description = ATLLocation.Path; HomePlaylistAddingApplyToAllLocationSettingControl.Description = ATLLocation.Path;
} }
else else
@@ -112,7 +145,7 @@ namespace VDownload.Views.Home
TextBoxExtensions.SetMask(HomePlaylistAddingPanelFilterMinDurationTextBox, (string)new TimeSpanToTextBoxMaskConverter().Convert(MaxDuration, null, null, null)); TextBoxExtensions.SetMask(HomePlaylistAddingPanelFilterMinDurationTextBox, (string)new TimeSpanToTextBoxMaskConverter().Convert(MaxDuration, null, null, null));
TextBoxExtensions.SetMask(HomePlaylistAddingPanelFilterMaxDurationTextBox, (string)new TimeSpanToTextBoxMaskConverter().Convert(MaxDuration, null, null, null)); TextBoxExtensions.SetMask(HomePlaylistAddingPanelFilterMaxDurationTextBox, (string)new TimeSpanToTextBoxMaskConverter().Convert(MaxDuration, null, null, null));
HashSet<int> maskElements = new HashSet<int>(); HashSet<int> maskElements = new HashSet<int>();
foreach (TimeSpan ts in new List<TimeSpan>{ MinDuration, MaxDuration } ) foreach (TimeSpan ts in new List<TimeSpan> { MinDuration, MaxDuration })
{ {
if (Math.Floor(ts.TotalHours) > 0) maskElements.Add(int.Parse(Math.Floor(ts.TotalHours).ToString()[0].ToString())); if (Math.Floor(ts.TotalHours) > 0) maskElements.Add(int.Parse(Math.Floor(ts.TotalHours).ToString()[0].ToString()));
if (Math.Floor(ts.TotalMinutes) > 0) if (Math.Floor(ts.TotalMinutes) > 0)
@@ -130,50 +163,10 @@ namespace VDownload.Views.Home
} }
TextBoxExtensions.SetCustomMask(HomePlaylistAddingPanelFilterMinDurationTextBox, string.Join(',', maskElementsString)); TextBoxExtensions.SetCustomMask(HomePlaylistAddingPanelFilterMinDurationTextBox, string.Join(',', maskElementsString));
TextBoxExtensions.SetCustomMask(HomePlaylistAddingPanelFilterMaxDurationTextBox, string.Join(',', maskElementsString)); TextBoxExtensions.SetCustomMask(HomePlaylistAddingPanelFilterMaxDurationTextBox, string.Join(',', maskElementsString));
if (Math.Floor(MaxDuration.TotalHours) > 0) HomePlaylistAddingPanelFilterMinDurationTextBox.Text += $"{Math.Floor(MinDuration.TotalHours)}:"; HomePlaylistAddingPanelFilterMinDurationTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(MinDuration, MaxDuration);
if (Math.Floor(MaxDuration.TotalMinutes) > 0) HomePlaylistAddingPanelFilterMinDurationTextBox.Text += Math.Floor(MaxDuration.TotalHours) > 0 ? $"{MinDuration.Minutes:00}:" : $"{MinDuration.Minutes}:"; HomePlaylistAddingPanelFilterMaxDurationTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(MaxDuration);
HomePlaylistAddingPanelFilterMinDurationTextBox.Text += Math.Floor(MaxDuration.TotalMinutes) > 0 ? $"{MinDuration.Seconds:00}" : $"{MinDuration.Seconds}";
if (Math.Floor(MaxDuration.TotalHours) > 0) HomePlaylistAddingPanelFilterMaxDurationTextBox.Text += $"{Math.Floor(MaxDuration.TotalHours)}:";
if (Math.Floor(MaxDuration.TotalMinutes) > 0) HomePlaylistAddingPanelFilterMaxDurationTextBox.Text += Math.Floor(MaxDuration.TotalHours) > 0 ? $"{MaxDuration.Minutes:00}:" : $"{MaxDuration.Minutes}:";
HomePlaylistAddingPanelFilterMaxDurationTextBox.Text += Math.Floor(MaxDuration.TotalMinutes) > 0 ? $"{MaxDuration.Seconds:00}" : $"{MaxDuration.Seconds}";
} }
#endregion
#region PROPERTIES
// BASE PLAYLIST DATA
private IPlaylistService PlaylistService { get; set; }
// PLAYLIST DATA
private IconElement SourceImage { get; set; }
private string Name { get; set; }
// APPLY TO ALL OPTIONS
public StorageFolder ATLLocation { get; set; }
public double ATLSchedule { get; set; }
// DELETED VIDEOS
public List<HomePlaylistAddingPanelVideoPanel> DeletedVideos = new List<HomePlaylistAddingPanelVideoPanel>();
public List<HomePlaylistAddingPanelVideoPanel> HiddenVideos = new List<HomePlaylistAddingPanelVideoPanel>();
// FILTER MIN MAX
private long MinViews { get; set; }
private long MaxViews { get; set; }
private DateTime MinDate { get; set; }
private DateTime MaxDate { get; set; }
private TimeSpan MinDuration { get; set; }
private TimeSpan MaxDuration { get; set; }
#endregion
#region EVENT HANDLERS VOIDS
// FILTER CHANGED // FILTER CHANGED
private void FilterChanged() private void FilterChanged()
{ {
@@ -201,13 +194,13 @@ namespace VDownload.Views.Home
} }
catch (ArgumentException) { } catch (ArgumentException) { }
List<HomePlaylistAddingPanelVideoPanel> allVideos = new List<HomePlaylistAddingPanelVideoPanel>(); List<HomeSerialAddingVideoPanel> allVideos = new List<HomeSerialAddingVideoPanel>();
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in HomePlaylistAddingPanelVideosList.Children) allVideos.Add(videoPanel); foreach (HomeSerialAddingVideoPanel videoPanel in HomePlaylistAddingPanelVideosList.Children) allVideos.Add(videoPanel);
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in HiddenVideos) allVideos.Add(videoPanel); foreach (HomeSerialAddingVideoPanel videoPanel in HiddenVideos) allVideos.Add(videoPanel);
HomePlaylistAddingPanelVideosList.Children.Clear(); HomePlaylistAddingPanelVideosList.Children.Clear();
HiddenVideos.Clear(); HiddenVideos.Clear();
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in allVideos) foreach (HomeSerialAddingVideoPanel videoPanel in allVideos)
{ {
if ( if (
!titleRegex.IsMatch(videoPanel.VideoService.Metadata.Title) || !titleRegex.IsMatch(videoPanel.VideoService.Metadata.Title) ||
@@ -252,46 +245,41 @@ namespace VDownload.Views.Home
// APPLY ATL LOCATION BUTTON CLICKED // APPLY ATL LOCATION BUTTON CLICKED
private void HomePlaylistAddingApplyToAllApplyLocationButton_Click(object sender, RoutedEventArgs e) private void HomePlaylistAddingApplyToAllApplyLocationButton_Click(object sender, RoutedEventArgs e)
{ {
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in HomePlaylistAddingPanelVideosList.Children) foreach (HomeSerialAddingVideoPanel videoPanel in HomePlaylistAddingPanelVideosList.Children)
{ {
videoPanel.Location = ATLLocation; videoPanel.HomeVideoAddingOptionsControl.ChangeLocation(ATLLocation);
videoPanel.HomePlaylistAddingVideoPanelLocationSettingControl.Description = ATLLocation != null ? ATLLocation.Path : $@"{UserDataPaths.GetDefault().Downloads}\VDownload";
} }
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in DeletedVideos) foreach (HomeSerialAddingVideoPanel videoPanel in DeletedVideos)
{ {
videoPanel.Location = ATLLocation; videoPanel.HomeVideoAddingOptionsControl.ChangeLocation(ATLLocation);
videoPanel.HomePlaylistAddingVideoPanelLocationSettingControl.Description = ATLLocation != null ? ATLLocation.Path : $@"{UserDataPaths.GetDefault().Downloads}\VDownload";
} }
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in HiddenVideos) foreach (HomeSerialAddingVideoPanel videoPanel in HiddenVideos)
{ {
videoPanel.Location = ATLLocation; videoPanel.HomeVideoAddingOptionsControl.ChangeLocation(ATLLocation);
videoPanel.HomePlaylistAddingVideoPanelLocationSettingControl.Description = ATLLocation != null ? ATLLocation.Path : $@"{UserDataPaths.GetDefault().Downloads}\VDownload";
} }
} }
// ATL SCHEDULE NUMBERBOX VALUE CHANGED // ATL SCHEDULE NUMBERBOX VALUE CHANGED
private void HomePlaylistAddingApplyToAllScheduleNumberBox_ValueChanged(Microsoft.UI.Xaml.Controls.NumberBox sender, Microsoft.UI.Xaml.Controls.NumberBoxValueChangedEventArgs args) private void HomePlaylistAddingApplyToAllScheduleNumberBox_LostFocus(object sender, RoutedEventArgs e)
{ {
ATLSchedule = HomePlaylistAddingApplyToAllScheduleNumberBox.Value; if (double.IsNaN(HomePlaylistAddingApplyToAllScheduleNumberBox.Value)) HomePlaylistAddingApplyToAllScheduleNumberBox.Value = ATLSchedule;
else ATLSchedule = HomePlaylistAddingApplyToAllScheduleNumberBox.Value;
} }
// APPLY ATL SCHEDULE BUTTON CLICKED // APPLY ATL SCHEDULE BUTTON CLICKED
private void HomePlaylistAddingApplyToAllApplyScheduleButton_Click(object sender, RoutedEventArgs e) private void HomePlaylistAddingApplyToAllApplyScheduleButton_Click(object sender, RoutedEventArgs e)
{ {
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in HomePlaylistAddingPanelVideosList.Children) foreach (HomeSerialAddingVideoPanel videoPanel in HomePlaylistAddingPanelVideosList.Children)
{ {
videoPanel.Schedule = ATLSchedule; videoPanel.HomeVideoAddingOptionsControl.ChangeSchedule(ATLSchedule);
videoPanel.HomePlaylistAddingVideoPanelScheduleNumberBox.Value = ATLSchedule;
} }
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in DeletedVideos) foreach (HomeSerialAddingVideoPanel videoPanel in DeletedVideos)
{ {
videoPanel.Schedule = ATLSchedule; videoPanel.HomeVideoAddingOptionsControl.ChangeSchedule(ATLSchedule);
videoPanel.HomePlaylistAddingVideoPanelScheduleNumberBox.Value = ATLSchedule;
} }
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in HiddenVideos) foreach (HomeSerialAddingVideoPanel videoPanel in HiddenVideos)
{ {
videoPanel.Schedule = ATLSchedule; videoPanel.HomeVideoAddingOptionsControl.ChangeSchedule(ATLSchedule);
videoPanel.HomePlaylistAddingVideoPanelScheduleNumberBox.Value = ATLSchedule;
} }
} }
@@ -335,20 +323,12 @@ namespace VDownload.Views.Home
if (parsedTimeSpan < MinDuration || parsedTimeSpan > MaxDuration) if (parsedTimeSpan < MinDuration || parsedTimeSpan > MaxDuration)
{ {
string newMinDuration = ""; HomePlaylistAddingPanelFilterMinDurationTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(MinDuration, MaxDuration);
if (Math.Floor(MaxDuration.TotalHours) > 0) newMinDuration += $"{Math.Floor(MinDuration.TotalHours)}:";
if (Math.Floor(MaxDuration.TotalMinutes) > 0) newMinDuration += Math.Floor(MaxDuration.TotalHours) > 0 ? $"{MinDuration.Minutes:00}:" : $"{MinDuration.Minutes}:";
newMinDuration += Math.Floor(MaxDuration.TotalMinutes) > 0 ? $"{MinDuration.Seconds:00}" : $"{MinDuration.Seconds}";
HomePlaylistAddingPanelFilterMinDurationTextBox.Text = newMinDuration;
} }
} }
else else
{ {
string newMinDuration = ""; HomePlaylistAddingPanelFilterMinDurationTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(MinDuration, MaxDuration);
if (Math.Floor(MaxDuration.TotalHours) > 0) newMinDuration += $"{Math.Floor(MinDuration.TotalHours)}:";
if (Math.Floor(MaxDuration.TotalMinutes) > 0) newMinDuration += Math.Floor(MaxDuration.TotalHours) > 0 ? $"{MinDuration.Minutes:00}:" : $"{MinDuration.Minutes}:";
newMinDuration += Math.Floor(MaxDuration.TotalMinutes) > 0 ? $"{MinDuration.Seconds:00}" : $"{MinDuration.Seconds}";
HomePlaylistAddingPanelFilterMinDurationTextBox.Text = newMinDuration;
} }
FilterChanged(); FilterChanged();
} }
@@ -367,20 +347,12 @@ namespace VDownload.Views.Home
if (parsedTimeSpan < MinDuration || parsedTimeSpan > MaxDuration) if (parsedTimeSpan < MinDuration || parsedTimeSpan > MaxDuration)
{ {
string newMaxDuration = ""; HomePlaylistAddingPanelFilterMaxDurationTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(MaxDuration);
if (Math.Floor(MaxDuration.TotalHours) > 0) newMaxDuration += $"{Math.Floor(MaxDuration.TotalHours)}:";
if (Math.Floor(MaxDuration.TotalMinutes) > 0) newMaxDuration += Math.Floor(MaxDuration.TotalHours) > 0 ? $"{MaxDuration.Minutes:00}:" : $"{MaxDuration.Minutes}:";
newMaxDuration += Math.Floor(MaxDuration.TotalMinutes) > 0 ? $"{MaxDuration.Seconds:00}" : $"{MaxDuration.Seconds}";
HomePlaylistAddingPanelFilterMaxDurationTextBox.Text = newMaxDuration;
} }
} }
else else
{ {
string newMaxDuration = ""; HomePlaylistAddingPanelFilterMaxDurationTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(MaxDuration);
if (Math.Floor(MaxDuration.TotalHours) > 0) newMaxDuration += $"{Math.Floor(MaxDuration.TotalHours)}:";
if (Math.Floor(MaxDuration.TotalMinutes) > 0) newMaxDuration += Math.Floor(MaxDuration.TotalHours) > 0 ? $"{MaxDuration.Minutes:00}:" : $"{MaxDuration.Minutes}:";
newMaxDuration += Math.Floor(MaxDuration.TotalMinutes) > 0 ? $"{MaxDuration.Seconds:00}" : $"{MaxDuration.Seconds}";
HomePlaylistAddingPanelFilterMaxDurationTextBox.Text = newMaxDuration;
} }
FilterChanged(); FilterChanged();
} }
@@ -388,7 +360,7 @@ namespace VDownload.Views.Home
// RESTORE REMOVED VIDEOS BUTTON CLICKED // RESTORE REMOVED VIDEOS BUTTON CLICKED
private void HomePlaylistAddingPanelFilterRemovedRestoreButton_Click(object sender, RoutedEventArgs e) private void HomePlaylistAddingPanelFilterRemovedRestoreButton_Click(object sender, RoutedEventArgs e)
{ {
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in DeletedVideos) foreach (HomeSerialAddingVideoPanel videoPanel in DeletedVideos)
{ {
HomePlaylistAddingPanelVideosList.Children.Add(videoPanel); HomePlaylistAddingPanelVideosList.Children.Add(videoPanel);
} }
@@ -399,7 +371,6 @@ namespace VDownload.Views.Home
DeletedVideos.Clear(); DeletedVideos.Clear();
} }
// SOURCE BUTTON CLICKED // SOURCE BUTTON CLICKED
private async void HomePlaylistAddingPanelSourceButton_Click(object sender, RoutedEventArgs e) private async void HomePlaylistAddingPanelSourceButton_Click(object sender, RoutedEventArgs e)
{ {
@@ -412,19 +383,22 @@ namespace VDownload.Views.Home
{ {
// Pack tasks data // Pack tasks data
List<TaskData> taskDataList = new List<TaskData>(); List<TaskData> taskDataList = new List<TaskData>();
foreach (HomePlaylistAddingPanelVideoPanel videoPanel in HomePlaylistAddingPanelVideosList.Children) foreach (HomeSerialAddingVideoPanel videoPanel in HomePlaylistAddingPanelVideosList.Children)
{ {
TaskData taskData = new TaskData TaskData taskData = new TaskData
{ {
VideoService = videoPanel.VideoService, VideoService = videoPanel.VideoService,
MediaType = videoPanel.MediaType, TaskOptions = new TaskOptions()
Stream = videoPanel.Stream, {
TrimStart = videoPanel.TrimStart, MediaType = videoPanel.HomeVideoAddingOptionsControl.MediaType,
TrimEnd = videoPanel.TrimEnd, Stream = videoPanel.HomeVideoAddingOptionsControl.Stream,
Filename = videoPanel.Filename, TrimStart = videoPanel.HomeVideoAddingOptionsControl.TrimStart,
Extension = videoPanel.Extension, TrimEnd = videoPanel.HomeVideoAddingOptionsControl.TrimEnd,
Location = videoPanel.Location, Filename = videoPanel.HomeVideoAddingOptionsControl.Filename,
Schedule = videoPanel.Schedule, Extension = videoPanel.HomeVideoAddingOptionsControl.Extension,
Location = videoPanel.HomeVideoAddingOptionsControl.Location,
Schedule = videoPanel.HomeVideoAddingOptionsControl.Schedule,
}
}; };
taskDataList.Add(taskData); taskDataList.Add(taskData);
} }

View File

@@ -1,128 +0,0 @@
<UserControl
x:Class="VDownload.Views.Home.HomePlaylistAddingPanelVideoPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:VDownload.Views.Home"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
xmlns:cc="using:VDownload.Controls"
xmlns:ex="using:Microsoft.Toolkit.Uwp.UI"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ms-appx:///Resources/Colors.xaml"/>
<ResourceDictionary Source="ms-appx:///Resources/Icons.xaml"/>
<ResourceDictionary Source="ms-appx:///Resources/Converters.xaml"/>
</ResourceDictionary.MergedDictionaries>
<x:String x:Key="MetadataIconSize">14</x:String>
<x:String x:Key="MetadataTextSize">11</x:String>
</ResourceDictionary>
</UserControl.Resources>
<muxc:Expander HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" Background="{ThemeResource HomePlaylistAddingVideoPanelContentBackgroundColor}">
<muxc:Expander.Header>
<Grid Margin="-5,10,-15,10" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" Height="80" Source="{x:Bind ThumbnailImage}"/>
<Grid Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Spacing="5" Orientation="Horizontal">
<Image Width="{StaticResource MetadataIconSize}" Source="{ThemeResource AuthorIcon}"/>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{StaticResource MetadataTextSize}" Text="{x:Bind Author}"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="0" Spacing="5" Orientation="Horizontal">
<Image Width="{StaticResource MetadataIconSize}" Source="{ThemeResource ViewsIcon}"/>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{StaticResource MetadataTextSize}" Text="{x:Bind Views}"/>
</StackPanel>
<StackPanel Grid.Row="0" Grid.Column="1" Spacing="5" Orientation="Horizontal">
<Image Width="{StaticResource MetadataIconSize}" Source="{ThemeResource DateIcon}"/>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{StaticResource MetadataTextSize}" Text="{x:Bind Date}"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="1" Spacing="5" Orientation="Horizontal">
<Image Width="{StaticResource MetadataIconSize}" Source="{ThemeResource DurationIcon}"/>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{StaticResource MetadataTextSize}" Text="{x:Bind Duration}"/>
</StackPanel>
</Grid>
<TextBlock Grid.Row="0" Grid.Column="1" FontSize="15" VerticalAlignment="Center" FontWeight="SemiBold" Text="{x:Bind Title}"/>
<AppBarButton Grid.Row="0" Grid.Column="2" Margin="0,-4,0,-4" Width="40" Height="48" Icon="{x:Bind SourceImage}" Click="HomePlaylistAddingVideoPanelSourceButton_Click"/>
<AppBarButton Grid.Row="1" Grid.Column="2" Margin="0,-4,0,-4" Width="40" Height="48" Icon="Delete" Click="HomePlaylistAddingVideoPanelDeleteButton_Click"/>
</Grid>
</muxc:Expander.Header>
<muxc:Expander.Content>
<StackPanel Spacing="30">
<StackPanel>
<TextBlock x:Uid="HomePlaylistAddingVideoPanelDownloadingOptionsHeaderTextBlock" Margin="0,0,0,10" FontWeight="SemiBold"/>
<cc:SettingControl x:Uid="HomePlaylistAddingVideoPanelMediaTypeSettingControl" Margin="0,0,0,10" Icon="{ThemeResource MediaTypeIcon}">
<cc:SettingControl.SettingContent>
<ComboBox x:Name="HomePlaylistAddingVideoPanelMediaTypeSettingControlComboBox" SelectionChanged="HomePlaylistAddingVideoPanelMediaTypeSettingControlComboBox_SelectionChanged"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
<cc:SettingControl x:Name="HomePlaylistAddingVideoPanelQualitySettingControl" Margin="0,0,0,10" x:Uid="HomePlaylistAddingVideoPanelQualitySettingControl" Icon="{ThemeResource QualityIcon}">
<cc:SettingControl.SettingContent>
<ComboBox x:Name="HomePlaylistAddingVideoPanelQualitySettingControlComboBox" SelectionChanged="HomePlaylistAddingVideoPanelQualitySettingControlComboBox_SelectionChanged"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
<cc:SettingControl x:Uid="HomePlaylistAddingVideoPanelTrimSettingControl" Icon="{ThemeResource TrimIcon}">
<cc:SettingControl.SettingContent>
<StackPanel Orientation="Horizontal" Spacing="5">
<TextBox x:Name="HomePlaylistAddingVideoPanelTrimStartTextBox" ex:TextBoxExtensions.CustomMask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskElementsConverter}}" ex:TextBoxExtensions.Mask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskConverter}}" TextChanged="HomePlaylistAddingVideoPanelTrimStartTextBox_TextChanged"/>
<TextBlock VerticalAlignment="Center" Text="-"/>
<TextBox x:Name="HomePlaylistAddingVideoPanelTrimEndTextBox" ex:TextBoxExtensions.CustomMask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskElementsConverter}}" ex:TextBoxExtensions.Mask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskConverter}}" TextChanged="HomePlaylistAddingVideoPanelTrimEndTextBox_TextChanged"/>
</StackPanel>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
</StackPanel>
<StackPanel Spacing="10">
<TextBlock x:Uid="HomePlaylistAddingVideoPanelFileOptionsHeaderTextBlock" FontWeight="SemiBold"/>
<cc:SettingControl x:Uid="HomePlaylistAddingVideoPanelFileSettingControl" Icon="{ThemeResource FileIcon}">
<cc:SettingControl.SettingContent>
<Grid ColumnSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="HomePlaylistAddingVideoPanelFilenameTextBox" Grid.Column="0" MaxWidth="170" HorizontalAlignment="Right" IsSpellCheckEnabled="False" TextChanged="HomePlaylistAddingVideoPanelFilenameTextBox_TextChanged"/>
<ComboBox x:Name="HomePlaylistAddingVideoPanelExtensionComboBox" Grid.Column="1" HorizontalAlignment="Stretch" SelectionChanged="HomePlaylistAddingVideoPanelExtensionComboBox_SelectionChanged"/>
</Grid>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
<cc:SettingControl x:FieldModifier="public" x:Name="HomePlaylistAddingVideoPanelLocationSettingControl" x:Uid="HomePlaylistAddingVideoPanelLocationSettingControl" Icon="{ThemeResource LocationIcon}">
<cc:SettingControl.SettingContent>
<Button x:Uid="HomePlaylistAddingVideoPanelLocationBrowseButton" Click="HomePlaylistAddingVideoPanelLocationBrowseButton_Click"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
</StackPanel>
<StackPanel Spacing="10">
<TextBlock x:Uid="HomePlaylistAddingVideoPanelTaskOptionsHeaderTextBlock" FontWeight="SemiBold"/>
<cc:SettingControl x:Uid="HomePlaylistAddingVideoPanelScheduleSettingControl" Icon="{ThemeResource ScheduleIcon}">
<cc:SettingControl.SettingContent>
<muxc:NumberBox x:FieldModifier="public" x:Name="HomePlaylistAddingVideoPanelScheduleNumberBox" MaxWidth="100" Value="0" Minimum="0" SpinButtonPlacementMode="Compact" ValueChanged="HomePlaylistAddingVideoPanelScheduleNumberBox_ValueChanged"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
</StackPanel>
</StackPanel>
</muxc:Expander.Content>
</muxc:Expander>
</UserControl>

View File

@@ -1,325 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using VDownload.Core.Enums;
using VDownload.Core.Interfaces;
using VDownload.Core.Services;
using VDownload.Core.Structs;
using Windows.ApplicationModel.Resources;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
namespace VDownload.Views.Home
{
public sealed partial class HomePlaylistAddingPanelVideoPanel : UserControl
{
#region CONSTANTS
private readonly ResourceDictionary ImagesRes = new ResourceDictionary { Source = new Uri("ms-appx:///Resources/Images.xaml") };
#endregion
#region CONSTRUCTORS
public HomePlaylistAddingPanelVideoPanel(IVideoService videoService)
{
this.InitializeComponent();
// Set video service object
VideoService = videoService;
// Set metadata
ThumbnailImage = VideoService.Metadata.Thumbnail != null ? new BitmapImage { UriSource = VideoService.Metadata.Thumbnail } : (BitmapImage)ImagesRes["UnknownThumbnailImage"];
SourceImage = new BitmapIcon { UriSource = new Uri($"ms-appx:///Assets/Sources/{VideoService.GetType().Namespace.Split(".").Last()}.png"), ShowAsMonochrome = false };
Title = VideoService.Metadata.Title;
Author = VideoService.Metadata.Author;
Views = VideoService.Metadata.Views.ToString();
Date = VideoService.Metadata.Date.ToString(CultureInfo.InstalledUICulture.DateTimeFormat.ShortDatePattern);
Duration = $"{(Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0 ? $"{Math.Floor(VideoService.Metadata.Duration.TotalHours):0}:" : "")}{VideoService.Metadata.Duration.Minutes:00}:{VideoService.Metadata.Duration.Seconds:00}";
// Set media type
foreach (string mediaType in Enum.GetNames(typeof(MediaType)))
{
HomePlaylistAddingVideoPanelMediaTypeSettingControlComboBox.Items.Add(ResourceLoader.GetForCurrentView().GetString($"MediaType{mediaType}Text"));
}
HomePlaylistAddingVideoPanelMediaTypeSettingControlComboBox.SelectedIndex = (int)Config.GetValue("default_media_type");
// Set quality
foreach (BaseStream stream in VideoService.BaseStreams)
{
HomePlaylistAddingVideoPanelQualitySettingControlComboBox.Items.Add($"{stream.Height}p{(stream.FrameRate > 0 ? stream.FrameRate.ToString() : "N/A")}");
}
HomePlaylistAddingVideoPanelQualitySettingControlComboBox.SelectedIndex = 0;
// Set trim start
TrimStart = new TimeSpan(0);
if (Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0) HomePlaylistAddingVideoPanelTrimStartTextBox.Text += $"{new string('0', Math.Floor(VideoService.Metadata.Duration.TotalHours).ToString().Length)}:";
if (Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0) HomePlaylistAddingVideoPanelTrimStartTextBox.Text += Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0 ? "00:" : $"{new string('0', VideoService.Metadata.Duration.Minutes.ToString().Length)}:";
HomePlaylistAddingVideoPanelTrimStartTextBox.Text += Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0 ? "00" : $"{new string('0', VideoService.Metadata.Duration.Seconds.ToString().Length)}";
// Set trim end
TrimEnd = VideoService.Metadata.Duration;
if (Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0) HomePlaylistAddingVideoPanelTrimEndTextBox.Text += $"{Math.Floor(VideoService.Metadata.Duration.TotalHours)}:";
if (Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0) HomePlaylistAddingVideoPanelTrimEndTextBox.Text += Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0 ? $"{VideoService.Metadata.Duration.Minutes:00}:" : $"{VideoService.Metadata.Duration.Minutes}:";
HomePlaylistAddingVideoPanelTrimEndTextBox.Text += Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0 ? $"{VideoService.Metadata.Duration.Seconds:00}" : $"{VideoService.Metadata.Duration.Seconds}";
// Set filename
string temporaryFilename = (string)Config.GetValue("default_filename");
Dictionary<string, string> filenameStandardTemplates = new Dictionary<string, string>()
{
{ "<title>", VideoService.Metadata.Title },
{ "<author>", VideoService.Metadata.Author },
{ "<views>", VideoService.Metadata.Views.ToString() },
{ "<id>", VideoService.ID },
};
foreach (KeyValuePair<string, string> template in filenameStandardTemplates) temporaryFilename = temporaryFilename.Replace(template.Key, template.Value);
Dictionary<Regex, IFormattable> filenameFormatTemplates = new Dictionary<Regex, IFormattable>()
{
{ new Regex(@"<date_pub:(?<format>.*)>"), VideoService.Metadata.Date },
{ new Regex(@"<date_now:(?<format>.*)>"), DateTime.Now },
{ new Regex(@"<duration:(?<format>.*)>"), VideoService.Metadata.Duration },
};
foreach (KeyValuePair<Regex, IFormattable> template in filenameFormatTemplates) foreach (Match templateMatch in template.Key.Matches(temporaryFilename)) temporaryFilename = temporaryFilename.Replace(templateMatch.Value, template.Value.ToString(templateMatch.Groups["format"].Value, null));
foreach (char c in System.IO.Path.GetInvalidFileNameChars()) temporaryFilename = temporaryFilename.Replace(c, ' ');
HomePlaylistAddingVideoPanelFilenameTextBox.Text = temporaryFilename;
Filename = temporaryFilename;
// Set location
if (!(bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("last_media_location"))
{
Task<StorageFolder> task = StorageApplicationPermissions.FutureAccessList.GetFolderAsync("last_media_location").AsTask();
Location = task.Result;
HomePlaylistAddingVideoPanelLocationSettingControl.Description = Location.Path;
}
else if ((bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("custom_media_location"))
{
Task<StorageFolder> task = StorageApplicationPermissions.FutureAccessList.GetFolderAsync("selected_media_location").AsTask();
Location = task.Result;
HomePlaylistAddingVideoPanelLocationSettingControl.Description = Location.Path;
}
else
{
Location = null;
HomePlaylistAddingVideoPanelLocationSettingControl.Description = $@"{UserDataPaths.GetDefault().Downloads}\VDownload";
}
// Set minutes to start
Schedule = 0;
}
#endregion
#region PROPERTIES
// BASE VIDEO DATA
public IVideoService VideoService { get; set; }
// VIDEO DATA
private ImageSource ThumbnailImage { get; set; }
private IconElement SourceImage { get; set; }
private string Title { get; set; }
private string Author { get; set; }
private string Views { get; set; }
private string Date { get; set; }
private string Duration { get; set; }
// VIDEO OPTIONS
public MediaType MediaType { get; set; }
public BaseStream Stream { get; set; }
public TimeSpan TrimStart { get; set; }
public TimeSpan TrimEnd { get; set; }
public string Filename { get; set; }
public MediaFileExtension Extension { get; set; }
public StorageFolder Location { get; set; }
public double Schedule { get; set; }
#endregion
#region EVENT HANDLERS VOIDS
// MEDIA TYPE COMBOBOX SELECTION CHANGED
private void HomePlaylistAddingVideoPanelMediaTypeSettingControlComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MediaType = (MediaType)HomePlaylistAddingVideoPanelMediaTypeSettingControlComboBox.SelectedIndex;
if (HomePlaylistAddingVideoPanelMediaTypeSettingControlComboBox.SelectedIndex == (int)MediaType.OnlyAudio)
{
HomePlaylistAddingVideoPanelQualitySettingControl.Visibility = Visibility.Collapsed;
HomePlaylistAddingVideoPanelQualitySettingControlComboBox.SelectedIndex = VideoService.BaseStreams.Count() - 1;
HomePlaylistAddingVideoPanelExtensionComboBox.Items.Clear();
foreach (AudioFileExtension extension in Enum.GetValues(typeof(AudioFileExtension)))
{
HomePlaylistAddingVideoPanelExtensionComboBox.Items.Add(extension);
}
HomePlaylistAddingVideoPanelExtensionComboBox.SelectedIndex = (int)Config.GetValue("default_audio_extension") - 3;
}
else
{
HomePlaylistAddingVideoPanelQualitySettingControl.Visibility = Visibility.Visible;
HomePlaylistAddingVideoPanelQualitySettingControlComboBox.SelectedIndex = 0;
HomePlaylistAddingVideoPanelExtensionComboBox.Items.Clear();
foreach (VideoFileExtension extension in Enum.GetValues(typeof(VideoFileExtension)))
{
HomePlaylistAddingVideoPanelExtensionComboBox.Items.Add(extension);
}
HomePlaylistAddingVideoPanelExtensionComboBox.SelectedIndex = (int)Config.GetValue("default_video_extension");
}
}
// QUALITY COMBOBOX SELECTION CHANGED
private void HomePlaylistAddingVideoPanelQualitySettingControlComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Stream = VideoService.BaseStreams[HomePlaylistAddingVideoPanelQualitySettingControlComboBox.SelectedIndex];
}
// TRIM START TEXTBOX TEXT CHANGED
private void HomePlaylistAddingVideoPanelTrimStartTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!HomePlaylistAddingVideoPanelTrimStartTextBox.Text.Contains('_'))
{
string[] segments = HomePlaylistAddingVideoPanelTrimStartTextBox.Text.Split(':').Reverse().ToArray();
int.TryParse(segments.ElementAtOrDefault(0), out int seconds);
int.TryParse(segments.ElementAtOrDefault(1), out int minutes);
int.TryParse(segments.ElementAtOrDefault(2), out int hours);
TimeSpan parsedTimeSpan = new TimeSpan(hours, minutes, seconds);
if (parsedTimeSpan < VideoService.Metadata.Duration && parsedTimeSpan > new TimeSpan(0)) TrimStart = parsedTimeSpan;
else
{
TrimStart = new TimeSpan(0);
string newText = string.Empty;
if (Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0) newText += $"{new string('0', Math.Floor(VideoService.Metadata.Duration.TotalHours).ToString().Length)}:";
if (Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0) newText += Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0 ? "00:" : $"{new string('0', VideoService.Metadata.Duration.Minutes.ToString().Length)}:";
newText += Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0 ? "00" : $"{new string('0', VideoService.Metadata.Duration.Seconds.ToString().Length)}";
if (newText != HomePlaylistAddingVideoPanelTrimStartTextBox.Text) HomePlaylistAddingVideoPanelTrimStartTextBox.Text = newText;
}
}
}
// TRIM END TEXTBOX TEXT CHANGED
private void HomePlaylistAddingVideoPanelTrimEndTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!HomePlaylistAddingVideoPanelTrimEndTextBox.Text.Contains('_'))
{
string[] segments = HomePlaylistAddingVideoPanelTrimEndTextBox.Text.Split(':').Reverse().ToArray();
int.TryParse(segments.ElementAtOrDefault(0), out int seconds);
int.TryParse(segments.ElementAtOrDefault(1), out int minutes);
int.TryParse(segments.ElementAtOrDefault(2), out int hours);
TimeSpan parsedTimeSpan = new TimeSpan(hours, minutes, seconds);
if (parsedTimeSpan < VideoService.Metadata.Duration && parsedTimeSpan > new TimeSpan(0)) TrimEnd = parsedTimeSpan;
else
{
TrimEnd = VideoService.Metadata.Duration;
string newText = string.Empty;
if (Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0) newText += $"{Math.Floor(VideoService.Metadata.Duration.TotalHours)}:";
if (Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0) newText += Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0 ? $"{TrimEnd.Minutes:00}:" : $"{TrimEnd.Minutes}:";
newText += Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0 ? $"{TrimEnd.Seconds:00}" : $"{TrimEnd.Seconds}";
if (newText != HomePlaylistAddingVideoPanelTrimEndTextBox.Text) HomePlaylistAddingVideoPanelTrimEndTextBox.Text = newText;
}
}
}
// FILENAME TEXTBOX TEXT CHANGED
private void HomePlaylistAddingVideoPanelFilenameTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string oldFilename = HomePlaylistAddingVideoPanelFilenameTextBox.Text;
string newFilename = oldFilename;
foreach (char c in System.IO.Path.GetInvalidFileNameChars()) newFilename = newFilename.Replace(c, ' ');
if (oldFilename != newFilename)
{
HomePlaylistAddingVideoPanelFilenameTextBox.Text = newFilename;
Filename = newFilename;
}
}
// EXTENSION COMBOBOX SELECTION CHANGED
private void HomePlaylistAddingVideoPanelExtensionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Extension = (MediaFileExtension)HomePlaylistAddingVideoPanelExtensionComboBox.SelectedIndex + (MediaType == MediaType.OnlyAudio ? 3 : 0);
}
// SCHEDULE NUMBERBOX VALUE CHANGED
private void HomePlaylistAddingVideoPanelScheduleNumberBox_ValueChanged(Microsoft.UI.Xaml.Controls.NumberBox sender, Microsoft.UI.Xaml.Controls.NumberBoxValueChangedEventArgs args)
{
Schedule = HomePlaylistAddingVideoPanelScheduleNumberBox.Value;
}
// LOCATION BROWSE BUTTON CLICKED
private async void HomePlaylistAddingVideoPanelLocationBrowseButton_Click(object sender, RoutedEventArgs e)
{
FolderPicker picker = new FolderPicker
{
SuggestedStartLocation = PickerLocationId.Downloads
};
picker.FileTypeFilter.Add("*");
StorageFolder selectedFolder = await picker.PickSingleFolderAsync();
if (selectedFolder != null)
{
try
{
await(await selectedFolder.CreateFileAsync("VDownloadLocationAccessTest")).DeleteAsync();
StorageApplicationPermissions.FutureAccessList.AddOrReplace("last_media_location", selectedFolder);
Location = selectedFolder;
HomePlaylistAddingVideoPanelLocationSettingControl.Description = Location.Path;
}
catch (UnauthorizedAccessException) { }
}
}
// SOURCE BUTTON CLICKED
private async void HomePlaylistAddingVideoPanelSourceButton_Click(object sender, RoutedEventArgs e)
{
// Launch the website
await Windows.System.Launcher.LaunchUriAsync(VideoService.VideoUrl);
}
// DELETE BUTTON CLICKED
private void HomePlaylistAddingVideoPanelDeleteButton_Click(object sender, RoutedEventArgs e)
{
DeleteRequested?.Invoke(this, EventArgs.Empty);
}
#endregion
#region EVENT HANDLERS
public event EventHandler DeleteRequested;
#endregion
}
}

View File

@@ -8,6 +8,7 @@
xmlns:ex="using:Microsoft.Toolkit.Uwp.UI" xmlns:ex="using:Microsoft.Toolkit.Uwp.UI"
xmlns:cc="using:VDownload.Controls" xmlns:cc="using:VDownload.Controls"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls" xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
Loading="HomeVideoAddingPanel_Loading"
mc:Ignorable="d"> mc:Ignorable="d">
@@ -80,7 +81,6 @@
<Setter Target="HomeVideoAddingPanelDMetadataR2.Height" Value="Auto"/> <Setter Target="HomeVideoAddingPanelDMetadataR2.Height" Value="Auto"/>
<Setter Target="HomeVideoAddingPanelDMetadataC1.Width" Value="1*"/> <Setter Target="HomeVideoAddingPanelDMetadataC1.Width" Value="1*"/>
<Setter Target="HomeVideoAddingPanelDMetadataC2.Width" Value="1*"/> <Setter Target="HomeVideoAddingPanelDMetadataC2.Width" Value="1*"/>
<Setter Target="HomeVideoAddingFilenameTextBox.MaxWidth" Value="180"/>
</VisualState.Setters> </VisualState.Setters>
</VisualState> </VisualState>
<VisualState> <VisualState>
@@ -137,7 +137,6 @@
<Setter Target="HomeVideoAddingPanelDMetadataR2.Height" Value="1*"/> <Setter Target="HomeVideoAddingPanelDMetadataR2.Height" Value="1*"/>
<Setter Target="HomeVideoAddingPanelDMetadataC1.Width" Value="Auto"/> <Setter Target="HomeVideoAddingPanelDMetadataC1.Width" Value="Auto"/>
<Setter Target="HomeVideoAddingPanelDMetadataC2.Width" Value="Auto"/> <Setter Target="HomeVideoAddingPanelDMetadataC2.Width" Value="Auto"/>
<Setter Target="HomeVideoAddingFilenameTextBox.MaxWidth" Value="250"/>
</VisualState.Setters> </VisualState.Setters>
</VisualState> </VisualState>
</VisualStateGroup> </VisualStateGroup>
@@ -199,60 +198,9 @@
</Grid> </Grid>
</Grid> </Grid>
<!-- PROPERTIES PANEL --> <!-- Options PANEL -->
<ScrollViewer Grid.Row="1"> <ScrollViewer Grid.Row="1">
<StackPanel Spacing="30"> <ContentControl x:Name="HomeVideoAddingOptionsControlParent" HorizontalContentAlignment="Stretch"/>
<StackPanel>
<TextBlock x:Uid="HomeVideoAddingDownloadingOptionsHeaderTextBlock" Margin="0,0,0,10" FontWeight="SemiBold"/>
<cc:SettingControl x:Uid="HomeVideoAddingMediaTypeSettingControl" Margin="0,0,0,10" Icon="{ThemeResource MediaTypeIcon}">
<cc:SettingControl.SettingContent>
<ComboBox x:Name="HomeVideoAddingMediaTypeSettingControlComboBox" Width="150" SelectionChanged="HomeVideoAddingMediaTypeSettingControlComboBox_SelectionChanged"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
<cc:SettingControl x:Name="HomeVideoAddingQualitySettingControl" Margin="0,0,0,10" x:Uid="HomeVideoAddingQualitySettingControl" Icon="{ThemeResource QualityIcon}">
<cc:SettingControl.SettingContent>
<ComboBox x:Name="HomeVideoAddingQualitySettingControlComboBox" Width="150" SelectionChanged="HomeVideoAddingQualitySettingControlComboBox_SelectionChanged"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
<cc:SettingControl x:Uid="HomeVideoAddingTrimSettingControl" Icon="{ThemeResource TrimIcon}">
<cc:SettingControl.SettingContent>
<StackPanel Orientation="Horizontal" Spacing="5">
<TextBox x:Name="HomeVideoAddingTrimStartTextBox" ex:TextBoxExtensions.CustomMask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskElementsConverter}}" ex:TextBoxExtensions.Mask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskConverter}}" TextChanged="HomeVideoAddingTrimStartTextBox_TextChanged"/>
<TextBlock VerticalAlignment="Center" Text="-"/>
<TextBox x:Name="HomeVideoAddingTrimEndTextBox" ex:TextBoxExtensions.CustomMask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskElementsConverter}}" ex:TextBoxExtensions.Mask="{x:Bind VideoService.Metadata.Duration, Converter={StaticResource TimeSpanToTextBoxMaskConverter}}" TextChanged="HomeVideoAddingTrimEndTextBox_TextChanged"/>
</StackPanel>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
</StackPanel>
<StackPanel Spacing="10">
<TextBlock x:Uid="HomeVideoAddingFileOptionsHeaderTextBlock" FontWeight="SemiBold"/>
<cc:SettingControl x:Uid="HomeVideoAddingFileSettingControl" Icon="{ThemeResource FileIcon}">
<cc:SettingControl.SettingContent>
<Grid ColumnSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="HomeVideoAddingFilenameTextBox" Grid.Column="0" MaxWidth="300" HorizontalAlignment="Right" IsSpellCheckEnabled="False" TextChanged="HomeVideoAddingFilenameTextBox_TextChanged"/>
<ComboBox x:Name="HomeVideoAddingExtensionComboBox" Grid.Column="1" HorizontalAlignment="Stretch" SelectionChanged="HomeVideoAddingExtensionComboBox_SelectionChanged"/>
</Grid>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
<cc:SettingControl x:Name="HomeVideoAddingLocationSettingControl" x:Uid="HomeVideoAddingLocationSettingControl" Icon="{ThemeResource LocationIcon}">
<cc:SettingControl.SettingContent>
<Button x:Uid="HomeVideoAddingLocationBrowseButton" Click="HomeVideoAddingLocationBrowseButton_Click"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
</StackPanel>
<StackPanel Spacing="10">
<TextBlock x:Uid="HomeVideoAddingTaskOptionsHeaderTextBlock" FontWeight="SemiBold"/>
<cc:SettingControl x:Uid="HomeVideoAddingScheduleSettingControl" Icon="{ThemeResource ScheduleIcon}">
<cc:SettingControl.SettingContent>
<muxc:NumberBox x:Name="HomeVideoAddingScheduleNumberBox" MaxWidth="100" Value="0" Minimum="0" SpinButtonPlacementMode="Compact" ValueChanged="HomeVideoAddingScheduleNumberBox_ValueChanged"/>
</cc:SettingControl.SettingContent>
</cc:SettingControl>
</StackPanel>
</StackPanel>
</ScrollViewer> </ScrollViewer>
</Grid> </Grid>
</UserControl> </UserControl>

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@@ -9,6 +10,7 @@ using VDownload.Core.EventArgs;
using VDownload.Core.Interfaces; using VDownload.Core.Interfaces;
using VDownload.Core.Services; using VDownload.Core.Services;
using VDownload.Core.Structs; using VDownload.Core.Structs;
using VDownload.Views.Home.Controls;
using Windows.ApplicationModel.Resources; using Windows.ApplicationModel.Resources;
using Windows.Storage; using Windows.Storage;
using Windows.Storage.AccessCache; using Windows.Storage.AccessCache;
@@ -48,70 +50,8 @@ namespace VDownload.Views.Home
Date = VideoService.Metadata.Date.ToString(CultureInfo.InstalledUICulture.DateTimeFormat.ShortDatePattern); Date = VideoService.Metadata.Date.ToString(CultureInfo.InstalledUICulture.DateTimeFormat.ShortDatePattern);
Duration = TimeSpanCustomFormat.ToOptTHBaseMMSS(VideoService.Metadata.Duration); Duration = TimeSpanCustomFormat.ToOptTHBaseMMSS(VideoService.Metadata.Duration);
// Set media type // Set video options control
foreach (string mediaType in Enum.GetNames(typeof(MediaType))) HomeVideoAddingOptionsControl = new HomeAddingVideoOptions(VideoService);
{
HomeVideoAddingMediaTypeSettingControlComboBox.Items.Add(ResourceLoader.GetForCurrentView().GetString($"MediaType{mediaType}Text"));
}
HomeVideoAddingMediaTypeSettingControlComboBox.SelectedIndex = (int)Config.GetValue("default_media_type");
// Set quality
foreach (BaseStream stream in VideoService.BaseStreams)
{
HomeVideoAddingQualitySettingControlComboBox.Items.Add($"{stream.Height}p{(stream.FrameRate > 0 ? stream.FrameRate.ToString() : "N/A")}");
}
HomeVideoAddingQualitySettingControlComboBox.SelectedIndex = 0;
// Set trim start
TrimStart = TimeSpan.Zero;
HomeVideoAddingTrimStartTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(TrimStart, VideoService.Metadata.Duration);
// Set trim end
TrimEnd = VideoService.Metadata.Duration;
HomeVideoAddingTrimStartTextBox.Text = TimeSpanCustomFormat.ToOptTHMMBaseSS(TrimEnd);
// Set filename
string temporaryFilename = (string)Config.GetValue("default_filename");
Dictionary<string, string> filenameStandardTemplates = new Dictionary<string, string>()
{
{ "<title>", VideoService.Metadata.Title },
{ "<author>", VideoService.Metadata.Author },
{ "<views>", VideoService.Metadata.Views.ToString() },
{ "<id>", VideoService.ID },
};
foreach (KeyValuePair<string, string> template in filenameStandardTemplates) temporaryFilename = temporaryFilename.Replace(template.Key, template.Value);
Dictionary<Regex, IFormattable> filenameFormatTemplates = new Dictionary<Regex, IFormattable>()
{
{ new Regex(@"<date_pub:(?<format>.*)>"), VideoService.Metadata.Date },
{ new Regex(@"<date_now:(?<format>.*)>"), DateTime.Now },
{ new Regex(@"<duration:(?<format>.*)>"), VideoService.Metadata.Duration },
};
foreach (KeyValuePair<Regex, IFormattable> template in filenameFormatTemplates) foreach (Match templateMatch in template.Key.Matches(temporaryFilename)) temporaryFilename = temporaryFilename.Replace(templateMatch.Value, template.Value.ToString(templateMatch.Groups["format"].Value, null));
foreach (char c in System.IO.Path.GetInvalidFileNameChars()) temporaryFilename = temporaryFilename.Replace(c, ' ');
Filename = temporaryFilename;
HomeVideoAddingFilenameTextBox.Text = Filename;
// Set location
if (!(bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("last_media_location"))
{
Task<StorageFolder> task = StorageApplicationPermissions.FutureAccessList.GetFolderAsync("last_media_location").AsTask();
Location = task.Result;
HomeVideoAddingLocationSettingControl.Description = Location.Path;
}
else if ((bool)Config.GetValue("custom_media_location") && StorageApplicationPermissions.FutureAccessList.ContainsItem("custom_media_location"))
{
Task<StorageFolder> task = StorageApplicationPermissions.FutureAccessList.GetFolderAsync("selected_media_location").AsTask();
Location = task.Result;
HomeVideoAddingLocationSettingControl.Description = Location.Path;
}
else
{
Location = null;
HomeVideoAddingLocationSettingControl.Description = $@"{UserDataPaths.GetDefault().Downloads}\VDownload";
}
// Set minutes to start
Schedule = 0;
} }
#endregion #endregion
@@ -132,15 +72,8 @@ namespace VDownload.Views.Home
private string Date { get; set; } private string Date { get; set; }
private string Duration { get; set; } private string Duration { get; set; }
// VIDEO OPTIONS // OPTIONS CONTROL
private MediaType MediaType { get; set; } private HomeAddingVideoOptions HomeVideoAddingOptionsControl { get; set; }
private BaseStream Stream { get; set; }
private TimeSpan TrimStart { get; set; }
private TimeSpan TrimEnd { get; set; }
private string Filename { get; set; }
private MediaFileExtension Extension { get; set; }
private StorageFolder Location { get; set; }
private double Schedule { get; set; }
#endregion #endregion
@@ -148,148 +81,12 @@ namespace VDownload.Views.Home
#region EVENT HANDLERS VOIDS #region EVENT HANDLERS VOIDS
// MEDIA TYPE COMBOBOX SELECTION CHANGED private async void HomeVideoAddingPanel_Loading(FrameworkElement sender, object args)
private void HomeVideoAddingMediaTypeSettingControlComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ {
MediaType = (MediaType)HomeVideoAddingMediaTypeSettingControlComboBox.SelectedIndex; await HomeVideoAddingOptionsControl.Init();
if (HomeVideoAddingMediaTypeSettingControlComboBox.SelectedIndex == (int)MediaType.OnlyAudio) HomeVideoAddingOptionsControlParent.Content = HomeVideoAddingOptionsControl;
{
HomeVideoAddingQualitySettingControl.Visibility = Visibility.Collapsed;
HomeVideoAddingQualitySettingControlComboBox.SelectedIndex = VideoService.BaseStreams.Count() - 1;
HomeVideoAddingExtensionComboBox.Items.Clear();
foreach (AudioFileExtension extension in Enum.GetValues(typeof(AudioFileExtension)))
{
HomeVideoAddingExtensionComboBox.Items.Add(extension);
}
HomeVideoAddingExtensionComboBox.SelectedIndex = (int)Config.GetValue("default_audio_extension") - 3;
}
else
{
HomeVideoAddingQualitySettingControl.Visibility = Visibility.Visible;
HomeVideoAddingQualitySettingControlComboBox.SelectedIndex = 0;
HomeVideoAddingExtensionComboBox.Items.Clear();
foreach (VideoFileExtension extension in Enum.GetValues(typeof(VideoFileExtension)))
{
HomeVideoAddingExtensionComboBox.Items.Add(extension);
}
HomeVideoAddingExtensionComboBox.SelectedIndex = (int)Config.GetValue("default_video_extension");
}
} }
// QUALITY COMBOBOX SELECTION CHANGED
private void HomeVideoAddingQualitySettingControlComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Stream = VideoService.BaseStreams[HomeVideoAddingQualitySettingControlComboBox.SelectedIndex];
}
// TRIM START TEXTBOX TEXT CHANGED
private void HomeVideoAddingTrimStartTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!HomeVideoAddingTrimStartTextBox.Text.Contains('_'))
{
string[] segments = HomeVideoAddingTrimStartTextBox.Text.Split(':').Reverse().ToArray();
int.TryParse(segments.ElementAtOrDefault(0), out int seconds);
int.TryParse(segments.ElementAtOrDefault(1), out int minutes);
int.TryParse(segments.ElementAtOrDefault(2), out int hours);
TimeSpan parsedTimeSpan = new TimeSpan(hours, minutes, seconds);
if (parsedTimeSpan < VideoService.Metadata.Duration && parsedTimeSpan > new TimeSpan(0)) TrimStart = parsedTimeSpan;
else
{
TrimStart = new TimeSpan(0);
string newText = string.Empty;
if (Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0) newText += $"{new string('0', Math.Floor(VideoService.Metadata.Duration.TotalHours).ToString().Length)}:";
if (Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0) newText += Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0 ? "00:" : $"{new string('0', VideoService.Metadata.Duration.Minutes.ToString().Length)}:";
newText += Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0 ? "00" : $"{new string('0', VideoService.Metadata.Duration.Seconds.ToString().Length)}";
if (newText != HomeVideoAddingTrimStartTextBox.Text) HomeVideoAddingTrimStartTextBox.Text = newText;
}
}
}
// TRIM END TEXTBOX TEXT CHANGED
private void HomeVideoAddingTrimEndTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!HomeVideoAddingTrimEndTextBox.Text.Contains('_'))
{
string[] segments = HomeVideoAddingTrimEndTextBox.Text.Split(':').Reverse().ToArray();
int.TryParse(segments.ElementAtOrDefault(0), out int seconds);
int.TryParse(segments.ElementAtOrDefault(1), out int minutes);
int.TryParse(segments.ElementAtOrDefault(2), out int hours);
TimeSpan parsedTimeSpan = new TimeSpan(hours, minutes, seconds);
if (parsedTimeSpan < VideoService.Metadata.Duration && parsedTimeSpan > new TimeSpan(0)) TrimEnd = parsedTimeSpan;
else
{
TrimEnd = VideoService.Metadata.Duration;
string newText = string.Empty;
if (Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0) newText += $"{Math.Floor(VideoService.Metadata.Duration.TotalHours)}:";
if (Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0) newText += Math.Floor(VideoService.Metadata.Duration.TotalHours) > 0 ? $"{TrimEnd.Minutes:00}:" : $"{TrimEnd.Minutes}:";
newText += Math.Floor(VideoService.Metadata.Duration.TotalMinutes) > 0 ? $"{TrimEnd.Seconds:00}" : $"{TrimEnd.Seconds}";
if (newText != HomeVideoAddingTrimEndTextBox.Text) HomeVideoAddingTrimEndTextBox.Text = newText;
}
}
}
// FILENAME TEXTBOX TEXT CHANGED
private void HomeVideoAddingFilenameTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string oldFilename = HomeVideoAddingFilenameTextBox.Text;
string newFilename = oldFilename;
foreach (char c in System.IO.Path.GetInvalidFileNameChars()) newFilename = newFilename.Replace(c, ' ');
if (oldFilename != newFilename)
{
HomeVideoAddingFilenameTextBox.Text = newFilename;
Filename = newFilename;
}
}
// EXTENSION COMBOBOX SELECTION CHANGED
private void HomeVideoAddingExtensionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Extension = (MediaFileExtension)HomeVideoAddingExtensionComboBox.SelectedIndex + (MediaType == MediaType.OnlyAudio ? 3 : 0);
}
// SCHEDULE NUMBERBOX VALUE CHANGED
private void HomeVideoAddingScheduleNumberBox_ValueChanged(Microsoft.UI.Xaml.Controls.NumberBox sender, Microsoft.UI.Xaml.Controls.NumberBoxValueChangedEventArgs args)
{
Schedule = HomeVideoAddingScheduleNumberBox.Value;
}
// LOCATION BROWSE BUTTON CLICKED
private async void HomeVideoAddingLocationBrowseButton_Click(object sender, RoutedEventArgs e)
{
// Create location picker
FolderPicker picker = new FolderPicker
{
SuggestedStartLocation = PickerLocationId.Downloads
};
picker.FileTypeFilter.Add("*");
// Select location
StorageFolder selectedFolder = await picker.PickSingleFolderAsync();
if (selectedFolder != null)
{
try
{
await (await selectedFolder.CreateFileAsync("VDownloadLocationAccessTest")).DeleteAsync();
StorageApplicationPermissions.FutureAccessList.AddOrReplace("last_media_location", selectedFolder);
Location = selectedFolder;
HomeVideoAddingLocationSettingControl.Description = Location.Path;
}
catch (UnauthorizedAccessException) { }
}
}
// SOURCE BUTTON CLICKED // SOURCE BUTTON CLICKED
public async void HomeVideoAddingPanelSourceButton_Click(object sender, RoutedEventArgs e) public async void HomeVideoAddingPanelSourceButton_Click(object sender, RoutedEventArgs e)
{ {
@@ -304,14 +101,17 @@ namespace VDownload.Views.Home
TaskData taskData = new TaskData TaskData taskData = new TaskData
{ {
VideoService = VideoService, VideoService = VideoService,
MediaType = MediaType, TaskOptions = new TaskOptions()
Stream = Stream, {
TrimStart = TrimStart, MediaType = HomeVideoAddingOptionsControl.MediaType,
TrimEnd = TrimEnd, Stream = HomeVideoAddingOptionsControl.Stream,
Filename = Filename, TrimStart = HomeVideoAddingOptionsControl.TrimStart,
Extension = Extension, TrimEnd = HomeVideoAddingOptionsControl.TrimEnd,
Location = Location, Filename = HomeVideoAddingOptionsControl.Filename,
Schedule = Schedule, Extension = HomeVideoAddingOptionsControl.Extension,
Location = HomeVideoAddingOptionsControl.Location,
Schedule = HomeVideoAddingOptionsControl.Schedule,
}
}; };
// Request task adding // Request task adding