Archived
1
0
This repository has been archived on 2026-04-22. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
FoxTube/FoxTube/App.xaml.cs
T
2019-02-08 12:50:43 +03:00

271 lines
10 KiB
C#

using Google.Apis.YouTube.v3.Data;
using Microsoft.AppCenter;
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;
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 App()
{
SettingsStorage.LoadData();
switch (SettingsStorage.Theme)
{
case 0:
RequestedTheme = ApplicationTheme.Light;
break;
case 1:
RequestedTheme = ApplicationTheme.Dark;
break;
}
ApplicationLanguages.PrimaryLanguageOverride = SettingsStorage.Language;
CheckVersion();
InitializeComponent();
Suspending += OnSuspending;
UnhandledException += UnhandledError;
AppCenter.Start("45774462-9ea7-438a-96fc-03982666f39e", typeof(Analytics));
AppCenter.SetCountryCode(SettingsStorage.Region);
}
/// <summary>
/// Comparing current version with last recorded version. If doesn't match, poping up changelog notification
/// </summary>
public async void CheckVersion()
{
PackageVersion ver = Package.Current.Id.Version;
if (SettingsStorage.Version != $"{ver.Major}.{ver.Minor}")
{
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;
ToastNotificationManager.CreateToastNotifier().Show(FoxTube.Background.Notification.GetChangelogToast(e.GetAttribute("version")));
SettingsStorage.Version = $"{ver.Major}.{ver.Minor}";
}
catch
{
Debug.WriteLine("Unable to retrieve changelog");
}
}
}
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (!(Window.Current.Content is Frame rootFrame))
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
ActivateToastBackgoundTask();
ActivateBackgoundTask();
}
/// <summary>
/// Initializes background task for processing toast notifications' clicks
/// </summary>
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();
}
/// <summary>
/// Initializes background task for checking user's subscriptions and poping toast notifications when new video is uploaded
/// </summary>
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 async override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
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('|');
switch (arguments[0])
{
case "later":
try
{
if (!SecretsVault.IsAuthorized)
SecretsVault.CheckAuthorization(false);
if (!SecretsVault.IsAuthorized)
throw new Exception("Not authenticated");
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();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
break;
case "download":
await Launcher.LaunchFileAsync(await StorageFile.GetFileFromPathAsync(arguments[1]));
break;
}
}
deferral.Complete();
}
protected override void OnActivated(IActivatedEventArgs e)
{
base.OnActivated(e);
if (!(Window.Current.Content is Frame rootFrame))
{
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage));
}
Window.Current.Activate();
if (e is ToastNotificationActivatedEventArgs)
{
string[] args = (e as ToastNotificationActivatedEventArgs).Argument.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.Remove(args[1]);
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();
SettingsStorage.SaveData();
DownloadAgent.QuitPrompt();
deferral.Complete();
}
private void UnhandledError(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
{
Analytics.TrackEvent("The app crashed", new Dictionary<string, string>()
{
{ "Exception", e.Exception.GetType().ToString() },
{ "Class", e.ToString() },
{ "Details", e.Message }
});
}
}
}