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/Classes/Processes.cs
T
Michael Gordeev 6d093c90f5 Done frame controls
Related Work Items: #314, #315
2019-08-11 10:51:22 +03:00

249 lines
10 KiB
C#

using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.Services.Store.Engagement;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Resources;
using Windows.Data.Xml.Dom;
using Windows.System;
using Windows.System.Power;
using Windows.UI.Core;
using Windows.UI.Notifications;
using Windows.UI.Popups;
using Windows.UI.Xaml;
namespace FoxTube.Classes
{
public static class Processes
{
static CoreWindowActivationState windowState = CoreWindowActivationState.CodeActivated;
static ResourceLoader resources = ResourceLoader.GetForViewIndependentUse("Inbox");
static Stopwatch sw = new Stopwatch();
public static async void InitializeApp() => await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
CheckVersion();
RegisterToastTask();
if (Settings.DevNotifications || Settings.VideoNotifications)
RegisterTask();
else
UnregisterTask();
AppCenter.Start("45774462-9ea7-438a-96fc-03982666f39e", typeof(Analytics));
AppCenter.SetCountryCode(Settings.Region);
sw.Start();
Window.Current.Activated += (s, e) => windowState = e.WindowActivationState;
// TODO: Initialize other stuff
if (Settings.ProcessClipboard)
{
Clipboard.ContentChanged += ParseClipboard;
ParseClipboard();
}
PromptFeedback();
});
public static void SuspendApp()
{
sw.Stop();
Settings.Uptime += sw.Elapsed;
// TODO: Save other stuff
Analytics.TrackEvent("Session terminated", new Dictionary<string, string>
{
{ "Uptime", sw.Elapsed.ToString() },
{ "Total time", Settings.Uptime.ToString() }
});
}
static async void ParseClipboard(object sender = null, object e = null)
{
if (windowState != CoreWindowActivationState.Deactivated || !Settings.ProcessClipboard)
return;
try
{
string link = await Clipboard.GetContent().GetTextAsync();
if (!link.Contains("youtube") && !link.Contains("youtu.be"))
return;
string type = string.Empty;
string name = string.Empty;
if (YoutubeExplode.YoutubeClient.TryParseChannelId(link, out string id))
{
type = "channel";
name = (await new YoutubeExplode.YoutubeClient().GetChannelAsync(id)).Title;
}
else if (YoutubeExplode.YoutubeClient.TryParsePlaylistId(link, out id))
{
type = "playlist";
name = (await new YoutubeExplode.YoutubeClient().GetPlaylistAsync(id)).Title;
}
else if (YoutubeExplode.YoutubeClient.TryParseUsername(link, out id))
{
id = await new YoutubeExplode.YoutubeClient().GetChannelIdAsync(id);
type = "channel";
name = (await new YoutubeExplode.YoutubeClient().GetChannelAsync(id)).Title;
}
else if (YoutubeExplode.YoutubeClient.TryParseVideoId(link, out id))
{
type = "video";
name = (await new YoutubeExplode.YoutubeClient().GetVideoAsync(id)).Title;
}
if (string.IsNullOrWhiteSpace(id))
return;
XmlDocument toastXml = new XmlDocument();
toastXml.LoadXml($@"<toast launch='clipboard|{type}|{id}'>
<visual>
<binding template='ToastGeneric'>
<text>{resources.GetString("/Toasts/clipboardHead")}</text>
<text>{name}</text>
<text>{resources.GetString($"/Generic/{type}")}</text>
</binding>
</visual>
<actions>
<action content='{resources.GetString("/Toasts/clipboardOpen")}' arguments='clipboard|{type}|{id}'/>
</actions>
</toast>");
ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
}
catch { }
}
static void CheckVersion()
{
if (Settings.GetCurrentVersion() == Settings.Version)
return;
try
{
XmlDocument toast = new XmlDocument();
toast.LoadXml($@"<toast activationType='foreground' launch='changelog|{Settings.GetCurrentVersion()}'>
<visual>
<binding template='ToastGeneric'>
<image placement='hero' src='ms-appx:///Assets/WhatsNewThumb.png'/>
<image placement='appLogoOverride' hint-crop='circle' src='ms-appx:///Assets/NewsAvatar.png'/>
<text>{resources.GetString("/Inbox/changelog")}</text>
<text>{resources.GetString("/Inbox/whatsNew")} {Settings.GetCurrentVersion()}</text>
</binding>
</visual>
</toast>");
ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toast));
Settings.Version = Settings.GetCurrentVersion();
}
catch { }
}
static async void RegisterToastTask()
{
if (BackgroundTaskRegistration.AllTasks.Any(i => i.Value.Name.Equals("foxtubeToast")))
return;
var backgroundRequest = await BackgroundExecutionManager.RequestAccessAsync();
if (backgroundRequest == BackgroundAccessStatus.DeniedBySystemPolicy ||
backgroundRequest == BackgroundAccessStatus.DeniedByUser ||
backgroundRequest == BackgroundAccessStatus.Unspecified)
return;
BackgroundTaskBuilder builder = new BackgroundTaskBuilder() { Name = "foxtubeToast" };
builder.SetTrigger(new ToastNotificationActionTrigger());
BackgroundTaskRegistration registration = builder.Register();
}
static async void RegisterTask()
{
if (BackgroundTaskRegistration.AllTasks.Any(i => i.Value.Name.Equals("foxtubeBackground")))
return;
var backgroundRequest = await BackgroundExecutionManager.RequestAccessAsync();
if (backgroundRequest == BackgroundAccessStatus.DeniedBySystemPolicy ||
backgroundRequest == BackgroundAccessStatus.DeniedByUser ||
backgroundRequest == BackgroundAccessStatus.Unspecified ||
PowerManager.EnergySaverStatus == EnergySaverStatus.On)
return;
BackgroundTaskBuilder builder = new BackgroundTaskBuilder()
{
Name = "foxtubeBackgound",
IsNetworkRequested = true,
TaskEntryPoint = "FoxTube.Background.BackgroundProcessor"
};
builder.SetTrigger(new TimeTrigger(15, false));
BackgroundTaskRegistration registration = builder.Register();
}
static void UnregisterTask()
{
if (!(BackgroundTaskRegistration.AllTasks.Values.ToList().Find(i => i.Name == "foxtubeBackground") is IBackgroundTaskRegistration task))
return;
task.Unregister(true);
}
static async void PromptFeedback()
{
if (Settings.Uptime.TotalHours >= 12 && Settings.PromptFeedback)
{
Analytics.TrackEvent("Prompting feedback", new Dictionary<string, string>
{
{ "Total uptime", Settings.Uptime.ToString() }
});
MessageDialog dialog = new MessageDialog(resources.GetString("/Dialogs/feedbackMessage"));
dialog.Commands.Add(new UICommand(resources.GetString("/Dialogs/dontAsk"), (command) => Settings.PromptFeedback = false));
dialog.Commands.Add(new UICommand(resources.GetString("/Dialogs/promptLater")));
dialog.Commands.Add(new UICommand(resources.GetString("/Dialogs/sure"), async (command) =>
{
Settings.PromptFeedback = false;
if (StoreServicesFeedbackLauncher.IsSupported())
await StoreServicesFeedbackLauncher.GetDefault().LaunchAsync();
else
await Launcher.LaunchUriAsync("mailto:feedback@xfox111.net".ToUri());
}));
dialog.DefaultCommandIndex = 2;
dialog.CancelCommandIndex = 1;
await dialog.ShowAsync();
}
if (Settings.Uptime.TotalHours >= 24 && Settings.PromptReview)
{
Analytics.TrackEvent("Prompting review", new Dictionary<string, string>
{
{ "Total uptime", Settings.Uptime.ToString() }
});
MessageDialog dialog = new MessageDialog(resources.GetString("/Dialogs/rate"));
dialog.Commands.Add(new UICommand(resources.GetString("/Dialogs/dontAsk"), (command) => Settings.PromptReview = false));
dialog.Commands.Add(new UICommand(resources.GetString("/Dialogs/promptLater")));
dialog.Commands.Add(new UICommand(resources.GetString("/Dialogs/sure"), async (command) =>
{
Settings.PromptReview = false;
await Launcher.LaunchUriAsync("ms-windows-store://review/?ProductId=9NCQQXJTDLFH".ToUri());
}));
dialog.DefaultCommandIndex = 2;
dialog.CancelCommandIndex = 1;
await dialog.ShowAsync();
}
}
}
}