ソースを参照

云文档 - 优化ViewModel逻辑,加载历史登录用户信息

chenrongqian 2 年 前
コミット
e993c9d149

+ 13 - 5
PDF Office/ViewModels/HomePanel/CloudDrive/CloudDriveContentViewModel.cs

@@ -10,15 +10,23 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
 {
     public class CloudDriveContentViewModel : BindableBase
     {
-        public DelegateCommand OpenCloudDriveCommand { get; set; }
+      
+      
+
+     ///   public DelegateCommand CheckDriveCommand { get; set; }
+       // public DelegateCommand OpenCloudDriveCommand { get; set; }
         public CloudDriveContentViewModel()
         {
-            OpenCloudDriveCommand = new DelegateCommand(OpenCloudDrive_Click);
+           
+           // CheckDriveCommand = new DelegateCommand(CheckDrive);
 
-        }
-        public void OpenCloudDrive_Click()
-        {
+
+
+        //    OpenCloudDriveCommand = new DelegateCommand(OpenCloudDrive_Click);
+            
 
         }
+
+     
     }
 }

+ 50 - 0
PDF Office/ViewModels/HomePanel/CloudDrive/CloudFilesContentViewModel.cs

@@ -8,18 +8,68 @@ using System.Threading.Tasks;
 
 namespace PDF_Office.ViewModels.HomePanel.CloudDrive
 {
+    //各云盘事件
     public class CloudFilesContentViewModel : BindableBase
     {
+        public GoogleDriveViewModel GoogleDrive;
         public DelegateCommand OpenCloudDriveCommand { get; set; }
+        public DelegateCommand CheckDriveUsersCommand { get; set; }
+
+        //向外触发
+        public event EventHandler<bool> isFoundUserHandler;
         public CloudFilesContentViewModel()
         {
+            GoogleDrive = new GoogleDriveViewModel();
+
             OpenCloudDriveCommand = new DelegateCommand(OpenCloudDrive_Click);
+            OpenCloudDriveCommand = new DelegateCommand(CheckDriveUsers);
+
+            CheckDriveUsersCommand = new DelegateCommand(CheckDriveUsers);
+
 
+         
         }
+
+        #region 云盘公用接口
+
+        public async void CheckDriveUsers()
+        {
+            var result = await GetHistoryUser();
+            isFoundUserHandler?.Invoke(null, result);
+
+        }
+
+        #endregion
         public void OpenCloudDrive_Click()
         {
 
         }
 
+
+        #region 谷歌云盘
+
+        public void LoginUser_Click()
+        {
+
+        }
+
+        public async Task<bool> GetHistoryUser()
+        {
+            bool isFound = false;
+
+            if (await GoogleDrive.GetHistoryUsers())
+            {
+                isFound = true;
+            }
+            return isFound;
+
+        }
+
+        #endregion
+
+
+
+
+
     }
 }

+ 18 - 95
PDF Office/ViewModels/HomePanel/CloudDrive/GoogleDriveUserItem.cs

@@ -18,9 +18,8 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
     //对单用户账号处理核心功能
     public class GoogleDriveUserItem
     {
-        public GoogleDriveUser User { get; private set; }
-        public static string[] Scopes = { DriveService.Scope.Drive };
-        public  DriveService Service { get; private set; }
+        public GoogleDriveUser User { get;  set; }
+        public  DriveService Service { get; set; }
         private List<GoogleDriveFiles> GoogleDriveFilesList = new List<GoogleDriveFiles>();
 
         public GoogleDriveUserItem()
@@ -29,93 +28,7 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
             
         }
 
