Archived
1
0

Region settings fixed

Channel page cover fixed
Livestream toasts added
This commit is contained in:
Michael Gordeev
2019-04-04 22:10:47 +03:00
parent d745611ca5
commit b875124c1a
12 changed files with 175 additions and 40 deletions
+28 -15
View File
@@ -1,4 +1,7 @@
using Newtonsoft.Json;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -17,6 +20,11 @@ namespace FoxTube.Background
private DateTime lastCheck;
private readonly ApplicationDataContainer settings = ApplicationData.Current.RoamingSettings;
dynamic prefs;
private readonly YouTubeService Service = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "AIzaSyBgHrCnrlzlVmk0cJKL8RqP9Y8x6XSuk_0",
ApplicationName = "FoxTube"
});
BackgroundTaskDeferral def;
public async void Run(IBackgroundTaskInstance taskInstance)
@@ -53,35 +61,40 @@ namespace FoxTube.Background
{
Dictionary<string, string> subscriptions = JsonConvert.DeserializeObject<Dictionary<string, string>>(settings.Values["subscriptions"] as string);
List<XmlElement> results = new List<XmlElement>();
List<SearchResult> results = new List<SearchResult>();
foreach (var s in subscriptions)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(await new HttpClient().GetStringAsync($"https://www.youtube.com/feeds/videos.xml?channel_id={s.Key}"));
SearchResource.ListRequest request = Service.Search.List("snippet");
request.PublishedAfter = lastCheck;
request.ChannelId = s.Key;
request.Type = "video";
request.MaxResults = 5;
SearchListResponse response = await request.ExecuteAsync();
List<XmlElement> items = new List<XmlElement>();
foreach (XmlElement i in doc["feed"].ChildNodes)
if (i.Name == "entry" && DateTime.Parse(i["published"].InnerText) > lastCheck)
items.Add(i);
items.OrderByDescending(i => DateTime.Parse(i["published"].InnerText));
foreach(XmlElement i in items)
foreach (SearchResult i in response.Items)
{
results.Add(i);
if(i.Snippet.LiveBroadcastContent == "live")
ToastNotificationManager.CreateToastNotifier().Show(
Notification.GetVideoToast(i["yt:videoId"].InnerText, s.Key, i["title"].InnerText, i["author"]["name"].InnerText, (await new YoutubeExplode.YoutubeClient().GetVideoAsync(i["yt:videoId"].InnerText)).Thumbnails.MediumResUrl, DateTime.Parse(i["published"].InnerText), s.Value));
Notification.GetStreamToast(i.Id.VideoId, i.Snippet.ChannelId, i.Snippet.Title, i.Snippet.ChannelTitle, i.Snippet.Thumbnails.Medium.Url, i.Snippet.PublishedAt.Value, s.Value));
else if(i.Snippet.LiveBroadcastContent == "upcoming")
ToastNotificationManager.CreateToastNotifier().Show(
Notification.GetUpcomingToast(i.Id.VideoId, i.Snippet.ChannelId, i.Snippet.Title, i.Snippet.ChannelTitle, i.Snippet.Thumbnails.Medium.Url, i.Snippet.PublishedAt.Value, s.Value));
else
ToastNotificationManager.CreateToastNotifier().Show(
Notification.GetVideoToast(i.Id.VideoId, i.Snippet.ChannelId, i.Snippet.Title, i.Snippet.ChannelTitle, i.Snippet.Thumbnails.Medium.Url, i.Snippet.PublishedAt.Value, s.Value));
}
}
results.OrderBy(i => i.Snippet.PublishedAt);
TileUpdater updater = TileUpdateManager.CreateTileUpdaterForApplication();
updater.EnableNotificationQueue(true);
updater.Clear();
for (int i = 0; i < 5 && i < results.Count; i++)
updater.Update(Tiles.GetTileLayout(System.Security.SecurityElement.Escape(results[i]["title"].InnerText), System.Security.SecurityElement.Escape(results[i]["author"]["name"].InnerText), (await new YoutubeExplode.YoutubeClient().GetVideoAsync(results[i]["yt:videoId"].InnerText)).Thumbnails.MediumResUrl.Replace("&", "%26"), subscriptions[results[i]["author"]["url"].InnerText.Split('/').Last()]));
updater.Update(Tiles.GetTileLayout(System.Security.SecurityElement.Escape(results[i].Snippet.Title), System.Security.SecurityElement.Escape(results[i].Snippet.ChannelTitle), results[i].Snippet.Thumbnails.Medium.Url.Replace("&", "%26"), subscriptions[results[i].Snippet.ChannelId]));
}
catch { }
}
+50
View File
@@ -23,6 +23,10 @@ namespace FoxTube.Background
{ "changelog", "Список изменений" },
{ "changelogHeader", "Что нового в версии" },
{ "videoContent", "загрузил новое видео" },
{ "live", "ПРЯМОЙ ЭФИР" },
{ "upcoming", "Запланирован" },
{ "liveContent", "начал прямой эфир" },
{ "upcomingContent", "запланировал прямой эфир" },
{ "goChannel", "Открыть канал" }
};
else
@@ -32,6 +36,10 @@ namespace FoxTube.Background
{ "changelog", "Changelog" },
{ "changelogHeader", "What's new in version" },
{ "videoContent", "uploaded a new video" },
{ "live", "LIVE" },
{ "upcoming", "Upcoming" },
{ "liveContent", "started live broadcast" },
{ "upcomingContent", "planned live broadcast" },
{ "goChannel", "Go to channel" }
};
}
@@ -76,6 +84,48 @@ namespace FoxTube.Background
return new ToastNotification(template);
}
public static ToastNotification GetStreamToast(string id, string channelId, string title, string channel, string thumbnail, DateTimeOffset timeStamp, string avatar)
{
XmlDocument template = new XmlDocument();
string ts = $"{timeStamp.Year}-{timeStamp.Month:00}-{timeStamp.Day:00}T{timeStamp.Hour:00}:{timeStamp.Minute:00}:{timeStamp.Second:00}Z";
template.LoadXml($@"<toast activationType='foreground' launch='video|{id}' displayTimestamp='{ts}'>
<visual>
<binding template='ToastGeneric'>
<image placement='hero' src='{thumbnail.Replace("&", "%26")}'/>
<image placement='appLogoOverride' hint-crop='circle' src='{avatar.Replace("&", "%26") ?? "http://foxgame-studio.000webhostapp.com/FoxTubeAssets/LogoAvatar.png"}'/>
<text>🔴 [{languagePack["live"]}] {System.Security.SecurityElement.Escape(title)}</text>
<text>{System.Security.SecurityElement.Escape(channel)} {languagePack["liveContent"]}</text>
</binding>
</visual>
<actions>
<action content='{languagePack["goChannel"]}' activationType='foreground' arguments='channel|{channelId}'/>
</actions>
</toast>");
return new ToastNotification(template);
}
public static ToastNotification GetUpcomingToast(string id, string channelId, string title, string channel, string thumbnail, DateTimeOffset timeStamp, string avatar)
{
XmlDocument template = new XmlDocument();
string ts = $"{timeStamp.Year}-{timeStamp.Month:00}-{timeStamp.Day:00}T{timeStamp.Hour:00}:{timeStamp.Minute:00}:{timeStamp.Second:00}Z";
template.LoadXml($@"<toast activationType='foreground' launch='video|{id}' displayTimestamp='{ts}'>
<visual>
<binding template='ToastGeneric'>
<image placement='hero' src='{thumbnail.Replace("&", "%26")}'/>
<image placement='appLogoOverride' hint-crop='circle' src='{avatar.Replace("&", "%26") ?? "http://foxgame-studio.000webhostapp.com/FoxTubeAssets/LogoAvatar.png"}'/>
<text>🔴 [{languagePack["upcoming"]}] {System.Security.SecurityElement.Escape(title)}</text>
<text>{System.Security.SecurityElement.Escape(channel)} {languagePack["upcomingContent"]}</text>
</binding>
</visual>
<actions>
<action content='{languagePack["goChannel"]}' activationType='foreground' arguments='channel|{channelId}'/>
</actions>
</toast>");
return new ToastNotification(template);
}
public static ToastNotification GetInternalToast(string id, string header, string content, string thumbnail, string avatar)
{
+6
View File
@@ -7,5 +7,11 @@
<Color x:Key="SystemAccentColor">Red</Color>
<Style TargetType="Button" BasedOn="{StaticResource ButtonRevealStyle}"/>
<Style TargetType="ListViewItem" BasedOn="{StaticResource ListViewItemRevealStyle}"/>
<Style TargetType="TextBlock">
<Setter Property="SelectionHighlightColor" Value="Red"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="SelectionHighlightColor" Value="Red"/>
</Style>
</Application.Resources>
</Application>
+17 -2
View File
@@ -5,7 +5,7 @@
<en-US>### What's new:
- Improved stability and speed of the app
- Fixed a lot of bugs
- Fixed player
- Rebuilt player
- Added animations and acrylic
### Following features awaits their implementation:
@@ -17,8 +17,23 @@
<ru-RU>### Что нового:
- Улучшена стабильность и скорость приложения
- Исправлена куча багов
- Исправлен плеер
- Переработан плеер
- Добавлены анимации и акрил
- Добавлена информация об аккаунте
- Добавлена история
- Добавлен плейлист "Посмотреть позже"
- Добавлены вкладки "Рекоммендованные" и "Подписки" на домашней странице
- Добавлена маленькая иконка канала при прокрутке вниз на странице канала
- Добавлена возможность удалять комментарии
- Переработано скачивание видео
- Добавлен прозрачный заголовок окна
- Добавлены всплывающие уведомления с просьбой оценить приложение и оставить отзыв (появляются после 12 и 24 часов активного использования)
- Переработана сетка карточек
- Добавлена информация о дате публикации видео на странице просмотра
- Обратный отсчет для стримов переработан и перенесен вверх страницы
- Список видео текущего плейлиста сразу перематывается на текущее
- Текст выделяется красным, а не текущим цветом системы
- Добавлены уведомления для прямых эфиров
### Следующие функции ждут своего внедрения:
- История и плейлист 'Посмотреть позже' (прогресс есть, но нужно еще работать)
+2 -2
View File
@@ -11,7 +11,7 @@
xmlns:Windows10version1809="http://schemas.microsoft.com/winfx/2006/xaml/presentation?IsApiContractPresent(Windows.Foundation.UniversalApiContract, 7)"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" SizeChanged="Grid_SizeChanged">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
@@ -30,7 +30,7 @@
</Grid>
</ParallaxView>
<ScrollViewer ViewChanged="ScrollViewer_ViewChanged" Name="videoScroll">
<StackPanel Background="{ThemeResource AppBarBackgroundThemeBrush}" Margin="0,300,0,0" Visibility="Visible">
<StackPanel Background="{ThemeResource AppBarBackgroundThemeBrush}" Margin="0,300,0,0" Name="infoStack" Visibility="Visible">
<Grid Name="infoPanel">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
+6
View File
@@ -282,6 +282,12 @@ namespace FoxTube.Pages
private void ChannelCover_ImageOpened(object sender, RoutedEventArgs e)
{
channelCover.Opacity = 1;
infoStack.Margin = new Thickness(0, channelCover.ActualHeight, 0, 0);
}
private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
{
infoStack.Margin = new Thickness(0, channelCover.ActualHeight, 0, 0);
}
private void Share(DataTransferManager sender, DataRequestedEventArgs args)
+1
View File
@@ -34,6 +34,7 @@
<TextBlock x:Name="AppTitle"
Text="FoxTube"
VerticalAlignment="Center"
Margin="12, 8, 0, 0"
Style="{StaticResource CaptionTextBlockStyle}" />
</Border>
-5
View File
@@ -131,12 +131,7 @@ namespace FoxTube
public void SetTitleBar(CoreApplicationViewTitleBar coreTitleBar = null)
{
if (coreTitleBar != null)
{
bool full = ApplicationView.GetForCurrentView().IsFullScreenMode;
double left = 12 + (full ? 0 : coreTitleBar.SystemOverlayLeftInset);
AppTitle.Margin = new Thickness(left, 8, 0, 0);
AppTitleBar.Height = coreTitleBar.Height;
}
var titleBar = ApplicationView.GetForCurrentView().TitleBar;
+4 -4
View File
@@ -9,7 +9,7 @@
<StackPanel Orientation="Vertical">
<TextBlock x:Uid="/General/preferences" Text="Preferences" FontSize="28"/>
<TextBlock x:Uid="/General/regNsearch" Text="Region &#x26; search" FontSize="22"/>
<TextBlock x:Uid="/General/regNsearch" Text="Region &#x26; search" FontSize="22" Margin="0,10,0,0"/>
<ComboBox x:Uid="/General/interfaceLang" Header="App interface language" MinWidth="250" Name="language" SelectionChanged="language_SelectionChanged">
<ComboBoxItem x:Uid="/General/en" Content="English (United States)" Tag="en-US"/>
<ComboBoxItem x:Uid="/General/ru" Content="Russian (Russia)" Tag="ru-RU"/>
@@ -26,18 +26,18 @@
<ComboBoxItem x:Uid="/General/strict" Content="Strict"/>
</ComboBox>
<TextBlock x:Uid="/General/playback" Text="Playback" FontSize="22"/>
<TextBlock x:Uid="/General/playback" Text="Playback" FontSize="22" Margin="0,10,0,0"/>
<ComboBox x:Uid="/General/quality" Width="250" Header="Default video playback quality" Name="quality" SelectionChanged="quality_SelectionChanged">
<ComboBoxItem Tag="remember" x:Uid="/General/remember" Content="Remember my choice"/>
</ComboBox>
<ToggleSwitch x:Uid="/General/metered" OnContent="Notify when playing on metered connection" OffContent="Notify when playing on metered connection" Name="mobileWarning" Toggled="mobileWarning_Toggled"/>
<ToggleSwitch x:Uid="/General/autoplay" OnContent="Play videos automatically" OffContent="Play videos automatically" Name="autoplay" Toggled="autoplay_Toggled"/>
<TextBlock x:Uid="/General/notifications" Text="Notifications" FontSize="22"/>
<TextBlock x:Uid="/General/notifications" Text="Notifications" FontSize="22" Margin="0,10,0,0"/>
<ToggleSwitch x:Uid="/General/newVideo" Name="newVideo" OnContent="Notify when someone of your subscriptions uploaded new video" OffContent="Notify when someone of your subscriptions uploaded new video" Toggled="notification_IsEnabledChanged"/>
<ToggleSwitch x:Uid="/General/devNotifications" Name="devNews" OnContent="Recieve messages from developers" OffContent="Recieve messages from developers" Toggled="devNews_Toggled"/>
<TextBlock x:Uid="/General/color" Text="Color mode" FontSize="22"/>
<TextBlock x:Uid="/General/color" Text="Color mode" FontSize="22" Margin="0,10,0,0"/>
<RadioButton x:Uid="/General/colorLight" Content="Light" Name="light" GroupName="color" Checked="RadioButton_Checked"/>
<RadioButton x:Uid="/General/colorDark" Content="Dark" Name="dark" GroupName="color" Checked="RadioButton_Checked"/>
<RadioButton x:Uid="/General/colorDefault" Content="Windows default" Name="system" GroupName="color" Checked="RadioButton_Checked"/>
+5 -7
View File
@@ -51,19 +51,17 @@ namespace FoxTube.Pages.SettingsPages
async void InitializeRegions()
{
I18nRegionsResource.ListRequest regRequest = SecretsVault.Service.I18nRegions.List("snippet");
regRequest.Hl = SettingsStorage.Language;
I18nRegionListResponse regResponse = await regRequest.ExecuteAsync();
foreach(I18nRegion i in regResponse.Items)
{
region.Items.Add(new ComboBoxItem
regResponse.Items.ForEach(i => region.Items.Add(new ComboBoxItem
{
Content = i.Snippet.Name,
Tag = i.Snippet.Gl
});
if (SettingsStorage.Region == i.Snippet.Gl)
region.SelectedItem = region.Items.Last();
}
}));
region.SelectedItem = region.Items.Find(i => ((ComboBoxItem)i).Tag as string == SettingsStorage.Region) ?? region.Items.Find(i => ((ComboBoxItem)i).Tag as string == SettingsStorage.Language.Remove(0, 3));
I18nLanguagesResource.ListRequest langRequest = SecretsVault.Service.I18nLanguages.List("snippet");
langRequest.Hl = SettingsStorage.Language;
I18nLanguageListResponse langResponse = await langRequest.ExecuteAsync();
foreach(I18nLanguage i in langResponse.Items)
{
+37 -2
View File
@@ -112,7 +112,35 @@
</AppBarButton>
<AppBarButton x:Uid="/VideoPage/addTo" Name="addTo" Label="Add to" Icon="Add" Visibility="Collapsed">
<AppBarButton.Flyout>
<Flyout>
<MenuFlyout x:Name="addList">
<MenuFlyoutItem Text="New playlist" Name="newPlaylist" Click="NewPlaylist_Click">
<MenuFlyoutItem.Icon>
<FontIcon Glyph="&#xE109;"/>
</MenuFlyoutItem.Icon>
</MenuFlyoutItem>
<ToggleMenuFlyoutItem Text="Watch later" Background="Red" Name="wl" Click="Wl_Click">
<MenuFlyoutItem.Icon>
<FontIcon Glyph="&#xE728;"/>
</MenuFlyoutItem.Icon>
</ToggleMenuFlyoutItem>
<MenuFlyoutSeparator/>
<ToggleMenuFlyoutItem Text="Cats">
<ToggleMenuFlyoutItem.Icon>
<FontIcon Glyph="&#xE292;"/>
</ToggleMenuFlyoutItem.Icon>
</ToggleMenuFlyoutItem>
<ToggleMenuFlyoutItem Text="Dogs">
<ToggleMenuFlyoutItem.Icon>
<FontIcon Glyph="&#xE292;"/>
</ToggleMenuFlyoutItem.Icon>
</ToggleMenuFlyoutItem>
<ToggleMenuFlyoutItem Text="Porn">
<ToggleMenuFlyoutItem.Icon>
<FontIcon Glyph="&#xE292;"/>
</ToggleMenuFlyoutItem.Icon>
</ToggleMenuFlyoutItem>
</MenuFlyout>
<!--<Flyout>
<ScrollViewer Margin="-12" MaxHeight="300">
<NavigationViewList Width="200" IsMultiSelectCheckBoxEnabled="True" SelectionMode="Multiple">
<NavigationViewItem Content="Watch later">
@@ -148,7 +176,7 @@
</NavigationViewItem>
</NavigationViewList>
</ScrollViewer>
</Flyout>
</Flyout>-->
</AppBarButton.Flyout>
</AppBarButton>
<AppBarButton x:Uid="/VideoPage/refresh" Name="refresh" Click="refresh_Click" Icon="Refresh" Label="Refresh page"/>
@@ -196,6 +224,13 @@
</Pivot>
</Grid>
<ContentDialog PrimaryButtonText="Create and add" Title="New playlist" DefaultButton="Primary" PrimaryButtonClick="ContentDialog_PrimaryButtonClick" Name="playlistDialog">
<StackPanel>
<TextBox PlaceholderText="Enter playlist name" Name="newListName"/>
<TextBlock Text="Invalid name: playlist with the name already exists" TextWrapping="WrapWholeWords" Foreground="Red" Visibility="Collapsed" Name="newListErr"/>
</StackPanel>
</ContentDialog>
<local:LoadingPage Grid.ColumnSpan="2" Visibility="Collapsed" x:Name="loading" RefreshPage="refresh_Click"/>
</Grid>
</Page>
+16
View File
@@ -566,5 +566,21 @@ namespace FoxTube.Pages
subscribe.Content = resources.GetString("/Cards/subscribe/Content");
}
}
private async void NewPlaylist_Click(object sender, RoutedEventArgs e)
{
//TODO: Localize strings
await playlistDialog.ShowAsync();
}
private void Wl_Click(object sender, RoutedEventArgs e)
{
}
private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}
}
}