Пример #1
0
        /// <summary>
        /// タイムラインを取得します。
        /// </summary>
        /// <param name="twitterContext">タイムラインを取得するユーザー。</param>
        /// <param name="count">取得するツイートの数。200以下でなければなりません。</param>
        /// <param name="since_id">指定したIDより大きなIDを持つ結果のみを返します(つまり、より新しい)。APIを介してアクセスできるツイートの数には制限があります。ツイートの制限がsince_id以来発生している場合は、since_idは、利用可能な最も古いIDに強制されます。</param>
        /// <param name="max_id">指定されたIDと同じか、それより古いIDを持つ結果のみを返します(つまり、より古い)。</param>
        /// <param name="trim_user">trueに設定すると、タイムライン上で返される各ツイートはステータスのみ作者数値IDを含むユーザーオブジェクトが含まれます。完全なユーザーオブジェクトを受け取るためには、このパラメータを省略します。</param>
        /// <param name="exclude_replies">trueに設定すると、取得するタイムラインからリツイートやリプライは除外されます。</param>
        /// <param name="contributor_details"></param>
        /// <param name="include_entities"></param>
        /// <returns>ツイートのList。</returns>
        public static async Task<List<Status>> HomeTimeline(TwitterContext twitterContext,
            double count = 0,
            string since_id = null,
            string max_id = null,
            bool trim_user = false,
            bool exclude_replies = false,
            bool contributor_details = false,
            bool include_entities = true)
        {
            StringDictionary query = new StringDictionary();
            query["count"] = count.ToString();
            query["since_id"] = since_id;
            query["max_id"] = max_id;
            query["trim_user"] = trim_user.ToString();
            query["exclude_replies"] = exclude_replies.ToString();
            query["contributor_details"] = contributor_details.ToString();
            query["include_entities"] = include_entities.ToString();

            string source = await new TwitterRequest(
                twitterContext, API.Methods.GET, new Uri(API.Urls.Statuses_HomeTimeline), query).Request();

            dynamic json = Utility.DynamicJson.Parse(source);

            var statuses = new List<Status>();
            foreach (dynamic status in json)
            {
                statuses.Add(new Status(status.ToString()));
            }
            return statuses;
        }
Пример #2
0
		public static async Task<string> access_token(TwitterContext twitterContext, string oauth_verifier)
		{
			StringDictionary query = new StringDictionary();
			query["oauth_verifier"] = oauth_verifier;

            return await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.Oauth_AccessToken), query).Request();
		}
Пример #3
0
        /// <summary>
        /// リクエスト ヘッダー文字列を生成します。
        /// </summary>
        /// <param name="context">リクエストに使用されるトークンセット。</param>
        /// <param name="method"></param>
        /// <param name="requestUrl"></param>
        /// <param name="queryDictionary"></param>
        /// <returns></returns>
        public static string GenerateRequestHeader(TwitterContext context, string method, string requestUrl, StringDictionary queryDictionary = null)
        {
            Debug.WriteLine("-\t## リクエスト ヘッダーを構築します");

            string header = String.Empty;
            string headerParams = String.Empty;

            var oauth = new OAuthBase();
            string nonce = oauth.GenerateNonce();
            string timeStamp = oauth.GenerateTimeStamp();

            var paramDictionary = new SortedDictionary<string, string>();
            AddPercentEncodedItem(paramDictionary, "oauth_consumer_key", context.ConsumerKey);
            AddPercentEncodedItem(paramDictionary, "oauth_nonce", nonce);
            AddPercentEncodedItem(paramDictionary, "oauth_signature", GenerateSignature(context, method, requestUrl, nonce, "HMAC-SHA1", timeStamp, "1.0", queryDictionary));
            AddPercentEncodedItem(paramDictionary, "oauth_signature_method", "HMAC-SHA1");
            AddPercentEncodedItem(paramDictionary, "oauth_timestamp", timeStamp);
            AddPercentEncodedItem(paramDictionary, "oauth_token", context.AccessToken != null ? context.AccessToken : null);
            AddPercentEncodedItem(paramDictionary, "oauth_version", "1.0");

            foreach (var kvp in paramDictionary)
            {
                if (kvp.Value != null)
                    headerParams += (headerParams.Length > 0 ? ", " : String.Empty) + kvp.Key + "=\"" + kvp.Value + "\"";
            }

            header = "OAuth " + headerParams;

            Debug.WriteLine("-\t## リクエスト ヘッダー構築完了: [Authorization] " + header);
            return header;
        }
Пример #4
0
        /// <summary>
        /// シグネチャ文字列を生成します。
        /// </summary>
        /// <param name="context">リクエストに使用されるトークンセット。</param>
        /// <param name="method">リクエストのメソッド。</param>
        /// <param name="url">リクエストのURL。</param>
        /// <param name="nonce">ランダムな文字列。</param>
        /// <param name="signatureMethod">シグネチャ メソッド。</param>
        /// <param name="timeStamp">現在の時刻のタイムスタンプ。</param>
        /// <param name="oAuthVersion">OAuthのバージョン文字列。</param>
        /// <param name="QueryDictionary">リクエストのパラメータ。</param>
        /// <returns></returns>
        public static string GenerateSignature(TwitterContext context, string method, string url, string nonce, string signatureMethod, string timeStamp, string oAuthVersion, StringDictionary QueryDictionary = null)
        {
            Debug.WriteLine("-\t-\t## シグネチャを生成します");

            var parameters = new SortedDictionary<string, string>();
            parameters.Add("oauth_consumer_key", context.ConsumerKey);
            parameters.Add("oauth_nonce", nonce);
            parameters.Add("oauth_signature_method", signatureMethod);
            parameters.Add("oauth_timestamp", timeStamp);
            parameters.Add("oauth_token", context.AccessToken != null ? context.AccessToken : null);
            parameters.Add("oauth_version", oAuthVersion);

            // Add parameters to request parameter
            if (QueryDictionary != null)
            {
                foreach (DictionaryEntry k in QueryDictionary)
                {
                    if (k.Value != null)
                        parameters.Add((string)k.Key, (string)k.Value);
                }
            }

            #if DEBUG
            foreach (KeyValuePair<string, string> p in parameters)
            {
                if (p.Value != null)
                    Debug.WriteLine(p.Value.Length > 1000 ? "-\t-\t-\t## [" + p.Key + "] : (1000文字以上)" : "-\t-\t-\t## [" + p.Key + "] : " + p.Value);
            }
            #endif

            string stringParameter = String.Empty;

            foreach (var kvp in parameters)
            {
                if (kvp.Value != null)
                    stringParameter +=
                        (stringParameter.Length > 0 ? "&" : String.Empty) +
                        UrlEncode(kvp.Key, Encoding.UTF8) +
                        "=" + UrlEncode(kvp.Value, Encoding.UTF8);
            }

            Debug.WriteLine(stringParameter.Length > 1000 ? "-\t-\t-\t## パラメータ生成完了: (1000文字以上)" : "-\t-\t-\t## パラメータ生成完了: " + stringParameter);

            // Generate signature base string
            string signatureBaseString = UrlEncode(method, Encoding.UTF8) + "&"
                + UrlEncode(url, Encoding.UTF8) + "&"
                + UrlEncode(stringParameter, Encoding.UTF8);

            Debug.WriteLine(signatureBaseString.Length > 1000 ? "-\t-\t-\t## シグネチャ ベース ストリング生成完了: (1000文字以上)" : "-\t-\t-\t## シグネチャ ベース ストリング生成完了: " + signatureBaseString);

            var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(
                UrlEncode(context.ConsumerSecret, Encoding.UTF8) +
                "&" + (!String.IsNullOrEmpty(context.AccessTokenSecret) ? UrlEncode(context.AccessTokenSecret, Encoding.UTF8) : String.Empty)));

            // Convert to Base64
            string signature = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString)));

            Debug.WriteLine("-\t-\t## シグネチャ生成完了: " + signature);
            return signature;
        }
Пример #5
0
        /// <summary>
        /// TwitterContextのアイコンを更新します。
        /// </summary>
        /// <param name="twitterContext">更新するアカウント。</param>
        /// <param name="image">base64エンコードされたgifまたはjpgまたはpngの画像。</param>
        /// <returns>更新されたユーザー。</returns>
        public static async Task<Twitter.User> UpdateProfileImage(TwitterContext twitterContext, string image)
        {
            StringDictionary query = new StringDictionary();
            query["image"] = image;

            return new User(await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.Account_UpdateProfileImage), query).Request());
        }