-        #region   请求身份验证
-
-        /// <summary>
-        /// 获取登录过的账号
-        /// </summary>
-        /// <returns>历史账号</returns>
-        public  async Task<List<DriveService>> GetHistoryService()
-        {
-            DirectoryInfo TheFolder = new DirectoryInfo(GoogleDriveViewModel.FilesPathTemp);
-            List<DriveService> DriveServices = new List<DriveService>();
-
-            foreach (var directorieItem in TheFolder.GetDirectories())
-            {
-                var driveServiceItem = await GetServiceAsync(directorieItem.Name);
-
-                if (driveServiceItem != null)
-                {
-                    DriveServices.Add(driveServiceItem);
-                }
-            }
-            return DriveServices;
-        }
-
-        /// <summary>
-        ///  异步获取Google服务的包信息,避免UI线程卡死
-        /// </summary>
-        /// <param name="userInfoFile"></param>
-        [Obsolete]
-        public async Task<DriveService> GetServiceAsync(string userInfoFile = "")
-        {
-            DriveService service = null;
-
-            await Task.Run(() =>
-            {
-
-                service = GetService(userInfoFile);
-            });
-
-            if (userInfoFile == "")
-            {
-                if (service != null)
-                    Service = service;
-            }
-
-            return service;
-        }
-
-        /// <summary>
-        /// 获取Google服务的包信息(包含访问令牌,App Key密钥等)
-        /// </summary>
-        /// <param name="FilePath">登录过的用户文件;若为空,则为新用户登录</param>
-        /// <returns></returns>
-        [Obsolete]
-        private  DriveService GetService(string FilePath = "")
-        {
-            UserCredential credential;
-
-            if (FilePath == "")
-            {
-                var time = DateTime.Now.ToString("yyyyMMddHHmmss");
-                FilePath = System.IO.Path.Combine(GoogleDriveViewModel.FilesPathTemp, time + ".json");
-            }
-
-
-            using (var stream = new FileStream(GoogleDriveViewModel.CredentialsPath, FileMode.Open, FileAccess.Read))
-            {
-                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
-                    GoogleClientSecrets.Load(stream).Secrets,
-                    Scopes,
-                    "user",
-                    CancellationToken.None,
-                    new FileDataStore(FilePath, true)).Result;
-                User.CurrentCredential = credential;
-            }
-
-            //create Drive API service.
-            DriveService service = new DriveService(new BaseClientService.Initializer()
-            {
-                HttpClientInitializer = credential,
-                ApplicationName = "PDF Office",
-            });
-
-            return service;
-        }
-
-
-        #endregion
+      
 
         #region   对用户账号处理
 
@@ -136,7 +49,7 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
         /// 获取帐号
         /// </summary>
         /// <returns>返回用户帐号地址</returns>
-        public string GetUserAcount()
+        private async Task<string> GetUserAcount()
         {
             string userAcount = "";
             if (Service != null)
@@ -149,6 +62,16 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
             return userAcount;
         }
 
+        /// <summary>
+        /// 获取帐号
+        /// </summary>
+        /// <returns>返回用户帐号地址</returns>
+        public async Task<string> GetUserAcountAsync()
+        {
+            return await GetUserAcount();
+        }
+
+
         #endregion
 
 
@@ -165,10 +88,10 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
         /// <summary>
         /// 对单个用户,获取文件列表
         /// </summary>
