public void ParseTwitterErrorMessage_WithApiV2Error_Parses()
        {
            TwitterErrorDetails errorDetails = TwitterErrorHandler.ParseTwitterErrorMessage(ApiV2ErrorJson);

            Assert.IsNotNull(errorDetails);
            Assert.AreEqual("Invalid Request", errorDetails.Title);
            Assert.AreEqual("One or more parameters to your request was invalid.", errorDetails.Detail);
            Assert.AreEqual("https://api.twitter.com/labs/2/problems/invalid-request", errorDetails.Type);
            List <Error> errors = errorDetails.Errors;

            Assert.IsNotNull(errors);
            Assert.AreEqual(2, errors.Count);
            Error error = errors[1];

            Assert.AreEqual("[q] is not one of [query,start_time,end_time,since_id,until_id,max_results,next_token,expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields]", error.Message);
            Dictionary <string, string[]> parameters = error.Parameters;

            Assert.IsNotNull(parameters);
            Assert.AreEqual(1, parameters.Count);
            Assert.IsTrue(parameters.ContainsKey("q"));
            string[] values = parameters["q"];
            Assert.IsNotNull(values);
            Assert.AreEqual(1, values.Count());
            string value = values.First();

            Assert.AreEqual("LINQ%20to%20Twitter", value);
        }
Ejemplo n.º 2
0
        internal async Task <string> HttpGetAsync(string oauthUrl, IDictionary <string, string> parameters)
        {
            var req = new HttpRequestMessage(HttpMethod.Get, oauthUrl);

            req.Headers.Add("Authorization", GetAuthorizationString(HttpMethod.Get.ToString(), oauthUrl, parameters));
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;

            var handler = new HttpClientHandler();

            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip;
            }
            if (Proxy != null && handler.SupportsProxy)
            {
                handler.Proxy = Proxy;
            }

            var msg = await new HttpClient(handler).SendAsync(req).ConfigureAwait(false);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return(await msg.Content.ReadAsStringAsync().ConfigureAwait(false));
        }
        async Task GetBearerTokenAsync()
        {
            var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, OAuth2Token);

            req.Headers.Add("Authorization", "Basic " + BasicToken);
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;
            req.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");

            var handler = new HttpClientHandler();

            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip;
            }
            if (Proxy != null && handler.SupportsProxy)
            {
                handler.Proxy = Proxy;
            }

            var client = new HttpClient(handler);

            var msg = await client.SendAsync(req).ConfigureAwait(false);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            string response = await msg.Content.ReadAsStringAsync().ConfigureAwait(false);

            var responseJson = JsonDocument.Parse(response);

            BearerToken = responseJson.RootElement.GetProperty("access_token").GetString();
        }
        public void ParseTwitterErrorMessage_WithUnrecognizedContent_SendsErrorMessage()
        {
            const string GarbageIn = "This is garbage";

            TwitterErrorDetails errorDetails = TwitterErrorHandler.ParseTwitterErrorMessage(GarbageIn);

            Assert.IsNotNull(errorDetails);
            Assert.IsTrue(errorDetails.Title?.StartsWith("Unhandled Error") ?? false);
            Assert.AreEqual(GarbageIn, errorDetails.Detail);
        }
        public void ParseTwitterErrorMessage_Handles_String_Types()
        {
            string stringError = "{\"errors\":\"sharing is not permissible for this status (Share validations failed)\"}";

            TwitterErrorHandler.TwitterErrorDetails details =
                TwitterErrorHandler.ParseTwitterErrorMessage(stringError);

            Assert.IsNotNull(details);
            Assert.AreEqual(
                "sharing is not permissible for this status (Share validations failed)",
                details.Message);
        }
        public void ParseTwitterErrorMessage_WithApiV1RequestError_Parses()
        {
            TwitterErrorDetails errorDetails = TwitterErrorHandler.ParseTwitterErrorMessage(MediaErrorJson);

            Assert.IsNotNull(errorDetails);
            List <Error> errors = errorDetails.Errors;

            Assert.IsNotNull(errors);
            Assert.AreEqual(1, errors.Count);
            Error error = errors.First();

            Assert.AreEqual("/1.1/media/metadata/create.json", error.Request);
            Assert.AreEqual("media_id field must be provided.", error.Message);
        }
        public void ParseTwitterErrorMessage_WithApiV1Error_Parses()
        {
            TwitterErrorDetails errorDetails = TwitterErrorHandler.ParseTwitterErrorMessage(ApiV1ErrorJson);

            Assert.IsNotNull(errorDetails);
            List <Error> errors = errorDetails.Errors;

            Assert.IsNotNull(errors);
            Assert.AreEqual(1, errors.Count);
            Error error = errors.First();

            Assert.AreEqual(144, error.Code);
            Assert.AreEqual("No status found with that ID.", error.Message);
        }
