Archived
1
0

DownloadAgent fixes and improvements

This commit is contained in:
Michael Gordeev
2018-07-12 10:57:33 +03:00
parent 71cc12106c
commit 9163fcf2ae
11 changed files with 172 additions and 98 deletions
+52 -5
View File
@@ -1,8 +1,13 @@
using System; using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml; using System.Xml;
using Windows.ApplicationModel.Background; using Windows.ApplicationModel.Background;
@@ -15,14 +20,23 @@ namespace FoxTube.Background
{ {
public List<Notification> Notifications = new List<Notification>(); public List<Notification> Notifications = new List<Notification>();
private DateTime lastCheck; private DateTime lastCheck = DateTime.Now;
private ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; private ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
private ClientSecrets Secrets => new ClientSecrets()
{
ClientId = "349735264870-2ekqlm0a4mkg3mmrfcv90s3qp3o15dq0.apps.googleusercontent.com",
ClientSecret = "BkVZOAaCU2Zclf0Zlicg6y2_"
};
BackgroundTaskDeferral def; BackgroundTaskDeferral def;
public async void Run(IBackgroundTaskInstance taskInstance) public async void Run(IBackgroundTaskInstance taskInstance)
{ {
XmlDocument doc = new XmlDocument();
def = taskInstance.GetDeferral(); def = taskInstance.GetDeferral();
XmlDocument doc = new XmlDocument();
if (settings.Values["lastCheck"] == null)
settings.Values.Add("lastCheck", XmlConvert.ToString(DateTime.Now));
else lastCheck = XmlConvert.ToDateTime(settings.Values["lastCheck"] as string, XmlDateTimeSerializationMode.Unspecified);
if (settings.Values["notificationsHistory"] != null) if (settings.Values["notificationsHistory"] != null)
doc.LoadXml(settings.Values["notificationsHistory"] as string); doc.LoadXml(settings.Values["notificationsHistory"] as string);
@@ -40,16 +54,49 @@ namespace FoxTube.Background
def.Complete(); def.Complete();
} }
void CheckAccount() async void CheckAccount()
{ {
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, new[] { Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoProfile, YouTubeService.Scope.YoutubeForceSsl }, "user", CancellationToken.None);
if (credential == null)
return;
SubscriptionsResource.ListRequest subRequest = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "FoxTube"
}).Subscriptions.List("snippet");
subRequest.Mine = true;
subRequest.MaxResults = 50;
SubscriptionListResponse subResponse = await subRequest.ExecuteAsync();
List<string> subs = new List<string>();
foreach (Subscription s in subResponse.Items)
subs.Add(s.Snippet.ResourceId.ChannelId);
string nextToken = subResponse.NextPageToken;
while (nextToken != null)
{
subRequest.PageToken = nextToken;
subResponse = await subRequest.ExecuteAsync();
foreach (Subscription s in subResponse.Items)
subs.Add(s.Snippet.ResourceId.ChannelId);
}
foreach(string s in subs)
{
var request = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "AIzaSyBgHrCnrlzlVmk0cJKL8RqP9Y8x6XSuk_0",
ApplicationName = "FoxTube"
}).Activities.List("snippet");
}
} }
void CheckAnnouncements() void CheckAnnouncements()
{ {
XmlDocument doc = new XmlDocument(); XmlDocument doc = new XmlDocument();
doc.Load(XmlReader.Create("http://foxgame.hol.es/ftp.xml")); doc.Load(XmlReader.Create("http://foxgame.hol.es/ftp.xml"));
if ((XmlConvert.ToDateTime((doc["posts"].FirstChild as XmlElement).GetAttribute("time"), XmlDateTimeSerializationMode.Utc) - DateTime.UtcNow).TotalSeconds > 0) if ((XmlConvert.ToDateTime((doc["posts"].FirstChild as XmlElement).GetAttribute("time"), XmlDateTimeSerializationMode.Utc) - lastCheck).TotalSeconds > 0)
Notifications.Add(new Notification(NotificationType.Internal, Notifications.Add(new Notification(NotificationType.Internal,
doc["posts"].FirstChild["notificationHeader"].InnerText, doc["posts"].FirstChild["notificationHeader"].InnerText,
doc["posts"].FirstChild["content"].InnerText, doc["posts"].FirstChild["content"].InnerText,
+15 -1
View File
@@ -110,9 +110,23 @@
<Compile Include="BackgroundProcessor.cs" /> <Compile Include="BackgroundProcessor.cs" />
<Compile Include="Notification.cs" /> <Compile Include="Notification.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ToastTemplates.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Google.Apis">
<Version>1.30.0-beta02</Version>
</PackageReference>
<PackageReference Include="Google.Apis.Auth">
<Version>1.30.0-beta02</Version>
</PackageReference>
<PackageReference Include="Google.Apis.Core">
<Version>1.30.0-beta02</Version>
</PackageReference>
<PackageReference Include="Google.Apis.Oauth2.v2">
<Version>1.29.2.994</Version>
</PackageReference>
<PackageReference Include="Google.Apis.YouTube.v3">
<Version>1.29.2.1006</Version>
</PackageReference>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform"> <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>6.1.5</Version> <Version>6.1.5</Version>
</PackageReference> </PackageReference>
+63 -3
View File
@@ -39,6 +39,12 @@ namespace FoxTube.Background
Thumbnail = thumbnailUrl; Thumbnail = thumbnailUrl;
} }
public string GetXml()
{
return string.Empty;
}
public UIElement GetNotification() public UIElement GetNotification()
{ {
StackPanel stackPanel = new StackPanel() { Margin = new Thickness(10, 0, 0, 0) }; StackPanel stackPanel = new StackPanel() { Margin = new Thickness(10, 0, 0, 0) };
@@ -155,17 +161,71 @@ namespace FoxTube.Background
break; break;
case NotificationType.Video: case NotificationType.Video:
template.LoadXml($@"<toast launch='action=viewPhoto&amp;photoId=92187'> template.LoadXml($@"<toast launch='action=viewPhoto&amp;photoId=92187'>
<visual>
<binding template='ToastGeneric'>
<image placement='appLogoOverride' hint-crop='circle' src='{Avatar}'/>
<text>{Channel} uploaded a new video</text>
<text>{Content}</text>
<image src='{Thumbnail}'/>
</binding>
</visual>
<actions>
<action content='Watch later'
activationType='background'
arguments='likePhoto&amp;photoId=92187'/>
<action content='Go to channel'
arguments='action=commentPhoto&amp;photoId=92187'/>
</actions>
</toast>");
break; break;
case NotificationType.Internal: case NotificationType.Internal:
string thumb1 = string.IsNullOrWhiteSpace(Thumbnail) ? "Assets/AnnouncementThumb.png" : Thumbnail; string thumb1 = string.IsNullOrWhiteSpace(Thumbnail) ? "Assets/AnnouncementThumb.png" : Thumbnail;
<text>{Content}</text> template.LoadXml($@"<toast launch='action=openThread&amp;threadId=92187'>
<visual>
<binding template='ToastGeneric'>
<image placement='hero' src='{thumb1}'/>
<image placement='appLogoOverride' hint-crop='circle' src='Assets/LogoAvatar.png'/>
<text>{Channel}</text>
<text hint-maxLines='5'>{Content}</text>
</binding>
</visual>
<actions>
<action content='Watch full post'
arguments='action=commentPhoto&amp;photoId=92187'/>
<action content='Manage notifications'
arguments='action=commentPhoto&amp;photoId=92187'/>
</actions>
</toast>");
break; break;
case NotificationType.Post: case NotificationType.Post:
string thumb2 = string.IsNullOrWhiteSpace(Thumbnail) ? "" : $"<image placement='hero' src ='{Thumbnail}'/>"; string thumb2 = string.IsNullOrWhiteSpace(Thumbnail) ? "" : $"<image placement='hero' src ='{Thumbnail}'/>";
<actions> template.LoadXml($@"<toast launch='action=openThread&amp;threadId=92187'>
<visual>
<binding template='ToastGeneric'>
{thumb2}
<image placement='appLogoOverride' hint-crop='circle' src='{Avatar}'/>
<text>{Channel}</text>
<text hint-maxLines='5'>{Content}</text>
</binding>
</visual>
<actions>
<input id='textBox' type='text' placeHolderContent='Leave a comment'/>
<action content='Send'
imageUri='Assets/Icons/send.png'
hint-inputId='textBox'
activationType='background'
arguments='action=reply&amp;threadId=92187'/>
<action content='Like'
arguments='action=commentPhoto&amp;photoId=92187'/>
</actions>
</toast>");
break; break;
} }
-45
View File
@@ -1,45 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FoxTube.Background
{
public static class ToastTemplates
{
public static string Comment =
@"<toast launch='action=openThread&amp;threadId=92187'>
<visual>
<binding template='ToastGeneric'>
<image placement='appLogoOverride' hint-crop='circle' src='Assets/Icons/Profile.png'/>
<text>[ChannelName] posted a new comment</text>
<text>[VideoName]</text>
</binding>
</visual>
<actions>
<input id='textBox' type='text' placeHolderContent='Send a reply'/>
<action content='Send' imageUri='Assets/Icons/Send.png'
hint-inputId='textBox' activationType='background'
arguments='action=reply&amp;threadId=92187'/>
<action content='Like'
arguments='action=commentPhoto&amp;photoId=92187'/>
<action content='Go to comment'
arguments='action=commentPhoto&amp;photoId=92187'/>
</actions>
</toast>";
public static string Video =
@"<toast launch='action=viewPhoto&amp;photoId=92187'>
<visual>
<binding template='ToastGeneric'>
<image placement='appLogoOverride' hint-crop='circle' src='Assets/Icons/Profile.png'/>
<text>[ChannelName] uploaded a new video</text>
<text>[VideoName]</text>
<image src='Assets/videoThumbSample.png'/>
</binding>
</visual>
<actions>
@@ -6,24 +6,26 @@ using System.Threading.Tasks;
using System.Xml; using System.Xml;
using System.IO; using System.IO;
using MyToolkit.Multimedia; using MyToolkit.Multimedia;
using Windows.Storage;
namespace FoxTube.Controls namespace FoxTube.Controls
{ {
public class DownloadAgent public class DownloadAgent
{ {
public List<DownloadItem> Items = new List<DownloadItem>(); public List<DownloadItem> Items = new List<DownloadItem>();
public event ObjectEventHandler ListChanged;
private ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
XmlDocument doc = new XmlDocument(); XmlDocument doc = new XmlDocument();
string path = $@"{Directory.GetCurrentDirectory()}\DownloadHistory.xml";
public DownloadAgent() public DownloadAgent()
{ {
if (File.Exists(path)) if (settings.Values["downloadHistory"] != null)
doc.Load(path); doc.LoadXml(settings.Values["downloadHistory"] as string);
else else
{ {
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null)); doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
doc.AppendChild(doc.CreateElement("downloads")); doc.AppendChild(doc.CreateElement("downloads"));
doc.Save(path); settings.Values.Add("downloadHistory", doc.InnerXml);
} }
foreach(XmlElement e in doc["downloads"].ChildNodes) foreach(XmlElement e in doc["downloads"].ChildNodes)
@@ -48,16 +50,19 @@ namespace FoxTube.Controls
item.DownloadComplete += Item_DownloadComplete; item.DownloadComplete += Item_DownloadComplete;
Items.Add(item); Items.Add(item);
ListChanged.Invoke(item, new ObjectEventArgs("add"));
} }
private void Item_DownloadComplete(object sender, EventArgs e) private void Item_DownloadComplete(object sender, ObjectEventArgs e)
{ {
doc["downloads"].AppendChild((e as ObjectEventArgs).Parameters[0] as XmlElement); doc["downloads"].InnerXml += e.Parameters[0];
settings.Values["downloadHistory"] = doc.InnerXml;
} }
private void Item_DownloadCanceled(object sender, EventArgs e) private void Item_DownloadCanceled(object sender, ObjectEventArgs e)
{ {
Items.Remove(sender as DownloadItem); Items.Remove(sender as DownloadItem);
ListChanged.Invoke(sender, new ObjectEventArgs("remove"));
} }
} }
} }
+3 -1
View File
@@ -6,7 +6,9 @@ using System.Threading.Tasks;
namespace FoxTube namespace FoxTube
{ {
public class ObjectEventArgs : EventArgs public delegate void ObjectEventHandler(object sender, ObjectEventArgs args);
public class ObjectEventArgs
{ {
public List<object> Parameters = new List<object>(); public List<object> Parameters = new List<object>();
public ObjectEventArgs(params object[] args) public ObjectEventArgs(params object[] args)
+9 -25
View File
@@ -1,30 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Windows.UI.Xaml.Media;
using Windows.UI;
using Windows.UI.Xaml.Documents;
using System.Net; using System.Net;
using System.Threading; using System.Threading;
using Windows.Data.Json;
using Windows.Storage.Streams;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Services; using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3; using Google.Apis.YouTube.v3;
using Google.Apis.Auth.OAuth2.Responses;
using Windows.Storage;
using Google.Apis.YouTube.v3.Data; using Google.Apis.YouTube.v3.Data;
using Windows.Storage;
namespace FoxTube namespace FoxTube
{ {
@@ -32,7 +16,7 @@ namespace FoxTube
{ {
#region Static Information #region Static Information
public static NetworkCredential EmailCredential => new NetworkCredential("youwillneverknowthisadress@gmail.com", "thisisthepassword12345"); public static NetworkCredential EmailCredential => new NetworkCredential("youwillneverknowthisadress@gmail.com", "thisisthepassword12345");
private static ClientSecrets Secrets => new ClientSecrets() public static ClientSecrets Secrets => new ClientSecrets()
{ {
ClientId = "349735264870-2ekqlm0a4mkg3mmrfcv90s3qp3o15dq0.apps.googleusercontent.com", ClientId = "349735264870-2ekqlm0a4mkg3mmrfcv90s3qp3o15dq0.apps.googleusercontent.com",
ClientSecret = "BkVZOAaCU2Zclf0Zlicg6y2_" ClientSecret = "BkVZOAaCU2Zclf0Zlicg6y2_"
@@ -70,6 +54,7 @@ namespace FoxTube
public Google.Apis.YouTube.v3.Data.Channel channel; public Google.Apis.YouTube.v3.Data.Channel channel;
public UserCredential Credential; public UserCredential Credential;
public event EventHandler AuthorizationStateChanged; public event EventHandler AuthorizationStateChanged;
private ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
public async void Authorize() public async void Authorize()
{ {
@@ -77,6 +62,9 @@ namespace FoxTube
catch { } catch { }
if(Credential != null) if(Credential != null)
{ {
if (settings.Values["authorized"] == null)
settings.Values.Add("authorized", true);
else settings.Values["authorized"] = true;
IsLoged = true; IsLoged = true;
AuthorizationStateChanged.Invoke(this, null); AuthorizationStateChanged.Invoke(this, null);
} }
@@ -139,17 +127,13 @@ namespace FoxTube
{ {
Credential = null; Credential = null;
AuthorizationStateChanged.Invoke(this, null); AuthorizationStateChanged.Invoke(this, null);
settings.Values["authorized"] = false;
} }
} }
public async void CheckAuthorization() public void CheckAuthorization()
{ {
var token = await new AuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer() if (settings.Values["authorized"] == null || !(bool)settings.Values["authorized"])
{
ClientSecrets = Secrets,
DataStore = null
}).LoadTokenAsync("user", CancellationToken.None);
if (token == null)
IsLoged = false; IsLoged = false;
else else
Authorize(); Authorize();
+4 -5
View File
@@ -31,8 +31,8 @@ namespace FoxTube.Controls
string uri; string uri;
string Id; string Id;
public event EventHandler DownloadCanceled; public event ObjectEventHandler DownloadCanceled;
public event EventHandler DownloadComplete; public event ObjectEventHandler DownloadComplete;
WebClient client = new WebClient(); WebClient client = new WebClient();
@@ -91,9 +91,8 @@ namespace FoxTube.Controls
{ {
progressPanel.Visibility = Visibility.Collapsed; progressPanel.Visibility = Visibility.Collapsed;
donePanel.Visibility = Visibility.Visible; donePanel.Visibility = Visibility.Visible;
XmlElement node = new XmlDocument().CreateElement("item"); string node = $@"<item>
node.InnerXml = $@"<item>
<title{title.Text}></title> <title{title.Text}></title>
<snippet> <snippet>
<quality>{quality.Text.Split(' ')[1]}</quality> <quality>{quality.Text.Split(' ')[1]}</quality>
+1 -1
View File
@@ -101,7 +101,7 @@
<Compile Include="Controls\CommentCard.xaml.cs"> <Compile Include="Controls\CommentCard.xaml.cs">
<DependentUpon>CommentCard.xaml</DependentUpon> <DependentUpon>CommentCard.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Controls\DownloadAgent.cs" /> <Compile Include="Classes\DownloadAgent.cs" />
<Compile Include="Controls\DownloadItem.xaml.cs"> <Compile Include="Controls\DownloadItem.xaml.cs">
<DependentUpon>DownloadItem.xaml</DependentUpon> <DependentUpon>DownloadItem.xaml</DependentUpon>
</Compile> </Compile>
+13 -1
View File
@@ -18,6 +18,7 @@ using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast
namespace FoxTube.Pages namespace FoxTube.Pages
{ {
@@ -27,15 +28,26 @@ namespace FoxTube.Pages
public sealed partial class Downloads : Page public sealed partial class Downloads : Page
{ {
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
DownloadAgent agent = Methods.MainPage.Agent;
public Downloads() public Downloads()
{ {
this.InitializeComponent(); this.InitializeComponent();
path.Text = settings.Values["defaultDownload"] as string; path.Text = settings.Values["defaultDownload"] as string;
foreach (DownloadItem item in Methods.MainPage.Agent.Items) agent.ListChanged += UpdateList;
foreach (DownloadItem item in agent.Items)
stack.Children.Add(item); stack.Children.Add(item);
} }
private void UpdateList(object sender, ObjectEventArgs e)
{
if (e.Parameters[0] == "remove")
stack.Children.Remove(sender as DownloadItem);
else if (e.Parameters[0] == "add")
stack.Children.Add(sender as DownloadItem);
}
private async void changePath_Click(object sender, RoutedEventArgs e) private async void changePath_Click(object sender, RoutedEventArgs e)
{ {
FolderPicker picker = new FolderPicker() FolderPicker picker = new FolderPicker()
-4
View File
@@ -47,10 +47,6 @@ namespace FoxTube
/// </summary> /// </summary>
public enum RightPaneState { Full, Collapsed, Hidden } public enum RightPaneState { Full, Collapsed, Hidden }
public interface IPageNesting
{
void GoToSettings(int pageIndex = 0);
}
public sealed partial class MainPage : Page public sealed partial class MainPage : Page
{ {