-        public  async Task<List<GoogleDriveFiles>> GetDriveFiles(DriveService service = null)
+        public async Task<List<GoogleDriveFiles>> GetDriveFiles(DriveService service = null)
         {
             if (service == null)
-                service = await GetServiceAsync();
+                return null;
 
             // define parameters of request.
             FilesResource.ListRequest FileListRequest = service.Files.List();
@@ -206,7 +129,7 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
         public  async Task<bool> FileUpload(string filepath)
         {
             if (Service == null)
-                Service = await GetServiceAsync();
+                return false;
 
             var FileMetaData = new Google.Apis.Drive.v3.Data.File();
             var str = filepath.LastIndexOf("\\");
@@ -245,7 +168,7 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
         public  async Task<string> DownloadGoogleFile(GoogleDriveFiles googleDriveFiles, string savePath)
         {
             if (Service == null)
-                Service = await GetServiceAsync();
+                return "";
 
             string fileId = googleDriveFiles.Id;
             if (string.IsNullOrEmpty(fileId))

+ 124 - 2
PDF Office/ViewModels/HomePanel/CloudDrive/GoogleDriveViewModel.cs

@@ -19,17 +19,136 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
     //多用户UX交互
     public class GoogleDriveViewModel
     {
-
-        public List<GoogleDriveUserItem> GoogleDriveUsers = new List<GoogleDriveUserItem>();
+        public static string[] Scopes = { DriveService.Scope.Drive };
+        private static readonly string GoogleDriveAppName = "PDF Office";
         public static string FilesPathTemp { get; private set; }
         public static string CredentialsPath { get; private set; }
 
+
+        public List<GoogleDriveUserItem> GoogleDriveUsers = new List<GoogleDriveUserItem>();
+
+
         public GoogleDriveViewModel()
         {
             GetFilesPathTemp();
             GetCredentialsPath();
         }
 
+
+
+        #region   请求身份验证
+
+        public async Task<bool> GetHistoryUsers()
+        {
+            var tuples = await GetHistoryService();
+            GoogleDriveUsers.Clear();
+            foreach (var tuple in tuples)
+            {
+
+                if (tuple != null && tuple.Item1 != null && tuple.Item2 != null)
+                {
+                    AddGoogleDriveUser(tuple);
+                }
+            }
+
+            if (GoogleDriveUsers.Count > 0)
+            {
+                return true;
+            }
+            return false;
+        }
+
+        public async void AddGoogleDriveUser(Tuple<DriveService, UserCredential> tuple)
+        {
+            GoogleDriveUserItem user = new GoogleDriveUserItem();
+            user.Service = tuple.Item1;
+            user.User.CurrentCredential = tuple.Item2;
+            user.User.UserAccount = await user.GetUserAcountAsync();
+            GoogleDriveUsers.Add(user);
+        }
+
+
+
+        /// <summary>
+        /// 获取登录过的账号
+        /// </summary>
+        /// <returns>历史账号</returns>
+        private async Task<List<Tuple<DriveService, UserCredential>>> GetHistoryService()
+        {
+            DirectoryInfo TheFolder = new DirectoryInfo(GoogleDriveViewModel.FilesPathTemp);
+            List<Tuple<DriveService, UserCredential>> DriveServices = new List<Tuple<DriveService, UserCredential>>();
+
+            foreach (var directorieItem in TheFolder.GetDirectories())
+            {
+                var driveServiceItem = await GetServiceAsync(directorieItem.Name);
+
+                if (driveServiceItem != null)
+                {
+                    DriveServices.Add(driveServiceItem);
+                }
+            }
+            return DriveServices;
+        }
+
+        /// <summary>
+        ///  异步获取Google服务的包信息,避免UI线程卡死
+        /// </summary>
+        /// <param name="userInfoFile"></param>
+        [Obsolete]
+        public async Task<Tuple<DriveService, UserCredential>> GetServiceAsync(string userInfoFile = "")
+        {
+            Tuple<DriveService, UserCredential> tuple = null;
+            await Task.Run(() =>
+            {
+                 tuple = GetService(userInfoFile);
+            });
+            return tuple;
+        }
+
+        /// <summary>
+        /// 获取Google服务的包信息(包含访问令牌,App Key密钥等)
+        /// </summary>
+        /// <param name="FilePath">登录过的用户文件;若为空,则为新用户登录</param>
+        /// <returns></returns>
+        [Obsolete]
+        private Tuple<DriveService, UserCredential>  GetService(string FilePath = "")
+        {
+            Tuple<DriveService, UserCredential> tuple = null;
+            UserCredential credential;
+
+            if (FilePath == "")
+            {
+                var time = DateTime.Now.ToString("yyyyMMddHHmmss");
+                FilePath = System.IO.Path.Combine(GoogleDriveViewModel.FilesPathTemp, time + ".json");
+            }
+
+
+            using (var stream = new FileStream(GoogleDriveViewModel.CredentialsPath, FileMode.Open, FileAccess.Read))
+            {
+                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
+                    GoogleClientSecrets.Load(stream).Secrets,
+                    Scopes,
+                    "user",
+                    CancellationToken.None,
+                    new FileDataStore(FilePath, true)).Result;
+            }
+
+            //create Drive API service.
+            DriveService service = new DriveService(new BaseClientService.Initializer()
+            {
+                HttpClientInitializer = credential,
+                ApplicationName = GoogleDriveAppName
+            });
+
+            return tuple = new Tuple<DriveService, UserCredential>(service, credential);
+        }
+
+
+        #endregion
+
+
+        #region  云文档的用户帐户缓存路径和身份验证文件
+
         /// <summary>
         /// 获取或创建缓存登录帐户信息
         /// </summary>
@@ -54,6 +173,9 @@ namespace PDF_Office.ViewModels.HomePanel.CloudDrive
             CredentialsPath = filePath;
         }
 
+        #endregion
+
+
     }
 
 }

