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/Pages/MainPage.xaml.cs
T
2019-02-03 19:57:39 +03:00

783 lines
31 KiB
C#

using System;
using System.Collections.Generic;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Windows.UI.Notifications;
using Windows.UI.Xaml.Media.Imaging;
using System.Xml;
using Google.Apis.YouTube.v3.Data;
using Windows.ApplicationModel.Core;
using Windows.System;
using Google.Apis.Oauth2.v2;
using Google.Apis.Oauth2.v2.Data;
using FoxTube.Pages;
using Windows.ApplicationModel;
using System.Net;
using Windows.UI.Popups;
using Windows.Networking.Connectivity;
using Windows.UI.Core;
using Windows.ApplicationModel.Resources;
using Windows.Storage;
using System.IO;
namespace FoxTube
{
public enum Sender { Menu, Frame, None }
/// <summary>
/// Main app's layout
/// </summary>
public sealed partial class MainPage : Page
{
// TODO: Refactor main page
Sender s = Sender.None;
readonly ResourceLoader resources = ResourceLoader.GetForCurrentView("Main");
public MainPage()
{
InitializeComponent();
CheckVersion();
SecretsVault.AuthorizationStateChanged += AuthorizationStateChanged;
SecretsVault.SubscriptionsChanged += SecretsVault_SubscriptionsChanged;
SecretsVault.Purchased += (sender, e) =>
{
removeAds.Visibility = (e[0] as bool?).Value ? Visibility.Collapsed : Visibility.Visible;
content.Navigate(typeof(Home));
};
SecretsVault.CheckAuthorization();
SecretsVault.CheckAddons();
SetTitleBar();
}
/// <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");
}
}
}
public Video GetCurrentItem()
{
try { return (videoPlaceholder.Content as VideoPage).item; }
catch { return null; }
}
public string GetPlaylist()
{
try { return (videoPlaceholder.Content as VideoPage).playlistId; }
catch { return null; }
}
public void SetTitleBar()
{
var titleBar = ApplicationView.GetForCurrentView().TitleBar;
titleBar.BackgroundColor = Colors.Red;
titleBar.ButtonBackgroundColor = Colors.Red;
titleBar.ButtonHoverBackgroundColor = Colors.IndianRed;
titleBar.ButtonPressedBackgroundColor = Colors.DarkRed;
titleBar.ButtonInactiveBackgroundColor = Colors.Black;
titleBar.ForegroundColor = Colors.White;
CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = false;
}
/// <summary>
/// Invoked when subscriptions are edited to edit menu
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void SecretsVault_SubscriptionsChanged(object sender, params object[] args)
{
if ((string)args[0] == "add" && nav.MenuItems.Count < 19)
{
subsHeader.Visibility = Visibility.Visible;
Subscription s = args[1] as Subscription;
StackPanel panel = new StackPanel()
{
Orientation = Orientation.Horizontal,
Padding = new Thickness(5)
};
panel.Children.Add(new PersonPicture()
{
Height = 20,
Margin = new Thickness(-5, 0, 15, 0),
ProfilePicture = new BitmapImage(new Uri(s.Snippet.Thumbnails.Medium.Url))
});
panel.Children.Add(new TextBlock() { Text = s.Snippet.Title });
nav.MenuItems.Add(new NavigationViewItem()
{
Content = panel,
Name = (nav.MenuItems.Count - 9).ToString(),
Padding = new Thickness(-5)
});
}
else if ((string)args[0] == "remove" && (int)args[1] < 10)
{
nav.MenuItems.RemoveAt((int)args[1] + 9);
if(SecretsVault.Subscriptions.Count >= 10)
{
Subscription s = SecretsVault.Subscriptions[9];
StackPanel panel = new StackPanel()
{
Orientation = Orientation.Horizontal,
Padding = new Thickness(5)
};
panel.Children.Add(new PersonPicture()
{
Height = 20,
Margin = new Thickness(-5, 0, 15, 0),
ProfilePicture = new BitmapImage(new Uri(s.Snippet.Thumbnails.Medium.Url))
});
panel.Children.Add(new TextBlock() { Text = s.Snippet.Title });
nav.MenuItems.Add(new NavigationViewItem()
{
Content = panel,
Name = (nav.MenuItems.Count - 9).ToString(),
Padding = new Thickness(-5)
});
}
}
}
private async void AuthorizationStateChanged(object sender, params object[] e)
{
if(e[0] as bool? == true)
{
account.Visibility = Visibility.Collapsed;
try
{
Userinfoplus info = await new Oauth2Service(SecretsVault.Initializer).Userinfo.Get().ExecuteAsync();
myName.Text = info.Name;
((avatar.Content as StackPanel).Children[0] as PersonPicture).ProfilePicture = new BitmapImage(new Uri(info.Picture));
}
catch { }
avatar.Visibility = Visibility.Visible;
toChannel.Visibility = Visibility.Visible;
toSubscriptions.Visibility = Visibility.Visible;
libHeader.Visibility = Visibility.Visible;
toHistory.Visibility = Visibility.Visible;
toLiked.Visibility = Visibility.Visible;
toLater.Visibility = Visibility.Visible;
if (SecretsVault.Subscriptions.Count > 0)
{
subsHeader.Visibility = Visibility.Visible;
for(int k = 0; k < SecretsVault.Subscriptions.Count && k < 10; k++)
try
{
Subscription s = SecretsVault.Subscriptions[k];
StackPanel panel = new StackPanel()
{
Orientation = Orientation.Horizontal,
Padding = new Thickness(5)
};
panel.Children.Add(new PersonPicture()
{
Height = 20,
Margin = new Thickness(-5, 0, 15, 0),
ProfilePicture = new BitmapImage(new Uri(s.Snippet.Thumbnails.Medium.Url))
});
panel.Children.Add(new TextBlock() { Text = s.Snippet.Title });
nav.MenuItems.Add(new NavigationViewItem()
{
Content = panel,
Name = k.ToString(),
Padding = new Thickness(-5)
});
}
catch { continue; }
}
}
else if (e[0] as bool? == false)
{
for (int k = nav.MenuItems.Count - 1; k > 8; k--)
nav.MenuItems.RemoveAt(k);
account.Visibility = Visibility.Visible;
avatar.Visibility = Visibility.Collapsed;
toChannel.Visibility = Visibility.Collapsed;
toSubscriptions.Visibility = Visibility.Collapsed;
libHeader.Visibility = Visibility.Collapsed;
toHistory.Visibility = Visibility.Collapsed;
toLiked.Visibility = Visibility.Collapsed;
toLater.Visibility = Visibility.Collapsed;
subsHeader.Visibility = Visibility.Collapsed;
subsHeader.Visibility = Visibility.Collapsed;
}
else
{
MessageDialog dialog = new MessageDialog(resources.GetString("/Main/connectErrContent"), resources.GetString("/Main/connectErrHeader"));
dialog.Commands.Add(new UICommand(resources.GetString("/Main/tryAgain"), (command) =>
{
SecretsVault.Authorize();
}));
dialog.Commands.Add(new UICommand(resources.GetString("/Main/quit"), (command) =>
{
Methods.CloseApp();
}));
dialog.CancelCommandIndex = 1;
dialog.DefaultCommandIndex = 0;
await dialog.ShowAsync();
}
if(e[0] as bool? != null)
DownloadAgent.Initialize();
content.Navigate(typeof(Home));
if (videoPlaceholder.Content != null)
GoToVideo((videoPlaceholder.Content as VideoPage).videoId);
}
private async void Feedback_Click(object sender, TappedRoutedEventArgs e)
{
await Launcher.LaunchUriAsync(new Uri("feedback-hub:"));
}
private async void CreateAccount_Click(object sender, RoutedEventArgs e)
{
await Launcher.LaunchUriAsync(new Uri("https://accounts.google.com/signup/v2/webcreateaccount?ManageAccount&flowName=GlifWebSignIn&flowEntry=SignUp"));
}
private void SignIn_Click(object sender, RoutedEventArgs e)
{
SecretsVault.Authorize();
}
private void MyChannel_Click(object sender, RoutedEventArgs e)
{
GoToChannel(SecretsVault.AccountId);
}
private void Logout_Click(object sender, RoutedEventArgs e)
{
SecretsVault.Deauthenticate();
}
public void GoToSearch(SearchParameters args)
{
nav.IsPaneOpen = false;
content.Navigate(typeof(Search), args);
}
public void GoToChannel(string id)
{
content.Navigate(typeof(ChannelPage), id);
}
public void GoToHome()
{
content.Navigate(typeof(Home));
}
public async void GoToVideo(string id, string playlistId = null)
{
bool cancel = false;
try
{
var connection = NetworkInformation.GetInternetConnectionProfile().GetConnectionCost();
if (SettingsStorage.CheckConnection && (connection.NetworkCostType == NetworkCostType.Fixed || connection.NetworkCostType == NetworkCostType.Variable))
{
MessageDialog dialog = new MessageDialog(resources.GetString("/Main/metered"))
{
DefaultCommandIndex = 2,
CancelCommandIndex = 1
};
dialog.Commands.Add(new UICommand(resources.GetString("/Main/yes")));
dialog.Commands.Add(new UICommand(resources.GetString("/Main/no"), (command) => cancel = true));
if(SecretsVault.IsAuthorized)
dialog.Commands.Add(new UICommand(resources.GetString("/Main/addLater"), (command) =>
{
try
{
PlaylistItem item = new PlaylistItem()
{
Snippet = new PlaylistItemSnippet()
{
ResourceId = new ResourceId()
{
Kind = "youtube#video",
VideoId = id
},
PlaylistId = "WL"
}
};
SecretsVault.Service.PlaylistItems.Insert(item, "snippet").Execute();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
cancel = true;
}));
await dialog.ShowAsync();
}
}
catch { }
if (cancel)
return;
if (videoPlaceholder.Content != null)
(videoPlaceholder.Content as VideoPage).player.close_Click(this, null);
videoPlaceholder.Content = null;
Fullscreen(false);
videoPlaceholder.Navigate(typeof(VideoPage), new string[2] { id, playlistId });
MaximizeVideo();
}
public void GoToDeveloper(string id)
{
content.Navigate(typeof(Settings), $"inbox&{id}");
}
public void GoToPlaylist(string id)
{
content.Navigate(typeof(PlaylistPage), id);
}
public void GoToDownloads()
{
content.Navigate(typeof(Downloads));
}
private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (videoPlaceholder.Content != null)
(videoPlaceholder.Content as VideoPage).player.UpdateSize();
}
public void MinimizeAsInitializer()
{
if(videoPlaceholder.Content != null)
{
if ((videoPlaceholder.Content as VideoPage).loading.State != LoadingState.Loaded)
CloseVideo();
else
{
try { (videoPlaceholder.Content as VideoPage).player.minimize_Click(this, null); }
catch { }
}
}
}
public void MinimizeVideo()
{
videoPlaceholder.Width = 432;
videoPlaceholder.Height = 243;
videoPlaceholder.VerticalAlignment = VerticalAlignment.Bottom;
videoPlaceholder.HorizontalAlignment = HorizontalAlignment.Right;
videoPlaceholder.Margin = new Thickness(0, 0, 25, 50);
if (content.CanGoBack)
nav.IsBackEnabled = true;
else
nav.IsBackEnabled = false;
Dictionary<Type, Action> switchCase = new Dictionary<Type, Action>()
{
{ typeof(Settings), () => nav.Header = resources.GetString("/Main/settings/Content") },
{ typeof(ChannelPage), () => nav.Header = resources.GetString("/Main/channel") },
{ typeof(PlaylistPage), () => nav.Header = resources.GetString("/Main/playlist") },
{ typeof(Search), () => nav.Header = resources.GetString("/Main/searchPlaceholder/PlaceholderText") },
{ typeof(Subscriptions), () => nav.Header = resources.GetString("/Main/subscriptions/Content") },
{ typeof(History), () => nav.Header = resources.GetString("/Main/history/Content") },
{ typeof(Home), () => nav.Header = resources.GetString("/Main/home/Content") },
{ typeof(Downloads), () => nav.Header = resources.GetString("/Main/downloads/Content") }
};
if (content.SourcePageType == typeof(Home) || content.SourcePageType == typeof(Settings) || content.SourcePageType == typeof(Subscriptions))
{
nav.ExpandedModeThresholdWidth = 1008;
if (nav.DisplayMode == NavigationViewDisplayMode.Expanded)
nav.IsPaneOpen = true;
}
else
nav.ExpandedModeThresholdWidth = short.MaxValue;
try { switchCase[content.SourcePageType](); }
catch { }
}
public void MaximizeVideo()
{
videoPlaceholder.Width = double.NaN;
videoPlaceholder.Height = double.NaN;
videoPlaceholder.VerticalAlignment = VerticalAlignment.Stretch;
videoPlaceholder.HorizontalAlignment = HorizontalAlignment.Stretch;
videoPlaceholder.Margin = new Thickness(0);
nav.IsBackEnabled = true;
if (videoPlaceholder.Content != null)
{
nav.Header = resources.GetString("/Main/video");
nav.ExpandedModeThresholdWidth = short.MaxValue;
nav.IsPaneOpen = false;
}
}
public void Fullscreen(bool on)
{
if (on)
{
nav.CompactModeThresholdWidth = short.MaxValue;
nav.ExpandedModeThresholdWidth = short.MaxValue;
try
{
nav.IsPaneVisible = false;
}
catch
{
nav.CompactPaneLength = 0;
nav.OpenPaneLength = 0;
}
nav.Margin = new Thickness(0, -45, 0, 0);
}
else
{
nav.CompactModeThresholdWidth = 641;
if(videoPlaceholder.Content == null)
nav.ExpandedModeThresholdWidth = 1008;
nav.Margin = new Thickness(0);
try
{
nav.IsPaneVisible = true;
}
catch
{
nav.CompactPaneLength = new NavigationView().CompactPaneLength;
nav.OpenPaneLength = new NavigationView().OpenPaneLength; ;
}
if (videoPlaceholder.Content != null && nav.IsPaneOpen)
nav.IsPaneOpen = false;
SetTitleBar();
}
nav.UpdateLayout();
}
public void CloseVideo()
{
if (ApplicationView.GetForCurrentView().IsFullScreenMode)
{
ApplicationView.GetForCurrentView().ExitFullScreenMode();
Fullscreen(false);
}
videoPlaceholder.Content = null;
GC.Collect();
Window.Current.CoreWindow.PointerCursor = new CoreCursor(CoreCursorType.Arrow, 0);
MaximizeVideo();
if (content.CanGoBack)
nav.IsBackEnabled = true;
else
nav.IsBackEnabled = false;
}
private void Search_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
if(!string.IsNullOrWhiteSpace(search.Text))
GoToSearch(new SearchParameters(search.Text));
}
private void Search_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (search.Text.Length > 2 && args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load($"http://suggestqueries.google.com/complete/search?ds=yt&client=toolbar&q={search.Text}");
List<string> suggestions = new List<string>();
for (int i = 0; i < doc["toplevel"].ChildNodes.Count && i < 5; i++)
suggestions.Add(doc["toplevel"].ChildNodes[i]["suggestion"].GetAttribute("data"));
search.ItemsSource = suggestions;
}
catch (WebException)
{
search.ItemsSource = new List<string>();
}
}
}
private void Nav_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
Debug.WriteLine("Menu selection changed");
try
{
if (s == Sender.None)
{
s = Sender.Menu;
if (args.IsSettingsSelected)
content.Navigate(typeof(Settings));
else
{
if (args.SelectedItem == toHome)
content.Navigate(typeof(Home));
else if (args.SelectedItem == toHistory)
content.Navigate(typeof(History), "HL");
else if (args.SelectedItem == toLiked)
content.Navigate(typeof(PlaylistPage), SecretsVault.UserChannel.ContentDetails.RelatedPlaylists.Likes);
else if (args.SelectedItem == toLater)
content.Navigate(typeof(History), "WL");
else if (args.SelectedItem == toSubscriptions)
content.Navigate(typeof(Subscriptions));
else if (args.SelectedItem == toDownloads)
content.Navigate(typeof(Downloads));
else if (args.SelectedItem == toChannel)
content.Navigate(typeof(ChannelPage), SecretsVault.UserChannel.Id);
else
content.Navigate(typeof(ChannelPage), SecretsVault.Subscriptions[Convert.ToInt32((args.SelectedItem as NavigationViewItem).Name)].Snippet.ResourceId.ChannelId);
}
}
else
s = Sender.None;
}
catch { }
}
public void Content_Navigated(object sender, NavigationEventArgs e)
{
Dictionary<Type, Action> switchCase = new Dictionary<Type, Action>()
{
{ typeof(Settings), () => nav.Header = resources.GetString("/Main/settings/Content") },
{ typeof(ChannelPage), () => nav.Header = resources.GetString("/Main/channel") },
{ typeof(PlaylistPage), () => nav.Header = resources.GetString("/Main/playlist") },
{ typeof(Search), () => nav.Header = resources.GetString("/Main/searchPlaceholder/PlaceholderText") },
{ typeof(Subscriptions), () => nav.Header = resources.GetString("/Main/subscriptions/Content") },
{ typeof(History), () =>
{
if((content.Content as History).id == "HL")
nav.Header = resources.GetString("/Main/history/Content");
else
nav.Header = resources.GetString("/Main/later/Content");
} },
{ typeof(Home), () => nav.Header = resources.GetString("/Main/home/Content") },
{ typeof(Downloads), () => nav.Header = resources.GetString("/Main/downloads/Content") }
};
try { switchCase[e.SourcePageType](); }
catch { }
if (s == Sender.None)
{
s = Sender.Frame;
Dictionary<Type, Action> navCase = new Dictionary<Type, Action>()
{
{ typeof(Settings), () =>
{
if(nav.SelectedItem != nav.SettingsItem)
nav.SelectedItem = nav.SettingsItem;
else
s = Sender.None;
} },
{ typeof(ChannelPage), () =>
{
if(sender.GetType() != typeof(ChannelPage))
{
Methods.NeedToResponse = true;
s = Sender.None;
return;
}
Methods.NeedToResponse = false;
if(SecretsVault.IsAuthorized)
{
if((content.Content as ChannelPage).channelId == SecretsVault.UserChannel.Id)
{
if(nav.SelectedItem != toChannel)
nav.SelectedItem = toChannel;
else
s = Sender.None;
}
else
{
bool found = false;
for(int k = 0; k < SecretsVault.Subscriptions.Count && k < 10; k++)
if(SecretsVault.Subscriptions[k].Snippet.ResourceId.ChannelId == (content.Content as ChannelPage).channelId)
{
if(nav.SelectedItem != nav.MenuItems[k + 9])
nav.SelectedItem = nav.MenuItems[k + 9];
else
s = Sender.None;
found = true;
break;
}
if(!found)
nav.SelectedItem = null;
}
}
else
nav.SelectedItem = null;
} },
{ typeof(PlaylistPage), () =>
{
if(sender.GetType() != typeof(PlaylistPage))
{
Methods.NeedToResponse = true;
s = Sender.None;
return;
}
Methods.NeedToResponse = false;
if((content.Content as PlaylistPage).playlistId == SecretsVault.UserChannel.ContentDetails.RelatedPlaylists.Likes)
{
if(nav.SelectedItem != toLiked)
nav.SelectedItem = toLiked;
else
s = Sender.None;
}
else
nav.SelectedItem = null;
} },
{ typeof(Search), () => nav.SelectedItem = null },
{typeof(Subscriptions), () =>
{
if(nav.SelectedItem != toSubscriptions)
nav.SelectedItem = toSubscriptions;
else
s = Sender.None;
} },
{ typeof(History), () =>
{
if((content.Content as History).id == "HL")
{
if(nav.SelectedItem != toHistory)
nav.SelectedItem = toHistory;
else
s = Sender.None;
}
else
{
if(nav.SelectedItem != toLater)
nav.SelectedItem = toLater;
else
s = Sender.None;
}
} },
{ typeof(Home), () =>
{
if(nav.SelectedItem != toHome)
nav.SelectedItem = toHome;
else
s = Sender.None;
} },
{ typeof(Downloads), () =>
{
if(nav.SelectedItem != toDownloads)
nav.SelectedItem = toDownloads;
else
s = Sender.None;
} }
};
try { navCase[content.SourcePageType](); }
catch
{
nav.SelectedItem = null;
}
}
else
s = Sender.None;
if (content.CanGoBack)
nav.IsBackEnabled = true;
else
nav.IsBackEnabled = false;
if (content.SourcePageType == typeof(Home) || content.SourcePageType == typeof(Settings) || content.SourcePageType == typeof(Subscriptions))
{
nav.ExpandedModeThresholdWidth = 1008;
if (nav.DisplayMode == NavigationViewDisplayMode.Expanded)
nav.IsPaneOpen = true;
}
else
nav.ExpandedModeThresholdWidth = short.MaxValue;
if (videoPlaceholder.Content != null && videoPlaceholder.HorizontalAlignment == HorizontalAlignment.Stretch)
MinimizeAsInitializer();
}
private void Nav_BackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args)
{
if (videoPlaceholder.Content != null)
{
if ((videoPlaceholder.Content as VideoPage).loading.State != LoadingState.Loaded)
CloseVideo();
else if (videoPlaceholder.HorizontalAlignment == HorizontalAlignment.Stretch)
MinimizeAsInitializer();
}
else
content.GoBack();
}
private void Page_PreviewKeyUp(object sender, KeyRoutedEventArgs e)
{
if(videoPlaceholder.Content != null && FocusManager.GetFocusedElement().GetType() != typeof(TextBox))
{
e.Handled = true;
(videoPlaceholder.Content as VideoPage).player.KeyUpPressed(sender, e);
}
}
private void OpenContext(object sender, TappedRoutedEventArgs e)
{
((NavigationViewItem)sender).ContextFlyout.ShowAt((NavigationViewItem)sender);
}
private void RemoveAds_Tapped(object sender, TappedRoutedEventArgs e)
{
SecretsVault.GetAdblock();
}
private void Web_Tapped(object sender, TappedRoutedEventArgs e)
{
content.Navigate(typeof(Browser));
}
}
}