Exemple #1
0
        public override void UpdateCache()
        {
            var account = mastodonClient.GetCurrentUser().Result;

            IDCache = account.UserName;
            Name    = account.DisplayName;
        }
        /// <summary>
        /// 登録された情報でクライアントを作成して返します。エラー発生時は null を返します。
        /// </summary>
        /// <param name="showError">エラー発生時にメッセージボックスを出力するか。</param>
        /// <param name="control">プログレスバーの存在するコントロール。</param>
        /// <param name="progressBar">進捗状況を表示するプログレスバー。</param>
        /// <returns>作成したクライアント。エラー発生時は null を返します。</returns>
        public async Task <MastodonClient> CreateClient(bool showError, Control control = null, ProgressBar progressBar = null)
        {
            // Mastodon Instance へのアプリケーションの登録
            AuthenticationClient authClient;
            AppRegistration      appRegistration;

            try
            {
                authClient      = new AuthenticationClient(instance);
                appRegistration = await authClient.CreateApp(Assembly.GetExecutingAssembly().GetName().Name, Scope.Read | Scope.Write | Scope.Follow);
            }
            catch (Exception e)
            {
                logger.ErrorFormat($"{instance}: サーバ接続に失敗 - {e.Message}");
                if (showError)
                {
                    Utilities.ShowError($"{instance} に接続できません。\nドメイン名を確認してください。");
                }
                return(null);
            }
            control?.Invoke((MethodInvoker)(() => progressBar.Value = 33));

            // アクセストークンの取得
            Auth auth;

            try
            {
                auth = await authClient.ConnectWithPassword(email, password);
            }
            catch (Exception e)
            {
                logger.ErrorFormat($"{instance}: アカウントへの接続に失敗 - {e.Message}");
                if (showError)
                {
                    Utilities.ShowError("アカウントに接続できません。\nメールアドレス・パスワードを確認してください。");
                }
                return(null);
            }
            control?.Invoke((MethodInvoker)(() => progressBar.Value = 66));

            // クライアントを作成
            client = new MastodonClient(appRegistration, auth);
            var user = await client.GetCurrentUser();

            AccountName = $"{user.UserName}@{instance}";
            Icon        = user.AvatarUrl;
            control?.Invoke((MethodInvoker)(() => progressBar.Value = 100));
            return(client);
        }
Exemple #3
0
        private async Task Run()
        {
            Dictionary <string, string> uri_list = new Dictionary <string, string>();

            var appRegistration = new AppRegistration {
                Instance     = hostName,
                ClientId     = clientId,
                ClientSecret = clientSecret,
                Scope        = Scope.Read | Scope.Write
            };
            var authClient = new AuthenticationClient(appRegistration);

            var auth = await authClient.ConnectWithPassword(mail, pass);

            client = new MastodonClient(appRegistration, auth);

            var account = await client.GetCurrentUser();

            this.userId = account.AccountName;

            // LTL処理
            streaming           = client.GetLocalStreaming();
            streaming.OnUpdate += (sender, e) => {
                TextWrite(e.Status);
            };

            //通知処理
            homeStreaming = client.GetUserStreaming();
            homeStreaming.OnNotification += (sender, e) => {
                NotificationWrite(e.Notification);
            };

            // メディア処理用
            media = new MediaEditClass(ref client);

            Timer timer = new Timer();

            timer.Interval = DefaultValues.TOOTS_INTERVAL;
            timer.Tick    += (object sender, EventArgs e) => {
                // トゥート回数のリセット
                tootsCounter = 0;
            };
            timer.Start();

            streaming.Start();
            homeStreaming.Start();
        }
        public async IAsyncEnumerable <StatusUpdate> GetStatusUpdatesAsync()
        {
            var self = await _client.GetCurrentUser();

            string max_id = "";

            while (true)
            {
                var statuses = await _client.GetHomeTimeline(max_id);

                if (!statuses.Any())
                {
                    break;
                }

                foreach (var s in statuses)
                {
                    var author = new Author {
                        Username   = s.Account.UserName,
                        AvatarUrl  = s.Account.AvatarUrl,
                        ProfileUrl = s.Account.ProfileUrl
                    };
                    yield return(new StatusUpdate {
                        Host = Host,
                        Id = s.Id,
                        CanDelete = s.Account.Id == self.Id,
                        Author = author,
                        Timestamp = s.CreatedAt,
                        LinkUrl = s.Url,
                        Html = !string.IsNullOrEmpty(s.SpoilerText)
                            ? WebUtility.HtmlEncode(s.SpoilerText)
                            : s.Content,
                        AdditionalImages = s.MediaAttachments.Select(m => new StatusUpdateMedia {
                            ImageUrl = m.Url,
                            LinkUrl = m.Url,
                            AltText = m.Description
                        }).ToList(),
                        RepostedFrom = s.Reblog?.Account?.UserName
                    });
                }
                max_id = statuses.NextPageMaxId;
            }
        }
