Ejemplo n.º 1
0
                            Environment.SpecialFolder.ApplicationData), "CloudManagerDB");   //zb:"C:\\Users\\Michael\\AppData\\Roaming\\CloudManagerDB

        private async void OnAuthCompleted()
        {
            Thread t = null;
            client.GetAccessTokenAsync((userLogin) =>
            {
                //Save the Token and Secret we get here to save future logins
                _userLogin = userLogin;

                //_client = new DropNetClient(apiKey, appSecret, _userLogin.Token, _userLogin.Secret, null);
                t = Thread.CurrentThread;
                this.SaveSecrets();
                //SignedIn = true;
            },
                     (error) =>
                     {
                         /////////////////////
                     });

            Thread.Sleep(5000);     //Thread dauaert zu lange daher noch stoppen.
            //while (t.ThreadState == ThreadState.Running);
            
            
            if(this.loginFinished != null)
            {
                this.loginFinished();
            }
            
        }
Ejemplo n.º 2
0
 public UserLogin GetAccessToken(string code, string redirectUri)
 {
     RestRequest request = _requestHelper.CreateOAuth2AccessTokenRequest(code, redirectUri, _apiKey, _appsecret);
     var response = Execute<OAuth2AccessToken>(ApiType.Base, request);
     var userLogin = new UserLogin { Token = response.Access_Token };
     UserLogin = userLogin;
     return userLogin;
 }
Ejemplo n.º 3
0
        public DropNetClient(string apiKey, string appSecret, string userToken, string userSecret)
        {
            _apiKey = apiKey;
            _appsecret = appSecret;

            _userLogin = new UserLogin { Token = userToken, Secret = userSecret };

            LoadClient();
        }
Ejemplo n.º 4
0
 public void GetAccessTokenAsync(Action<UserLogin> success, Action<DropboxException> failure, string code, string redirectUri)
 {
     RestRequest request = _requestHelper.CreateOAuth2AccessTokenRequest(code, redirectUri, _apiKey, _appsecret);
     ExecuteAsync<OAuth2AccessToken>(ApiType.Base, request, response =>
     {
         var userLogin = new UserLogin { Token = response.Access_Token };
         UserLogin = userLogin;
         success(userLogin);
     }, failure);
 }
Ejemplo n.º 5
0
 public bool SaveDropboxToken(UserLogin userLogin)
 {
     if (!CheckForPrefs()) //true if no prefs exist
         return CreateDropboxOnlyPrefs(userLogin);
     var saver = new PrefSaver();
     var prefs = saver.LoadPrefs();
     prefs.UserSecret = userLogin.Secret;
     prefs.UserToken = userLogin.Token;
     saver.SavePrefs(prefs);
     return true;
 }
Ejemplo n.º 6
0
        private static void SaveToken(UserLogin user)
        {
            var appSettings = IsolatedStorageSettings.ApplicationSettings;
            const string userToken = "userToken";

            if (appSettings.Contains(userToken))
            {
                appSettings.Remove(userToken);
            }

            appSettings.Add(userToken, user);
            appSettings.Save();
        }
Ejemplo n.º 7
0
        private void LoginCompleted(UserLogin info)
        {
            Dispatcher.BeginInvoke(() =>
            {
                progBusy.IsBusy = false;

                txtPassword.Password = string.Empty;

                var folder = NavigationContext
                    .QueryString["folder"];

                this.NavigateTo<List>(
                    "token={0}&secret={1}&path=/&folder={2}",
                    info.Token, info.Secret, folder);
            });
        }
Ejemplo n.º 8
0
        public DropStorage(Action<string> webViewCallback)
        {
            _webViewCallback = webViewCallback;

            _client = new DropNetClient(DROPBOX_APP_KEY, DROPBOX_APP_SECRET);

            //Get Request Token 
            _client.GetToken();

            var authUri = _client.BuildAuthorizeUrl();
            //Process.Start(authUri);
            _webViewCallback(authUri);

            //don't need it, web view callback is blocking 
            //var dlg = new AuthDlg(StorageType.Dropbox);
            //dlg.ShowDialog();

            _accessToken = _client.GetAccessToken(); //Store this token for "remember me" function
        }