Пример #6
0
        /// <summary>
        /// 対象のツイートをリツイートします。
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="id">リツイートするツイートのID。</param>
        /// <returns></returns>
        public static async Task<string> Retweet(TwitterContext twitterContext,
            string id)
        {
            StringDictionary query = new StringDictionary();
            query["id"] = id;

            return await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.Statuses_Retweet + id + ".json"), query).Request();
        }
Пример #7
0
        /// <summary>
        /// 対象のツイートをお気に入りから削除します。
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="id">対象のツイートのID。</param>
        /// <returns>対象のツイート</returns>
        public static async Task<Twitter.Status> Destroy(TwitterContext twitterContext, string id)
        {
            StringDictionary query = new StringDictionary();
            query["id"] = id;

            string res = await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.Favorites_Destroy), query).Request();
            return res != null ? new Status(res) : null;
        }
Пример #8
0
        /// <summary>
        /// リストを削除します。
        /// </summary>
        /// <param name="twitterContext"></param>
        /// <param name="slug"></param>
        /// <param name="owner_screen_name"></param>
        /// <returns></returns>
        public static async Task<string> Destroy(TwitterContext twitterContext, string slug, string owner_screen_name)
        {
            var query = new StringDictionary();
            query["slug"] = slug;
            query["owner_screen_name"] = owner_screen_name;

            return await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.Lists_Destroy), query).Request();
        }
Пример #9
0
        /// <summary>
        /// UserStreamを初期化します。
        /// </summary>
        public UserStream(TwitterContext twitterContext)
            : base(twitterContext)
        {
            this.StreamMessaged += new StreamMessagedEventHandler(StreamingCallback);

            this.Url = "https://userstream.twitter.com/1.1/user.json";
            this.Host = "userstream.twitter.com";
            this.Method = Methods.GET;
        }
Пример #10
0
		public static async Task<string> AccessToken(TwitterContext twitterContext, string x_auth_username, string x_auth_password)
		{
			StringDictionary query = new StringDictionary();
			query["x_auth_username"] = x_auth_username;
			query["x_auth_password"] = x_auth_password;
			query["x_auth_mode"] = "client_auth";

            return await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.Oauth_AccessToken), query).Request();
		}
Пример #11
0
        /// <summary>
        /// ダイレクト メッセージを送信します。
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="text">ダイレクト メッセージの本文。</param>
        /// <param name="screen_name">宛先のユーザーのScreenName。</param>
        /// <param name="id">宛先のユーザーのID。</param>
        /// <returns></returns>
        public static async Task<string> New(TwitterContext twitterContext, string text, string screen_name = null, string id = null)
        {
            var query = new StringDictionary();
            query["text"] = text;
            query["screen_name"] = screen_name;
            query["user_id"] = id;

            return await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.DirectMessages_New), query).Request();
        }
Пример #12
0
        /// <summary>
        /// リストを作成します。
        /// </summary>
        /// <param name="twitterContext">リストを作成するユーザー。</param>
        /// <param name="name">リスト名。</param>
        /// <param name="mode">リストの公開状態。 public または private のいずれかを指定します。nullまたは指定しなかった場合はpublic(公開)になります。</param>
        /// <param name="description">リストの説明。</param>
        /// <returns></returns>
        public static async Task<string> Create(TwitterContext twitterContext, string name, string description, string mode = null)
        {
            var query = new StringDictionary();
            query["name"] = name;
            query["mode"] = mode;
            query["description"] = description;

            return await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.Lists_Create), query).Request();
        }
Пример #13
0
        /// <summary>
        /// アカウントのプロフィールを各種変更します。
        /// </summary>
        /// <param name="twitterContext">更新するアカウント。</param>
        /// <param name="name">名前。nullまたは指定しなかった場合はこのパラメータは更新されません。</param>
        /// <param name="url">ウェブサイト URL。nullまたは指定しなかった場合はこのパラメータは更新されません。</param>
        /// <param name="location">場所。nullまたは指定しなかった場合はこのパラメータは更新されません。</param>
        /// <param name="description">自己紹介。nullまたは指定しなかった場合はこのパラメータは更新されません。</param>
        /// <returns>更新されたユーザー。</returns>
        public static async Task<Twitter.User> UpdateProfile(TwitterContext twitterContext, string name = null, Uri url = null, string location = null, string description = null)
        {
            StringDictionary query = new StringDictionary();
            query["name"] = name;
            query["url"] = url.ToString();
            query["location"] = location;
            query["description"] = description;

            return new User(await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.Account_UpdateProfile), query).Request());
        }
Пример #14
0
        public void AddGuestAuthorToAliasReturnsOneGuestAuthor()
        {
            Database.SetInitializer(new TweetInitializer());
            var context = new TwitterContext();
            var firstTwitterAlias=context.Aliases.First();
            var newPerson = new Person {Name = "Julie", AliasAdministrator = firstTwitterAlias};
            context.People.Add(newPerson);
            Assert.IsTrue(firstTwitterAlias.Admins.Count == 1);

         
        }
Пример #15
0
        /// <summary>
        /// 指定したユーザーのフォローを解除します。
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="screen_name">フォローを解除するユーザーのScreenName。</param>
        /// <param name="id">フォローを解除するユーザーのID。</param>
        /// <returns>フォローを解除されたユーザー</returns>
        public static async Task<Twitter.User> Destory(TwitterContext twitterContext, string screen_name = null, string id = null)
        {
            StringDictionary query = new StringDictionary();
            query["screen_name"] = screen_name;
            query["user_id"] = id;

            return new Twitter.User(
                await new TwitterRequest(
                    twitterContext, API.Methods.POST,
                    new Uri(API.Urls.Friendships_Destroy), query).Request());
        }
Пример #16
0
        /// <summary>
        /// 新しいツイートを投稿します。
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="status">本文。</param>
        /// <param name="in_reply_to_status_id">返信元になるツイートのID。</param>
        /// <param name="media"></param>
        /// <returns></returns>
        public static async Task<string> Update(TwitterContext twitterContext,
            string status,
            string in_reply_to_status_id = null)
        {
            StringDictionary query = new StringDictionary();
            query["status"] = status;
            query["in_reply_to_status_id"] = in_reply_to_status_id;

            return await new TwitterRequest(
                twitterContext, API.Methods.POST, new Uri(API.Urls.Statuses_Update), query).Request();
        }
Пример #17
0
        /// <summary>
        /// 指定されたユーザーをミュートします。
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="screen_name">ミュートするユーザーのScreenName。</param>
        /// <param name="id">ミュートするユーザーのID。</param>
        /// <returns>ミュートされたユーザー</returns>
        public static async Task<Twitter.User> UsersCreate(TwitterContext twitterContext, string screen_name = null, string id = null)
        {
            StringDictionary query = new StringDictionary();
            query["screen_name"] = screen_name;
            query["user_id"] = id;

            return new Twitter.User(
                await new TwitterRequest(
                    twitterContext, API.Methods.POST,
                    new Uri(API.Urls.Mutes_Users_Create), query).Request());
        }
Пример #18
0
        /// <summary>
        /// 指定したユーザーをフォローします。
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="screen_name">フォローするユーザーのScreenName。</param>
        /// <param name="id">フォローするユーザーのID。</param>
        /// <param name="follow">このユーザーからの通知を受け取るかどうかを示す System.Boolean 値。</param>
        /// <returns>フォローされたユーザー</returns>
        public static async Task<Twitter.User> Create(TwitterContext twitterContext, string screen_name = null, string id = null, bool follow = false)
        {
            StringDictionary query = new StringDictionary();
            query["screen_name"] = screen_name;
            query["user_id"] = id;
            query["follow"] = follow.ToString();

            return new Twitter.User(
                await new TwitterRequest(
                    twitterContext, API.Methods.POST,
                    new Uri(API.Urls.Friendships_Create), query).Request());
        }
