public async Task UploadFileAsync(FileInfo file, string uploadWithFilename)
        {
            if (_dropboxClient == null)
            {
                var(accessToken, refreshToken) = await _configRepository.GetDropboxTokensAsync();

                _dropboxClient = new DropboxClient(accessToken, refreshToken, _dropboxOptions.SmallSqliteKitAppKey,
                                                   _dropboxOptions.SmallSqliteKitAppSecret, new DropboxClientConfig());

                if (!await _dropboxClient.RefreshAccessToken(new[] { "files.content.write" }))
                {
                    _logger.LogWarning($"Could not refresh Dropbox access token");
                    return;
                }
            }

            var dropboxFilename = string.IsNullOrWhiteSpace(uploadWithFilename) ? file.Name : uploadWithFilename;

            dropboxFilename = $"{(dropboxFilename.StartsWith('/') ? string.Empty : "/")}{dropboxFilename}.gz";

            using var fileToUploadStream = file.OpenRead();
            using var outputStream       = new MemoryStream();
            using (var stream = new GZipStream(outputStream, CompressionLevel.Optimal, true))
                await fileToUploadStream.CopyToAsync(stream);

            outputStream.Position = 0;
            var uploadedFile = await _dropboxClient.Files.UploadAsync(dropboxFilename, WriteMode.Overwrite.Instance, body : outputStream);

            _logger.LogTrace($"Saved {uploadedFile.PathDisplay}/{uploadedFile.Name} rev {uploadedFile.Rev}");
        }
        public async Task SaveUserAccountAsync(UserAccount userAccount)
        {
            context.UserAccounts.Update(userAccount);
            await context.SaveChangesAsync();

            logger.LogInformation("User account saved.");

            if (string.IsNullOrEmpty(userAccount.DropboxAccessToken) || string.IsNullOrEmpty(userAccount.DropboxRefreshToken))
            {
                logger.LogDebug("User account has no Dropbox token");
                return;
            }

            using var contentStream = new MemoryStream(Encoding.ASCII.GetBytes(userAccount.PasswordDatabase));
            using var dropboxClient = new DropboxClient(userAccount.DropboxAccessToken, userAccount.DropboxRefreshToken,
                                                        dropboxConfig.Value.KeepItSaferAppKey, dropboxConfig.Value.KeepItSaferAppSecret, new DropboxClientConfig());
            if (!await dropboxClient.RefreshAccessToken(new[] { "files.content.write" }))
            {
                logger.LogWarning($"Could not refresh Dropbox access token");
                return;
            }

            var file = await dropboxClient.Files.UploadAsync(
                "/keepitsafer.db.json",
                WriteMode.Overwrite.Instance,
                body : contentStream);

            logger.LogTrace($"Saved {file.PathDisplay}/{file.Name} rev {file.Rev}");
        }
示例#3
0
        private async Task <int> Run()
        {
            DropboxCertHelper.InitializeCertPinning();

            string[] scopeList = new string[3] {
                "files.metadata.read", "files.content.read", "account_info.read"
            };
            var uid = await this.AcquireAccessToken(scopeList, IncludeGrantedScopes.None);

            if (string.IsNullOrEmpty(uid))
            {
                return(1);
            }

            // Specify socket level timeout which decides maximum waiting time when no bytes are
            // received by the socket.
            var httpClient = new HttpClient(new WebRequestHandler {
                ReadWriteTimeout = 10 * 1000
            })
            {
                // Specify request level timeout which decides maximum time that can be spent on
                // download/upload files.
                Timeout = TimeSpan.FromMinutes(20)
            };

            try
            {
                var config = new DropboxClientConfig("SimpleOAuthApp")
                {
                    HttpClient = httpClient
                };

                var client = new DropboxClient(Settings.Default.AccessToken, Settings.Default.RefreshToken, ApiKey, ApiSecret, config);

                // This call should succeed since the correct scope has been acquired
                await GetCurrentAccount(client);

                Console.WriteLine("Refreshing without scope account_info.read");
                var newScopes = new string[] { "files.metadata.read", "files.content.read" };
                await client.RefreshAccessToken(newScopes);

                try
                {
                    // This should fail since token does not have "account_info.read" scope
                    await GetCurrentAccount(client);
                }
                catch (Exception)
                {
                    Console.WriteLine("Correctly failed with invalid scope");
                }
                Console.WriteLine("Attempting to try again with include_granted_scopes");
                await this.AcquireAccessToken(newScopes, IncludeGrantedScopes.User);

                var clientNew = new DropboxClient(Settings.Default.AccessToken, Settings.Default.RefreshToken, ApiKey, ApiSecret, config);
                await GetCurrentAccount(clientNew);

                Console.WriteLine("Oauth Test Complete!");
                Console.WriteLine("Exit with any key");
                Console.ReadKey();
            }
            catch (HttpException e)
            {
                Console.WriteLine("Exception reported from RPC layer");
                Console.WriteLine("    Status code: {0}", e.StatusCode);
                Console.WriteLine("    Message    : {0}", e.Message);
                if (e.RequestUri != null)
                {
                    Console.WriteLine("    Request uri: {0}", e.RequestUri);
                }
            }

            return(0);
        }