Ejemplo n.º 9
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _client = new DropNetClient("zta6zq4gmjrjz6y", "30qfyt4yzwcltlj");

            if (File.Exists("accessToken.json"))
            {
                var json = File.ReadAllText("accessToken.json");
                _accessToken = JsonConvert.DeserializeObject<UserLogin>(json);
                _client.UserLogin = _accessToken;
                GetMetaData();
            }
            else
            {
                _client.GetToken();
                var url = _client.BuildAuthorizeUrl();
                dropboxPermissionsPanel.Visibility = Visibility.Visible;
                regularPanel.Visibility = Visibility.Hidden;
                webBrowser.Navigate(url);
            }
        }
Ejemplo n.º 10
0
        private void brwLogin_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.Host.Contains("google"))
            {
                //Callback url reached, user has completed authorization

                //Now convert the request token into an access token
                _client.GetAccessTokenAsync((userLogin) =>
                    {
                        //Save the Token and Secret we get here to save future logins
                        _userLogin = userLogin;

                        LoadContents();
                    },
                    (error) =>
                    {
                        //Some sort of error
                        MessageBox.Show(error.Response.Content);
                    });
            }
        }
Ejemplo n.º 11
0
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            _browser.Navigating += _browser_Navigating;
            _browser.Navigated += _browser_Navigated;
            _browser.LoadCompleted += BrowserOnLoadCompleted;

            if (_browser.Source != null && _browser.Source.AbsoluteUri.Contains("verify_code"))
            {
                return;
            }

            _client.GetTokenAsync(userLogin =>
                                      {
                                          _userLogin = userLogin;
                                          const string redirectUrl = "http://" + RedirectUrl;
                                          var url = _client.BuildAuthorizeUrl(_userLogin, redirectUrl);
                                          _browser.Navigate(new Uri(url));
                                      },
                                      error => MessageBox.Show(Labels.ConnectionErrorMessage, Labels.ConnectionErrorTitle, MessageBoxButton.OK));
        }
Ejemplo n.º 12
0
        public UserLogin PostWebAuth(string token)
        {
            _restClient.BaseUrl = _apiBaseUrl;
            _restClient.Authenticator = new OAuthAuthenticator(_restClient.BaseUrl, _apiKey, _appsecret, token, "");

            var request = _requestHelper.CreateAccessToken();

            var response = _restClient.Execute(request);

            int idx, end;
            String KeySecret = "oauth_token_secret=";
            String KeyToken = "oauth_token=";

            UserLogin = new UserLogin();

            // Get secret
            idx = response.Content.LastIndexOf(KeySecret);
            if (idx == -1)
                return null;
            idx += KeySecret.Length;
            end = response.Content.IndexOf('&', idx);
            if (end == -1)
                end = response.Content.Length;
            UserLogin.Secret = response.Content.Substring(idx, end - idx);

            // Get token
            idx = response.Content.LastIndexOf(KeyToken);
            if (idx == -1)
                return null;
            idx += KeyToken.Length;
            end = response.Content.IndexOf('&', idx);
            if (end == -1)
                end = response.Content.Length;
            UserLogin.Token = response.Content.Substring(idx, end - idx);

            return UserLogin;
        }
Ejemplo n.º 13
0
 private bool CreateDropboxOnlyPrefs(UserLogin userLogin)
 {
     if (userLogin != null) {
         var prefs = new UserPrefs {UserSecret = userLogin.Secret, UserToken = userLogin.Token};
         SavePrefs(prefs);
         return true;
     }
     return false;
 }
Ejemplo n.º 14
0
 public static void ClearUserLogin()
 {
     _userToken = null;
     IsolatedStorageSettings.ApplicationSettings.Remove("userToken");
     IsolatedStorageSettings.ApplicationSettings.Save();
 }
