Esempio n. 1
0
        public static void UserTimeline()
        {
            IAsyncResult asyncResult = TwitterTimelineAsync.UserTimeline(
                Configuration.GetTokens(),
                new UserTimelineOptions(),
                new TimeSpan(0, 2, 0),
                PerformCommonTimelineTests);

            asyncResult.AsyncWaitHandle.WaitOne();

            UserTimelineOptions User_Options = new UserTimelineOptions();

            User_Options.ScreenName = "twitterapi";
            User_Options.Count      = 8;

            TwitterResponse <TwitterStatusCollection> timelineResponse = TwitterTimeline.UserTimeline(Configuration.GetTokens(), User_Options);

            PerformCommonTimelineTests(timelineResponse);

            timelineResponse = TwitterTimeline.UserTimeline(User_Options);
            PerformCommonTimelineTests(timelineResponse);
        }
Esempio n. 2
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                List <decimal> tmp = new List <decimal> {
                    19273963, 19617105
                };

                //TwitterResponse<UserIdCollection> Response = TwitterFriendship.FollowersIds(Tokens, new UsersIdsOptions { ScreenName = "FlyAirNZ", Cursor = -1 });
                //var Response = TwitterUser.Lookup(Tokens, new LookupUsersOptions() { UserIds = new TwitterIdCollection(tmp) });
                var Response = TwitterTimeline.UserTimeline(
                    Tokens,
                    new UserTimelineOptions
                {
                    UserId = 19273963,
                    Count  = 200,
                    //SkipUser = false, //get the user's full details so it matches the User object in our db context.
                    SkipUser        = true,
                    IncludeRetweets = true
                }
                    );

                var rate = Response.RateLimiting;

                AppendLineToOutput(string.Format("{0} out of {1} calls remaining ; resets at {2} ({3})"
                                                 , rate.Remaining
                                                 , rate.Total
                                                 , rate.ResetDate.ToLocalTime()
                                                 , rate.ResetDate.Subtract(DateTime.UtcNow).TotalMinutes.ToString()
                                                 ));
            }
            catch (Exception ex)
            {
                AppendLineToOutput("Error : " + ex.Message);
                AppendLineToOutput(ex.StackTrace);
            }
        }