Пример #19
0
        /// <summary>
        /// 対象のアカウントをスパムとして報告します。
        /// 
        /// Report the specified user as a spam account to Twitter.
        /// Additionally performs the equivalent of POST blocks/create on behalf of the authenticated user.
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="user_id">スパム報告されるユーザーのID。</param>
        /// <param name="screen_name">スパム報告されるユーザーのScreenName。</param>
        /// <returns>スパム報告されたユーザー</returns>
        public static async Task<Twitter.User> ReportSpam(TwitterContext twitterContext, string user_id = null, string screen_name = null)
        {
            StringDictionary query = new StringDictionary();

            if (user_id != string.Empty)
                query["user_id"] = user_id;
            else if (screen_name != string.Empty)
                query["screen_name"] = screen_name;

            return new User(
                await new TwitterRequest(
                    twitterContext, API.Methods.POST,
                    new Uri(API.Urls.Users_ReportSpam), query).Request());
        }
Пример #20
0
        /// <summary>
        /// ユーザーを取得します。
        /// 
        /// Returns a variety of information about the user specified by the required user_id or screen_name parameter.
        /// The author's most recent Tweet will be returned inline when possible.
        ///
        /// GET users/lookup is used to retrieve a bulk collection of user objects.
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="user_id">取得するユーザーのID。</param>
        /// <param name="screen_name">取得するユーザーのScreenName。</param>
        /// <returns>ユーザー</returns>
        public static async Task<Twitter.User> Show(TwitterContext twitterContext, string user_id = null, string screen_name = null)
        {
            StringDictionary query = new StringDictionary();

            if (!string.IsNullOrEmpty(user_id))
                query["user_id"] = user_id;
            else if (!string.IsNullOrEmpty(screen_name))
                query["screen_name"] = screen_name;

            return new User(
                await new TwitterRequest(
                    twitterContext, API.Methods.GET,
                    new Uri(API.Urls.Users_Show), query).Request());
        }
Пример #21
0
        /// <summary>
        /// SiteStream を初期化します。
        /// </summary>
        /// <param name="follow">ツイートを受け取るユーザーのユーザーIDのリスト</param>
        public SiteStream(TwitterContext twitterContext, params string[] follow)
            : base(twitterContext)
        {
            this.StreamMessaged += new StreamMessagedEventHandler(StreamingCallback);

            this.Url = "https://sitestream.twitter.com/1.1/site.json";
            this.Host = "sitestream.twitter.com";
            this.Method = Methods.GET;

            StringDictionary query = new StringDictionary();

            query["follow"] = string.Join(",", follow);

            this.Parameter = query;
        }
Пример #22
0
 /// <summary>
 /// Twitterへのリクエストを作成します。
 /// </summary>
 /// <param name="twitterContext">リクエストを行うTwitterContext。</param>
 /// <param name="method">APIのリクエストに使用するHTTPメソッド。</param>
 /// <param name="url">APIのURL。</param>
 /// <param name="query">リクエストのパラメータ。</param>
 public TwitterRequest(
     TwitterContext twitterContext = null,
     Methods method = Methods.POST,
     Uri url = null,
     StringDictionary query = null,
     string proxy = null,
     string userAgent = null)
 {
     this.TwitterContext = twitterContext;
     this.Method = method;
     this.Url = url;
     this.Parameter = query;
     this.Proxy = proxy;
     this.UserAgent = userAgent;
 }
Пример #23
0
        /// <summary>
        /// Streamを初期化します。
        /// </summary>
        public StreamingBase(TwitterContext twitterContext)
        {
            this.TwitterContext = twitterContext;
            this.IsGZip = true;

            this.Stream += new StreamEventHandler(StreamingCallback);
        }
Пример #24
0
        /// <summary>
        /// ツイートを取得します。
        /// </summary>
        /// <param name="twitterContext">自分。</param>
        /// <param name="id">取得するツイートのID。</param>
        /// <returns></returns>
        public static async Task<Twitter.Status> Show(TwitterContext twitterContext,
            string id)
        {
            StringDictionary query = new StringDictionary();
            query["id"] = id;

            return new Status(await new TwitterRequest(twitterContext, API.Methods.GET, new Uri(API.Urls.Statuses_Show), query).Request());
        }
        public void readTweetData(int displayResults = 0)
        {
            List <Status> results = new List <Status>();

            try
            {
                //string tweetURL = "https://api.twitter.com/2/tweets/sample/stream/";
                //string tweetURL2 = "https://api.twitter.com/2/tweets/sample/stream?tweet.fields=attachments";


                var twitterContext = new TwitterContext(authorizer);

                //List<Status> results = new List<Status>();
                var tweets = from tweet in twitterContext.Status where tweet.Type == StatusType.Home select tweet;
                results = tweets.Select(t => t).ToList();

                //Number of Tweets
                tallyNumberOfTweets(results.Count);

                //Tweets With URLs
                List <Status> tweetsWithURL = results.Where(t => t.Text.Contains("http")).ToList();
                tallyTweetsWithURL(tweetsWithURL.Count);

                //percent tweets with URL
                calculatePercenttewwtswithURL(tweetsWithURL.Count, results.Count);


                //List<TweetQuery> tttttt = twitterContext.Tweets.ToList<TweetQuery>();


                //List<Status> t2 = (List<Status>)tweets.Where(t => t.Text.Contains("http"));

                //from tweet in twitterContext.Status where tweet.Type == StatusType.Home  select twee
                List <Status> results2 = new List <Status>();
                var           tweets2  = from tweet in twitterContext.Status where tweet.Type == StatusType.Mentions select tweet;
                results2 = tweets2.Select(t => t).ToList();


                List <Status> results3 = new List <Status>();
                var           tweets3  = from tweet in twitterContext.Status where tweet.Type == StatusType.User select tweet;
                results3 = tweets3.Select(t => t).ToList();


                //Time Deltas
                DateTime curent   = DateTime.Now;
                TimeSpan timespan = curent.Subtract(startDateTime);

                //Calculate Counts
                tweetsPerSecond = numberofTweets / timespan.Seconds;
                tweetsPerMinute = (timespan.Minutes <= 0) ? numberofTweets : (numberofTweets / timespan.Minutes);
                tweetsPerHour   = (timespan.Hours <= 0) ? numberofTweets : numberofTweets / timespan.Hours;


                if (displayResults == 2)
                {
                    // Output stored in memory object
                    var output_data = analizeData();
                }
                mylogger.LogAllData();
            }
            catch (Exception ex)
            {
                var error = ex.Message + " " + ex.InnerException;
                //RESET();
                return;
            }

            //tweets.ToList().ForEach(t =>  results.Add(text));

            processStreamData processor = processStreamData.Instance;

            processor.tallyNumberOfTweets(results.Count);


            processStreamData processor2 = processStreamData.Instance;

            processor2.tallyNumberOfTweets(10);
        }
Пример #26
0
 public Commands(TwitterContext master)
 {
     this.Master = master;
 }
Пример #27
0
        static async Task ShowFavoritesAsync(TwitterContext twitterCtx)
        {
            const int PerQueryFavCount = 200;

            // set from a value that you previously saved
            ulong sinceID = 1;

            var favsResponse =
                await
                    (from fav in twitterCtx.Favorites
                    where fav.Type == FavoritesType.Favorites &&
                    fav.Count == PerQueryFavCount &&
                    fav.TweetMode == TweetMode.Extended
                    select fav)
                .ToListAsync();

            if (favsResponse == null)
            {
                Console.WriteLine("No favorites returned from Twitter.");
                return;
            }

            var favList = new List <Favorites>(favsResponse);

            // first tweet processed on current query
            ulong maxID = favList.Min(fav => fav.StatusID) - 1;

            do
            {
                favsResponse =
                    await
                        (from fav in twitterCtx.Favorites
                        where fav.Type == FavoritesType.Favorites &&
                        fav.Count == PerQueryFavCount &&
                        fav.SinceID == sinceID &&
                        fav.MaxID == maxID
                        select fav)
                    .ToListAsync();

                if (favsResponse == null || favsResponse.Count == 0)
                {
                    break;
                }

                // reset first tweet to avoid re-querying the
                // same list you just received
                maxID = favsResponse.Min(fav => fav.StatusID) - 1;
                favList.AddRange(favsResponse);
            } while (favsResponse.Count > 0);

            favList.ForEach(fav =>
            {
                if (fav != null && fav.User != null)
                {
                    Console.WriteLine(
                        "Name: {0}, Tweet: {1}",
                        fav.User.ScreenNameResponse, fav.Text);
                }
            });

            // save this in your db for this user so you can set
            // sinceID accurately the next time you do a query
            // and avoid querying the same tweets again.
            ulong newSinceID = favList.Max(fav => fav.SinceID);
        }
