Пример #1
0
        public DropboxConnector(string clientId, string clientSecret, IUserTokenRepository repository)
        {
            if (repository == null) throw new ArgumentNullException("repository");

            _repository = repository;

            var token = _repository.TryRetrieveTokenFromDatabase(HardcodedUser.Id);

            _accessToken = token.DropboxAccessToken;

            var options = new Options
            {
                ClientId = clientId,
                ClientSecret = clientSecret,
                RedirectUri = "http://localhost:52110/dropbox/oauth",
                UseSandbox = true,
                AccessToken = _accessToken
            };

            _client = new Client(options);
        }
Пример #2
0
        public async Task<ActionResult> Index()
        {
                //initialize dropbox auth options
            var options = new Options
            {
                ClientId = "rnizd2wt4vhv4cn",
                ClientSecret = "k8exfknbce45n5g",
                RedirectUri = "https://fedup.azurewebsites.net/Incident"
                //RedirectUri = "http://localhost:49668/Incident"
            };

                // Initialize a new Client (without an AccessToken)
            var dropboxClient = new Client(options);

                // Get the OAuth Request Url
            var authRequestUrl = await dropboxClient.Core.OAuth2.AuthorizeAsync("code");

            if (Request.QueryString["code"] == null)
            {
                    // Navigate to authRequestUrl using the browser, and retrieve the Authorization Code from the response
                Response.Redirect(authRequestUrl.ToString());
            }
                //get authcode from querstring param
            var authCode = Request.QueryString["code"];

            // Exchange the Authorization Code with Access/Refresh tokens
            var token = await dropboxClient.Core.OAuth2.TokenAsync(authCode);

            // Get account info
            var accountInfo = await dropboxClient.Core.Accounts.AccountInfoAsync();
            Console.WriteLine("Uid: " + accountInfo.uid);
            Console.WriteLine("Display_name: " + accountInfo.display_name);
            Console.WriteLine("Email: " + accountInfo.email);

            // Get root folder without content
            var rootFolder = await dropboxClient.Core.Metadata.MetadataAsync("/", list: false);
            Console.WriteLine("Root Folder: {0} (Id: {1})", rootFolder.Name, rootFolder.path);

            // Get root folder with content
            rootFolder = await dropboxClient.Core.Metadata.MetadataAsync("/", list: true);
            foreach (var folder in rootFolder.contents)
            {
                Console.WriteLine(" -> {0}: {1} (Id: {2})",
                    folder.is_dir ? "Folder" : "File", folder.Name, folder.path);
            }

            // Initialize a new Client (with an AccessToken)
            var client2 = new Client(options);

            // Find a file in the root folder
            var file = rootFolder.contents.FirstOrDefault(x => x.is_dir == false);
            var files = rootFolder.contents.ToList();

            // Download a file
            
            foreach (var item in files)
            {
                var tempFile = Path.GetTempFileName();
                if (item.path.Substring(item.path.Length - 4) == ".mp3")
                {
                    using (var fileStream = System.IO.File.OpenWrite(tempFile))
                    {

                        await client2.Core.Metadata.FilesAsync(item.path, fileStream);

                        fileStream.Flush();
                        fileStream.Close();
                    }

                    int length = item.path.Length;
                    string destination = item.path.Substring(0, length - 4) + ".mp3";
                    destination = AppDomain.CurrentDomain.BaseDirectory + destination.Substring(1);
                    System.IO.File.Copy(tempFile, destination, true);
                }
            }


            List<incident> Incidents = new List<incident>();

            IFirebaseConfig config = new FirebaseConfig
            {
                AuthSecret = "0dwRwB8V2QmJTM9NbKtWfqlys91LwZguvE67oS1f",
                BasePath = "https://fedup.firebaseio.com/"
            };

                //initialize new firebase client
            IFirebaseClient client = new FirebaseClient(config);

            bool hasNext = true;
            int counter = 1;
            do
            {
                try
                {
                    //pull current row
                    FirebaseResponse response = await client.GetAsync(counter.ToString());

                    //parse our json object
                    incident jsonObject = JsonConvert.DeserializeObject<incident>(response.Body);

                    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
                    dtDateTime = dtDateTime.AddSeconds(jsonObject.timestamp).ToLocalTime();

                    jsonObject.newTimeStamp = dtDateTime;

                    Incidents.Add(jsonObject);
                }
                catch
                {
                    hasNext = false;
                    break;
                }
                counter++;
            }
            while (hasNext);

            ViewBag.Incidents = Incidents;

            return View();
        }
Пример #3
0
        /// <summary>
        /// Will cause an immediate redirect
        /// </summary>
        private RedirectResult ConnectDropBox()
        {
            // Initialize a new Client (without an AccessToken)
            var client = new Client(options);

            // Get the OAuth Request Url
            var authRequestUrl = client.Core.OAuth2.AuthorizeAsync("code").Result;

            return Redirect(authRequestUrl.ToString());
        }
Пример #4
0
        private DropboxViewModel AuthorizeDropBox()
        {
            var authCode = Request.QueryString["code"];

            var client = new Client(options);

            var model = new DropboxViewModel();
            if (authCode != null) {
                try {
                    // Exchange the Authorization Code with Access/Refresh tokens
                    var token = client.Core.OAuth2.TokenAsync(authCode).Result;

                    // Get account info
                    var accountInfo = client.Core.Accounts.AccountInfoAsync().Result;
                    model.UID = accountInfo.uid.ToString();
                    model.DisplayName = accountInfo.display_name;
                    model.Email = accountInfo.email;

                    // Save the token to user settings
                    Service.UserSettings.SaveSetting(BaseUserSettingService.SettingKeys.DropboxToken, token.access_token,
                        GetCurrentUserGuid());
                } catch (AggregateException ex) {
                    model.DisplayName = ex.InnerException.Message;
                } catch (Exception ex) {
                    model.DisplayName = ex.Message;
                }
            } else {
                model.DisplayName = "Dropbox was not connected.";
            }

            return model;
        }