+ 1 - 1
PDF Office/Views/HomePanel/CloudDrive/CloudDriveContent.xaml

@@ -4,7 +4,7 @@
              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
              xmlns:local="clr-namespace:PDF_Office.Views.HomePanel.CloudDrive"
-              xmlns:prism ="http://prismlibrary.com/"
+             xmlns:prism ="http://prismlibrary.com/"
              prism:ViewModelLocator.AutoWireViewModel="True"
              mc:Ignorable="d" 
              d:DesignHeight="450" d:DesignWidth="800">

+ 4 - 1
PDF Office/Views/HomePanel/CloudDrive/CloudFilesContent.xaml

@@ -3,6 +3,8 @@
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
+             xmlns:prism ="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
              xmlns:local="clr-namespace:PDF_Office.Views.HomePanel.CloudDrive"
              mc:Ignorable="d" 
              d:DesignHeight="450" d:DesignWidth="800">
@@ -39,7 +41,8 @@
             <ListBox x:Name="Listusers" Width="170">
                 <ListBox.ItemTemplate>
                     <DataTemplate>
-                        <TextBlock Text="{Binding Name}"/>
+                        <TextBlock Text="{Binding UserAccount}"/>
+                        
                     </DataTemplate>
                 </ListBox.ItemTemplate>
             </ListBox>

+ 47 - 4
PDF Office/Views/HomePanel/CloudDrive/CloudFilesContent.xaml.cs

@@ -23,7 +23,9 @@ namespace PDF_Office.Views.HomePanel.CloudDrive
     public partial class CloudFilesContent : UserControl
     {
         private List<string> list = new List<string>();
-        private GoogleDriveViewModel GoogleDrive = new GoogleDriveViewModel();
+      //  private GoogleDriveViewModel GoogleDrive = new GoogleDriveViewModel();
+
+        private CloudFilesContentViewModel CloudFilesDrive=>DataContext as CloudFilesContentViewModel;
 
         private CloudType cloudType;
         public CloudFilesContent()
@@ -34,9 +36,39 @@ namespace PDF_Office.Views.HomePanel.CloudDrive
             list.Add("GoogleDrive");
             list.Add("OneDrive");
             ListFolder.ItemsSource = list;
-           // Listusers.ItemsSource = list;
-          //  combCloudDisk.ItemsSource = list;
-           // ListvmFiles.ItemsSource = list;
+            // Listusers.ItemsSource = list;
+            //  combCloudDisk.ItemsSource = list;
+            // ListvmFiles.ItemsSource = list;
+            this.Loaded += usercontrol_Loaded;
+        }
+
+        private void usercontrol_Loaded(object sender, RoutedEventArgs e)
+        {
+          if(CloudFilesDrive != null)
+            {
+                CloudFilesDrive.isFoundUserHandler += isFoundUserEvent;
+                CloudFilesDrive.CheckDriveUsers();
+            }
+        }
+
+        private async void isFoundUserEvent(object sender, bool e)
+        {
+            isShow = e;
+            if(isShow)
+            {
+                List<GoogleDriveUser> GoogleDriveUsers = new List<GoogleDriveUser>();
+            //    await Task.Run(async () =>
+             //   {
+                    foreach (var item in CloudFilesDrive.GoogleDrive.GoogleDriveUsers)
+                    {
+
+                        GoogleDriveUsers.Add(item.User);
+                    }
+             //   });
+
+                
+                Listusers.ItemsSource = GoogleDriveUsers;
+            }
         }
 
         public void SelectCloudTye(CloudType cloudType)