Пример #28
0
        internal static async Task RunAsync(TwitterContext twitterCtx)
        {
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                case '0':
                    Console.WriteLine("\n\tLooking...\n");
                    await LookupUsersAsync(twitterCtx);

                    break;

                case '1':
                    Console.WriteLine("\n\tShowing...\n");
                    await ShowUserDetailsAsync(twitterCtx);

                    break;

                case '2':
                    Console.WriteLine("\n\tSearching...\n");
                    await FindUsersAsync(twitterCtx);

                    break;

                case '3':
                    Console.WriteLine("\n\tShowing...\n");
                    await GetContributeesAsync(twitterCtx);

                    break;

                case '4':
                    Console.WriteLine("\n\tSearching...\n");
                    await GetContributorsAsync(twitterCtx);

                    break;

                case '5':
                    Console.WriteLine("\n\tGetting...\n");
                    await GetBannerSizesAsync(twitterCtx);

                    break;

                case '6':
                    Console.WriteLine("\n\tGetting...\n");
                    await GetUsersInSuggestedCategoriesAsync(twitterCtx);

                    break;

                case '7':
                    Console.WriteLine("\n\tGetting  ...\n");
                    await GetSuggestedCategoryListQueryAsync(twitterCtx);

                    break;

                case '8':
                    Console.WriteLine("\n\tGetting...\n");
                    await ShowUsersInCategoryAsync(twitterCtx);

                    break;

                case '9':
                    Console.WriteLine("\n\tReport spammer...\n");
                    await ReportSpammerAsync(twitterCtx);

                    break;

                case 'q':
                case 'Q':
                    Console.WriteLine("\nReturning...\n");
                    break;

                default:
                    Console.WriteLine(key + " is unknown");
                    break;
                }
            } while (char.ToUpper(key) != 'Q');
        }
Пример #29
0
 public ThreadsService(ILogger <ThreadsService> logger, TwitterContext twitterContext)
 {
     _logger         = logger;
     _twitterContext = twitterContext;
 }
Пример #30
0
        internal static async Task RunAsync(TwitterContext twitterCtx)
        {
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                case '0':
                    Console.WriteLine("\n\tAdding Webhook...\n");
                    await AddWebhookAsync(twitterCtx);

                    break;

                case '1':
                    Console.WriteLine("\n\tListing Webhooks....\n");
                    await ListWebhooksAsync(twitterCtx);

                    break;

                case '2':
                    Console.WriteLine("\n\tDeleting Webhook...\n");
                    await DeleteWebhookAsync(twitterCtx);

                    break;

                case '3':
                    Console.WriteLine("\n\tSending Challenge Response Check...\n");
                    await SendChallengeResponseCheckAsync(twitterCtx);

                    break;

                case '4':
                    Console.WriteLine("\n\tAdding subscription...\n");
                    await AddSubscriptionAsync(twitterCtx);

                    break;

                case '5':
                    Console.WriteLine("\n\tShowing subscriptions...\n");
                    await ShowSubscriptionsAsync(twitterCtx);

                    break;

                case '6':
                    Console.WriteLine("\n\tDeleting subscription...\n");
                    await DeleteSubscriptionAsync(twitterCtx);

                    break;

                case 'q':
                case 'Q':
                    Console.WriteLine("\nReturning...\n");
                    break;

                default:
                    Console.WriteLine(key + " is unknown");
                    break;
                }
            } while (char.ToUpper(key) != 'Q');
        }
Пример #31
0
        private async void ExecuteLoadTweetsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;
            try {
                Tweets.Clear();
                var auth = new ApplicationOnlyAuthorizer()
                {
                    CredentialStore = new InMemoryCredentialStore {
                        ConsumerKey    = "ZTmEODUCChOhLXO4lnUCEbH2I",
                        ConsumerSecret = "Y8z2Wouc5ckFb1a0wjUDT9KAI6DUat5tFNdmIkPLl8T4Nyaa2J",
                    },
                };
                await auth.AuthorizeAsync();

                var twitterContext = new TwitterContext(auth);

#if __IOS__
                //Temp work around, will investigate
                IQueryable <LinqToTwitter.Status> queryResponse =
                    (from tweet in twitterContext.Status
                     where tweet.Type == StatusType.User &&
                     tweet.ScreenName == "shanselman" &&
                     tweet.Count == 100 &&
                     tweet.IncludeRetweets == true &&
                     tweet.ExcludeReplies == true
                     select tweet);

                var queryTweets = queryResponse.ToList();
                var tweets      =
                    (from tweet in queryTweets
                     select new Tweet {
                    StatusID = tweet.StatusID,
                    ScreenName = tweet.User.ScreenNameResponse,
                    Text = tweet.Text,
                    CurrentUserRetweet = tweet.CurrentUserRetweet,
                    CreatedAt = tweet.CreatedAt
                }).ToList();
#else
                var tweets =
                    await(from tweet in twitterContext.Status
                          where tweet.Type == StatusType.User &&
                          tweet.ScreenName == "shanselman" &&
                          tweet.Count == 100 &&
                          tweet.IncludeRetweets == true &&
                          tweet.ExcludeReplies == true
                          select new Tweet
                {
                    StatusID           = tweet.StatusID,
                    ScreenName         = tweet.User.ScreenNameResponse,
                    Text               = tweet.Text,
                    CurrentUserRetweet = tweet.CurrentUserRetweet,
                    CreatedAt          = tweet.CreatedAt
                }).ToListAsync();
#endif

                foreach (var tweet in tweets)
                {
                    Tweets.Add(tweet);
                }
            } catch (Exception ex) {
                var page = new ContentPage();
                page.DisplayAlert("Error", "Unable to load twitter.", "OK", null);
            }

            IsBusy = false;
        }
        /// <summary>
        /// calls the twitter api to get timeline results for a user
        /// </summary>
        /// <returns></returns>
        public static List <Status> GetUserTimeline(TimelineParams inputParams)
        {
            // check the cache for existing data
            List <Status> tweets = (List <Status>)CacheHelper.GetFromCache(CacheKey.UserTimeline, BuildParamString(inputParams));

            if (tweets == null)
            {
                tweets = new List <Status>();

                ulong  lastTweetId = 0;
                string searchScreenName;

                // a valid context
                TwitterContext context = ContextHelper.GetContext();

                // if a screen name has not been provided then get the current users screen name and last tweet id
                if (string.IsNullOrEmpty(inputParams.ScreenName))
                {
                    User authenticatedUser = ContextHelper.GetAuthenticatedUser();
                    searchScreenName = authenticatedUser.Identifier.ScreenName;

                    if (authenticatedUser.Status != null)
                    {
                        lastTweetId = ulong.Parse(authenticatedUser.Status.StatusID);
                    }
                }
                // if a screen name has been provided then get the user and store thier last tweet id
                else
                {
                    searchScreenName = inputParams.ScreenName;

                    var users = from u in context.User
                                where u.Type == UserType.Show &&
                                u.ScreenName == inputParams.ScreenName
                                select u;

                    User user = users.SingleOrDefault();
                    lastTweetId = ulong.Parse(user.Status.StatusID);
                }

                try
                {
                    // Here it is necesary to get the tweets in chunks and add the results to the tweets list
                    // as the number of results returned from the api call is effectively up to the count supplied
                    // due to limitations in the twitter REST api

                    //set a max loops value as a backup
                    int maxloops = 5, count = 0;

                    while (tweets.Count < inputParams.TweetCount && count < maxloops)
                    {
                        //increment the count
                        count++;

                        List <Status> chunkList;

                        chunkList = (from tweet in context.Status
                                     where tweet.Type == StatusType.User &&
                                     tweet.ExcludeReplies == !inputParams.ShowReplies &&
                                     tweet.IncludeRetweets == inputParams.IncludeRetweets &&
                                     tweet.Count == inputParams.TweetCount &&
                                     tweet.ScreenName == searchScreenName &&
                                     tweet.MaxID == lastTweetId
                                     orderby tweet.CreatedAt descending
                                     select tweet).ToList();

                        // add the chunk items into the tweet list
                        foreach (Status tweet in chunkList)
                        {
                            if (tweets.Count < inputParams.TweetCount)
                            {
                                tweets.Add(tweet);
                            }
                        }

                        // store the last tweet recieved so we dont get the same ones next loop (-1 to prevent re-retrieving the last tweet)
                        if (tweets.Count > 0)
                        {
                            lastTweetId = ulong.Parse(chunkList[chunkList.Count - 1].StatusID) - 1;
                        }
                    }

                    CacheHelper.AddToCache(tweets, ConfigHelper.GetAppSetting <int>(ConfigKey.TwitterCacheDuration, 20), CacheKey.UserTimeline, BuildParamString(inputParams));
                }
                catch (TwitterQueryException ex)
                {
                }
            }

            return(tweets);
        }
        /// <summary>
        /// calls the twitter api to get tweets form a list
        /// </summary>
        /// <returns></returns>
        public static List <Status> GetList(TimelineParams inputParams)
        {
            // check the cache for existing data
            List <Status> tweets = (List <Status>)CacheHelper.GetFromCache(CacheKey.UserTimeline, BuildParamString(inputParams));

            if (tweets == null)
            {
                tweets = new List <Status>();

                string searchScreenName = inputParams.ScreenName;
                ulong  lastTweetId      = 0;

                // a valid context
                TwitterContext context = ContextHelper.GetContext();

                // if a screen name has not been provided then get the current users screen name
                if (string.IsNullOrEmpty(inputParams.ScreenName))
                {
                    User authenticatedUser = ContextHelper.GetAuthenticatedUser();
                    searchScreenName = authenticatedUser.Identifier.ScreenName;
                }

                try
                {
                    // Here it is necesary to get the tweets in chunks and add the results to the tweets list
                    // as the number of results returned from the api call is effectively up to the count supplied
                    // due to limitations in the twitter REST api

                    //set a max loops value as a backup
                    int maxloops = 5, count = 0;

                    while (tweets.Count < inputParams.TweetCount && count < maxloops)
                    {
                        //increment the count
                        count++;

                        List <Status> chunkList;

                        if (lastTweetId == 0)
                        {
                            chunkList = (from list in context.List
                                         where list.Type == ListType.Statuses &&
                                         list.OwnerScreenName == searchScreenName &&
                                         list.Slug == inputParams.ListName &&     // name of list to get statuses for
                                         list.Count == inputParams.TweetCount
                                         select list)
                                        .First().Statuses;
                        }
                        else
                        {
                            chunkList = (from list in context.List
                                         where list.Type == ListType.Statuses &&
                                         list.OwnerScreenName == searchScreenName &&
                                         list.Slug == inputParams.ListName &&          // name of list to get statuses for
                                         list.Count == inputParams.TweetCount &&
                                         list.MaxID == lastTweetId
                                         select list)
                                        .First().Statuses;
                        }
                        // add the chunk items into the tweet list
                        foreach (Status tweet in chunkList)
                        {
                            if (tweets.Count < inputParams.TweetCount && (inputParams.IncludeRetweets || (tweet.RetweetedStatus == null || tweet.RetweetedStatus.User == null)))
                            {
                                tweets.Add(tweet);
                            }
                        }

                        // store the last tweet recieved so we dont get the same ones next loop (-1 to prevent re-retrieving the last tweet)
                        if (tweets.Count > 0)
                        {
                            lastTweetId = ulong.Parse(chunkList[chunkList.Count - 1].StatusID) - 1;
                        }
                    }

                    CacheHelper.AddToCache(tweets, ConfigHelper.GetAppSetting <int>(ConfigKey.TwitterCacheDuration, 20), CacheKey.UserTimeline, BuildParamString(inputParams));
                }
                catch (TwitterQueryException ex)
                {
                }
            }

            return(tweets);
        }