Esempio n. 3
0
        void doit(SearchTypeEnum searchType)
        {
            if (_isRunning)
            {
                Invokers.SetAppendText(textBox1, true, 100, "Already running!");

                return;
            }

            _isRunning = true;

            try {
                string twitterUsername = Common.GetRegistryEntry(Constants.RegistryKeys.TwitterScreenName, string.Empty);

                if (twitterUsername == string.Empty)
                {
                    Invokers.SetAppendText(textBox1, true, 100, "Twitter Username must not be blank");

                    EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterScreenName", string.Empty);
                    EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterMessage", string.Empty);
                    EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterSuccess", false);

                    return;
                }

                if (!twitterUsername.StartsWith("@"))
                {
                    twitterUsername = "******" + twitterUsername;
                }

                Invokers.SetAppendText(textBox1, true, 100, "Polling {0}", twitterUsername);

                OAuthTokens token = new OAuthTokens {
                    AccessToken       = Common.GetRegistryEntry(Constants.RegistryKeys.TwitterAccessToken, string.Empty),
                    AccessTokenSecret = Common.GetRegistryEntry(Constants.RegistryKeys.TwitterAccessTokenSecret, string.Empty),
                    ConsumerKey       = Constants.TwitterConsumerKey,
                    ConsumerSecret    = Constants.TwitterConsumerSecret
                };

                TwitterResponse <TwitterStatusCollection> timeline;

                if (searchType == SearchTypeEnum.Tweets)
                {
                    timeline = TwitterTimeline.UserTimeline(token, new UserTimelineOptions {
                        Count           = 10,
                        ScreenName      = twitterUsername,
                        IncludeRetweets = false
                    });
                }
                else
                {
                    timeline = TwitterTimeline.Mentions(token, new TimelineOptions()
                    {
                        Count           = 10,
                        IncludeRetweets = false
                    });
                }

                if (timeline.Result != RequestResult.Success)
                {
                    Invokers.SetAppendText(textBox1, true, 100, timeline.ErrorMessage);

                    EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterScreenName", string.Empty);
                    EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterMessage", string.Empty);
                    EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterSuccess", false);

                    return;
                }

                for (int i = 0; i < timeline.ResponseObject.Count; i++)
                {
                    TwitterStatus message = timeline.ResponseObject[i];

                    if (searchType == SearchTypeEnum.Tweets)
                    {
                        if (message.CreatedDate <= _lastTweetDateTime)
                        {
                            EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterScreenName", string.Empty);
                            EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterMessage", string.Empty);
                            EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterSuccess", false);

                            continue;
                        }

                        _lastTweetDateTime = message.CreatedDate;
                    }
                    else
                    {
                        if (message.CreatedDate <= _lastMentionDateTime)
                        {
                            EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterScreenName", string.Empty);
                            EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterMessage", string.Empty);
                            EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterSuccess", false);

                            continue;
                        }

                        _lastMentionDateTime = message.CreatedDate;
                    }

                    // remove the tagged twitter name from the message
                    string messageText = Regex.Replace(message.Text, twitterUsername, string.Empty, RegexOptions.IgnoreCase);

                    // remove double spaces
                    while (messageText.Contains("  "))
                    {
                        messageText = messageText.Replace("  ", " ");
                    }

                    // remove start and ending white spaces
                    messageText = messageText.Trim();

                    Invokers.SetAppendText(textBox1, true, 100, "{0} - {1}", message.User.ScreenName, messageText);

                    EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterScreenName", message.User.ScreenName);
                    EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterMessage", messageText);
                    EZ_Builder.Scripting.VariableManager.SetVariable("$TwitterSuccess", true);

                    return;
                }
            } catch (Exception ex) {
                Invokers.SetAppendText(textBox1, true, 100, "Error: {0}", ex.Message);
            } finally {
                Invokers.SetAppendText(textBox1, true, 100, "Done");

                _isRunning = false;
            }
        }
        internal static CommandResult GetTimelines(decimal[] ids, bool resume)
        {
            if (!IsInitiated)
            {
                return(CommandResult.NotInitiated);
            }

            foreach (var id in ids)
            {
                if (id == 0)
                {
                    continue;
                }

                var UserToProcess = (new TwitterContext()).Users.FirstOrDefault(u => u.Id == id);

                if (UserToProcess == null)
                {
                    Form.AppendLineToOutput(string.Format("User with id {0} does not exist in the database.", id), Color.DarkSlateBlue);
                    continue;
                }
                //else continue and get user's timeline

                string  ScreenName       = UserToProcess.ScreenName;
                decimal IdNumber         = UserToProcess.Id;
                long    NumberOfStatuses = UserToProcess.NumberOfStatuses;

                TwitterContext db = null;
                try
                {
                    //var _friendshipContext = new TwitterEntitiesForFriendship();

                    TwitterResponse <TwitterStatusCollection> TimelineResponse;
                    int numTweets            = 0;
                    int duplicatesFoundTotal = 0;

                    Form.AppendLineToOutput(string.Format("Attempt to save timeline for {0} ({1} tweets).", ScreenName, NumberOfStatuses), Color.DarkSlateBlue);

                    decimal EarliestTweetId = 0;

                    if (resume)
                    {
                        EarliestTweetId = GetEarliestTweetId(id);
                    }
                    do
                    {
                        TimelineResponse = TwitterTimeline.UserTimeline(
                            Tokens,
                            new UserTimelineOptions
                        {
                            UserId = IdNumber,
                            Count  = MaxNumberOfTweets,
                            //SkipUser = false, //get the user's full details so it matches the User object in our db context.
                            SkipUser        = true,
                            MaxStatusId     = EarliestTweetId,
                            IncludeRetweets = true
                        }
                            );

                        if (TimelineResponse.Result == RequestResult.Success)
                        {
                            TwitterStatusCollection tweets = TimelineResponse.ResponseObject;
                            int duplicates = 0;
                            if (tweets == null || tweets.Count == 0)
                            {
                                break;
                            }
                            else
                            {
                                foreach (TwitterStatus tweet in tweets)
                                {
                                    //refresh context
                                    db = new TwitterContext();
                                    db.Configuration.AutoDetectChangesEnabled = false;

                                    if (!db.Tweets.Any(t => t.Id == tweet.Id)) //only continue if the tweet doesn't already exist
                                    {
                                        SaveTweet(tweet);

                                        numTweets++;
                                    }
                                    else
                                    {
                                        duplicates++;;
                                    }
                                }

                                duplicatesFoundTotal += duplicates;
                                EarliestTweetId       = tweets.LastOrDefault().Id - 1;
                            }

                            Form.AppendLineToOutput(string.Format("{0} tweets now saved for {1} (id:{2}). {3} duplicate {4} not saved.", numTweets, ScreenName, IdNumber, duplicatesFoundTotal, duplicatesFoundTotal == 1 ? "tweet" : "tweets"), Color.DarkSlateBlue);

                            //if we are getting no more new tweets then assume saved timeline is now up to date.
                            if (duplicates == tweets.Count)
                            {
                                break;
                            }
                        }
                        else if (TimelineResponse.Result == RequestResult.RateLimited)
                        {
                            WaitForRateLimitReset(TimelineResponse);

                            Form.AppendLineToOutput("Resuming GetTimelines command", Color.DarkSlateBlue);
                            continue;
                        }
                        else if (TimelineResponse.Result == RequestResult.Unauthorized || TimelineResponse.Result == RequestResult.FileNotFound)
                        {
                            /**
                             * Attempt to fix a bug discovered on 2012-06-21: user no longer exists so Twitter returns a
                             * FileNotFound error ('sorry the page no longer exists'). Because of the hack above which
                             * forces the loop to continue it keeps looping and getting the same error until all 350 calls
                             * are exhausted then repeats and repeats :(
                             *
                             * Attempted fix/change is: added "|| timelineResponse.Result == RequestResult.FileNotFound"
                             * treat no-longer-existant users the same as protected users.
                             **/
                            Form.AppendLineToOutput(string.Format("User {0} is now private or no longer exists.", ScreenName), Color.DarkSlateBlue);

                            //Set user to protected.
                            using (var tmpDb = new TwitterContext())
                            {
                                var u = tmpDb.Users.Find(IdNumber);
                                u.IsProtected = true;
                                tmpDb.SaveChanges();
                            }

                            break; //give up with current user
                        }
                        else
                        {
                            HandleTwitterizerError <TwitterStatusCollection>(TimelineResponse);

                            //log that this user should be retried later
                            File.AppendAllText(@".\users-to-retry.txt", IdNumber.ToString() + Environment.NewLine);

                            break; //give up with current user for now
                        }
                    } while (TimelineResponse.ResponseObject != null && TimelineResponse.ResponseObject.Count > 0);
                }
                catch (Exception e)
                {
                    Exception current = e;
                    Form.AppendLineToOutput(string.Format("Unexpected exception : {0}", e.Message), Color.DarkSlateBlue);

                    while (current.InnerException != null)
                    {
                        Form.AppendLineToOutput(string.Format("Inner exception : {0}", current.InnerException.Message), Color.DarkSlateBlue);
                        current = current.InnerException;
                    }

                    //log that this user should be retried later
                    File.AppendAllText(@".\users-to-retry.txt", IdNumber.ToString() + Environment.NewLine);

                    continue; //give up with current user
                }
                finally
                {
                    if (db != null)
                    {
                        db.Dispose();
                    }
                }
            }

            return(CommandResult.Success);
        }
