diff --git a/FoxTube/App.xaml.cs b/FoxTube/App.xaml.cs
index 09122f7..0d49758 100644
--- a/FoxTube/App.xaml.cs
+++ b/FoxTube/App.xaml.cs
@@ -1,34 +1,20 @@
-using Google.Apis.YouTube.v3.Data;
-using Microsoft.AppCenter;
+using FoxTube.Classes;
using Microsoft.AppCenter.Analytics;
-using System;
using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Xml;
-using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
-using Windows.ApplicationModel.Background;
using Windows.Globalization;
-using Windows.Storage;
-using Windows.System.Power;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
-using Windows.UI.Xaml.Navigation;
namespace FoxTube
{
sealed partial class App : Application
{
- public static string[] AvailableLanguages => new[] { "en-US", "ru-RU" };
-
- Stopwatch sw = new Stopwatch();
public App()
{
SettingsStorage.LoadData();
-
+
switch (SettingsStorage.Theme)
{
case 0:
@@ -40,113 +26,30 @@ namespace FoxTube
}
ApplicationLanguages.PrimaryLanguageOverride = SettingsStorage.Language;
- CheckVersion();
-
InitializeComponent();
- Suspending += OnSuspending;
- UnhandledException += UnhandledError;
-
- AppCenter.Start("45774462-9ea7-438a-96fc-03982666f39e", typeof(Analytics));
- AppCenter.SetCountryCode(SettingsStorage.Region);
-
- sw.Start();
- }
-
- ///
- /// Comparing current version with last recorded version. If doesn't match, poping up changelog notification
- ///
- public async void CheckVersion()
- {
- PackageVersion ver = Package.Current.Id.Version;
- if (SettingsStorage.Version != $"{ver.Major}.{ver.Minor}.{ver.Build}")
+ Suspending += (s, e) => Processes.SuspendApp();
+ UnhandledException += (s, e) => Analytics.TrackEvent("The app crashed", new Dictionary()
{
- try
- {
- XmlDocument changelog = new XmlDocument();
- StorageFile file = await (await Package.Current.InstalledLocation.GetFolderAsync(@"Assets\Data")).GetFileAsync("Patchnotes.xml");
- changelog.Load(await file.OpenStreamForReadAsync());
- XmlElement e = changelog["items"].ChildNodes[0] as XmlElement;
+ { "Exception", e.Exception.GetType().ToString() },
+ { "Details", e.Message },
+ { "StackTrace", e.Exception.StackTrace }
+ });
- ToastNotificationManager.CreateToastNotifier().Show(Background.Notification.GetChangelogToast(e.GetAttribute("version")));
-
- SettingsStorage.Version = $"{ver.Major}.{ver.Minor}.{ver.Build}";
- }
- catch (Exception e)
- {
- Analytics.TrackEvent("Unable to retrieve changelog", new Dictionary
- {
- { "Exception", e.GetType().ToString() },
- { "Message", e.Message },
- { "App version", $"{ver.Major}.{ver.Minor}.{ver.Revision}.{ver.Build}" },
- { "StackTrace", e.StackTrace }
- });
- }
- }
+ Processes.InitializeApp();
}
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
- if (!(Window.Current.Content is Frame rootFrame))
- {
- rootFrame = new Frame();
- rootFrame.NavigationFailed += OnNavigationFailed;
- Window.Current.Content = rootFrame;
- }
+ if (!(Window.Current.Content is Frame))
+ Window.Current.Content = new Frame();
if (e.PrelaunchActivated == false)
{
- if (rootFrame.Content == null)
- rootFrame.Navigate(typeof(MainPage), e.Arguments);
+ if ((Window.Current.Content as Frame).Content == null)
+ (Window.Current.Content as Frame).Navigate(typeof(MainPage), e.Arguments);
Window.Current.Activate();
}
-
- ActivateToastBackgoundTask();
- ActivateBackgoundTask();
- }
-
- ///
- /// Initializes background task for processing toast notifications' clicks
- ///
- public async void ActivateToastBackgoundTask()
- {
- const string taskName = "FoxtubeToastBackground";
- if (BackgroundTaskRegistration.AllTasks.Any(i => i.Value.Name.Equals(taskName)))
- return;
-
- var backgroundRequest = await BackgroundExecutionManager.RequestAccessAsync();
- if (backgroundRequest == BackgroundAccessStatus.DeniedBySystemPolicy || backgroundRequest == BackgroundAccessStatus.DeniedByUser)
- return;
-
- BackgroundTaskBuilder builder = new BackgroundTaskBuilder() { Name = taskName };
- builder.SetTrigger(new ToastNotificationActionTrigger());
-
- BackgroundTaskRegistration registration = builder.Register();
- }
-
- ///
- /// Initializes background task for checking user's subscriptions and poping toast notifications when new video is uploaded
- ///
- public async void ActivateBackgoundTask()
- {
- const string taskName = "FoxtubeBackgound";
- if (BackgroundTaskRegistration.AllTasks.Any(i => i.Value.Name.Equals(taskName)))
- return;
-
- var backgroundRequest = await BackgroundExecutionManager.RequestAccessAsync();
- var saverRequest = PowerManager.EnergySaverStatus;
- if (backgroundRequest == BackgroundAccessStatus.DeniedBySystemPolicy || backgroundRequest == BackgroundAccessStatus.DeniedByUser || saverRequest == EnergySaverStatus.On)
- return;
-
- BackgroundTaskBuilder builder = new BackgroundTaskBuilder()
- {
- Name = taskName,
- IsNetworkRequested = true,
- TaskEntryPoint = "FoxTube.Background.BackgroundProcessor"
- };
- builder.SetTrigger(new TimeTrigger(15, false));
-
- BackgroundTaskRegistration registration = builder.Register();
}
protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
@@ -154,50 +57,10 @@ namespace FoxTube
var deferral = args.TaskInstance.GetDeferral();
base.OnBackgroundActivated(args);
- if (args.TaskInstance.Task.Name == "FoxtubeToastBackground" && args.TaskInstance.TriggerDetails is ToastNotificationActionTriggerDetail details)
- {
- string[] arguments = details.Argument.Split('|');
+ if (args.TaskInstance.Task.Name == "FoxtubeToastBackground" || !(args.TaskInstance.TriggerDetails is ToastNotificationActionTriggerDetail details))
+ return;
- switch (arguments[0])
- {
- case "later":
- try
- {
- SecretsVault.AuthorizationStateChanged += async (s, e) =>
- {
- if ((bool)e[0])
- {
- PlaylistItem item = new PlaylistItem()
- {
- Snippet = new PlaylistItemSnippet()
- {
- ResourceId = new ResourceId()
- {
- Kind = "youtube#video",
- VideoId = arguments[1]
- },
- PlaylistId = "WL"
- }
- };
-
- await SecretsVault.Service.PlaylistItems.Insert(item, "snippet").ExecuteAsync();
- }
- };
- SecretsVault.CheckAuthorization(false);
- }
- catch (Exception e)
- {
- Analytics.TrackEvent("Failed to add video to WL from toast", new Dictionary
- {
- { "Exception", e.GetType().ToString() },
- { "Message", e.Message },
- { "Video ID", arguments[1] },
- { "StackTrace", e.StackTrace }
- });
- }
- break;
- }
- }
+ Processes.ProcessToast(details.Argument);
deferral.Complete();
}
@@ -206,7 +69,8 @@ namespace FoxTube
{
base.OnActivated(e);
- if (!(Window.Current.Content is Frame rootFrame))
+ //TODO: Check this shit
+ /*if (!(Window.Current.Content is Frame rootFrame))
{
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
@@ -217,88 +81,15 @@ namespace FoxTube
if (rootFrame.Content == null)
rootFrame.Navigate(typeof(MainPage));
- Window.Current.Activate();
+ Window.Current.Activate();*/
- switch (e.Kind)
- {
- case ActivationKind.ToastNotification:
- if (SecretsVault.IsAuthorized)
- ProcessToast((e as ToastNotificationActivatedEventArgs).Argument);
- else
- SecretsVault.AuthorizationStateChanged += (s, arg) => ProcessToast((e as ToastNotificationActivatedEventArgs).Argument);
- break;
- }
- }
+ if (e.Kind != ActivationKind.ToastNotification)
+ return;
- private void ProcessToast(string arg)
- {
- string[] args = arg.Split('|');
- switch (args[0])
- {
- case "changelog":
- case "inbox":
- Methods.MainPage.GoToDeveloper(args[1]);
- break;
-
- case "video":
- Methods.MainPage.GoToVideo(args[1]);
- break;
-
- case "channel":
- Methods.MainPage.GoToChannel(args[1]);
- break;
-
- case "download":
- Methods.MainPage.GoToDownloads();
- break;
- case "dcancel":
- DownloadAgent.Cancel(args[1]);
- break;
- case "clipboard":
- switch (args[1])
- {
- case "video":
- Methods.MainPage.GoToVideo(args[2]);
- break;
- case "channel":
- Methods.MainPage.GoToChannel(args[2]);
- break;
- case "playlist":
- Methods.MainPage.GoToPlaylist(args[2]);
- break;
- }
- break;
- }
- }
-
- void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
- {
- throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
- }
-
- private void OnSuspending(object sender, SuspendingEventArgs e)
- {
- var deferral = e.SuspendingOperation.GetDeferral();
-
- sw.Stop();
- SettingsStorage.Uptime += sw.Elapsed;
-
- HistorySet.Save();
- SettingsStorage.SaveData();
- DownloadAgent.QuitPrompt();
- Controls.Player.ManifestGenerator.ClearRoaming();
- deferral.Complete();
- Analytics.TrackEvent("Session terminated");
- }
-
- private void UnhandledError(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
- {
- Analytics.TrackEvent("The app crashed", new Dictionary()
- {
- { "Exception", e.Exception.GetType().ToString() },
- { "Details", e.Message },
- { "StackTrace", e.Exception.StackTrace }
- });
+ if (SecretsVault.IsAuthorized)
+ Processes.ProcessToast((e as ToastNotificationActivatedEventArgs).Argument);
+ else
+ SecretsVault.AuthorizationStateChanged += (arg) => Processes.ProcessToast((e as ToastNotificationActivatedEventArgs).Argument);
}
}
}
diff --git a/FoxTube/Classes/AdaptiveCommandBar.cs b/FoxTube/Classes/AdaptiveCommandBar.cs
index 3b88891..3af6a2d 100644
--- a/FoxTube/Classes/AdaptiveCommandBar.cs
+++ b/FoxTube/Classes/AdaptiveCommandBar.cs
@@ -4,9 +4,7 @@ namespace FoxTube.Classes
{
class AdaptiveCommandBar : CommandBar
{
- public AdaptiveCommandBar()
- {
+ public AdaptiveCommandBar() =>
ClosedDisplayMode = SettingsStorage.AppBarClosedMode;
- }
}
}
diff --git a/FoxTube/Classes/DownloadAgent.cs b/FoxTube/Classes/DownloadAgent.cs
index 8c7fd4d..1cfffdf 100644
--- a/FoxTube/Classes/DownloadAgent.cs
+++ b/FoxTube/Classes/DownloadAgent.cs
@@ -3,26 +3,26 @@ using System.Collections.Generic;
using Windows.Storage;
using Newtonsoft.Json;
using YoutubeExplode.Models.MediaStreams;
-using Google.Apis.YouTube.v3.Data;
using FoxTube.Controls;
using FoxTube.Pages;
using Microsoft.AppCenter.Analytics;
+using YoutubeExplode.Models;
namespace FoxTube
{
public static class DownloadAgent
{
public static List Items { get; set; } = new List();
- private static readonly ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
+ static readonly ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
public static Downloads Page { get; set; }
public static StorageFolder Downloads { get; set; }
public static async void Initialize()
{
- Downloads = await KnownFolders.VideosLibrary.CreateFolderAsync("FoxTube", CreationCollisionOption.OpenIfExists);
Items.Clear();
try
{
+ Downloads = await KnownFolders.VideosLibrary.CreateFolderAsync("FoxTube", CreationCollisionOption.OpenIfExists);
List containers = JsonConvert.DeserializeObject>((string)settings.Values[$"downloads"]);
containers.ForEach(i => Items.Add(new DownloadItem(i)));
}
@@ -38,10 +38,8 @@ namespace FoxTube
}
}
- public static void Add(MediaStreamInfo info, Video meta, string qualty)
- {
- Items.Insert(0, new DownloadItem(info, meta, qualty));
- }
+ public static void Add((MediaStreamInfo info, Video meta, string qualty) e) =>
+ Items.Insert(0, new DownloadItem(e.info, e.meta, e.qualty));
public static void Remove(DownloadItem item)
{
diff --git a/FoxTube/Classes/Extensions.cs b/FoxTube/Classes/Extensions.cs
new file mode 100644
index 0000000..7efc0f9
--- /dev/null
+++ b/FoxTube/Classes/Extensions.cs
@@ -0,0 +1,34 @@
+using Google.Apis.YouTube.v3.Data;
+using System;
+using System.Threading.Tasks;
+
+namespace FoxTube.Classes
+{
+ public delegate void SubscriptionsChangedEventHandler(string action, Subscription subscription);
+ public delegate void AuthorizationChangedEventHandler(bool? isAuthorized);
+ public delegate void MinimodeChangedEventHandler(bool isOn);
+ public delegate void SimpleEventHandler();
+ public delegate void PlaylistItemChangedEventHandler(string id);
+ public delegate void NavigationEventHanlder(Type sourcePageType, object parameter);
+
+ public static class Extensions
+ {
+ public static bool Belongs(this double num, double x1, double x2)
+ {
+ return num > x1 && num < x2;
+ }
+ }
+
+ public interface INavigationPage
+ {
+ object Parameter { get; set; }
+ }
+
+ public interface ICard
+ {
+ Task Initialize();
+ void ItemClicked();
+ }
+
+ public enum PlayerDisplayState { Normal, Minimized, Compact }
+}
diff --git a/FoxTube/Classes/InboxItem.cs b/FoxTube/Classes/InboxItem.cs
index 6ea8f09..f2def2f 100644
--- a/FoxTube/Classes/InboxItem.cs
+++ b/FoxTube/Classes/InboxItem.cs
@@ -9,55 +9,18 @@ namespace FoxTube.Classes
{
public InboxItemType Type { get; set; } = InboxItemType.Default;
public DateTime TimeStamp { get; set; }
- public string TimeStampString
- {
- get
- {
- if (Type == InboxItemType.PatchNote)
- return TimeStamp.ToShortDateString();
- else
- return TimeStamp.ToString();
- }
- }
+ public string TimeStampString => Type == InboxItemType.PatchNote ? TimeStamp.ToShortDateString() : TimeStamp.ToString();
public string Subject { get; set; }
public string Content { get; set; }
public string Id { get; set; }
private ResourceLoader resources = ResourceLoader.GetForCurrentView("Inbox");
-
- public string Icon
- {
- get
- {
- if (Type == InboxItemType.PatchNote)
- return "\xE728";
- else
- return "\xE119";
- }
- }
- public string Subtitle
- {
- get
- {
- if (Type == InboxItemType.PatchNote)
- return resources.GetString("changelog");
- else
- return resources.GetString("dev");
- }
- }
- public string Title
- {
- get
- {
- if (Type == InboxItemType.PatchNote)
- return $"{resources.GetString("whatsnew")}{Id}";
- else
- return Subject;
- }
- }
+ public string Icon => Type == InboxItemType.PatchNote ? "\xE728" : "\xE119";
+ public string Subtitle => Type == InboxItemType.PatchNote ? resources.GetString("changelog") : resources.GetString("dev");
+ public string Title => Type == InboxItemType.PatchNote ? $"{resources.GetString("whatsnew")}{Id}" : Subject;
public InboxItem(string version, string content, DateTime timeStamp)
{
diff --git a/FoxTube/Classes/ManifestGenerator.cs b/FoxTube/Classes/ManifestGenerator.cs
index 6cea736..c187b16 100644
--- a/FoxTube/Classes/ManifestGenerator.cs
+++ b/FoxTube/Classes/ManifestGenerator.cs
@@ -16,7 +16,7 @@ using Windows.ApplicationModel.Resources;
using Windows.Storage;
using YoutubeExplode.Models.MediaStreams;
-namespace FoxTube.Controls.Player
+namespace FoxTube.Classes
{
public static class ManifestGenerator
{
@@ -82,7 +82,7 @@ namespace FoxTube.Controls.Player
}
}
- private static XmlElement GetVideoPresentation(XmlDocument doc, StreamInfo.VideoInfo info)
+ static XmlElement GetVideoPresentation(XmlDocument doc, StreamInfo.VideoInfo info)
{
XmlElement representation = doc.CreateElement("Representation");
representation.SetAttribute("bandwidth", GetBandwidth(info.Label));
@@ -108,7 +108,7 @@ namespace FoxTube.Controls.Player
return representation;
}
- private static XmlElement GetAudioPresentation(XmlDocument doc, StreamInfo.AudioInfo info)
+ static XmlElement GetAudioPresentation(XmlDocument doc, StreamInfo.AudioInfo info)
{
XmlElement audio = doc.CreateElement("Representation");
audio.SetAttribute("bandwidth", "200000");
@@ -133,7 +133,7 @@ namespace FoxTube.Controls.Player
return audio;
}
- private static async Task GetInfoAsync(Video info, VideoStreamInfo requestedQuality)
+ static async Task GetInfoAsync(Video info, VideoStreamInfo requestedQuality)
{
try
{
@@ -195,7 +195,7 @@ namespace FoxTube.Controls.Player
}
}
- public static Dictionary SplitQuery(string query)
+ static Dictionary SplitQuery(string query)
{
Dictionary dic = new Dictionary(StringComparer.OrdinalIgnoreCase);
string[] paramsEncoded = query.TrimStart('?').Split("&");
@@ -221,7 +221,7 @@ namespace FoxTube.Controls.Player
return dic;
}
- private static string GetBandwidth(string quality)
+ static string GetBandwidth(string quality)
{
string parsed = quality.Split('p')[0];
switch (quality)
@@ -301,41 +301,4 @@ namespace FoxTube.Controls.Player
await f.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
}
-
- public class StreamInfo
- {
- public class VideoInfo
- {
- public string IndexRange { get; set; }
- public string InitRange => $"0-{int.Parse(IndexRange.Split('-')[0]) - 1}";
- public string Itag { get; set; }
- public string Fps { get; set; }
- public string Url { get; set; }
- public string Codecs { get; set; }
- public string MimeType { get; set; }
- public string Height { get; set; }
- public string Width { get; set; }
- public string Label { get; set; }
- }
- public class AudioInfo
- {
- public string IndexRange { get; set; }
- public string InitRange => $"0-{int.Parse(IndexRange.Split('-')[0]) - 1}";
- public string SampleRate { get; set; }
- public string ChannelsCount { get; set; }
- public string Codecs { get; set; }
- public string MimeType { get; set; }
- public string Url { get; set; }
- public string Itag { get; set; }
- }
-
- public List Video { get; } = new List();
- public List Audio { get; } = new List();
- }
-
- public class StreamQuality
- {
- public Uri Url { get; set; }
- public string Resolution { get; set; }
- }
}
diff --git a/FoxTube/Classes/Methods.cs b/FoxTube/Classes/Methods.cs
index c744546..ca0190e 100644
--- a/FoxTube/Classes/Methods.cs
+++ b/FoxTube/Classes/Methods.cs
@@ -1,6 +1,7 @@
-using FoxTube.Pages;
+using FoxTube.Classes;
+using FoxTube.Controls.VideoPage;
+using Google.Apis.YouTube.v3.Data;
using Microsoft.AppCenter.Analytics;
-using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
@@ -9,7 +10,6 @@ using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
-using Windows.ApplicationModel.Core;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Resources;
using Windows.Storage.Streams;
@@ -26,21 +26,47 @@ namespace FoxTube
public delegate void ObjectEventHandler(object sender = null, params object[] args);
- public interface INavigationPage
- {
- object Parameter { get; set; }
- }
-
public static class Methods
{
private static readonly ResourceLoader resources = ResourceLoader.GetForCurrentView("Methods");
- public static CommentsPage CommentsPage { get; set; }
+ public static Comments CommentsPage { get; set; }
public static MainPage MainPage => (Window.Current.Content as Frame).Content as MainPage;
- public static void CloseApp()
+ public static async Task AddItemToWL(string id)
{
- CoreApplication.Exit();
+ try
+ {
+ SecretsVault.RefreshToken();
+
+ PlaylistItem item = new PlaylistItem
+ {
+ Snippet = new PlaylistItemSnippet
+ {
+ ResourceId = new ResourceId
+ {
+ Kind = "youtube#video",
+ VideoId = id
+ },
+ PlaylistId = "WL"
+ }
+ };
+
+ await SecretsVault.Service.PlaylistItems.Insert(item, "snippet").ExecuteAsync();
+ return true;
+ }
+ catch (Exception e)
+ {
+ Analytics.TrackEvent("Failed to add video to WL", new Dictionary
+ {
+ { "Exception", e.GetType().ToString() },
+ { "Message", e.Message },
+ { "Video ID", id },
+ { "StackTrace", e.StackTrace }
+ });
+
+ return false;
+ }
}
public static Uri ToUri(this string url)
@@ -49,10 +75,8 @@ namespace FoxTube
catch { return null; }
}
- public static string GuardFromNull(string str)
- {
- return str ?? string.Empty;
- }
+ public static string GuardFromNull(string str) =>
+ str ?? string.Empty;
public static void SendMail(string content)
{
@@ -68,22 +92,6 @@ namespace FoxTube
client.Send(msg);
}
- [Obsolete]
- public static string GetChars(this string str, int count)
- {
- try
- {
- string s = "";
- for (int i = 0; i < count; i++)
- s += str[i];
- return s;
- }
- catch
- {
- return "";
- }
- }
-
public static List