Пример #34
0
 /// <summary>
 /// Run all related results demos
 /// </summary>
 /// <param name="twitterCtx">TwitterContext</param>
 public static void Run(TwitterContext twitterCtx)
 {
     ShowRelatedResultsDemo(twitterCtx);
 }
Пример #35
0
 public Service()
 {
     twitterContext = new TwitterContext(authorizer);
 }
Пример #36
0
 public Service()
 {
     twitterContext = new TwitterContext(authorizer);
 }
Пример #37
0
        internal static async Task RunAsync(TwitterContext twitterCtx)
        {
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                case '0':
                    Console.WriteLine("\n\tShowing mentions timeline...");
                    await ShowMentionsTimelineAsync(twitterCtx);

                    break;

                case '1':
                    Console.WriteLine("\n\tShowing user timeline...\n");
                    await RunUserTimelineQueryAsync(twitterCtx);

                    break;

                case '2':
                    Console.WriteLine("\n\tShowing home timeline...\n");
                    await RunHomeTimelineQueryAsync(twitterCtx);

                    break;

                case '3':
                    Console.WriteLine("\n\tShowing retweets...\n");
                    await RetweetsOfMeStatusQueryAsync(twitterCtx);

                    break;

                case '4':
                    Console.WriteLine("\n\tShowing retweets...\n");
                    await RetweetsQueryAsync(twitterCtx);

                    break;

                case '5':
                    Console.WriteLine("\n\tDeleting tweet...\n");
                    await DeleteTweetAsync(twitterCtx);

                    break;

                case '6':
                    Console.WriteLine("\n\tTweeting...\n");
                    await TweetAsync(twitterCtx);

                    break;

                case '7':
                    Console.WriteLine("\n\tReplying...\n");
                    await ReplyAsync(twitterCtx);

                    break;

                case '8':
                    Console.WriteLine("\n\tRetweeting...\n");
                    await RetweetAsync(twitterCtx);

                    break;

                case '9':
                    Console.WriteLine("\n\tGetting oembed...\n");
                    await OEmbedStatusAsync(twitterCtx);

                    break;

                case 'a':
                case 'A':
                    Console.WriteLine("\n\tGetting retweeters...\n");
                    await RetweetersAsync(twitterCtx);

                    break;

                case 'q':
                case 'Q':
                    Console.WriteLine("\nReturning...\n");
                    break;

                default:
                    Console.WriteLine(key + " is unknown");
                    break;
                }
            } while (char.ToUpper(key) != 'Q');
        }
Пример #38
0
        public async Task RunUserTimelineQueryAsync(TwitterContext twitterCtx)
        {
            //List<Status> tweets =
            //    await
            //    (from tweet in twitterCtx.Status
            //     where tweet.Type == StatusType.User &&
            //           tweet.ScreenName == "JoeMayo"
            //     select tweet)
            //    .ToListAsync();

            const int MaxTweetsToReturn = 200;
            int       MaxTotalResults   = MaxTweets;

            // oldest id you already have for this search term
            ulong sinceID = 1;

            // used after the first query to track current session
            ulong maxID;

            var combinedSearchResults = new List <Status>();

            List <Status> tweets =
                await
                    (from tweet in twitterCtx.Status
                    where tweet.Type == StatusType.User &&
                    tweet.ScreenName == UserName &&
                    tweet.Count == MaxTweetsToReturn &&
                    tweet.SinceID == sinceID &&
                    tweet.TweetMode == TweetMode.Extended
                    select tweet)
                .ToListAsync();

            if (tweets != null)
            {
                combinedSearchResults.AddRange(tweets);
                ulong previousMaxID = ulong.MaxValue;
                do
                {
                    // one less than the newest id you've just queried
                    //maxID = tweets.Max(status => status.StatusID) - 1;
                    //sinceID = (ulong)combinedSearchResults.Count;
                    //maxID = sinceID + MaxTweetsToReturn;
                    //Debug.Assert(maxID < previousMaxID);
                    //previousMaxID = maxID;
                    // one less than the newest id you've just queried
                    maxID = tweets.Min(status => status.StatusID) - 1;

                    //Debug.Assert(maxID < previousMaxID);
                    previousMaxID = maxID;

                    tweets =
                        await
                            (from tweet in twitterCtx.Status
                            where tweet.Type == StatusType.User &&
                            tweet.ScreenName == UserName &&
                            tweet.Count == MaxTweetsToReturn &&
                            tweet.MaxID == maxID &&
                            tweet.SinceID == sinceID &&
                            tweet.TweetMode == TweetMode.Extended
                            select tweet)
                        .ToListAsync();

                    combinedSearchResults.AddRange(tweets);
                } while (tweets.Any() && combinedSearchResults.Count < MaxTotalResults);

                //PrintTweetsResults(tweets);
                Tweets =
                    (from tweet in combinedSearchResults
                     select new Tweet
                {
                    StatusID = tweet.StatusID,
                    ScreenName = tweet.User.ScreenNameResponse,
                    Text = tweet.FullText,
                    ImageUrl = tweet.User.ProfileImageUrl
                })
                    .ToList();
            }
            else
            {
                //Console.WriteLine("No entries found.");
                Tweets = new List <Tweet>();
                Tweets.Add(new Tweet()
                {
                    Text = "No entries found."
                });
            }
        }