Ejemplo n.º 15
0
 private static void Download(UserLogin login, Action<RestResponse> callback)
 {
     Validate(login);
     _client.GetFile("/BingleMaps.dat", callback);
 }
Ejemplo n.º 16
0
 private void SaveUserLogin(UserLogin userLogin) {
     var result = _prefSaver.SaveDropboxToken(userLogin);
     if (!result) MessageBox.Show(@"Failed to save Dropbox Token. Contact the app designer.");
 }
Ejemplo n.º 17
0
 public String GetMedialUrl(string path, AuthCredential credential)
 {
     if (String.IsNullOrEmpty(path))
     {
         return null;
     }
     var _client = new DropNetClient(MogConstants.DROPBOX_KEY, MogConstants.DROPBOX_SECRET);
     UserLogin User = new UserLogin() { Token = credential.Token, Secret = credential.Secret };
     _client.UserLogin = User;
     _client.UseSandbox = true;
     ShareResponse response = _client.GetMedia(path);
     return (response != null ? response.Url : null);
 }
Ejemplo n.º 18
0
 private static void Upload(UserLogin login, ObservableCollection<UserPin> userPins, Action<RestResponse> callback)
 {
     Validate(login);
     _client.UploadFileAsync("/", "BingleMaps.dat", SilverlightSerializer.Serialize(userPins), callback);
 }
Ejemplo n.º 19
0
        private MetaData Upload(byte[] data, string filename, AuthCredential credential, string remotePath = null)
        {
            UserLogin User = new UserLogin() { Token = credential.Token, Secret = credential.Secret };

            string file = System.IO.Path.GetFileName(filename);

            var _client = new DropNetClient(MogConstants.DROPBOX_KEY, MogConstants.DROPBOX_SECRET);
            _client.UserLogin = User;
            _client.UseSandbox = true;
            if (String.IsNullOrEmpty(remotePath))
            {
                remotePath = "/";
            }
            var uploaded = _client.UploadFile(remotePath, file, data); //FileInfo

            return uploaded;
        }
Ejemplo n.º 20
0
 private static void Validate(UserLogin login)
 {
     if (login == null)
     {
         throw new ArgumentException(@"login cannot be null.", "login");
     }
     if (_client == null)
     {
         _client = new DropNetClient(ApiKey, AppSecret, login.Token, login.Secret);
     }
 }
