Beispiel #1
0
        private async Task <(CloudStorageResult result, string folderId)> CreateFolderAsync(string fullFolderPath)
        {
            CloudStorageResult result = new CloudStorageResult();
            string             folderId;

            try
            {
                // check if folder already exist
                folderId = await TryGetFolderIdAsync(fullFolderPath);

                if (!string.IsNullOrEmpty(folderId))
                {
                    result.Status = Status.Success;
                    return(result, folderId);
                }

                var createResult = await dropboxClient.Files.CreateFolderV2Async(fullFolderPath);

                folderId      = createResult.Metadata.Id;
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                folderId       = null;
            }
            return(result, folderId);
        }
Beispiel #2
0
        public async Task <CloudStorageResult> InitAsync()
        {
            CloudStorageResult result = new CloudStorageResult();

            try
            {
                // 取得上次登入資訊
                string lastRefreshToken = LoadRefreshTokenDelegate?.Invoke();

                // 初始化
                result.Status = Status.NeedAuthenticate;
                oauthClient   = new OneDriveOauthClient(ApiKey, ApiSecret);
                if (!string.IsNullOrEmpty(lastRefreshToken))
                {
                    bool needLogin = !await oauthClient.RefreshTokenAsync(lastRefreshToken);

                    if (needLogin)
                    {
                        lastRefreshToken = null;
                    }
                    else
                    {
                        result.Status = Status.Success;
                        // 儲存新的access token/refresh token
                        SaveAccessTokenDelegate?.Invoke(oauthClient.AccessToken);
                        InitDriveService();
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Beispiel #3
0
        public async Task <(CloudStorageResult result, string folderId)> CreateFolderAsync(string fullFolderPath)
        {
            CloudStorageResult result   = new CloudStorageResult();
            string             folderId = null;

            if (string.IsNullOrEmpty(fullFolderPath))
            {
                return(result, null);
            }

            try
            {
                // need to create folder recursively
                var folders = fullFolderPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                // create first folder under root
                folderId = "root";
                foreach (string folderName in folders)
                {
                    folderId = await TryCreateFolder(folderId, folderName);
                }
                result.Status = Status.Success;
            }
            catch (Exception e)
            {
                result.Message = e.Message;
            }
            return(result, folderId);
        }
Beispiel #4
0
        public async Task <(CloudStorageResult, CloudStorageAccountInfo)> LoginAsync()
        {
            CloudStorageResult      result      = new CloudStorageResult();
            CloudStorageAccountInfo accountInfo = new CloudStorageAccountInfo();

            try
            {
                if (await oauthClient.GetTokenAsync())
                {
                    SaveAccessTokenDelegate?.Invoke(oauthClient.AccessToken);
                    SaveRefreshTokenDelegate?.Invoke(oauthClient.RefreshToken);
                    InitDriveService();
                    (result, accountInfo.userName, accountInfo.userEmail) = await GetUserInfoAsync();

                    if (result.Status == Status.Success)
                    {
                        (result, accountInfo.usedSpace, accountInfo.totalSpace) = await GetRootInfoAsync();
                    }
                }
                else
                {
                    result.Message = oauthClient.LastError;
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, accountInfo);
        }
Beispiel #5
0
        public async Task <CloudStorageResult> DeleteFileByIdAsync(string fileID)
        {
            CloudStorageResult result = new CloudStorageResult();

            if (string.IsNullOrEmpty(fileID))
            {
                return(result);
            }
            try
            {
                //fileID = fileID.Replace("id:", string.Empty);  // 要刪除前綴 "id:" 才是 dropbox 正確格式
                List <string> deletedIds = new List <string> {
                    fileID
                };
                var deleteResult = await dropboxClient.Files.DeleteV2Async(fileID);

                result.Status = Status.Success;
            }
            catch (ApiException <Dropbox.Api.FileRequests.DeleteFileRequestError> ex)
            {
                result.Message = ex.ToString();
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Beispiel #6
0
        public async Task <CloudStorageResult> DownloadFileByIdAsync(string fileID, string savePath, CancellationToken ct)
        {
            CloudStorageResult result = new CloudStorageResult();

            if (string.IsNullOrEmpty(fileID))
            {
                result.Status = Status.NotFound;
                return(result);
            }

            try
            {
                using (Stream downloadStream = await myDriveBuilder.Items[fileID].Content.Request().GetAsync(ct))
                {
                    using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
                    {
                        byte[] buffer = new byte[CHUNK_SIZE];
                        int    length;
                        do
                        {
                            // check if user cancelling
                            if (ct.IsCancellationRequested)
                            {
                                throw new TaskCanceledException("Download cancelled.");
                            }

                            // get each chunk from remote
                            length = await downloadStream.ReadAsync(buffer, 0, CHUNK_SIZE, ct);

                            await fileStream.WriteAsync(buffer, 0, length, ct);

                            // Update progress bar with the percentage.
                            Console.WriteLine($"Downloaded {length} bytes.");
                            OnProgressChanged(length);
                        } while (length > 0);
                        fileStream.Close();
                    }
                    downloadStream.Close();
                }
                result.Status = Status.Success;
            }
            catch (TaskCanceledException ex)
            {
                result.Status  = Status.Cancelled;
                result.Message = ex.Message;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Beispiel #7
0
        public async Task <(CloudStorageResult result, CloudStorageAccountInfo info)> GetAccountInfoAsync()
        {
            CloudStorageResult      result = new CloudStorageResult();
            CloudStorageAccountInfo info   = new CloudStorageAccountInfo();

            (result, info.userName, info.userEmail) = await GetUserInfoAsync();

            if (result.Status == Status.Success)
            {
                (result, info.usedSpace, info.totalSpace) = await GetRootInfoAsync();
            }
            return(result, info);
        }
Beispiel #8
0
        private async Task <CloudStorageResult> DownloadFileByPathAsync(string filePath, string savePath, CancellationToken ct)
        {
            CloudStorageResult result = new CloudStorageResult();

            try
            {
                // prepare file to download
                using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
                {
                    var getResult = await dropboxClient.Files.DownloadAsync(filePath);

                    using (Stream getStream = await getResult.GetContentAsStreamAsync())
                    {
                        byte[] buffer = new byte[CHUNK_SIZE];
                        int    length;
                        do
                        {
                            // check if user cancelling
                            if (ct.IsCancellationRequested)
                            {
                                throw new TaskCanceledException("Download cancelled.");
                            }
                            // get each chunk from remote
                            length = await getStream.ReadAsync(buffer, 0, CHUNK_SIZE, ct);

                            await fileStream.WriteAsync(buffer, 0, length, ct);

                            // Update progress bar with the percentage.
                            OnProgressChanged(length);
                        } while (length > 0);
                        getStream.Close();
                    }
                    // close the file
                    await fileStream.FlushAsync(ct);

                    fileStream.Close();
                }
                result.Status = Status.Success;
            }
            catch (TaskCanceledException ex)
            {
                result.Status  = Status.Cancelled;
                result.Message = ex.Message;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Beispiel #9
0
        public async Task <CloudStorageResult> InitAsync()
        {
            CloudStorageResult result = new CloudStorageResult();
            bool IsNeedLogin          = true;

            try
            {
                // 取得上次登入資訊
                LastAccessToken  = LoadAccessTokenDelegate?.Invoke();
                LastRefreshToken = LoadRefreshTokenDelegate?.Invoke();

                // 初始化
                oAuthWrapper = new DropBoxOauthClient(ApiKey, RedirectUrl);
                if (!string.IsNullOrEmpty(LastRefreshToken))  // offline 類型的 token
                {
                    IsNeedLogin = !await oAuthWrapper.RefreshTokenAsync(LastRefreshToken);

                    if (IsNeedLogin)
                    {
                        result.Status   = Status.NeedAuthenticate;
                        LastAccessToken = LastRefreshToken = null;
                    }
                    else
                    {
                        result.Status = Status.Success;
                        // 儲存新的access token/refresh token
                        SaveAccessTokenDelegate?.Invoke(oAuthWrapper.AccessToken);
                        InitDriveService();
                    }
                }
                else if (!string.IsNullOrEmpty(LastAccessToken))  // legacy 類型的 token,不需要refresh
                {
                    result.Status = Status.Success;
                    InitDriveService();
                }
                else
                {
                    // each token is empty, need login
                    result.Status  = Status.NeedAuthenticate;
                    result.Message = "Empty access and refresh token.";
                }
            }
            catch (Exception ex)
            {
                result.Status  = Status.UnknownError;
                result.Message = ex.Message;
            }
            return(result);
        }
Beispiel #10
0
        public async Task <(CloudStorageResult result, CloudStorageAccountInfo info)> GetAccountInfoAsync()
        {
            CloudStorageResult      result = new CloudStorageResult();
            CloudStorageAccountInfo info   = new CloudStorageAccountInfo();

            //if (string.IsNullOrEmpty(LastRefreshToken))
            //    return (result, info);

            (result, info.userName, info.userEmail) = await GetUserInfoAsync();

            if (result.Status == Status.Success)
            {
                (result, info.usedSpace, info.totalSpace) = await GetRootInfoAsync();
            }
            return(result, info);
        }
Beispiel #11
0
        public async Task <CloudStorageResult> DeleteFileByPathAsync(string filePath)
        {
            CloudStorageResult result = new CloudStorageResult();

            try
            {
                var deleteResult = await dropboxClient.Files.DeleteV2Async(filePath);

                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Beispiel #12
0
        public async Task <(CloudStorageResult result, string folderId)> CreateFolderAsync(string parentId, string folderName)
        {
            CloudStorageResult result   = new CloudStorageResult();
            string             folderId = null;

            try
            {
                folderId = await TryCreateFolder(parentId, folderName);

                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, folderId);
        }
Beispiel #13
0
        /// <summary>
        /// 取得User Name, Email
        /// </summary>
        private async Task <(CloudStorageResult result, string userName, string userEmail)> GetUserInfoAsync()
        {
            string             userName = null, userEmail = null;
            CloudStorageResult result = new CloudStorageResult();

            try
            {
                System.Net.WebRequest request = System.Net.WebRequest.Create(UerInfoEndpoint + oauthClient.AccessToken);
                request.Method      = "GET";
                request.ContentType = "application/json";
                // Get the response.
                System.Net.WebResponse response = await request.GetResponseAsync();

                // Display the status.
                //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = await reader.ReadToEndAsync();

                // Display the content.
                Console.WriteLine(responseFromServer);
                // Clean up the streams and the response.
                reader.Close();
                reader.Dispose();
                dataStream.Close();
                dataStream.Dispose();
                response.Close();
                response.Dispose();
                if (!string.IsNullOrEmpty(responseFromServer))
                {
                    Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(responseFromServer);
                    userEmail     = jObject["email"]?.ToString();
                    userName      = jObject["name"]?.ToString();
                    result.Status = Status.Success;
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, userName, userEmail);
        }
Beispiel #14
0
        private async Task <(CloudStorageResult, CloudStorageFile)> UploadFileToFolderByPathAsync(string filePath, string folderName, CancellationToken ct)
        {
            CloudStorageResult result    = new CloudStorageResult();
            CloudStorageFile   cloudFile = null;

            try
            {
                FileInfo fileInfo = new FileInfo(filePath);
                if (!fileInfo.Exists)
                {
                    result.Status  = Status.NotFound;
                    result.Message = $"File '{filePath}' does not exist.";
                    return(result, null);
                }

                // upload to dropbox root folder if folderName is empty
                if (string.IsNullOrEmpty(folderName))
                {
                    folderName = "/";
                }

                long fileSize = fileInfo.Length;
                if (fileSize <= CHUNK_SIZE)
                {
                    cloudFile = await UploadSmaillFile(filePath, folderName);

                    OnProgressChanged(fileSize);  // 一次回報全部進度
                }
                else
                {
                    cloudFile = await UploadBigFile(filePath, folderName, ct);
                }
                result.Status = Status.Success;
            }
            catch (TaskCanceledException ex)
            {
                result.Status  = Status.Cancelled;
                result.Message = ex.Message;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, cloudFile);
        }
Beispiel #15
0
        /// <summary>
        /// 取得User Name, Email
        /// </summary>
        private async Task <(CloudStorageResult result, string userName, string userEmail)> GetUserInfoAsync()
        {
            CloudStorageResult result = new CloudStorageResult();
            string             userName = null, userEmail = null;

            try
            {
                User me = await graphServiceClient.Users["me"].Request().GetAsync();
                userName      = me.DisplayName;
                userEmail     = me.Mail ?? me.UserPrincipalName;
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, userName, userEmail);
        }
Beispiel #16
0
        /// <summary>
        /// 取得空間資訊
        /// </summary>
        private async Task <(CloudStorageResult result, long usedSpace, long totalSpace)> GetRootInfoAsync()
        {
            long usedSpace = 0, totalSpace = 0;
            CloudStorageResult result = new CloudStorageResult();

            try
            {
                var usage = await dropboxClient.Users.GetSpaceUsageAsync();

                totalSpace    = (long)usage.Allocation.AsIndividual.Value.Allocated;
                usedSpace     = (long)usage.Used;
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, usedSpace, totalSpace);
        }
Beispiel #17
0
        /// <summary>
        /// 取得 User Name, Email
        /// </summary>
        private async Task <(CloudStorageResult result, string userName, string userEmail)> GetUserInfoAsync()
        {
            string             userName = null, userEmail = null;
            CloudStorageResult result = new CloudStorageResult();

            try
            {
                var fullAccount = await dropboxClient.Users.GetCurrentAccountAsync();

                userName      = fullAccount.Name.DisplayName;
                userEmail     = fullAccount.Email;
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, userName, userEmail);
        }
Beispiel #18
0
        /// <summary>
        /// 取得空間資訊,並初始化 Drive 物件
        /// </summary>
        private async Task <(CloudStorageResult result, long usedSpace, long totalSpace)> GetRootInfoAsync()
        {
            CloudStorageResult result = new CloudStorageResult();
            long usedSpace = 0, totalSpace = 0;

            try
            {
                myDriveBuilder = graphServiceClient.Me.Drive;
                Drive myDrive = await myDriveBuilder.Request().GetAsync();

                usedSpace     = myDrive.Quota.Used ?? 0;
                totalSpace    = myDrive.Quota.Total ?? 0;
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, usedSpace, totalSpace);
        }
Beispiel #19
0
        public async Task <CloudStorageResult> DeleteFileByIdAsync(string fileID)
        {
            CloudStorageResult result = new CloudStorageResult();

            if (string.IsNullOrEmpty(fileID))
            {
                result.Status = Status.NotFound;
                return(result);
            }

            try
            {
                await myDriveBuilder.Items[fileID].Request().DeleteAsync();
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Beispiel #20
0
        /// <summary>
        /// 取得空間資訊,totalSpace=-1 代表無限空間
        /// </summary>
        private async Task <(CloudStorageResult result, long usedSpace, long totalSpace)> GetRootInfoAsync()
        {
            long usedSpace = 0, totalSpace = 0;
            CloudStorageResult result = new CloudStorageResult();

            try
            {
                var getRequest = driveService.About.Get();
                getRequest.Fields = "*";  // Error: 'fields' parameter is required for this method
                About about = await getRequest.ExecuteAsync();

                totalSpace    = about.StorageQuota.Limit ?? -1;
                usedSpace     = about.StorageQuota.Usage ?? -1;
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result, usedSpace, totalSpace);
        }
Beispiel #21
0
        public CloudStorageResult AuthenticateFromUri(string state, string uri)
        {
            CloudStorageResult result = new CloudStorageResult();

            try
            {
                bool success = oAuthWrapper.ProcessUri(state, uri);
                if (success)
                {
                    result.Status    = Status.Success;
                    LastAccessToken  = oAuthWrapper.AccessToken;
                    LastRefreshToken = oAuthWrapper.RefreshToken;
                    SaveAccessTokenDelegate?.Invoke(LastAccessToken);
                    SaveRefreshTokenDelegate?.Invoke(LastRefreshToken);
                    InitDriveService();
                }
                result.Status = Status.NeedAuthenticate;
            }
            catch (Exception e)
            {
                result.Message = e.Message;
            }
            return(result);
        }
Beispiel #22
0
        public async Task <(CloudStorageResult, CloudStorageFile)> UploadFileToFolderByIdAsync(string filePath, string folderId, CancellationToken ct)
        {
            IDriveItemRequestBuilder driveItemsRequest;

            if (string.IsNullOrEmpty(folderId))
            {
                driveItemsRequest = myDriveBuilder.Root;
            }
            else
            {
                driveItemsRequest = myDriveBuilder.Items[folderId];
            }

            CloudStorageResult result = new CloudStorageResult();
            CloudStorageFile   file   = null;

            // Use properties to specify the conflict behavior in this case, replace
            var uploadProps = new DriveItemUploadableProperties
            {
                ODataType      = null,
                AdditionalData = new Dictionary <string, object>
                {
                    { "@microsoft.graph.conflictBehavior", "replace" }
                }
            };


            try
            {
                // Create an upload session for a file with the same name of the user selected file
                UploadSession session = await driveItemsRequest.ItemWithPath(Path.GetFileName(filePath)).CreateUploadSession(uploadProps).Request().PostAsync(ct);

                using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var fileUploadTask = new LargeFileUploadTask <DriveItem>(session, fileStream, CHUNK_SIZE);

                    // Create a callback that is invoked after each slice is uploaded
                    IProgress <long> progressCallback = new Progress <long>((progress) =>
                    {
                        Console.WriteLine($"Uploaded {progress} bytes.");
                        OnProgressChanged(progress);
                    });

                    // Upload the file
                    var uploadResult = await fileUploadTask.UploadAsync(progressCallback);

                    if (uploadResult.UploadSucceeded)
                    {
                        // The ItemResponse object in the result represents the created item.
                        file = new CloudStorageFile()
                        {
                            Name         = uploadResult.ItemResponse.Name,
                            Id           = uploadResult.ItemResponse.Id,
                            CreatedTime  = uploadResult.ItemResponse.CreatedDateTime?.DateTime ?? DateTime.MinValue,
                            ModifiedTime = uploadResult.ItemResponse.LastModifiedDateTime?.DateTime ?? DateTime.MinValue,
                            Size         = uploadResult.ItemResponse.Size ?? 0
                        };
                        result.Status = Status.Success;
                    }
                    else
                    {
                        result.Message = "Upload failed.";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }

            return(result, file);
        }