Пример #39
0
 public StartController(ILogger <StartController> logger, TwitterContext context)
 {
     this.logger = logger;
     this.db     = context;
 }
Пример #40
0
 public BaseService(TwitterContext context)
 {
     this.context = context;
 }
Пример #41
0
 public MessageServices(IHttpContextAccessor httpAccessor)
 {
     _dbContext = (TwitterContext)httpAccessor.HttpContext.RequestServices.GetService(typeof(TwitterContext));
 }
Пример #42
0
 public Twitter(string consumerKey, string consumerSecret)
 {
     auth       = SetAuth(consumerKey, consumerSecret).Result;
     twitterCtx = new TwitterContext(auth);
 }
Пример #43
0
		//namespace Utility
		//{
		//	public static class API
		//	{
		//		public static async Task<string> GetAuthorizeUrl(string oauth_consumer_key, string oauth_consumer_secret)
		//		{
		//			TwitterContext tw = new TwitterContext()
		//			{
		//				ConsumerKey = oauth_consumer_key,
		//				ConsumerSecret = oauth_consumer_secret
		//			};

		//			string res = await Twitter.API.REST.oauth.request_token(tw);

		//			string oauth_token = res.Substring(res.IndexOf("oauth_token") + "oauth_token".Length + 1, res.IndexOf("&") - (res.IndexOf("oauth_token") + "oauth_token".Length + 1));
		//			string oauth_token_secret = res.Substring(res.IndexOf("oauth_token_secret") + "oauth_token_secret".Length + 1, res.IndexOf("&", res.IndexOf("&") + 1) - (res.IndexOf("oauth_token_secret") + "oauth_token_secret".Length + 1));

		//			return "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth_token;
		//		}
		//	}
		//}

		public static async Task<string> authorize(TwitterContext twitterContext)
		{
            return await new TwitterRequest(twitterContext, API.Methods.GET, new Uri(API.Urls.Oauth_Authorize)).Request();
		}
Пример #44
0
 public API()
 {
     _twitterCtx = new TwitterContext(Auth);
 }
Пример #45
0
		public static async Task<string> request_token(TwitterContext twitterContext)
		{
            return await new TwitterRequest(twitterContext, API.Methods.POST, new Uri(API.Urls.Oauth_RequestToken)).Request();
		}
Пример #46
0
        internal static async Task RunAsync(TwitterContext twitterCtx)
        {
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                case '0':
                    Console.WriteLine("\n\tShowing friends...\n");
                    await ShowFriendsAsync(twitterCtx);

                    break;

                case '1':
                    Console.WriteLine("\n\tLooking up user ids...\n");
                    await LookupUserIDsAsync(twitterCtx);

                    break;

                case '2':
                    Console.WriteLine("\n\tGetting incoming...\n");
                    await IncomingFriendshipsAsync(twitterCtx);

                    break;

                case '3':
                    Console.WriteLine("\n\tGetting Outgoing...\n");
                    await OutgoingFriendshipsAsync(twitterCtx);

                    break;

                case '4':
                    Console.WriteLine("\n\tShowing no retweet IDs...\n");
                    await NoRetweetIDsAsync(twitterCtx);

                    break;

                case '5':
                    Console.WriteLine("\n\tGetting friends list...\n");
                    await FriendsListAsync(twitterCtx);

                    break;

                case '6':
                    Console.WriteLine("\n\tGetting followers list...\n");
                    await FollowersListAsync(twitterCtx);

                    break;

                case '7':
                    Console.WriteLine("\n\tShowing followers ids...\n");
                    await ShowFollowerIDsAsync(twitterCtx);

                    break;

                case '8':
                    Console.WriteLine("\n\tShowing friend ids...\n");
                    await ShowFriendIDsAsync(twitterCtx);

                    break;

                case '9':
                    Console.WriteLine("\n\tCreating friendship...\n");
                    await CreateFriendshipAsync(twitterCtx);

                    break;

                case 'a':
                case 'A':
                    Console.WriteLine("\n\tUnfollowing...\n");
                    await DestroyFriendshipAsync(twitterCtx);

                    break;

                case 'b':
                case 'B':
                    Console.WriteLine("\n\tUpdating friend settings...\n");
                    await UpdateFreindshipSettingsAsync(twitterCtx);

                    break;

                case 'q':
                case 'Q':
                    Console.WriteLine("\nReturning...\n");
                    break;

                default:
                    Console.WriteLine(key + " is unknown");
                    break;
                }
            } while (char.ToUpper(key) != 'Q');
        }
Пример #47
0
        static async Task DoDemosAsync()
        {
            var auth = ChooseAuthenticationStrategy();

            await auth.AuthorizeAsync();

            // This is how you access credentials after authorization.
            // The oauthToken and oauthTokenSecret do not expire.
            // You can use the userID to associate the credentials with the user.
            // You can save credentials any way you want - database, isolated storage, etc. - it's up to you.
            // You can retrieve and load all 4 credentials on subsequent queries to avoid the need to re-authorize.
            // When you've loaded all 4 credentials, LINQ to Twitter will let you make queries without re-authorizing.
            //
            //var credentials = auth.CredentialStore;
            //string oauthToken = credentials.OAuthToken;
            //string oauthTokenSecret = credentials.OAuthTokenSecret;
            //string screenName = credentials.ScreenName;
            //ulong userID = credentials.UserID;
            //

            var  twitterCtx = new TwitterContext(auth);
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                case '0':
                    Console.WriteLine("\n\tRunning Account Demos...\n");
                    await AccountDemos.RunAsync(twitterCtx);

                    break;

                case '1':
                    Console.WriteLine("\n\tRunning Block Demos...\n");
                    await BlockDemos.RunAsync(twitterCtx);

                    break;

                case '2':
                    Console.WriteLine("\n\tRunning Direct Message Demos...\n");
                    await DirectMessageDemos.RunAsync(twitterCtx);

                    break;

                case '3':
                    Console.WriteLine("\n\tRunning Favorite Demos...\n");
                    await FavoriteDemos.RunAsync(twitterCtx);

                    break;

                case '4':
                    Console.WriteLine("\n\tRunning Friendship Demos...\n");
                    await FriendshipDemos.RunAsync(twitterCtx);

                    break;

                case '5':
                    Console.WriteLine("\n\tRunning Geo Demos...\n");
                    await GeoDemos.RunAsync(twitterCtx);

                    break;

                case '6':
                    Console.WriteLine("\n\tRunning Help Demos...\n");
                    await HelpDemos.RunAsync(twitterCtx);

                    break;

                case '7':
                    Console.WriteLine("\n\tRunning List Demos...\n");
                    await ListDemos.RunAsync(twitterCtx);

                    break;

                case '8':
                    Console.WriteLine("\n\tRunning Raw Demos...\n");
                    await RawDemos.RunAsync(twitterCtx);

                    break;

                case '9':
                    Console.WriteLine("\n\tRunning Saved Search Demos...\n");
                    await SavedSearchDemos.RunAsync(twitterCtx);

                    break;

                case 'a':
                case 'A':
                    Console.WriteLine("\n\tRunning Search Demos...\n");
                    await SearchDemos.RunAsync(twitterCtx);

                    break;

                case 'b':
                case 'B':
                    Console.WriteLine("\n\tRunning Status Demos...\n");
                    await StatusDemos.RunAsync(twitterCtx);

                    break;

                case 'c':
                case 'C':
                    Console.WriteLine("\n\tRunning Stream Demos...\n");
                    await StreamDemos.RunAsync(twitterCtx);

                    break;

                case 'd':
                case 'D':
                    Console.WriteLine("\n\tRunning Trend Demos...\n");
                    await TrendDemos.RunAsync(twitterCtx);

                    break;

                case 'e':
                case 'E':
                    Console.WriteLine("\n\tRunning User Demos...\n");
                    await UserDemos.RunAsync(twitterCtx);

                    break;

                case 'f':
                case 'F':
                    Console.WriteLine("\n\tRunning Mutes Demos...\n");
                    await MuteDemos.RunAsync(twitterCtx);

                    break;

                case 'g':
                case 'G':
                    Console.WriteLine("\n\tRunning Vine Demos...\n");
                    await VineDemos.RunAsync(twitterCtx);

                    break;

                case 'q':
                case 'Q':
                    Console.WriteLine("\nQuitting...\n");
                    break;

                default:
                    Console.WriteLine(key + " is unknown");
                    break;
                }
            } while (char.ToUpper(key) != 'Q');
        }
