コード例 #1
0
        /// <summary>
        /// Open a connection to user streams service (Events, DirectMessages...).
        /// </summary>
        /// <param name="parser">Specific stream's result parser.</param>
        /// <param name="callback">Method invoked each time a result occurs.</param>
        /// <returns>Awaitable task.</returns>
        public Task StartUserStreamAsync(TwitterUserStreamParser parser, TwitterStreamCallbacks.TwitterStreamCallback callback)
        {
            try
            {
                var uri = new Uri($"{UserStreamUrl}/user.json?replies=all");

                _streamRequest = new TwitterOAuthRequest();

                return(_streamRequest.ExecuteGetStreamAsync(uri, _tokens, rawResult => callback(parser.Parse(rawResult))));
            }
            catch (WebException wex)
            {
                HttpWebResponse response = wex.Response as HttpWebResponse;
                if (response != null)
                {
                    if ((int)response.StatusCode == 429)
                    {
                        throw new TooManyRequestsException();
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new OAuthKeysRevokedException();
                    }
                }

                throw;
            }
        }
コード例 #2
0
        /// <summary>
        /// Get home time line data.
        /// </summary>
        /// <typeparam name="TSchema">Strong typed result.</typeparam>
        /// <param name="maxRecords">Upper record limit.</param>
        /// <param name="parser">Specific result parser.</param>
        /// <returns>Return strong typed list of results.</returns>
        private async Task <IEnumerable <TSchema> > GetHomeTimeLineAsync <TSchema>(int maxRecords, IParser <TSchema> parser)
            where TSchema : SchemaBase
        {
            try
            {
                var uri = new Uri($"{BaseUrl}/statuses/home_timeline.json?count={maxRecords}");

                TwitterOAuthRequest request = new TwitterOAuthRequest();
                var rawResult = await request.ExecuteGetAsync(uri, _tokens);

                return(parser.Parse(rawResult));
            }
            catch (WebException wex)
            {
                HttpWebResponse response = wex.Response as HttpWebResponse;
                if (response != null)
                {
                    if ((int)response.StatusCode == 429)
                    {
                        throw new TooManyRequestsException();
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new OAuthKeysRevokedException();
                    }
                }

                throw;
            }
        }
コード例 #3
0
        /// <summary>
        /// Search for specific hash tag with specific parser.
        /// </summary>
        /// <typeparam name="TSchema">Strong type for results.</typeparam>
        /// <param name="hashTag">Hash tag.</param>
        /// <param name="maxRecords">Upper record limit.</param>
        /// <param name="parser">Specific results parser.</param>
        /// <returns>Returns strongly typed list of results.</returns>
        public async Task <IEnumerable <TSchema> > SearchAsync <TSchema>(string hashTag, int maxRecords, IParser <TSchema> parser)
            where TSchema : SchemaBase
        {
            try
            {
                var uri = new Uri($"{BaseUrl}/search/tweets.json?q={Uri.EscapeDataString(hashTag)}&count={maxRecords}");
                TwitterOAuthRequest request = new TwitterOAuthRequest();
                var rawResult = await request.ExecuteGetAsync(uri, _tokens);

                var result = parser.Parse(rawResult);
                return(result
                       .Take(maxRecords)
                       .ToList());
            }
            catch (WebException wex)
            {
                HttpWebResponse response = wex.Response as HttpWebResponse;
                if (response != null)
                {
                    if ((int)response.StatusCode == 429)
                    {
                        throw new TooManyRequestsException();
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new OAuthKeysRevokedException();
                    }
                }

                throw;
            }
        }
コード例 #4
0
        private async Task <IEnumerable <TSchema> > GetCustomSearch <TSchema>(string query, Toolkit.Parsers.IParser <TSchema> parser)
            where TSchema : Toolkit.Parsers.SchemaBase
        {
            try
            {
                var uri = new Uri($"{BaseUrl}/{query}");

                TwitterOAuthRequest request = new TwitterOAuthRequest();
                var rawResult = await request.ExecuteGetAsync(uri, _tokens);

                return(parser.Parse(rawResult));
            }
            catch (WebException wex)
            {
                HttpWebResponse response = wex.Response as HttpWebResponse;
                if (response != null)
                {
                    if ((int)response.StatusCode == 429)
                    {
                        throw new TooManyRequestsException();
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new OAuthKeysRevokedException();
                    }
                }

                throw;
            }
        }