Ejemplo n.º 8
0
        async Task <string> HandleResponseAsync(HttpResponseMessage msg)
        {
            LastUrl = msg.RequestMessage.RequestUri;

            ResponseHeaders =
                (from header in msg.Headers
                 select new
            {
                header.Key,
                Value = string.Join(", ", header.Value)
            })
                .ToDictionary(
                    pair => pair.Key,
                    pair => pair.Value);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return(await msg.Content.ReadAsStringAsync().ConfigureAwait(false));
        }
Ejemplo n.º 9
0
        internal async Task <string> HttpPostAsync(string oauthUrl, IDictionary <string, string> parameters)
        {
            var postData =
                (from keyValPair in parameters
                 where !keyValPair.Key.StartsWith("oauth")
                 select keyValPair)
                .ToDictionary(pair => pair.Key, pair => pair.Value);

            var req = new HttpRequestMessage(HttpMethod.Post, oauthUrl);

            req.Headers.Add("Authorization", GetAuthorizationString(HttpMethod.Post.ToString(), oauthUrl, parameters));
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;

            var paramString =
                string.Join("&",
                            (from parm in postData
                             select parm.Key + "=" + Url.PercentEncode(parm.Value))
                            .ToList());
            var content = new StringContent(paramString, Encoding.UTF8, "application/x-www-form-urlencoded");

            req.Content = content;

            var handler = new HttpClientHandler();

            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip;
            }
            if (Proxy != null && handler.SupportsProxy)
            {
                handler.Proxy = Proxy;
            }

            var msg = await new HttpClient(handler).SendAsync(req).ConfigureAwait(false);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return(await msg.Content.ReadAsStringAsync().ConfigureAwait(false));
        }
Ejemplo n.º 10
0
        public async Task <string> QueryTwitterStreamAsync(Request request)
        {
            WriteLog(request.FullUrl, nameof(QueryTwitterStreamAsync));

            var handler = new HttpClientHandler();

            if (Authorizer.Proxy != null && handler.SupportsProxy)
            {
                handler.Proxy = Authorizer.Proxy;
            }

            StreamingClient = new HttpClient(handler)
            {
                Timeout = TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite)
            };

            var httpRequest = ConfigureRequest(request);

            var response = await StreamingClient.SendAsync(
                httpRequest, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

            await TwitterErrorHandler.ThrowIfErrorAsync(response).ConfigureAwait(false);

            Stream stream = await CreateStream(response).ConfigureAwait(false);

            const int CarriageReturn = 0x0D;
            const int LineFeed       = 0x0A;

            var memStr = new MemoryStream();

            byte[] readByte;

            while (stream.CanRead && !IsStreamClosed)
            {
                readByte = new byte[1];
                await stream.ReadAsync(readByte, 0, 1, CancellationToken).ConfigureAwait(false);

                byte nextByte = readByte.SingleOrDefault();

                CancellationToken.ThrowIfCancellationRequested();

                if (IsStreamClosed)
                {
                    break;
                }

                if (nextByte == 0xff)
                {
                    break;
                }

                if (nextByte != CarriageReturn && nextByte != LineFeed)
                {
                    memStr.WriteByte(nextByte);
                }

                if (nextByte == LineFeed)
                {
                    int    byteCount  = (int)memStr.Length;
                    byte[] tweetBytes = new byte[byteCount];

                    memStr.Position = 0;
                    await memStr.ReadAsync(tweetBytes, 0, byteCount, CancellationToken).ConfigureAwait(false);

                    string tweet       = Encoding.UTF8.GetString(tweetBytes, 0, byteCount);
                    var    strmContent = new Streaming.StreamContent(this, tweet);

                    await StreamingCallbackAsync(strmContent).ConfigureAwait(false);

                    memStr.Dispose();
                    memStr = new MemoryStream();
                }
            }

            IsStreamClosed = false;

            return("{}");
        }