@@ -53,5 +85,16 @@ namespace PDF_Office.Views.HomePanel.CloudDrive
         {
             SelectCloudTye(CloudType.GoogleDrive);
         }
+
+
+
+        public bool isShow
+        {
+            get { return (bool)GetValue(NormalIconProperty); }
+            set { SetValue(NormalIconProperty, value); }
+        }
+        public static readonly DependencyProperty NormalIconProperty =
+           DependencyProperty.Register("isShow", typeof(bool), typeof(CloudFilesContent), new PropertyMetadata(false));
+
     }
 }

+ 9 - 2
PDF Office/Views/HomePanel/HomeCloudContent.xaml

@@ -7,11 +7,18 @@
              xmlns:Cloud="clr-namespace:PDF_Office.Views.HomePanel.CloudDrive"
              xmlns:prism ="http://prismlibrary.com/"
              prism:ViewModelLocator.AutoWireViewModel="True"
+             xmlns:convert="clr-namespace:PDF_Office.DataConvert"
              Background="Yellow"
              mc:Ignorable="d" 
              d:DesignHeight="450" d:DesignWidth="800">
+    <UserControl.Resources>
+        <ResourceDictionary>
+            <convert:InvertBoolToVisibleConvert x:Key="InvertBoolToVisibleConvert" />
+            <convert:BoolToVisible x:Key="BoolToVisibleConvert" />
+        </ResourceDictionary>
+    </UserControl.Resources>
     <Grid>
-        <Cloud:CloudDriveContent x:Name="cloudDiskContent" Visibility="Visible" OpenCloudDriveHandler ="cloudDiskContent_OpenCloudDriveHandler"/>
-        <Cloud:CloudFilesContent x:Name="cloudFilesContent"  Visibility="Collapsed"/>
+        <Cloud:CloudDriveContent x:Name="cloudDiskContent" Visibility="{Binding ElementName=cloudFilesContent,Path=isShow, Converter={StaticResource  InvertBoolToVisibleConvert}}" OpenCloudDriveHandler ="cloudDiskContent_OpenCloudDriveHandler"/>
+        <Cloud:CloudFilesContent x:Name="cloudFilesContent"  Visibility="{Binding ElementName=cloudFilesContent,Path=isShow, Converter={StaticResource BoolToVisibleConvert}}"/>
     </Grid>
 </UserControl>

+ 14 - 1
PDF Office/Views/HomePanel/HomeCloudContent.xaml.cs

@@ -1,4 +1,5 @@
-using System;
+using PDF_Office.ViewModels.HomePanel.CloudDrive;
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
@@ -23,8 +24,20 @@ namespace PDF_Office.Views.HomePanel
         public HomeCloudContent()
         {
             InitializeComponent();
+            this.Loaded += HomeCloudContent_Load;
+
         }
 
+        private void HomeCloudContent_Load(object sender, RoutedEventArgs e)
+        {
+           var cloudDrives = cloudFilesContent.DataContext as CloudFilesContentViewModel;
+            if(cloudDrives != null)
+            {
+                cloudDrives.CheckDriveUsersCommand.Execute();
+            }
+        }
+
+
         private void cloudDiskContent_OpenCloudDriveHandler(object sender, bool e)
         {
             if(e)