Ejemplo n.º 21
0
        public static void Sync(UserLogin login, UserPinLog log, Action<HttpStatusCode> callback)
        {
            // Download data from server first.
            Download(login, downloadRsp =>
            {
                // Check if download is successful.
                if (downloadRsp.StatusCode == HttpStatusCode.NotFound)
                {
                    // If there is no online data, just upload local.
                    Upload(login, log.Pins, uploadRsp => SyncCallback(ref log, uploadRsp.StatusCode, callback));
                }
                else if (downloadRsp.StatusCode != HttpStatusCode.OK)
                {
                    SyncCallback(ref log, downloadRsp.StatusCode, callback);
                }
                else
                {
                    // If download is successful, try deserialize the data.
                    ObservableCollection<UserPin> onlinePins;
                    try
                    {
                        onlinePins = (ObservableCollection<UserPin>)SilverlightSerializer.Deserialize(downloadRsp.RawBytes);
                    }
                    catch
                    {
                        // If serialization fails, then the online data file might be corrupted.
                        // In this case, re-upload local pins to overwrite the online data file.
                        Upload(login, log.Pins, uploadRsp => SyncCallback(ref log, uploadRsp.StatusCode, callback));
                        return;
                    }
                    if (onlinePins.Count == 0)
                    {
                        // If online doesn't have pins, just upload local.
                        Upload(login, log.Pins, uploadRsp => SyncCallback(ref log, uploadRsp.StatusCode, callback));
                    }
                    else if (log.Pins.Count == 0 && log.Changes.Count == 0)
                    {
                        // If local doesn't have pins, just replace with online.
                        log.Pins = onlinePins;
                        callback(HttpStatusCode.OK);
                    }
                    else
                    {
                        // Worst case, do delta checks and update accordingly.
                        UserPin tempPin;
                        UserPinChange change;

                        // Process each online pin.
                        foreach (var onlinePin in onlinePins)
                        {
                            // Check if the local pin list contains the current online pin.
                            tempPin = log.GetPin(onlinePin.Key);
                            if (tempPin != null)
                            {
                                continue;
                            }
                            // If local doesn't have this online pin, check if this pin has been deleted locally.
                            change = log.GetChange(onlinePin.Key);
                            if (change == null)
                            {
                                // If the pin is not in the chagne list, then this pin is added by another source and synced to the online place.
                                // Add this pin to the local list, without logging it into the change list.
                                onlinePin.IsEditing = false;
                                log.Pins.Add(onlinePin);
                            }
                            else if (change.Action == UserPinAction.Delete)
                            {
                                // If the pin is in the chagne list, and the pin is marked for deletion,
                                // ignore adding this pin as it's supposed to be deleted.
                                continue;
                            }
                            else
                            {
                                // If none of the above happens, then there's something wrong, throw the exception.
                                throw new InvalidOperationException("There shouldn't be the case that an online user pin is missing from local list and the registered local change action for this pin is not deletion.");
                            }
                        }

                        var removeList = new Collection<UserPin>();
                        // Process each local pin.
                        foreach (var localPin in log.Pins)
                        {
                            // Check if the online pin list contains the current local pin.
                            tempPin = onlinePins.GetUserPin(localPin.Key);
                            if (tempPin != null)
                            {
                                continue;
                            }
                            // If online doesn't have this local pin, check if this pin is newly added.
                            change = log.GetChange(localPin.Key);
                            if (change == null)
                            {
                                // If this local pin is not in the change list, then this pin is removed by another source and synced to the online place.
                                // Add it to the pending remove list.
                                removeList.Add(localPin);
                            }
                            else if (change.Action == UserPinAction.Add)
                            {
                                // If the pin is in the change list, and the pin is marked as newly added,
                                // ignore removing this pin as it's supposed to be added.
                                continue;
                            }
                            else
                            {
                                // If none of the above happens, then there's somehting wrong, throw the exception.
                                throw new InvalidOperationException("There shouldn't be the case that an local user pin is missing from the online list and the registered local change action is not addition.");
                            }
                        }

                        // Remove pins from the pending removal list.
                        foreach (var localPin in removeList)
                        {
                            log.Pins.Remove(localPin);
                        }

                        // Clear pending removal list.
                        removeList.Clear();

                        // We are done syncing the pins locally, upload them now.
                        Upload(login, log.Pins, uploadRsp => SyncCallback(ref log, uploadRsp.StatusCode, callback));
                    }
                }
            });
        }
Ejemplo n.º 22
0
        private void WebBrowser1OnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.Hide();
            if (e.Url.Host.Contains("google"))
            {
                client.GetAccessTokenAsync(
                    user =>
                {
                    userLogin = user;
                    Invoke((MethodInvoker)
                    delegate
                    {
                        webBrowser1.Visible = false;
                    });

                    AccountInfo x = client.AccountInfo();

                    MessageBox.Show(x.display_name.ToString());
                },
                    error =>
                    {
                        var xError = error as DropboxRestException;
                        if (xError != null)
                        {
                            MessageBox.Show(xError.Response.Content);
                        }
                        else
                        {
                            MessageBox.Show(error.Message);
                        }
                    });
            }
        }
Ejemplo n.º 23
0
        void UserLoginParam(UserLogin userLogin)
        {
            //Dont need to do anything here with userLogin if we keep the same instance of DropNetClient

            //Now generate the url for the user to authorize the app

            App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,new Action(DoIt));
            
   
        }
