/// <summary>
        /// HTTP Get request for stream service.
        /// </summary>
        /// <param name="requestUri">Uri to make OAuth request.</param>
        /// <param name="tokens">Tokens to pass in request.</param>
        /// <param name="callback">Function invoked when stream available.</param>
        /// <param name="signatureManager">Signature manager to sign the OAuth requests</param>
        /// <returns>awaitable task</returns>
        public async Task ExecuteGetStreamAsync(Uri requestUri, TwitterOAuthTokens tokens, TwitterStreamCallbacks.RawJsonCallback callback, ISignatureManager signatureManager)
        {
            using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
            {
                var requestBuilder = new TwitterOAuthRequestBuilder(requestUri, tokens, signatureManager);

                request.Headers.Authorization = AuthenticationHeaderValue.Parse(requestBuilder.AuthorizationHeader);

                using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
                {
                    response.ThrowIfNotValid();
                    var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                    using (var reader = new StreamReader(responseStream))
                    {
                        while (!_abort && !reader.EndOfStream)
                        {
                            var result = reader.ReadLine();

                            if (!string.IsNullOrEmpty(result))
                            {
                                callback?.Invoke(result);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// HTTP Post request to specified Uri.
        /// </summary>
        /// <param name="requestUri">Uri to make OAuth request.</param>
        /// <param name="tokens">Tokens to pass in request.</param>
        /// <param name="boundary">Boundary used to separate data.</param>
        /// <param name="content">Data to post to server.</param>
        /// <param name="signatureManager">Signature manager to sign the OAuth requests</param>
        /// <returns>String result.</returns>
        public async Task <string> ExecutePostMultipartAsync(Uri requestUri, TwitterOAuthTokens tokens, string boundary, byte[] content, ISignatureManager signatureManager)
        {
            JsonElement mediaId = default;

            try
            {
                using var multipartFormDataContent = new MultipartFormDataContent(boundary);
                using var byteContent = new ByteArrayContent(content);
                multipartFormDataContent.Add(byteContent, "media");

                using var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
                var requestBuilder = new TwitterOAuthRequestBuilder(requestUri, tokens, signatureManager, "POST");

                request.Headers.Authorization = AuthenticationHeaderValue.Parse(requestBuilder.AuthorizationHeader);

                request.Content = multipartFormDataContent;

                using var response = await client.SendAsync(request).ConfigureAwait(false);

                response.ThrowIfNotValid();
                using var jsonResult = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                var jObj = await JsonDocument.ParseAsync(jsonResult).ConfigureAwait(false);

                mediaId = jObj.RootElement.GetProperty("media_id_string");
            }
            catch (ObjectDisposedException)
            {
                // known issue
                // http://stackoverflow.com/questions/39109060/httpmultipartformdatacontent-dispose-throws-objectdisposedexception
            }

            return(mediaId.ToString());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TwitterOAuthRequestBuilder"/> class.
        /// Authorization request builder.
        /// </summary>
        /// <param name="requestUri">Request Uri.</param>
        /// <param name="tokens">Tokens to form request.</param>
        /// <param name="signatureManager">Signature manager to sign the OAuth request</param>
        /// <param name="method">Method to use with request.</param>
        public TwitterOAuthRequestBuilder(Uri requestUri, TwitterOAuthTokens tokens, ISignatureManager signatureManager, string method = "GET")
        {
            _signatureManager = signatureManager;
            Verb = method;

            RequestUriWithoutQuery = new Uri(requestUri.AbsoluteWithoutQuery());

            if (!string.IsNullOrEmpty(requestUri.Query))
            {
                QueryParams = requestUri.GetQueryParams()
                              .Select(p => new OAuthParameter(p.Key, Uri.UnescapeDataString(p.Value)))
                              .ToList();
            }
            else
            {
                QueryParams = new List <OAuthParameter>();
            }

            EncodedRequestUri = GetEncodedUri(requestUri, QueryParams);

            Version         = new OAuthParameter("oauth_version", "1.0");
            Nonce           = new OAuthParameter("oauth_nonce", GenerateNonce());
            Timestamp       = new OAuthParameter("oauth_timestamp", GenerateTimeStamp());
            SignatureMethod = new OAuthParameter("oauth_signature_method", "HMAC-SHA1");
            ConsumerKey     = new OAuthParameter("oauth_consumer_key", tokens.ConsumerKey);
            ConsumerSecret  = new OAuthParameter("oauth_consumer_secret", tokens.ConsumerSecret);
            Token           = new OAuthParameter("oauth_token", tokens.AccessToken);
            TokenSecret     = new OAuthParameter("oauth_token_secret", tokens.AccessTokenSecret);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TwitterDataProvider"/> class.
        /// Constructor.
        /// </summary>
        /// <param name="tokens">OAuth tokens for request.</param>
        /// <param name="authenticationBroker">Authentication result interface.</param>
        /// <param name="passwordManager">Platform password manager</param>
        /// <param name="storageManager">Platform storage provider</param>
        /// <param name="signatureManager">Platform signature manager</param>
        public TwitterDataProvider(TwitterOAuthTokens tokens, IAuthenticationBroker authenticationBroker, IPasswordManager passwordManager, IStorageManager storageManager, ISignatureManager signatureManager)
        {
            if (string.IsNullOrEmpty(tokens.ConsumerSecret))
            {
                throw new ArgumentException("Missing consumer secret");
            }

            if (string.IsNullOrEmpty(tokens.ConsumerKey))
            {
                throw new ArgumentException("Missing consumer key");
            }

            if (string.IsNullOrEmpty(tokens.CallbackUri))
            {
                throw new ArgumentException("Missing callback uri");
            }

            _tokens = tokens;
            _authenticationBroker = authenticationBroker ?? throw new ArgumentException("Missing AuthenticationBroker");
            _passwordManager      = passwordManager ?? throw new ArgumentException("Missing PasswordManager");
            _storageManager       = storageManager ?? throw new ArgumentException("Missing StorageManager");
            _signatureManager     = signatureManager ?? throw new ArgumentException("Missing SignatureManager");

            if (_client == null)
            {
                HttpClientHandler handler = new HttpClientHandler();
                handler.AutomaticDecompression = DecompressionMethods.GZip;
                _client = new HttpClient(handler);
            }
        }
        /// <summary>
        /// HTTP Get request to specified Uri.
        /// </summary>
        /// <param name="requestUri">Uri to make OAuth request.</param>
        /// <param name="tokens">Tokens to pass in request.</param>
        /// <param name="signatureManager">Signature manager to sign the OAuth request</param>
        /// <returns>String result.</returns>
        public async Task <string> ExecuteGetAsync(Uri requestUri, TwitterOAuthTokens tokens, ISignatureManager signatureManager)
        {
            using var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
            var requestBuilder = new TwitterOAuthRequestBuilder(requestUri, tokens, signatureManager, "GET");

            request.Headers.Authorization = AuthenticationHeaderValue.Parse(requestBuilder.AuthorizationHeader);

            using var response = await client.SendAsync(request).ConfigureAwait(false);

            response.ThrowIfNotValid();
            return(ProcessErrors(await response.Content.ReadAsStringAsync().ConfigureAwait(false)));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initialize underlying provider with relevant token information.
        /// </summary>
        /// <param name="oAuthTokens">Token instance.</param>
        /// <param name="authenticationBroker">Authentication result interface.</param>
        /// <param name="passwordManager">Password Manager interface, store the password.</param>
        /// <param name="storageManager">Storage Manager interface</param>
        /// <param name="signatureManager">Signature manager to sign the OAuth request</param>
        /// <returns>Success or failure.</returns>
        public bool Initialize(TwitterOAuthTokens oAuthTokens, IAuthenticationBroker authenticationBroker, IPasswordManager passwordManager, IStorageManager storageManager, ISignatureManager signatureManager)
        {
            tokens = oAuthTokens ?? throw new ArgumentNullException(nameof(oAuthTokens));
            this.authenticationBroker = authenticationBroker ?? throw new ArgumentNullException(nameof(authenticationBroker));
            this.passwordManager      = passwordManager ?? throw new ArgumentNullException(nameof(passwordManager));
            this.storageManager       = storageManager ?? throw new ArgumentNullException(nameof(storageManager));
            this.signatureManager     = signatureManager ?? throw new ArgumentNullException(nameof(signatureManager));

            isInitialized = true;

            twitterDataProvider = null;

            return(true);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TwitterDataProvider"/> class.
 /// Constructor.
 /// </summary>
 /// <param name="tokens">OAuth tokens for request.</param>
 public TwitterDataProvider(TwitterOAuthTokens tokens)
 {
     _tokens = tokens;
     _authenticationBroker = new UwpAuthenticationBroker();
     _passwordManager      = new UwpPasswordManager();
     _storageManager       = new UwpStorageManager();
     _signatureManager     = new UwpSignatureManager();
     if (_client == null)
     {
         HttpClientHandler handler = new HttpClientHandler();
         handler.AutomaticDecompression = DecompressionMethods.GZip;
         _client = new HttpClient(handler);
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Initialize underlying provider with relevant token information.
        /// </summary>
        /// <param name="consumerKey">Consumer key.</param>
        /// <param name="consumerSecret">Consumer secret.</param>
        /// <param name="callbackUri">Callback URI. Has to match callback URI defined at apps.twitter.com (can be arbitrary).</param>
        /// <param name="authenticationBroker">Authentication result interface.</param>
        /// <param name="passwordManager">Password Manager interface, store the password.</param>
        /// <param name="storageManager">Storage Manager interface</param>
        /// <param name="signatureManager">Signature manager to sign the OAuth request</param>
        /// <returns>Success or failure.</returns>
        public bool Initialize(string consumerKey, string consumerSecret, string callbackUri, IAuthenticationBroker authenticationBroker, IPasswordManager passwordManager, IStorageManager storageManager, ISignatureManager signatureManager)
        {
            if (string.IsNullOrEmpty(consumerKey))
            {
                throw new ArgumentNullException(nameof(consumerKey));
            }

            if (string.IsNullOrEmpty(consumerSecret))
            {
                throw new ArgumentNullException(nameof(consumerSecret));
            }

            if (string.IsNullOrEmpty(callbackUri))
            {
                throw new ArgumentNullException(nameof(callbackUri));
            }

            if (authenticationBroker == null)
            {
                throw new ArgumentException(nameof(authenticationBroker));
            }

            if (passwordManager == null)
            {
                throw new ArgumentException(nameof(passwordManager));
            }

            if (storageManager == null)
            {
                throw new ArgumentException(nameof(storageManager));
            }

            if (signatureManager == null)
            {
                throw new ArgumentException(nameof(signatureManager));
            }

            var oAuthTokens = new TwitterOAuthTokens
            {
                ConsumerKey    = consumerKey,
                ConsumerSecret = consumerSecret,
                CallbackUri    = callbackUri
            };

            return(Initialize(oAuthTokens, authenticationBroker, passwordManager, storageManager, signatureManager));
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Initialize underlying provider with relevant token information.
 /// </summary>
 /// <param name="oAuthTokens">Token instance.</param>
 /// <returns>Success or failure.</returns>
 public bool Initialize(TwitterOAuthTokens oAuthTokens)
 {
     return(Initialize(oAuthTokens, new NetFrameworkAuthenticationBroker(), new NetFrameworkPasswordManager(), new NetFrameworkStorageManager(), new NetFrameworkSignatureManager()));
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Initialize underlying provider with relevant token information.
 /// </summary>
 /// <param name="oAuthTokens">Token instance.</param>
 /// <returns>Success or failure.</returns>
 public bool Initialize(TwitterOAuthTokens oAuthTokens)
 {
     return(Initialize(oAuthTokens, new UwpAuthenticationBroker(), new UwpPasswordManager(), new UwpStorageManager(), new UwpSignatureManager()));
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TwitterDataProvider"/> class.
 /// Constructor.
 /// </summary>
 /// <param name="tokens">OAuth tokens for request.</param>
 public TwitterDataProvider(TwitterOAuthTokens tokens)
     : this(tokens, new NetFrameworkAuthenticationBroker(), new NetFrameworkPasswordManager(), new NetFrameworkStorageManager(), new NetFrameworkSignatureManager())
 {
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TwitterDataProvider"/> class.
 /// Constructor.
 /// </summary>
 /// <param name="tokens">OAuth tokens for request.</param>
 public TwitterDataProvider(TwitterOAuthTokens tokens)
     : this(tokens, new UwpAuthenticationBroker(), new UwpPasswordManager(), new UwpStorageManager(), new UwpSignatureManager())
 {
 }