Esempio n. 5
0
        public ActionResult Profile(String screenname)
        {
            if (Session["LoggedASP"] != null)
            {
                ViewData["username"] = ((User)Session["LoggedUser"]).Username;
            }

            try
            {
                TwitterResponse <TwitterUser> user;
                if (Session["LoggedTwitter"] != null)
                {
                    OAuthTokens token = new OAuthTokens();
                    token.ConsumerKey       = ConfigurationManager.AppSettings["consumerKey"];
                    token.ConsumerSecret    = ConfigurationManager.AppSettings["consumerSecret"];
                    token.AccessToken       = ((User)Session["LoggedUser"]).TwitterToken;
                    token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret;
                    user = TwitterUser.Show(token, screenname);
                }
                else
                {
                    user = TwitterUser.Show(screenname);
                }

                if (String.IsNullOrEmpty(user.ErrorMessage))
                {
                    ViewData["content"] = "<img class='userImg' src='" + user.ResponseObject.ProfileImageLocation.ToString() + "' />Profil de <em>@" + user.ResponseObject.ScreenName + "</em> qui possède l'ID N°" + user.ResponseObject.Id + "<br />Il s'est enregistré sur Twitter le : " + user.ResponseObject.CreatedDate + " et il possède " + user.ResponseObject.NumberOfFollowers + " followers.";

                    UserTimelineOptions options = new UserTimelineOptions();
                    options.ScreenName      = screenname;
                    options.Count           = 100;
                    options.IncludeRetweets = true;

                    if (Session["LoggedTwitter"] != null)
                    {
                        OAuthTokens token = new OAuthTokens();
                        token.ConsumerKey       = ConfigurationManager.AppSettings["consumerKey"];
                        token.ConsumerSecret    = ConfigurationManager.AppSettings["consumerSecret"];
                        token.AccessToken       = ((User)Session["LoggedUser"]).TwitterToken;
                        token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret;

                        bool taRaceVanStaen = false;
                        if (screenname.ToLower() == TwitterUser.Show(token, Decimal.Parse(((User)Session["LoggedUser"]).TwitterID)).ResponseObject.ScreenName.ToLower())
                        {
                            taRaceVanStaen = false;
                        }

                        TwitterResponse <TwitterStatusCollection> truc = TwitterTimeline.UserTimeline(token, options);



                        if (String.IsNullOrEmpty(truc.ErrorMessage))
                        {
                            foreach (var item in truc.ResponseObject)
                            {
                                if (taRaceVanStaen)
                                {
                                    ViewData["tweets"] += "<div class='editTweet'><a href=''>Edit</a> <a href=''>Delete</a></div><div><a href=\"/User/" + item.User.ScreenName + "\">" + item.User.ScreenName + "</a> ---- " + item.Text.Replace("\n", "<br />").ToString() + "</div>";
                                }
                                else
                                {
                                    ViewData["tweets"] += "<div><a href=\"/User/" + item.User.ScreenName + "\">" + item.User.ScreenName + "</a> ---- " + item.Text.Replace("\n", "<br />").ToString() + "</div>";
                                }
                            }
                        }
                        else
                        {
                            ViewData["tweets"] = "Les tweets de cet utilisateur sont protégés.";
                        }
                    }
                    else
                    {
                        TwitterResponse <TwitterStatusCollection> truc = TwitterTimeline.UserTimeline(options);

                        if (String.IsNullOrEmpty(truc.ErrorMessage))
                        {
                            foreach (var item in truc.ResponseObject)
                            {
                                ViewData["tweets"] += "<div><a href=\"/User/" + item.User.ScreenName + "\">" + item.User.ScreenName + "</a> ---- " + item.Text.Replace("\n", "<br />").ToString() + "</div>";
                            }
                        }
                        else
                        {
                            ViewData["tweets"] = "Les tweets de cet utilisateur sont protégés.";
                        }
                    }
                    return(View("Index"));
                }
                else
                {
                    ViewData["errorMessage"] = user.ErrorMessage;
                    return(View("Error"));
                }
            }
            catch (Exception exception)
            {
                ViewData["errorMessage"] = exception.Message;
                return(View("Error"));
            }
        }