示例#4
0
        private async Task <int> Run()
        {
            DropboxCertHelper.InitializeCertPinning();

            string[] scopeList = new string[] { "files.metadata.read", "files.content.read", "account_info.read", "sharing.read" };
            var      uid       = await AcquireAccessToken(scopeList, IncludeGrantedScopes.None);

            if (string.IsNullOrEmpty(uid))
            {
                return(1);
            }

            // Specify socket level timeout which decides maximum waiting time when no bytes are received by the socket.
            var httpClient = new HttpClient(new WebRequestHandler {
                ReadWriteTimeout = 10 * 1000
            })
            {
                // Specify request level timeout which decides maximum time that can be spent on download/upload files.
                Timeout = TimeSpan.FromMinutes(20)
            };

            try
            {
                var config = new DropboxClientConfig("SimpleOAuthApp")
                {
                    HttpClient = httpClient
                };

                var client = new DropboxClient(Settings.Default.AccessToken, Settings.Default.RefreshToken, Settings.Default.ApiKey, Settings.Default.ApiSecret, config);
                var scopes = new string[] { "files.metadata.read", "files.content.read", "sharing.read" };
                await client.RefreshAccessToken(scopes);

                if (Settings.Default.SharedLinks == null || Settings.Default.SharedLinks.Count == 0)
                {
                    Settings.Default.SharedLinks = new System.Collections.Specialized.StringCollection();

                    Console.Write("Shared link URL: ");
                    var line = Console.ReadLine();
                    while (line.Length > 0)
                    {
                        Settings.Default.SharedLinks.Add(line);

                        Console.Write("Additional shared link URL (leave blank to finish): ");
                        line = Console.ReadLine();
                    }
                    Settings.Default.Save();
                }

                var sharedLinks = Settings.Default.SharedLinks;
                foreach (var sharedLinkUrl in sharedLinks)
                {
                    GetSharedLinkMetadataArg arg = new GetSharedLinkMetadataArg(sharedLinkUrl);
                    var sharedLinkMetaData       = await client.Sharing.GetSharedLinkMetadataAsync(arg);

                    var localDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), sharedLinkMetaData.Name);
                    Directory.CreateDirectory(localDir);

                    Console.WriteLine($"Processing shared link name: {sharedLinkMetaData.Name}");
                    if (Verbose)
                    {
                        Console.WriteLine($"Shared link local folder: {localDir}");
                    }

                    SharedLink    sharedLink    = new SharedLink(sharedLinkUrl);
                    ListFolderArg listFolderArg = new ListFolderArg(path: "", sharedLink: sharedLink);
                    var           listFiles     = await client.Files.ListFolderAsync(listFolderArg);

                    foreach (var listFile in listFiles.Entries)
                    {
                        try
                        {
                            if (Verbose)
                            {
                                Console.WriteLine($"Processing: {listFile.Name}");
                            }

                            // Get the remote object details
                            var remoteFile = listFile.AsFile;

                            // Construct a reference to the local equivalent
                            var localFile = Path.Combine(localDir, listFile.Name);
                            if (Verbose)
                            {
                                Console.WriteLine($"  Local filename: {localFile}");
                            }

                            // Do we have a file already
                            if (File.Exists(localFile))
                            {
                                if (Verbose)
                                {
                                    Console.WriteLine($"  Local file exists. Comparing timestamp");
                                }

                                var localTimestamp = File.GetLastWriteTimeUtc(localFile);

                                if (Verbose)
                                {
                                    Console.WriteLine($"  Checking {remoteFile.ServerModified} with {localTimestamp}");
                                }

                                if (DateTime.Compare(remoteFile.ServerModified, localTimestamp) == 0)
                                {
                                    if (Verbose)
                                    {
                                        Console.WriteLine($"  Skipping unchanged file: {listFile.Name}");
                                    }
                                    continue;
                                }
                            }

                            GetSharedLinkMetadataArg downloadArg = new GetSharedLinkMetadataArg(sharedLinkUrl, $"/{listFile.Name}");
                            if (Verbose)
                            {
                                Console.WriteLine($"SharedLinkUrl: {sharedLinkUrl}");
                                Console.WriteLine($"    File Name: {listFile.Name}");
                            }
                            var download = await client.Sharing.GetSharedLinkFileAsync(downloadArg);

                            Console.WriteLine($"  Downloading: {remoteFile.Name}");
                            using (var ms = new MemoryStream())
                            {
                                var bytes = await download.GetContentAsByteArrayAsync();

                                if (bytes.Length > 0)
                                {
                                    File.WriteAllBytes(localFile, bytes.ToArray());
                                    File.SetCreationTimeUtc(localFile, remoteFile.ServerModified);
                                    File.SetLastWriteTimeUtc(localFile, remoteFile.ServerModified);
                                }
                                else
                                {
                                    Console.Error.WriteLine($"No bytes downloaded");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.Error.WriteLine($"Failed during download: ${ex.Message}");
                        }
                    }

                    if (Verbose)
                    {
                        Console.WriteLine("Download complete!");
                    }
                }

                if (Verbose)
                {
                    Console.WriteLine("All downloads complete!");
                }

                if (PromptToExit)
                {
                    Console.WriteLine("Exit with any key");
                    Console.ReadKey();
                }
            }
            catch (HttpException e)
            {
                Console.WriteLine("Exception reported from RPC layer");
                Console.WriteLine("    Status code: {0}", e.StatusCode);
                Console.WriteLine("    Message    : {0}", e.Message);
                if (e.RequestUri != null)
                {
                    Console.WriteLine("    Request uri: {0}", e.RequestUri);
                }
            }

            return(0);
        }