コード例 #5
0
        /// <summary>
        /// Retrieve user timeline data with specific parser.
        /// </summary>
        /// <typeparam name="TSchema">Strong type for results.</typeparam>
        /// <param name="screenName">User screen name.</param>
        /// <param name="maxRecords">Upper record limit.</param>
        /// <param name="parser">Specific results parser.</param>
        /// <returns>Returns strongly typed list of results.</returns>
        public async Task <IEnumerable <TSchema> > GetUserTimeLineAsync <TSchema>(string screenName, int maxRecords, IParser <TSchema> parser)
            where TSchema : SchemaBase
        {
            string rawResult = null;

            try
            {
                var uri = new Uri($"{BaseUrl}/statuses/user_timeline.json?screen_name={screenName}&count={maxRecords}&include_rts=1");

                TwitterOAuthRequest request = new TwitterOAuthRequest();
                rawResult = await request.ExecuteGetAsync(uri, _tokens);

                var result = parser.Parse(rawResult);
                return(result
                       .Take(maxRecords)
                       .ToList());
            }
            catch (WebException wex)
            {
                HttpWebResponse response = wex.Response as HttpWebResponse;
                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new UserNotFoundException(screenName);
                    }

                    if ((int)response.StatusCode == 429)
                    {
                        throw new TooManyRequestsException();
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new OAuthKeysRevokedException();
                    }
                }

                throw;
            }
            catch
            {
                if (!string.IsNullOrEmpty(rawResult))
                {
                    var errors = JsonConvert.DeserializeObject <TwitterErrors>(rawResult);

                    throw new TwitterException {
                              Errors = errors
                    };
                }

                throw;
            }
        }
コード例 #6
0
        /// <summary>
        /// Retrieve user data.
        /// </summary>
        /// <param name="screenName">User screen name or null for current logged user</param>
        /// <returns>Returns user data.</returns>
        public async Task <TwitterUser> GetUserAsync(string screenName = null)
        {
            string rawResult = null;

            try
            {
                var userScreenName = screenName ?? UserScreenName;
                var uri            = new Uri($"{BaseUrl}/users/show.json?screen_name={userScreenName}");

                TwitterOAuthRequest request = new TwitterOAuthRequest();
                rawResult = await request.ExecuteGetAsync(uri, _tokens);

                return(JsonConvert.DeserializeObject <TwitterUser>(rawResult));
            }
            catch (WebException wex)
            {
                HttpWebResponse response = wex.Response as HttpWebResponse;
                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new UserNotFoundException(screenName);
                    }

                    if ((int)response.StatusCode == 429)
                    {
                        throw new TooManyRequestsException();
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new OAuthKeysRevokedException();
                    }
                }

                throw;
            }
            catch
            {
                if (!string.IsNullOrEmpty(rawResult))
                {
                    var errors = JsonConvert.DeserializeObject <TwitterErrors>(rawResult);

                    throw new TwitterException {
                              Errors = errors
                    };
                }

                throw;
            }
        }
コード例 #7
0
        /// <summary>
        /// Publish a picture to Twitter user's medias.
        /// </summary>
        /// <param name="stream">Picture stream.</param>
        /// <returns>Media ID</returns>
        public async Task <string> UploadPictureAsync(IRandomAccessStream stream)
        {
            var uri = new Uri($"{PublishUrl}/media/upload.json");

            // Get picture data
            var fileBytes = new byte[stream.Size];

            await stream.ReadAsync(fileBytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);

            stream.Seek(0);

            string boundary = DateTime.Now.Ticks.ToString("x");

            TwitterOAuthRequest request = new TwitterOAuthRequest();

            return(await request.ExecutePostMultipartAsync(uri, _tokens, boundary, fileBytes));
        }
コード例 #8
0
        /// <summary>
        /// Tweets a status update.
        /// </summary>
        /// <param name="status">Tweet text.</param>
        /// <param name="pictures">Pictures to attach to the tweet (up to 4).</param>
        /// <returns>Success or failure.</returns>
        public async Task <bool> TweetStatusAsync(TwitterStatus status, params IRandomAccessStream[] pictures)
        {
            try
            {
                var mediaIds = string.Empty;

                if (pictures != null && pictures.Length > 0)
                {
                    var ids = new List <string>();
                    foreach (var picture in pictures)
                    {
                        ids.Add(await UploadPictureAsync(picture));
                    }

                    mediaIds = "&media_ids=" + string.Join(",", ids);
                }

                var uri = new Uri($"{BaseUrl}/statuses/update.json?{status.RequestParameters}{mediaIds}");

                TwitterOAuthRequest request = new TwitterOAuthRequest();
                await request.ExecutePostAsync(uri, _tokens);

                return(true);
            }
            catch (WebException wex)
            {
                HttpWebResponse response = wex.Response as HttpWebResponse;
                if (response != null)
                {
                    if ((int)response.StatusCode == 429)
                    {
                        throw new TooManyRequestsException();
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new OAuthKeysRevokedException();
                    }
                }

                throw;
            }
        }
コード例 #9
0
        /// <summary>
        /// Publish a picture to Twitter user's medias.
        /// </summary>
        /// <param name="stream">Picture stream.</param>
        /// <returns>Media ID</returns>
        public async Task <string> UploadPicture(IRandomAccessStream stream)
        {
            var uri = new Uri($"{PublishUrl}/media/upload.json");

            // Get picture data
            var fileBytes = new byte[stream.Size];

            using (DataReader reader = new DataReader(stream))
            {
                await reader.LoadAsync((uint)stream.Size);

                reader.ReadBytes(fileBytes);
            }

            string boundary = DateTime.Now.Ticks.ToString("x");

            TwitterOAuthRequest request = new TwitterOAuthRequest();

            return(await request.ExecutePostMultipartAsync(uri, tokens, boundary, fileBytes));
        }
コード例 #10
0
 /// <summary>
 /// Stop user's stream
 /// </summary>
 public void StopStream()
 {
     _streamRequest?.Abort();
     _streamRequest = null;
 }