Exemple #5
0
        public AccountPanelViewModel(Config config)
        {
            Clients = config.Clients;

            var appRegistration = new ReactiveProperty<AppRegistration>();
            var authClient = new ReactiveProperty<AuthenticationClient>();

            Domain = new ReactiveProperty<string>();

            var canExecuteAuthCommand = Domain.Select(x => !string.IsNullOrWhiteSpace(x));
            AuthCommand = new ReactiveCommand(canExecuteAuthCommand);
            AuthCommand.Subscribe(async () =>
            {
                authClient.Value = new AuthenticationClient(Domain.Value);
                appRegistration.Value = await authClient.Value.CreateApp("Mayodon Client", Scope.Read);
                System.Diagnostics.Process.Start(authClient.Value.OAuthUrl());
            });

            AuthCode = new ReactiveProperty<string>();
            OKCommand = Observable.CombineLatest(
                appRegistration.Select(x => x != null),
                AuthCode.Select(x => !string.IsNullOrWhiteSpace(x)),
                (x, y) => x & y).ToReactiveCommand();
            OKCommand.Subscribe(async () =>
            {
                var auth = await authClient.Value.ConnectWithCode(AuthCode.Value);
                var client = new MastodonClient(appRegistration.Value, auth);
                var account = await client.GetCurrentUser();

                config.Clients.Add(new Client()
                {
                    App = appRegistration.Value,
                    Auth = auth,
                    Account = account
                });

                config.Save();

                Domain.Value = "";
                AuthCode.Value = "";
            });                
        }
        private async void AuthorizeWithCallback(string oauthVerifier)
        {
            if (_authorizeStep == AuthorizeStep.TwitterAuthorize)
            {
                Tokens tokens;
                try
                {
                    tokens = await _twitterOAuthSettion.GetTokensAsync(oauthVerifier);
                }
                catch
                {
                    await new MessageDialog(_resourceLoader.GetString("AuthorizePopup_OAuthAuthorizeError"))
                    .ShowAsync();
                    return;
                }
                finally
                {
                    AuthorizePopupAuthorizeButton.IsEnabled = true;
                }

                _accountInfo = new AccountInfo
                {
                    ConsumerKey       = tokens.ConsumerKey,
                    ConsumerSecret    = tokens.ConsumerSecret,
                    AccessToken       = tokens.AccessToken,
                    AccessTokenSecret = tokens.AccessTokenSecret,
                    ScreenName        = tokens.ScreenName,
                    UserId            = tokens.UserId,
                    Service           = "Twitter",
                    Instance          = ""
                };
            }
            else if (_authorizeStep == AuthorizeStep.MastodonAuthorize)
            {
                try
                {
                    var auth = await _mastodonOauthSettion.ConnectWithCode(oauthVerifier);

                    var client = new MastodonClient(_mastodonAppRegistration, auth);
                    var user   = await client.GetCurrentUser();

                    _accountInfo = new AccountInfo
                    {
                        ConsumerKey       = _mastodonAppRegistration.ClientId,
                        ConsumerSecret    = _mastodonAppRegistration.ClientSecret,
                        AccessToken       = auth.AccessToken,
                        AccessTokenSecret = "",
                        ScreenName        = user.UserName,
                        UserId            = user.Id,
                        Service           = "Mastodon",
                        Instance          = _mastodonOauthSettion.Instance
                    };
                }
                catch
                {
                    await new MessageDialog(_resourceLoader.GetString("AuthorizePopup_OAuthAuthorizeError"))
                    .ShowAsync();
                    return;
                }
                finally
                {
                    AuthorizePopupAuthorizeButton.IsEnabled = true;
                }
            }

            _authorizeStep = AuthorizeStep.Exit;
        }
        private async void AuthorizePopupAuthorizeButton_Click(object sender, RoutedEventArgs e)
        {
            var pin = AuthorizePopupAuthorizePinTextBox.Text.Trim();

            if (string.IsNullOrWhiteSpace(pin))
            {
                await new MessageDialog(_resourceLoader.GetString("AuthorizePopup_PincodeIsEmpty")).ShowAsync();
                return;
            }

            AuthorizePopupAuthorizeButton.IsEnabled = false;

            if (_authorizeStep == AuthorizeStep.TwitterAuthorize)
            {
                try
                {
                    var tokens = await _twitterOAuthSettion.GetTokensAsync(pin);

                    _accountInfo = new AccountInfo
                    {
                        ConsumerKey       = tokens.ConsumerKey,
                        ConsumerSecret    = tokens.ConsumerSecret,
                        AccessToken       = tokens.AccessToken,
                        AccessTokenSecret = tokens.AccessTokenSecret,
                        ScreenName        = tokens.ScreenName,
                        UserId            = tokens.UserId,
                        Service           = "Twitter",
                        Instance          = ""
                    };
                }
                catch
                {
                    await new MessageDialog(_resourceLoader.GetString("AuthorizePopup_OAuthAuthorizeError"))
                    .ShowAsync();
                    return;
                }
                finally
                {
                    AuthorizePopupAuthorizeButton.IsEnabled = true;
                }
            }
            else if (_authorizeStep == AuthorizeStep.MastodonAuthorize)
            {
                try
                {
                    var auth = await _mastodonOauthSettion.ConnectWithCode(pin);

                    var client = new MastodonClient(_mastodonAppRegistration, auth);
                    var user   = await client.GetCurrentUser();

                    _accountInfo = new AccountInfo
                    {
                        ConsumerKey       = _mastodonAppRegistration.ClientId,
                        ConsumerSecret    = _mastodonAppRegistration.ClientSecret,
                        AccessToken       = auth.AccessToken,
                        AccessTokenSecret = "",
                        ScreenName        = user.UserName,
                        UserId            = user.Id,
                        Service           = "Mastodon",
                        Instance          = _mastodonOauthSettion.Instance
                    };
                }
                catch
                {
                    await new MessageDialog(_resourceLoader.GetString("AuthorizePopup_OAuthAuthorizeError"))
                    .ShowAsync();
                    return;
                }
                finally
                {
                    AuthorizePopupAuthorizeButton.IsEnabled = true;
                }
            }

            _authorizeStep = AuthorizeStep.Exit;
        }
        public async Task LoginOauth()
        {
            if (string.IsNullOrEmpty(Server))
            {
                return;
            }
            IsLoading = true;
            try
            {
                var appRegistration = await GetAppRegistration();

                var authClient = new AuthenticationClient(appRegistration);
                var oauthUrl   = authClient.OAuthUrl((string.Format(_serverRedirect, Server)));
                var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.None,
                    new Uri(oauthUrl),
                    new System.Uri(string.Format(_serverRedirect, Server)));

                string result;
                string code = "";
                switch (webAuthenticationResult.ResponseStatus)
                {
                case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success:
                    // Successful authentication.
                    result = webAuthenticationResult.ResponseData.ToString();
                    var query    = QueryString.Parse(result);
                    var testCode = query.FirstOrDefault();
                    code = testCode?.Value;
                    break;

                case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp:
                    // HTTP error.
                    result = webAuthenticationResult.ResponseErrorDetail.ToString();
                    break;

                default:
                    // Other error.
                    result = webAuthenticationResult.ResponseData.ToString();
                    break;
                }

                if (string.IsNullOrEmpty(code))
                {
                    // TODO Add error screen
                }
                else
                {
                    var auth = await authClient.ConnectWithCode(code, string.Format(_serverRedirect, Server));

                    SettingsService.UserAuth = auth;
                    var client  = new MastodonClient(appRegistration, auth);
                    var account = await client.GetCurrentUser();

                    SettingsService.UserAccount             = account;
                    SettingsService.Instance.ServerInstance = Server;
                    IsLoggedIn = true;

                    if (App.IsTenFoot)
                    {
                        // NavigationService.Navigate(typeof(XboxViews.MainPage));
                    }
                    else
                    {
                        Views.Shell.Instance.ViewModel.IsLoggedIn = true;
                        NavigationService.Navigate(typeof(Views.MainPage));
                    }
                }
            }
            catch (Exception e)
            {
                await MessageDialogMaker.SendMessageDialogAsync(e.Message, false);
            }

            //var authUri = $"https://{Server}/oauth/authorize?response_type=code&client_id="

            IsLoading = false;
        }
Exemple #9
0
 private async Task <Account> GetCurrentUser()
 {
     Logger.NLogInfo($"GetCurrentUser on {Instance}.");
     return(await client.GetCurrentUser());
 }