Пример #48
0
 public TwitterRepository()
 {
     _twitterContext = TwitterContextFactory.CreateTwitterContext();
 }
Пример #49
0
        static async Task UpdateTwit(TwitterContext twitterCtx, string statues)
        {
            ulong  tweetid = tweetidparser(statues);
            string mesg    = messageparser(statues);
            string chkstr  = mesg.ToLower();

            if (mute)
            {
                if (chkstr.IndexOf("말") > 0)
                {
                    mute = false;
                    await ReplyAsync(twitterCtx, tweetid, "트윗을 합니다.");
                }
            }
            else
            {
                Console.WriteLine("Converted : " + mesg);
                if (chkstr.IndexOf("조용") > 0)
                {
                    mute = true;
                    mesg = "조용히 합니다. 말하기 전까지 모든 명령을 무시합니다.";
                }
                if (chkstr.IndexOf("꺼져") > 0)
                {
                    await ReplyAsync(twitterCtx, tweetid, "꺼집니다.");

                    System.Environment.Exit(0);
                }
                if (chkstr.IndexOf("분할") > 0)
                {
                    if (chkstr.IndexOf("켜") > 0)
                    {
                        splitsend = true;
                        mesg      = "트윗 분할을 켭니다.";
                    }
                    else
                    {
                        splitsend = false;
                        mesg      = "트윗 분할을 끕니다.";
                    }
                }
                if (chkstr.IndexOf("ip") > 0)
                {
                    mesg = DateTime.Now + "의 ipv4주소:" + ipv4parser(cmdparser("ipconfig"));
                }
                else if (chkstr.IndexOf("cmd:") > 0)
                {
                    mesg = System.Text.RegularExpressions.Regex.Matches(mesg, "\"(.*)\"", System.Text.RegularExpressions.RegexOptions.None)[0].Groups[1].Value;
                    mesg = cmdparser(mesg);
                    Console.WriteLine("Command-line prompt Triggerd");
                }
                if (splitsend && (mesg.Length > 120))
                {
                    await SplitSend(twitterCtx, tweetid, mesg);
                }
                else
                {
                    await ReplyAsync(twitterCtx, tweetid, mesg);
                }
            }
        }
Пример #50
0
        static async Task SendTypingIndicatorAsync(TwitterContext twitterCtx)
        {
            ulong recipientID = 15411837;

            await twitterCtx.IndicateTypingAsync(recipientID);
        }
Пример #51
0
 public BaseController(TwitterContext data)
 {
     Data = data;
 }
Пример #52
0
        internal static async Task RunAsync(TwitterContext twitterCtx)
        {
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                case '0':
                    Console.WriteLine("\n\tShowing DMs...\n");
                    await ShowDirectMessagesAsync(twitterCtx);

                    break;

                case '1':
                    Console.WriteLine("\n\tListing DMs...\n");
                    await ListDirectMessagesAsync(twitterCtx);

                    break;

                case '2':
                    Console.WriteLine("\n\tSending DM...\n");
                    await NewDirectMessageAsync(twitterCtx);

                    break;

                case '3':
                    Console.WriteLine("\n\tDeleting DM...\n");
                    await DeleteDirectMessageAsync(twitterCtx);

                    break;

                case '4':
                    Console.WriteLine("\n\tSending DM with media...\n");
                    await NewDirectMessageWithMediaAsync(twitterCtx);

                    break;

                case '5':
                    Console.WriteLine("\n\tSending DM with media...\n");
                    await NewDirectMessageWithCoordinatesAsync(twitterCtx);

                    break;

                case '6':
                    Console.WriteLine("\n\tSending DM with media...\n");
                    await NewDirectMessageWithPlaceAsync(twitterCtx);

                    break;

                case '7':
                    Console.WriteLine("\n\tSending Quick Reply Location...\n");
                    await RequestQuickReplyOptionsAsync(twitterCtx);

                    break;

                case '8':
                    Console.WriteLine("\n\tSending Button Choice...\n");
                    await RequestButtonChoiceAsync(twitterCtx);

                    break;

                case '9':
                    Console.WriteLine("\n\tSending Typing Indicator...\n");
                    await SendTypingIndicatorAsync(twitterCtx);

                    break;

                case 'a':
                case 'A':
                    Console.WriteLine("\n\tSending Message Read...\n");
                    await SendMessageReadAsync(twitterCtx);

                    break;

                case 'q':
                case 'Q':
                    Console.WriteLine("\nReturning...\n");
                    break;

                default:
                    Console.WriteLine(key + " is unknown");
                    break;
                }
            } while (char.ToUpper(key) != 'Q');
        }
