Пример #1
0
        public AuthViewModel()
        {
            Activator = new ViewModelActivator();
            var canSignIn = this.WhenAnyValue(x => x.Username, x => x.Password,
                                              (u, p) => !u.Empty() && !p.Empty());

            this.WhenActivated(d => {
                d(Avatar        = ReactiveCommand.CreateAsyncObservable(_ => GetAvatar()));
                d(SignIn        = ReactiveCommand.CreateAsyncObservable(canSignIn, _ => Authenticate()));
                d(Registration  = ReactiveCommand.Create());
                d(ResetPassword = ReactiveCommand.Create());

                // External links
                d(Registration.Subscribe(_ => Process.Start("http://hummingbird.me/users/sign_up")));
                d(ResetPassword.Subscribe(_ => Process.Start("http://hummingbird.me/users/password/new")));

                // Handle when signing in was successful
                d(SignIn.Subscribe(token => {
                    // Save the correct user data to the secure cache
                    var account      = Service.Get <Account>();
                    account.Username = Username;
                    account.Token    = token;
                    account.Save();

                    // Sign in was successful, Tell the MainView to change the content view
                    MessageBus.Current.SendMessage(new MediaViewModel() as ReactiveObject, "Content");
                }));

                // Handle when an exception is thrown during the sign in process
                d(SignIn.ThrownExceptions
                  .Select(x => {
                    if (x is ApiException)
                    {
                        var ex = x as ApiException;
                        if (ex.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            return(new UserError("Check your credentials, and try again."));
                        }
                    }
                    return(new UserError("There was an issue authenticating with Hummingbird."));
                })
                  .SelectMany(UserError.Throw)
                  .Subscribe(_ => {
                    // Error was thrown to the handler, empty out the credentials
                    Username = "";
                    Password = "";

                    // will set the avatar back to blank hummingbird
                    Avatar.Execute(null);
                }));

                // Execute the Avatar command so that the default image is set on the view
                Avatar.Execute(null);
            });
        }