Ejemplo n.º 24
0
        public Task<bool> SignIn()
        {
            // Get dropbox _client.
            this.tcs = new TaskCompletionSource<bool>();
            this._client = new DropNetClient(DROPBOX_CLIENT_KEY, DROPBOX_CLIENT_SECRET);

            // If dropbox user exists, get it.
            // Otherwise, get from user.
            UserLogin dropboxUser = null;
            if (App.ApplicationSettings.Contains(DROPBOX_USER_KEY))
                dropboxUser = (UserLogin)App.ApplicationSettings[DROPBOX_USER_KEY];

            if (dropboxUser != null)
            {
                this._client.UserLogin = dropboxUser;
                this._client.AccountInfoAsync((info) =>
                {
                    this.CurrentAccount = new StorageAccount(info.uid.ToString(), StorageAccount.StorageAccountType.DROPBOX, info.display_name, 0.0);
                    TaskHelper.AddTask(TaskHelper.STORAGE_EXPLORER_SYNC + this.GetStorageName(), StorageExplorer.Synchronize(this.GetStorageName()));
                    tcs.SetResult(true);                
                }, (fail) =>
                {
                    this.CurrentAccount = null;
                    tcs.SetResult(false);
                });
            }
            else
            {
                this._client.GetTokenAsync(async (userLogin) =>
                {
                    string authUri = this._client.BuildAuthorizeUrl(DROPBOX_AUTH_URI);
                    DropboxWebBrowserTask webBrowser = new DropboxWebBrowserTask(authUri);
                    await webBrowser.ShowAsync();

                    this._client.GetAccessTokenAsync(async (accessToken) =>
                    {
                        UserLogin user = new UserLogin();
                        user.Token = accessToken.Token;
                        user.Secret = accessToken.Secret;
                        this._client.UserLogin = user;

                        // Save dropbox user got and sign in setting.
                        try
                        {
                            this.CurrentAccount = await this.GetMyAccountAsync();

                            StorageAccount account = await App.AccountManager.GetStorageAccountAsync(this.CurrentAccount.Id);
                            if (account == null)
                                await App.AccountManager.CreateStorageAccountAsync(this.CurrentAccount);

                            App.ApplicationSettings[DROPBOX_SIGN_IN_KEY] = true;
                            App.ApplicationSettings[DROPBOX_USER_KEY] = user;
                            App.ApplicationSettings.Save();
                            TaskHelper.AddTask(TaskHelper.STORAGE_EXPLORER_SYNC + this.GetStorageName(), StorageExplorer.Synchronize(this.GetStorageName()));
                            tcs.SetResult(true);
                        }
                        catch
                        {
                            tcs.SetResult(false);
                        }
                    },
                    (error) =>
                    {
                        Debug.WriteLine(error.ToString());
                        tcs.SetResult(false);
                    });
                },
               (error) =>
               {
                   tcs.SetResult(false);
               });
            }
            return tcs.Task;
        }
Ejemplo n.º 25
0
        public void RegisterAccount(int tempCredentialId)
        {
            AuthCredential partialCredential = this.repoAuthCredential.GetById(tempCredentialId);

            try
            {
                UserLogin lg = new UserLogin { Token = partialCredential.Token, Secret = partialCredential.Secret };
                DropNetClient client = new DropNetClient(MogConstants.DROPBOX_KEY, MogConstants.DROPBOX_SECRET);
                client.UserLogin = lg;
                UserLogin accessToken = client.GetAccessToken();

                partialCredential.Token = accessToken.Token;
                partialCredential.Secret = accessToken.Secret;
                partialCredential.Status = CredentialStatus.Approved;
                this.repoAuthCredential.SaveChanges(partialCredential);
            }
            catch (DropNet.Exceptions.DropboxException exc)
            {//
                this.repoAuthCredential.Delete(partialCredential);
                throw new Exception("failed to register accoutn", exc);
            }
        }