Пример #53
0
        private void RealTimeSearchTwitter(TwitterContext twitterContext, string keyword, List <string> keys)
        {
            var streamItems =
                twitterContext.Streaming.Where(x => x.Type == StreamingType.Filter && x.Track == keyword).StreamingCallback(
                    x =>
            {
                if (x.Status == TwitterErrorStatus.Success)
                {
                    try
                    {
                        dynamic obj = JsonConvert.DeserializeObject(x.Content);

                        string text = obj.text;
                        var tag     = string.Empty;
                        foreach (var key in keys)
                        {
                            if (text.ToLowerInvariant().Contains(key))
                            {
                                tag = key;
                                break;
                            }
                        }

                        if (!string.IsNullOrEmpty(tag))
                        {
                            string userName   = obj.user.screen_name;
                            string userImgUrl = obj.user.profile_image_url_https;
                            string statusId   = obj.id_str;
                            var time          = DateTime.ParseExact((string)obj.created_at, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
                            string time2      = time.ToString("dd MMMM dddd - HH:mm", CultureInfo.InvariantCulture);

                            //find who you wil notify
                            var keywords = keywordRepository.AsQueryable().Where(y => y.Key == tag);
                            foreach (var organizationKeyword in keywords)
                            {
                                var orgKey = organizationKeyword;
                                ThreadPool.QueueUserWorkItem(m => pusherServer.Trigger(string.Format("presence-{0}", orgKey.OrganizationId), "tweet_added",
                                                                                       new { statusId, text, tag, userName, userImgUrl, time2 }));
                            }

                            this.tweetRepository.Add(
                                new Tweet
                            {
                                CreatedBy           = "System",
                                UpdatedBy           = "System",
                                TweetText           = text,
                                TweetStatusID       = statusId,
                                TwitterUserID       = obj.user.id_str,
                                TwitterUserImageUrl = userImgUrl,
                                TwitterUserName     = userName,
                                CreatedAt           = time,
                                UpdatedAt           = DateTime.Now,
                                Keyword             = tag
                            });
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }).SingleOrDefault();
        }
Пример #54
0
 public TwitterStatusRepository(TwitterContext context, ICache cache)
     : base(context, cache)
 {
 }
Пример #55
0
        public static async Task Main(string[] args)
        {
            // Bootstrap the app
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json")
                          .AddJsonFile("appsettings.Development.json", optional: true)
                          .AddEnvironmentVariables()
                          .AddConfigServer();

            Configuration = builder.Build();

            var factory = new LoggerFactory();

            factory.AddConsole(Configuration.GetSection("Logging"));

            var services = new ServiceCollection()
                           .AddDiscoveryClient(Configuration)
                           .AddOptions()
                           .BuildServiceProvider();

            TwitterCredentials twitterCreds = new TwitterCredentials();

            Configuration.GetSection("Twitter").Bind(twitterCreds);

            var auth = new SingleUserAuthorizer
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey      = twitterCreds.ConsumerKey,
                    ConsumerSecret   = twitterCreds.ConsumerSecret,
                    OAuthToken       = twitterCreds.AccessToken,
                    OAuthTokenSecret = twitterCreds.AccessTokenSecret
                }
            };
            await auth.AuthorizeAsync();

            var   ctx     = new TwitterContext(auth);
            ulong sinceId = 1;

            // next line Fails, not able to resolve IOptionsMonitor<EurekaClientOptions>
            var discoveryClient = services.GetRequiredService <IDiscoveryClient>();
            DiscoveryHttpClientHandler _handler = new DiscoveryHttpClientHandler(discoveryClient, factory.CreateLogger <DiscoveryHttpClientHandler>());
            var httpClient = new HttpClient(_handler, false);

            // begin monitoring
            Console.WriteLine("Entering the loop...");
            while (true)
            {
                string searchTerm = Configuration.GetValue <string>("twitterSearch");
                Console.WriteLine($"Checking for 10 tweets with query '{searchTerm}'");

                List <Status> searchResponse =
                    await(from s in ctx.Search where s.Query == searchTerm && s.Type == SearchType.Search && s.IncludeEntities == true && s.TweetMode == TweetMode.Extended && s.SinceID == sinceId && s.Count == 10 select s.Statuses).SingleOrDefaultAsync();

                if (searchResponse.Any())
                {
                    sinceId = searchResponse.Max(s => s.StatusID);
                    var texts = searchResponse.Select(t => t.FullText);
                    Console.WriteLine($"Found {texts.Count()} tweets");
                    foreach (var t in texts)
                    {
                        Console.WriteLine(t);
                    }

                    // post to web api
                    var apiResponse = await httpClient.PostAsync("http://SmartBulbs-Web/home/bulktext", new StringContent(JsonConvert.SerializeObject(texts), Encoding.UTF8, "application/json"));

                    if (apiResponse.IsSuccessStatusCode)
                    {
                        var responseBody = await apiResponse.Content.ReadAsJsonAsync <ColorChangeResponse>();

                        Console.WriteLine($"Aggregate sentiment value was {responseBody.Sentiment} which translates to #{responseBody.HexColor}");
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"Request failed, status code: {apiResponse.StatusCode}");
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                }
                else
                {
                    Console.WriteLine("No new tweets found");
                }
                Thread.Sleep(Configuration.GetValue <int>("sleepTime"));
            }
        }
Пример #56
0
        internal static async Task RunAsync(TwitterContext twitterCtx)
        {
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                case '0':
                    Console.WriteLine("\n\tVerifying Credentials...\n");
                    await VerifyCredentialsAsync(twitterCtx);

                    break;

                case '1':
                    Console.WriteLine("\n\tRequesting settings....\n");
                    await AccountSettingsAsync(twitterCtx);

                    break;

                case '2':
                    Console.WriteLine("\n\tUpdating colors...\n");
                    await UpdateAccountColorsAsync(twitterCtx);

                    break;

                case '3':
                    Console.WriteLine("\n\tUpdating image...\n");
                    await UpdateAccountImageAsync(twitterCtx);

                    break;

                case '4':
                    Console.WriteLine("\n\tUpdating image...\n");
                    await UpdateAccountBackgroundImageAsync(twitterCtx);

                    break;

                case '5':
                    Console.WriteLine("\n\tUpdating account...\n");
                    await UpdateAccountProfileAsync(twitterCtx);

                    break;

                case '6':
                    Console.WriteLine("\n\tUpdating account...\n");
                    await UpdateAccountSettingsAsync(twitterCtx);

                    break;

                case '7':
                    Console.WriteLine("\n\tUpdating device...\n");
                    await UpdateDeliveryDeviceAsync(twitterCtx);

                    break;

                case '8':
                    Console.WriteLine("\n\tUpdating banner...\n");
                    await UpdateProfileBannerAsync(twitterCtx);

                    break;

                case '9':
                    Console.WriteLine("\n\tRemoving banner...\n");
                    await RemoveProfileBannerAsync(twitterCtx);

                    break;

                case 'q':
                case 'Q':
                    Console.WriteLine("\nReturning...\n");
                    break;

                default:
                    Console.WriteLine(key + " is unknown");
                    break;
                }
            } while (char.ToUpper(key) != 'Q');
        }
 public TwitterFriendshipRepository(TwitterContext context, ICache cache)
     : base(context, cache)
 {
 }
Пример #58
0
 /// <summary>
 /// Run all trends related demos
 /// </summary>
 /// <param name="twitterCtx">TwitterContext</param>
 public static void Run(TwitterContext twitterCtx)
 {
     SearchAvailableTrendsDemo(twitterCtx);
     SearchClosestTrendsDemo(twitterCtx);
     SearchPlaceTrendsDemo(twitterCtx);
 }
Пример #59
0
 public Twitter(MvcAuthorizer Authorizer)
 {
     this.auth  = Authorizer;
     twitterCtx = new TwitterContext(auth);
 }
        //We start multiple actions in parallel to delete tweets
        void EraseTweetsAction(TwitterContext ctx, CancellationToken cancellationToken)
        {
            int nextTweetID = getNextTweetIDSync();

#if DEBUG_TEST
            Random rnd = new Random();
#endif

            //Are we done?
            while (nextTweetID != Int32.MinValue)
            {
                //We can't cancel here, we have already fetched a new ID and if we cancel here it will never be deteled
                Tweet tweet = mTweetsCollection[nextTweetID];

                //Clear Tweets logic here
                try
                {
#if DEBUG_TEST
                    Thread.Sleep(sleepFakeWaitMilliseconds);
                    if (rnd.Next() % 3 == 0)    // Simulate error
                    {
                        throw new ArgumentNullException();
                    }
                    else
                    {
                        Exception e = new Exception("Sorry, that page does not exist");
                        throw new Exception("", e);
                    }
#else
                    ulong         tid  = ulong.Parse(tweet.ID);
                    Status        ret  = null;
                    DirectMessage ret2 = null;

                    switch (TweetsEraseType)
                    {
                    case ApplicationSettings.EraseTypes.TweetsAndRetweets:
                        ret = ctx.DeleteTweetAsync(tid).Result;
                        break;

                    case ApplicationSettings.EraseTypes.Favorites:
                        ret = ctx.DestroyFavoriteAsync(tid).Result;
                        break;

                    case ApplicationSettings.EraseTypes.DirectMessages:
                        ret2 = ctx.DestroyDirectMessageAsync(tid, true).Result;
                        break;

                    default:
                        break;
                    }
#endif
                    tweet.Status = STATUS_DELETED;
                }
                catch (Exception ex)
                {
                    TwitterQueryException exception = ex.InnerException as TwitterQueryException;
                    if (exception != null && exception.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        tweet.Status = STATUS_NOT_FOUND;
                    }
                    else if (exception != null &&
                             (exception.StatusCode == System.Net.HttpStatusCode.Unauthorized || exception.StatusCode == System.Net.HttpStatusCode.Forbidden))
                    {
                        tweet.Status = STATUS_NOT_ALLOWED;
                    }
                    else
                    {
                        tweet.Status = STATUS_ERROR;
                        var tmp = new JsonTweet()
                        {
                            created_at = Helpers.DateTimeToString(tweet.Date), id_str = tweet.ID, text = tweet.Text
                        };

                        lock (_lockerNotDeletedTweetsLst)
                        {
                            notDeletedTweets.Add(tmp);
                        }
                    }
                }
                finally
                {
                    onDeletedTweetUIUpdate(tweet);
                }

                //We cancel once a tweet is completely handeled, we make sure not to request for a new one
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                nextTweetID = getNextTweetIDSync();
            }
        }