Archived
1
0

Fresh start

This commit is contained in:
Michael Gordeev
2019-07-19 19:24:20 +03:00
parent 3ded1f4f18
commit d6d37151b8
100 changed files with 30 additions and 10743 deletions
+1 -160
View File
@@ -1,171 +1,12 @@
using Google.Apis.Auth.OAuth2;
using Google.Apis.Oauth2.v2;
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;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Notifications;
using Windows.ApplicationModel.Background;
namespace FoxTube.Background
{
public sealed class BackgroundProcessor : IBackgroundTask
{
private DateTime lastCheck;
private readonly ApplicationDataContainer settings = ApplicationData.Current.RoamingSettings;
dynamic prefs;
BackgroundTaskDeferral def;
public async void Run(IBackgroundTaskInstance taskInstance)
{
try
{
def = taskInstance.GetDeferral();
if (settings.Values["lastCheck"] == null)
{
settings.Values["lastCheck"] = DateTime.Now.ToString();
def.Complete();
return;
}
else
lastCheck = DateTime.Parse(settings.Values["lastCheck"] as string);
prefs = JsonConvert.DeserializeObject<dynamic>(settings.Values["settings"] as string);
if ((bool)prefs.devNotifications)
CheckAnnouncements();
if ((bool)prefs.videoNotifications && (bool)prefs.hasAccount)
await CheckAccount();
}
finally
{
settings.Values["lastCheck"] = DateTime.Now.ToString();
def.Complete();
}
}
async Task CheckAccount()
{
try
{
UserCredential Credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "349735264870-2ekqlm0a4mkg3mmrfcv90s3qp3o15dq0.apps.googleusercontent.com",
ClientSecret = "BkVZOAaCU2Zclf0Zlicg6y2_"
},
new[]
{
Oauth2Service.Scope.UserinfoProfile,
Oauth2Service.Scope.UserinfoEmail,
YouTubeService.Scope.YoutubeForceSsl,
YouTubeService.Scope.Youtube,
YouTubeService.Scope.YoutubeUpload,
YouTubeService.Scope.YoutubeReadonly,
YouTubeService.Scope.Youtubepartner
},
"user",
CancellationToken.None);
if (Credential == null)
return;
YouTubeService service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = Credential,
ApplicationName = "FoxTube"
});
List<Subscription> subscriptions = new List<Subscription>();
List<SearchResult> results = new List<SearchResult>();
SubscriptionsResource.ListRequest subRequest = service.Subscriptions.List("snippet");
subRequest.Mine = true;
subRequest.MaxResults = 50;
subRequest.Order = SubscriptionsResource.ListRequest.OrderEnum.Relevance;
SubscriptionListResponse subResponse;
string nextToken = null;
do
{
subRequest.PageToken = nextToken;
subResponse = await subRequest.ExecuteAsync();
foreach (Subscription s in subResponse.Items)
subscriptions.Add(s);
nextToken = subResponse.NextPageToken;
} while (!string.IsNullOrWhiteSpace(nextToken));
foreach (Subscription item in subscriptions)
{
SearchResource.ListRequest request = service.Search.List("snippet");
request.PublishedAfter = lastCheck;
request.ChannelId = item.Snippet.ResourceId.ChannelId;
request.Type = "video";
request.MaxResults = 5;
SearchListResponse response = await request.ExecuteAsync();
foreach (SearchResult i in response.Items)
{
results.Add(i);
if (i.Snippet.LiveBroadcastContent == "live")
ToastNotificationManager.CreateToastNotifier().Show(
Notification.GetStreamToast(i.Id.VideoId, i.Snippet.ChannelId, i.Snippet.Title.ConvertEscapeSymbols(), i.Snippet.ChannelTitle, i.Snippet.Thumbnails.Medium.Url, i.Snippet.PublishedAt.Value, item.Snippet.Thumbnails.Default__.Url));
else if (i.Snippet.LiveBroadcastContent == "upcoming")
ToastNotificationManager.CreateToastNotifier().Show(
Notification.GetUpcomingToast(i.Id.VideoId, i.Snippet.ChannelId, i.Snippet.Title.ConvertEscapeSymbols(), i.Snippet.ChannelTitle, i.Snippet.Thumbnails.Medium.Url, i.Snippet.PublishedAt.Value, item.Snippet.Thumbnails.Default__.Url));
else
ToastNotificationManager.CreateToastNotifier().Show(
Notification.GetVideoToast(i.Id.VideoId, i.Snippet.ChannelId, i.Snippet.Title.ConvertEscapeSymbols(), i.Snippet.ChannelTitle, i.Snippet.Thumbnails.Medium.Url, i.Snippet.PublishedAt.Value, item.Snippet.Thumbnails.Default__.Url));
}
}
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].Snippet.Title.ConvertEscapeSymbols()), System.Security.SecurityElement.Escape(results[i].Snippet.ChannelTitle), results[i].Snippet.Thumbnails.Medium.Url.Replace("&", "%26"), subscriptions.Find(x => x.Snippet.ResourceId.ChannelId == results[i].Snippet.ChannelId).Snippet.Thumbnails.Medium.Url));
}
catch { }
}
async void CheckAnnouncements()
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(await new HttpClient().GetStringAsync("http://foxgame-studio.000webhostapp.com/foxtube-messages.xml"));
XmlElement item = doc["posts"].FirstChild as XmlElement;
DateTime date = DateTime.Parse(item.GetAttribute("time"));
if (date > lastCheck && date < DateTime.Now)
ToastNotificationManager.CreateToastNotifier().Show(
Notification.GetInternalToast(item["id"].InnerText,
item["header"][(string)prefs.language].InnerText,
item["content"][(string)prefs.language].InnerText,
item["thumbnail"].InnerText,
item["avatar"].InnerText));
}
catch { }
}
}
public static class Ext
{
public static string ConvertEscapeSymbols(this string str)
{
return str.Replace("&quot;", "\"").Replace("&apos;", "'").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&").Replace("&#34;", "\"").Replace("&#39;", "'").Replace("&#60;", "<").Replace("&#62;", ">").Replace("&#38;", "&");
}
}
}
@@ -108,7 +108,6 @@
</PropertyGroup>
<ItemGroup>
<Compile Include="BackgroundProcessor.cs" />
<Compile Include="ResourceCreators.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
-197
View File
@@ -1,197 +0,0 @@
using Google.Apis.YouTube.v3.Data;
using Microsoft.Toolkit.Uwp.Notifications;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.UI.Notifications;
namespace FoxTube.Background
{
public static class Notification
{
private static readonly Dictionary<string, string> languagePack = LoadPack();
private static Dictionary<string, string> LoadPack()
{
dynamic saved = JsonConvert.DeserializeObject<dynamic>(ApplicationData.Current.RoamingSettings.Values["settings"] as string);
string hl = saved.language;
if (hl == "ru-RU")
return new Dictionary<string, string>()
{
{ "addLater", "Посмотреть позже" },
{ "changelog", "Список изменений" },
{ "changelogHeader", "Что нового в версии" },
{ "videoContent", "загрузил новое видео" },
{ "live", "ПРЯМОЙ ЭФИР" },
{ "upcoming", "Запланирован" },
{ "liveContent", "начал прямой эфир" },
{ "upcomingContent", "запланировал прямой эфир" },
{ "goChannel", "Открыть канал" }
};
else
return new Dictionary<string, string>()
{
{ "addLater", "Add to Watch later" },
{ "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" }
};
}
public static ToastNotification GetChangelogToast(string version)
{
XmlDocument template = new XmlDocument();
template.LoadXml($@"<toast activationType='foreground' launch='changelog|{version}'>
<visual>
<binding template='ToastGeneric'>
<image placement='hero' src='http://foxgame-studio.000webhostapp.com/FoxTubeAssets/WhatsNewThumb.png'/>
<image placement='appLogoOverride' hint-crop='circle' src='http://foxgame-studio.000webhostapp.com/FoxTubeAssets/NewsAvatar.png'/>
<text>{languagePack["changelog"]}</text>
<text>{languagePack["changelogHeader"]} {version}</text>
</binding>
</visual>
</toast>");
return new ToastNotification(template);
}
public static ToastNotification GetVideoToast(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>{System.Security.SecurityElement.Escape(title)}</text>
<text>{System.Security.SecurityElement.Escape(channel)} {languagePack["videoContent"]}</text>
</binding>
</visual>
<actions>
<action content='{languagePack["addLater"]}' activationType='background' arguments='later|{id}'/>
<action content='{languagePack["goChannel"]}' activationType='foreground' arguments='channel|{channelId}'/>
</actions>
</toast>");
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)
{
XmlDocument template = new XmlDocument();
template.LoadXml($@"<toast activationType='foreground' launch='inbox|{id}'>
<visual>
<binding template='ToastGeneric'>
<image placement='hero' src='{thumbnail ?? "http://foxgame-studio.000webhostapp.com/FoxTubeAssets/AnnouncementThumb.png"}'/>
<image placement='appLogoOverride' hint-crop='circle' src='{avatar ?? "http://foxgame-studio.000webhostapp.com/FoxTubeAssets/LogoAvatar.png"}'/>
<text>{header}</text>
<text hint-maxLines='5'>{content}</text>
</binding>
</visual>
</toast>");
return new ToastNotification(template);
}
}
public static class Tiles
{
public static TileNotification GetTileLayout(string title, string channel, string thumbnail, string avatar)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml($@" <tile>
<visual>
<binding template='TileMedium' branding='none'>
<image placement='peek' src='{avatar?.Replace("&", "%26")}'/>
<image placement='background' src='{thumbnail?.Replace("&", "%26")}'/>
<text hint-style='base' hint-overlay='60'>{channel}</text>
<text hint-wrap='true' hint-style='captionSubtle'>{title}</text>
</binding>
<binding template='TileWide' Branding='nameAndLogo'>
<image placement='background' hint-overlay='60' src='{thumbnail?.Replace("&", "%26")}'/>
<group>
<subgroup hint-weight='33'>
<image src='{avatar?.Replace("&", "%26")}' hint-crop='circle' />
</subgroup>
<subgroup hint-textStacking='center'>
<text hint-style='base'>{channel}</text>
<text hint-wrap='true' hint-style='captionSubtle'>{title}</text>
</subgroup>
</group>
</binding>
<binding template='TileLarge' hint-textStacking='top' Branding='nameAndLogo'>
<image placement='background' hint-overlay='60' src='{thumbnail?.Replace("&", "%26")}'/>
<group>
<subgroup hint-weight='33'>
<image src='{avatar?.Replace("&", "%26")}' hint-crop='circle' />
</subgroup>
<subgroup hint-textStacking='center'>
<text hint-style='base'>{channel}</text>
<text hint-wrap='true' hint-style='captionSubtle'>{title}</text>
</subgroup>
</group>
</binding>
</visual>
</tile>");
return new TileNotification(doc);
}
}
}