Пример #5
0
        public ActionResult UpdateSpreadsheet()
        {
            var success = false;
            var message = "";
            try {
                // Get necessary settings
                var dropboxToken = Service.UserSettings.GetByUserKey(BaseUserSettingService.SettingKeys.DropboxToken, GetCurrentUserGuid());
                if (dropboxToken == null) {
                    throw new Exception("Dropbox is not connected. Cannot update spreadsheet. Check your dropbox settings anad make sure you are connected.");
                }
                var dbPath = Service.UserSettings.GetByUserKey(BaseUserSettingService.SettingKeys.DropboxPath, GetCurrentUserGuid());
                var dbFile = Service.UserSettings.GetByUserKey(BaseUserSettingService.SettingKeys.DropboxFile, GetCurrentUserGuid());
                if (dbPath == null || dbFile == null) {
                    throw new Exception("Dropbox is not setup. Cannot update spreadsheet. Check your dropbox settings anad make sure you are connected.");
                }

                // Get the transactions
                var logins = BankDataService.Logins.GetHouseholdLoginIds(GetHouseholdIdForCurrentUser());
                var transactions = BankDataService.Transactions.GetThisMonthsTransactions(logins);

                // Get the xls file
                var options = new Options();
                options.AccessToken = dropboxToken.SettingValue;
                var client = new Client(options);

                byte[] budgetFile;
                var results = client.Core.Metadata.SearchAsync(dbPath.SettingValue, dbFile.SettingValue).Result;
                foreach (var searchResult in results) {
                    budgetFile = new byte[searchResult.bytes];
                    using (var stream = new MemoryStream()) {
                        client.Core.Metadata.FilesAsync(searchResult.path, stream).Wait();
                        budgetFile = stream.ToArray();
                    }

                    budgetFile = WorkingBudgetUpdater.Update(budgetFile, transactions);

                    // Replace file after update
                    using (var stream = new MemoryStream(budgetFile)) {
                        client.Core.Metadata.FilesPutAsync(stream, Path.Combine(dbPath.SettingValue, dbFile.SettingValue)).Wait();
                    }
                    break;
                }

                success = true;
                message = "Spreadsheet Update was successful";
            } catch (Exception ex) {
                message = ex.Message;
            }

            return PartialView("CallbackStatus", new CallbackStatusViewModel() {
                Success = success,
                Message = message
            });
        }
Пример #6
0
 public LargeFileUploader(Client client, Stream dataSource)
 {
     _client = client;
     _dataSource = dataSource;
 }
Пример #7
0
        private static async Task Run()
        {
            var options = new Options
                {
                    ClientId = "...",
                    ClientSecret = "...",
                    RedirectUri = "..."
                };

            // Initialize a new Client (without an AccessToken)
            var client = new Client(options);

            // Get the OAuth Request Url
            var authRequestUrl = await client.Core.OAuth2.AuthorizeAsync("code");

            // TODO: Navigate to authRequestUrl using the browser, and retrieve the Authorization Code from the response
            var authCode = "...";

            // Exchange the Authorization Code with Access/Refresh tokens
            var token = await client.Core.OAuth2.TokenAsync(authCode);

            // Get account info
            var accountInfo = await client.Core.Accounts.AccountInfoAsync();
            Console.WriteLine("Uid: " + accountInfo.uid);
            Console.WriteLine("Display_name: " + accountInfo.display_name);
            Console.WriteLine("Email: " + accountInfo.email);

            // Get root folder without content
            var rootFolder = await client.Core.Metadata.MetadataAsync("/", list: false);
            Console.WriteLine("Root Folder: {0} (Id: {1})", rootFolder.Name, rootFolder.path);

            // Get root folder with content
            rootFolder = await client.Core.Metadata.MetadataAsync("/", list: true);
            foreach (var folder in rootFolder.contents)
            {
                Console.WriteLine(" -> {0}: {1} (Id: {2})", 
                    folder.is_dir ? "Folder" : "File", folder.Name, folder.path);
            }

            // Initialize a new Client (with an AccessToken)
            var client2 = new Client(options);

            // Create a new folder
            var newFolder = await client2.Core.FileOperations.CreateFolderAsync("/New Folder");

            // Find a file in the root folder
            var file = rootFolder.contents.FirstOrDefault(x => x.is_dir == false);

            // Download a file
            var tempFile = Path.GetTempFileName();
            using (var fileStream = System.IO.File.OpenWrite(tempFile))
            {
                await client2.Core.Metadata.FilesAsync(file.path, fileStream);
            }

            //Upload the downloaded file to the new folder

            using (var fileStream = System.IO.File.OpenRead(tempFile))
            {
                var uploadedFile =await client2.Core.Metadata.FilesPutAsync(fileStream, newFolder.path + "/" + file.Name);
            }

            // Search file based on name
            var searchResults = await client2.Core.Metadata.SearchAsync("/", file.Name);
            foreach (var searchResult in searchResults)
            {
                Console.WriteLine("Found: " + searchResult.path);
            }
        }
Пример #8
0
        private async Task<bool> TestAccessToken(string accessToken)
        {
            var options = new Options
            {
                AccessToken = accessToken,
                ClientId = this._settings.DropboxClientId,
                ClientSecret = this._settings.DropboxClientSecret,
            };

            var client = new Client(new SavvyHttpClientFactory(), new RequestGenerator(),  options);

            try
            {
                await client.Core.Accounts.AccountInfoAsync();
                return true;
            }
            // ReSharper disable once CatchAllClause
            catch
            {
                return false;
            }
        }