/// <summary>
 /// Create record to represent a twitter status.
 /// The result is returned as a normalized "StatusUpdateRecord" (the same record type is used for the different social network providers, to
 /// make the mashups easier to write and consume)
 /// </summary>
 /// <param name="search"></param>
 /// <returns></returns>
 private static IRecord CreateStatusRecord(LinqToTwitter.Status status)
 {
     if (String.IsNullOrEmpty(status.User.ScreenName))
     {
         status.User.ScreenName = status.User.Identifier.ScreenName;
     }
     if (String.IsNullOrEmpty(status.User.UserID))
     {
         status.User.UserID = status.User.Identifier.UserID;
     }
     return(RecordBase.CreateRecord(new StatusUpdateRecord
     {
         User = new SocialProfileRecord
         {
             UserID = status.User.UserID,
             Description = status.User.Description,
             LastName = status.User.Name,
             FirstName = "",
             ScreenName = "@" + status.User.ScreenName,
             PictureUrl = String.IsNullOrEmpty(status.User.ProfileImageUrlHttps) ? status.User.ProfileImageUrl : status.User.ProfileImageUrlHttps,
             //ProfileUrl = status.User.Url ?? ("https://twitter.com/" + status.User.ScreenName)
             // per Twitter guidelines we actually need this one to go to the Twitter profile, not their specified URL
             ProfileUrl = "https://twitter.com/" + status.User.ScreenName
         },
         Favorited = status.Favorited,
         Retweeted = status.Retweeted,
         StatusID = status.StatusID,
         Text = Twitterize(status.Text),
         CreatedAt = status.CreatedAt,
         Icon = "tweet.ico",
         StatusUrl = String.Format(TWITTER_STATUS_URL, status.User.ScreenName, status.StatusID),
         SocialNetwork = "Twitter"
     }));
 }
Esempio n. 2
0
 private static List <GeoCoordinate> GetCoordinatesFromTweet(LinqToTwitter.Status tweet)
 {
     return(tweet.Place?.BoundingBox?.Coordinates
            .Select(c => new GeoCoordinate(c.Latitude, c.Longitude))
            .ToList()
            ?? new List <GeoCoordinate>());
 }
Esempio n. 3
0
        void DataSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            switch (e.ListChangedType)
            {
            case ListChangedType.ItemAdded:
            {
                vScrollBar.Value = 0;
                Twitter.Status newTweet = DataSource[e.NewIndex];

                TweetPane newPane = new TweetPane(newTweet);
                newPane.Location = new Point(0, 0);
                newPane.Size     = new Size(panelTweetPanels.Width, 140);
                newPane.Visible  = true;
                foreach (var item in Panes)
                {
                    item.Location = new Point(item.Location.X, item.Location.Y + 140);
                }
                Panes.Add(newPane);
                panelTweetPanels.Controls.Add(newPane);
                vScrollBar.Maximum = Panes.Count * 140;
                newPane.Reply     += new TweetReplyEventHandler(TweetPane_Reply);
                break;
            }

            default:
                break;
            }
        }
Esempio n. 4
0
 private string GetTweetMediaUrl(Status status)
 {
     if (status.Entities != null && status.Entities.MediaEntities.Count > 0)
     {
         return status.Entities.MediaEntities[0].MediaUrlHttps;
     }
     return "";
 }
        public TweetTrackerAction(Status status, IEnumerable<CaptureSubject> addedTo)
        {
            this._addedTo = new ObservableCollection<CaptureSubject>(addedTo);
            this._colors = new GradientStopCollection();
            this._status = status;

            this.MakeGradients();
            this._colors.Freeze();
        }
Esempio n. 6
0
        private void Challenging(TwitterContext twitterContext, LinqToTwitter.Status challengeTweet)
        {
            Receive <BikeShareSystem.Challenge>(challenge =>
            {
                var result = GoogleMaps.Directions.Query(new DirectionsRequest
                {
                    Key         = _googleApiKey,
                    Origin      = new GoogleApi.Entities.Common.Location(challenge.From.Lat, challenge.From.Lon),
                    Destination = new GoogleApi.Entities.Common.Location(challenge.To.Lat, challenge.To.Lon),
                    TravelMode  = TravelMode.Bicycling,
                    Units       = Units.Imperial,
                });

                if (result.Status.GetValueOrDefault() == GoogleApi.Entities.Common.Enums.Status.Ok)
                {
                    var leg = result.Routes
                              .SelectMany(r => r.Legs)
                              .FirstOrDefault();
                    string status = BuildChallengeTweet(challenge, leg);

                    twitterContext.ReplyAsync(challengeTweet.StatusID, $"@{challengeTweet.User.ScreenNameResponse} {status}")
                    .ContinueWith(task =>
                    {
                        Console.WriteLine($"Tweeted {task.Result.Text}");
                        return(true);
                    },
                                  TaskContinuationOptions.ExecuteSynchronously)
                    .PipeTo(Self);
                }

                Become(() => Listening(twitterContext));

                Stash.UnstashAll();
            });

            ReceiveAny(_ => Stash.Stash());

            var fromCoordinate = GetPlaceCoordinate(new Regex(@"\bfrom\b\s+(?<Place>.*?)(\bto\b|$)", RegexOptions.IgnoreCase), challengeTweet.Text);
            var toCoordinate   = GetPlaceCoordinate(new Regex(@"\bto\b\s+(?<Place>.*?)(\bfrom\b|$)", RegexOptions.IgnoreCase), challengeTweet.Text);

            if (fromCoordinate == null)
            {
                List <GeoCoordinate> coordinates = GetCoordinatesFromTweet(challengeTweet);
                if (coordinates.Any())
                {
                    fromCoordinate = GetCentralGeoCoordinate(coordinates);
                }
            }

            TellAllBikeShareSystems(new BikeShareSystem.RequestChallenge
            {
                From           = fromCoordinate,
                To             = toCoordinate,
                AreaOfInterest = _settings.AreaOfInterest,
            });
        }
Esempio n. 7
0
 /// <summary>
 /// Creates instance from class
 /// </summary>
 /// <param name="tweet">handled tweet</param>
 public TweetPane(Twitter.Status tweet)
 {
     InitializeComponent();
     Tweet = tweet;
     richTextBoxMessage.Text   = tweet.Text;
     labelCreated.Text         = tweet.CreatedAt.ToString();
     labelUserName.Text        = tweet.User.Name;
     pictureBoxImage.Image     = WebImages[tweet.User.ProfileImageUrlHttps];
     linklabelFavorite.Enabled = !tweet.Favorited;
     linkLabelRetweet.Enabled  = !tweet.Retweeted;
 }
Esempio n. 8
0
 private static Tweet Map(Status source)
 {
     if (source == null) throw new ArgumentNullException("source");
     return new Tweet
     {
         ScreenName = source.ScreenName,
         Avatar = source.User.ProfileImageUrl,
         Message = source.Text,
         Timestamp = ToFriendlyDate(source.CreatedAt)
     };
 }
Esempio n. 9
0
 /// <summary>
 /// Creates instance from class 
 /// </summary>
 /// <param name="tweet">handled tweet</param>
 public TweetPane(Twitter.Status tweet)
 {
     InitializeComponent();
     Tweet = tweet;
     richTextBoxMessage.Text = tweet.Text;
     labelCreated.Text = tweet.CreatedAt.ToString();
     labelUserName.Text = tweet.User.Name;
     pictureBoxImage.Image = WebImages[tweet.User.ProfileImageUrlHttps];
     linklabelFavorite.Enabled = !tweet.Favorited;
     linkLabelRetweet.Enabled = !tweet.Retweeted;
 }
 private static TweetDto BuildTweetDto(Status tweet)
 {
     return new TweetDto
     {
         Id = tweet.StatusID.ToString(CultureInfo.InvariantCulture),
         TweetUri = new Uri(String.Format("https://twitter.com/statuses/ID/{0}", tweet.ID)),
         Text = tweet.Text,
         UserName = tweet.User.Name,
         CreatedAt = tweet.CreatedAt,
         UserProfileImageUri = new Uri(tweet.User.ProfileImageUrl)
     };
 }
Esempio n. 11
0
        public User(JsonData user)
        {
            if (user == null) return;

            var userID = user.GetValue<int>("id").ToString(CultureInfo.InvariantCulture);
            Identifier = new UserIdentifier
            {
                ID = userID,
                UserID = userID,
                ScreenName = user.GetValue<string>("screen_name")
            };
            Name = user.GetValue<string>("name");
            Location = user.GetValue<string>("location");
            Description = user.GetValue<string>("description");
            ProfileImageUrl = user.GetValue<string>("profile_image_url");
            ProfileImageUrlHttps = user.GetValue<string>("profile_image_url_https");
            Url = user.GetValue<string>("url");
            Protected = user.GetValue<bool>("protected");
            ProfileUseBackgroundImage = user.GetValue<bool>("profile_use_background_image");
            IsTranslator = user.GetValue<bool>("is_translator");
            FollowersCount = user.GetValue<int>("followers_count");
            DefaultProfile = user.GetValue<bool>("default_profile");
            ProfileBackgroundColor = user.GetValue<string>("profile_background_color");
            LangResponse = user.GetValue<string>("lang");
            ProfileTextColor = user.GetValue<string>("profile_text_color");
            ProfileLinkColor = user.GetValue<string>("profile_link_color");
            ProfileSidebarFillColor = user.GetValue<string>("profile_sidebar_fill_color");
            ProfileSidebarBorderColor = user.GetValue<string>("profile_sidebar_border_color");
            FriendsCount = user.GetValue<int>("friends_count");
            DefaultProfileImage = user.GetValue<bool>("default_profile_image");
            CreatedAt = user.GetValue<string>("created_at").GetDate(DateTime.MinValue);
            FavoritesCount = user.GetValue<int>("favourites_count");
            UtcOffset = user.GetValue<int>("utc_offset");
            TimeZone = user.GetValue<string>("time_zone");
            ProfileBackgroundImageUrl = user.GetValue<string>("profile_background_image_url");
            ProfileBackgroundImageUrlHttps = user.GetValue<string>("profile_background_image_url_https");
            ProfileBackgroundTile = user.GetValue<bool>("profile_background_tile");
            ProfileBannerUrl = user.GetValue<string>("profile_banner_url");
            StatusesCount = user.GetValue<int>("statuses_count");
            Notifications = user.GetValue<bool>("notifications");
            GeoEnabled = user.GetValue<bool>("geo_enabled");
            Verified = user.GetValue<bool>("verified");
            ContributorsEnabled = user.GetValue<bool>("contributors_enabled");
            Following = user.GetValue<bool>("following");
            ShowAllInlineMedia = user.GetValue<bool>("show_all_inline_media");
            ListedCount = user.GetValue<int>("listed_count");
            FollowRequestSent = user.GetValue<bool>("follow_request_sent");
            Status = new Status(user.GetValue<JsonData>("status"));
            CursorMovement = new Cursors(user);
        }
Esempio n. 12
0
        public DGStatus(Status source, DGAccount account)
        {
            m_visbile = true;
            Source = source;
            Account = account;            
            User = DGUser.GetUser(source.User);

            var mediaEntities = source.Entities.MediaEntities.Where(m => m.Type.Equals("photo", StringComparison.OrdinalIgnoreCase));

            if (mediaEntities.Any())
            {
                MainImageUrl = mediaEntities.First().MediaUrl;
                HasImages = true;
            }
        }               
        private static object MapStatus(Status status) {
            if (status == null || status.StatusID == 0)
                return null;

            return new {
                created_at = status.CreatedAt.ToString("F"),
                text = status.Text,
                id_str = status.StatusID,
                screen_name = status.User.ScreenName,
                retweeted_status = MapStatus(status.RetweetedStatus),
                user = new {
                    name = status.User.Name,
                    screen_name = status.User.ScreenName,
                    profile_image_url = status.User.ProfileImageUrl,
                    profile_image_url_https = status.User.ProfileImageUrlHttps,
                }
            };
        }
Esempio n. 14
0
        public PartialViewResult TwitterFeed()
        {
            Diagnostic.Start( "Twitter" );
            TwitterContext twitter = new TwitterContext();
            Status target;
            try
            {
                target = ( from tweet in twitter.Status
                                  where tweet.Type == StatusType.User &&
                                        tweet.ScreenName == "ghostmonk" &&
                                        tweet.IncludeRetweets == true &&
                                        tweet.Count == 1
                                  select tweet ).First();
            }
            catch
            {
                target = new Status { Text = FAIL_WHALE };
            }
            Diagnostic.Stop( "Twitter" );

            return PartialView( "Twitter", target );
        }
Esempio n. 15
0
        private void GettingBikeShareSystemInfo(TwitterContext twitterContext, LinqToTwitter.Status tweet)
        {
            Receive <BikeShareSystem.Status>(status =>
            {
                twitterContext.ReplyAsync(tweet.StatusID, $"@{tweet.User.ScreenNameResponse} There are {status.Bikes} bikes and {status.Docks} docks across {status.Stations} stations.")
                .ContinueWith(task =>
                {
                    Console.WriteLine($"Tweeted {task.Result.Text}");
                    return(true);
                },
                              TaskContinuationOptions.ExecuteSynchronously)
                .PipeTo(Self);

                Become(() => Listening(twitterContext));

                Stash.UnstashAll();
            });

            TellAllBikeShareSystems(new BikeShareSystem.RequestStatus
            {
                AreaOfInterest = _settings.AreaOfInterest,
            });
        }
Esempio n. 16
0
 void TweetPane_Reply(Twitter.Status tweet)
 {
     textBoxTweetContent.Text = "@" + tweet.User.Identifier.ScreenName;
     textBoxTweetContent.Focus();
 }
Esempio n. 17
0
        /// <summary>
        /// Takes the provided status and matches it against the
        /// key words to determine whether it should be added
        /// </summary>
        /// <param name="status">The status whose text is used
        /// to match it against the keywords</param>
        /// <returns>True if the status was added to this subject,
        /// otherwise false</returns>
        public bool AddStatus(Status status)
        {
            if (this._timer.Enabled)
            {
                foreach (var keyword in this._keywords)
                {
                    var match = Regex.Match(status.Text, keyword, RegexOptions.IgnoreCase);

                    if (match.Success)
                    {
                        this.AllStatusCount = this._allStatusCount + 1;
                        this._statuses.Add(status);
                        return true;
                    }
                }
            }

            return false;
        }
Esempio n. 18
0
        private void HandleTweet(Status status)
        {
            var addedTo = new List<CaptureSubject>();

            foreach (var subject in this._captureSubjects)
            {
                if (subject.AddStatus(status))
                {
                    addedTo.Add(subject);
                }
            }

            if (!(!this.Settings.HashTag.Equals(string.Empty) || addedTo.Count != 0))
            {
                return;
            }

            this.AddStatus(status);

            if (this.StatusProcessedEvent != null)
            {
                this.StatusProcessedEvent(new TweetTrackerAction(status, addedTo));
            }
        }
Esempio n. 19
0
        public static int AddTweetToDatabase(string UserID, Status newStatus)
        {
            using (var db = new Models.Database())
            {
                var TwitterStatus = new Models.TwitterStatus()
                {
                    TwitterAccount = db.TwitterAccounts.First(ta => ta.UserID == UserID),
                    TweetID = newStatus.StatusID.ToString(),
                    Text = newStatus.Text,
                    TimeTweeted = newStatus.CreatedAt,
                    TimeAdded = DateTime.UtcNow
                };

                db.TwitterStatuses.Add(TwitterStatus);
                db.SaveChanges();
                return TwitterStatus.ID;
            }
        }
Esempio n. 20
0
        private static void MapTweetToHtml(Status tweet, string uiMap, string match)
        {
            string[] matchParts = match.Split(':');

            
        }
Esempio n. 21
0
        public Status(JsonData status)
        {
            if (status == null) return;

            Retweeted = status.GetValue<bool>("retweeted");
            Source = status.GetValue<string>("source");
            InReplyToScreenName = status.GetValue<string>("in_reply_to_screen_name");
            PossiblySensitive = status.GetValue<bool>("possibly_sensitive");
            RetweetedStatus = new Status(status.GetValue<JsonData>("retweeted_status"));
            var contributors = status.GetValue<JsonData>("contributors");
            Contributors =
                contributors == null ?
                    new List<Contributor>() :
                    (from JsonData contributor in contributors
                     select new Contributor(contributor))
                    .ToList();
            var coords = status.GetValue<JsonData>("coordinates");
            if (coords != null)
            {
                Coordinates = new Coordinate(coords.GetValue<JsonData>("coordinates"));
            }
            else
            {
                Coordinates = new Coordinate();
            }
            Place = new Place(status.GetValue<JsonData>("place"));
            User = new User(status.GetValue<JsonData>("user"));
            RetweetCount = status.GetValue<int>("retweet_count");
            StatusID = status.GetValue<string>("id_str");
            FavoriteCount = status.GetValue<int?>("favorite_count");
            Favorited = status.GetValue<bool>("favorited");
            InReplyToStatusID = status.GetValue<string>("in_reply_to_status_id_str");
            Source = status.GetValue<string>("source");
            CreatedAt = status.GetValue<string>("created_at").GetDate(DateTime.MaxValue);
            InReplyToUserID = status.GetValue<string>("in_reply_to_user_id_str");
            Truncated = status.GetValue<bool>("truncated");
            Text = status.GetValue<string>("text");
            Annotation = new Annotation(status.GetValue<JsonData>("annotation"));
            Entities = new Entities(status.GetValue<JsonData>("entities"));
            var currentUserRetweet = status.GetValue<JsonData>("current_user_retweet");
            if (currentUserRetweet != null)
            {
                CurrentUserRetweet = currentUserRetweet.GetValue<ulong>("id");
            }
            var scopes = status.GetValue<JsonData>("scopes");
            Scopes =
                scopes == null ? new Dictionary<string, string>() :
                (from key in (scopes as IDictionary<string, JsonData>).Keys as List<string>
                 select new
                 {
                     Key = key,
                     Value = scopes[key].ToString()
                 })
                .ToDictionary(
                    key => key.Key,
                    val => val.Value);
            WithheldCopyright = status.GetValue<bool>("withheld_copyright");
            var withheldCountries = status.GetValue<JsonData>("withheld_in_countries");
            WithheldInCountries =
                withheldCountries == null ? new List<string>() :
                (from JsonData country in status.GetValue<JsonData>("withheld_in_countries")
                 select country.ToString())
                .ToList();
            WithheldScope = status.GetValue<string>("withheld_scope");
            MetaData = new StatusMetaData(status.GetValue<JsonData>("metadata"));
            Lang = status.GetValue<string>("lang");
            string filterLvl = status.GetValue<string>("filter_level");
            try
            {
                FilterLevel =
                    filterLvl == null ? FilterLevel.None :
                    (FilterLevel)Enum.Parse(typeof(FilterLevel), filterLvl, ignoreCase: true);
            }
            catch (ArgumentException)
            {
                FilterLevel = FilterLevel.None;
            }
        }
Esempio n. 22
0
        private void StartTwitterUserStream(TwitterContext context)
        {
            hadUserStreamFailure = false;
            context.Log = log;

            try
            {
                userStreamTask = context.Streaming
                    .Where(s => s.Type == LinqToTwitter.StreamingType.User)
                    .Select(strm => strm)
                    .StartAsync(async strm =>
                    {
                        await Task.Run(() =>
                        {
                            try
                            {
                                lastCallBackTimeUserStream = DateTime.Now;
                                if (userStream == null)
                                    log.WriteLine("{0}: Twitter Connection Established (UserStream)", DateTime.Now);
                                userStream = strm;
                                if (strm != null)
                                {
                                    /* LinqToTwitter v3.0 no longer has *.Status
                                    if (strm.Status == TwitterErrorStatus.RequestProcessingException)
                                    {
                                        var wex = strm.Error as WebException;
                                        if (wex != null && wex.Status == WebExceptionStatus.ConnectFailure)
                                        {
                                            log.WriteLine("{0}: LinqToTwitter UserStream Connection Failure (UserStream)", DateTime.Now);
                                            hadUserStreamFailure = true;
                                            //Will Be Restarted By Processing Queue
                                        }
                                    }
                                    else
                                    */
                                    if (!string.IsNullOrEmpty(strm.Content))
                                    {
                                        var status = new LinqToTwitter.Status(LitJson.JsonMapper.ToObject(strm.Content));
                                        if (status != null && status.StatusID > 0)
                                        {
                                            var tweet = new Tweet(status.RetweetedStatus.StatusID == 0 ? status : status.RetweetedStatus);
                                            lock (queue_lock)
                                            {
                                                queue.Add(tweet);
                                            }
                                            log.WriteLine("{0}: Added Item to Queue (UserStream): {1}", DateTime.Now, tweet.TweetText);
                                        }
                                        else
                                        {
                                            //If you can handle friends we will look for them
                                            if (processingStep is ITweepProcessingStep)
                                            {
                                                var jsonDataFriends = LitJson.JsonMapper.ToObject(strm.Content)
                                                    .FirstOrDefault(x => x.Key == "friends");

                                                //If this is a friends collection update we will notify you
                                                if (!jsonDataFriends.Equals(default(KeyValuePair<string, LitJson.JsonData>)) &&
                                                    jsonDataFriends.Value != null &&
                                                    jsonDataFriends.Value.IsArray)
                                                {
                                                    var friends = new List<LazyLoader<Tweep>>();
                                                    for (int i = 0; i < jsonDataFriends.Value.Count; i++)
                                                    {
                                                        friends.Add(TwitterModel.Instance(PrimaryUser.TwitterScreenName).GetLazyLoadedTweep(ulong.Parse(jsonDataFriends.Value[i].ToString()), Tweep.TweepType.Follower));
                                                    }

                                                    (processingStep as ITweepProcessingStep).ProcessTweeps(friends);
                                                }
                                                else
                                                    log.WriteLine("{0}: Unhandled Item in Stream (UserStream): {1}", DateTime.Now, strm.Content);
                                            }
                                            else
                                                log.WriteLine("{0}: Unhandled Item in Stream (UserStream): {1}", DateTime.Now, strm.Content);
                                        }
                                    }
                                    else
                                        log.WriteLine("{0}: Twitter Keep Alive (UserStream)", DateTime.Now);
                                }
                                else
                                    throw new ArgumentNullException("strm", "This value should never be null!");
                            }
                            catch (Exception ex)
                            {
                                log.WriteLine("{0}: Error (UserStream): {1}", DateTime.Now, ex.ToString());
                            }
                        });
                    });
            }
            catch (Exception ex)
            {
                log.WriteLine("{0}: Error (UserStream): {1}", DateTime.Now, ex.ToString());
            }
        }
        private void Start(string track = null)
        {
            TwitterContext context = new TwitterContext(new MvcAuthorizer()
            {
                CredentialStore = new LinqToTwitter.InMemoryCredentialStore()
                {
                    OAuthTokenSecret = ConfigurationManager.AppSettings["OAuthTokenSecret"],
                    ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
                    OAuthToken = ConfigurationManager.AppSettings["OAuthToken"]
                }
            });

            if (log != null)
                context.Log = log;

            track = track ?? ConfigurationManager.AppSettings["Track"];
            var trackList = !string.IsNullOrEmpty(track) ? track.ToLower().Split(',').OrderByDescending(x => x.Length).ToList() : new List<string>();

            try
            {
                streamTask = context.Streaming
                    .Where(s => s.Type == LinqToTwitter.StreamingType.Filter && s.Track == string.Join(",", trackList.Distinct()))
                    .Select(strm => strm)
                    .StartAsync(async strm =>
                    {
                        await Task.Run(() =>
                        {
                            try
                            {
                                stream = strm;
                                if (strm != null)
                                {
                                    if (!string.IsNullOrEmpty(strm.Content))
                                    {
                                        var status = new LinqToTwitter.Status(LitJson.JsonMapper.ToObject(strm.Content));
                                        if (status != null && status.StatusID > 0)
                                        {
                                            string statusText = status.Text.ToLower();
                                            if (trackList.Any(x => statusText.Contains(x)))
                                            {
                                                statusHandler(status.Text);
                                                if (log != null)
                                                    log.WriteLine("{0}: Status Handled: @{1} said [{2}]", DateTime.Now, status.User.ScreenName, status.Text);
                                            }
                                        }
                                        else if (log != null)
                                            log.WriteLine("{0}: Unhandled Item in Stream: {1}", DateTime.Now, strm.Content);
                                    }
                                    else if (log != null)
                                        log.WriteLine("{0}: Twitter Keep Alive", DateTime.Now);
                                }
                                else
                                    throw new ArgumentNullException("strm", "This value should never be null!");
                            }
                            catch (Exception ex)
                            {
                                if (log != null)
                                    log.WriteLine("{0}: Error (TrackerStream): {1}", DateTime.Now, ex.ToString());
                            }
                        });
                    });

            }
            catch (Exception ex)
            {
                if (log != null)
                    log.WriteLine("{0}: Error: {1}", DateTime.Now, ex.ToString());
            }
        }
        private void HandleTweet(StreamContent content)
        {
            if (content.Status != TwitterErrorStatus.Success)
            {
                Debug.WriteLine(content.Error.ToString());
                return;
            }

            var statusJson = ContentToJson(content);

            if(statusJson == null)
            {
                return;
            }

            var status = new Status(statusJson);

            if(status.Text == null)
            {
                return;
            }

            if (this._cultures != null)
            {
                foreach (var culture in this._cultures)
                {
                    if(status.Lang.Equals(culture))
                    {
                        this._listener(status);
                        break;
                    }
                }
            }
            else
            {
                this._listener(status);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Shreds an XML element into a Status object
        /// </summary>
        /// <param name="status">XML element with info</param>
        /// <returns>Newly populated status object</returns>
        public Status CreateStatus(XElement status)
        {
            if (status == null)
            {
                return null;
            }

            var dateParts =
                status.Element("created_at").Value.Split(' ');

            var createdAtDate =
                dateParts.Count() > 1 ?
                DateTime.Parse(
                    string.Format("{0} {1} {2} {3} GMT",
                    dateParts[1],
                    dateParts[2],
                    dateParts[5],
                    dateParts[3]),
                    CultureInfo.InvariantCulture) :
                DateTime.MinValue;

            var user = status.Element("user");

            var retweet = status.Element("retweeted_status");

            var rtDateParts =
                retweet == null ?
                    null :
                    retweet.Element("created_at").Value.Split(' ');

            var retweetedAtDate =
                retweet == null ?
                    DateTime.MinValue :
                    DateTime.Parse(
                        string.Format("{0} {1} {2} {3} GMT",
                        rtDateParts[1],
                        rtDateParts[2],
                        rtDateParts[5],
                        rtDateParts[3]),
                        CultureInfo.InvariantCulture);

            List<string> contributorIDs = null;

            if (status.Element("contributors") != null)
            {
                contributorIDs =
                    (from id in status.Element("contributors").Elements("user_id")
                     select id.Value)
                     .ToList();
            }

            XNamespace geoRss = "http://www.georss.org/georss";

            var geoStr =
               status.Element("geo") != null &&
               status.Element("geo").Element(geoRss + "point") != null ?
                   status.Element("geo").Element(geoRss + "point").Value :
                   string.Empty;

            Geo geo = new Geo();
            if (!string.IsNullOrEmpty(geoStr))
            {
                var coordArr = geoStr.Split(' ');

                double tempLatitude = 0;
                double tempLongitide = 0;

                if (double.TryParse(coordArr[Coordinate.LatitudePos], out tempLatitude) &&
                    double.TryParse(coordArr[Coordinate.LongitudePos], out tempLongitide))
                {
                    geo =
                        new Geo
                        {
                            Latitude = tempLatitude,
                            Longitude = tempLongitide
                        };
                }
            }

            var coordStr =
                status.Element("coordinates") != null &&
                status.Element("coordinates").Element(geoRss + "point") != null ?
                    status.Element("coordinates").Element(geoRss + "point").Value :
                    string.Empty;

            Coordinate coord = new Coordinate();
            if (!string.IsNullOrEmpty(coordStr))
            {
                var coordArr = coordStr.Split(' ');

                double tempLatitude = 0;
                double tempLongitide = 0;

                if (double.TryParse(coordArr[Coordinate.LatitudePos], out tempLatitude) &&
                    double.TryParse(coordArr[Coordinate.LongitudePos], out tempLongitide))
                {
                    coord =
                        new Coordinate
                        {
                            Latitude = tempLatitude,
                            Longitude = tempLongitide
                        };
                }
            }

            var place = new Place().CreatePlace(status.Element("place"));

            var usr = new User();

            var newStatus = new Status
            {
                CreatedAt = createdAtDate,
                Favorited =
                 bool.Parse(
                     string.IsNullOrEmpty(status.Element("favorited").Value) ?
                     "true" :
                     status.Element("favorited").Value),
                StatusID = status.Element("id").Value,
                InReplyToStatusID = status.Element("in_reply_to_status_id").Value,
                InReplyToUserID = status.Element("in_reply_to_user_id").Value,
                Source = status.Element("source").Value,
                Text = status.Element("text").Value,
                Truncated = bool.Parse(status.Element("truncated").Value),
                InReplyToScreenName =
                     status.Element("in_reply_to_screen_name") == null ?
                         string.Empty :
                         status.Element("in_reply_to_screen_name").Value,
                ContributorIDs = contributorIDs,
                Geo = geo,
                Coordinates = coord,
                Place = place,
                User = usr.CreateUser(user),
                Retweet =
                    retweet == null ?
                        null :
                        new Retweet
                        {
                            ID = retweet.Element("id").Value,
                            CreatedAt = retweetedAtDate,
                            Favorited =
                                bool.Parse(
                                    string.IsNullOrEmpty(retweet.Element("favorited").Value) ?
                                    "true" :
                                    retweet.Element("favorited").Value),
                            InReplyToScreenName = retweet.Element("in_reply_to_screen_name").Value,
                            InReplyToStatusID = retweet.Element("in_reply_to_status_id").Value,
                            InReplyToUserID = retweet.Element("in_reply_to_user_id").Value,
                            Source = retweet.Element("source").Value,
                            Text = retweet.Element("text").Value,
                            Truncated =
                                bool.Parse(
                                    string.IsNullOrEmpty(retweet.Element("truncated").Value) ?
                                    "true" :
                                    retweet.Element("truncated").Value),
                            RetweetingUser = usr.CreateUser(retweet.Element("user"))
                        }
            };

            return newStatus;
        }
        private TweetViewModel GetTweetViewModel(Status tweet)
        {
            var tvm = new TweetViewModel
            {
                ImageUrl = tweet.User.ProfileImageUrl,
                ScreenName = tweet.User.Identifier.ScreenName,
                MediaUrl = GetTweetMediaUrl(tweet),
                Tweet = tweet.Text,
                Id = tweet.StatusID,
                FavoriteCount = tweet.FavoriteCount.ToString(),
                RetweetCount = tweet.RetweetCount.ToString(),

            };
            tvm.HasMedia = !string.IsNullOrEmpty(tvm.MediaUrl);
            return tvm;
        }
Esempio n. 27
0
        private void StartTwitterUserStream(TwitterContext context)
        {
            hadUserStreamFailure = false;
            context.Log          = log;

            try
            {
                userStreamTask = context.Streaming
                                 .Where(s => s.Type == LinqToTwitter.StreamingType.User)
                                 .Select(strm => strm)
                                 .StartAsync(async strm =>
                {
                    await Task.Run(() =>
                    {
                        try
                        {
                            lastCallBackTimeUserStream = DateTime.Now;
                            if (userStream == null)
                            {
                                log.WriteLine("{0}: Twitter Connection Established (UserStream)", DateTime.Now);
                            }
                            userStream = strm;
                            if (strm != null)
                            {
                                /* LinqToTwitter v3.0 no longer has *.Status
                                 * if (strm.Status == TwitterErrorStatus.RequestProcessingException)
                                 * {
                                 *  var wex = strm.Error as WebException;
                                 *  if (wex != null && wex.Status == WebExceptionStatus.ConnectFailure)
                                 *  {
                                 *      log.WriteLine("{0}: LinqToTwitter UserStream Connection Failure (UserStream)", DateTime.Now);
                                 *      hadUserStreamFailure = true;
                                 *      //Will Be Restarted By Processing Queue
                                 *  }
                                 * }
                                 * else
                                 */
                                if (!string.IsNullOrEmpty(strm.Content))
                                {
                                    var status = new LinqToTwitter.Status(LitJson.JsonMapper.ToObject(strm.Content));
                                    if (status != null && status.StatusID > 0)
                                    {
                                        var tweet = new Tweet(status.RetweetedStatus.StatusID == 0 ? status : status.RetweetedStatus);
                                        lock (queue_lock)
                                        {
                                            queue.Add(tweet);
                                        }
                                        log.WriteLine("{0}: Added Item to Queue (UserStream): {1}", DateTime.Now, tweet.TweetText);
                                    }
                                    else
                                    {
                                        //If you can handle friends we will look for them
                                        if (processingStep is ITweepProcessingStep)
                                        {
                                            var jsonDataFriends = LitJson.JsonMapper.ToObject(strm.Content)
                                                                  .FirstOrDefault(x => x.Key == "friends");

                                            //If this is a friends collection update we will notify you
                                            if (!jsonDataFriends.Equals(default(KeyValuePair <string, LitJson.JsonData>)) &&
                                                jsonDataFriends.Value != null &&
                                                jsonDataFriends.Value.IsArray)
                                            {
                                                var friends = new List <LazyLoader <Tweep> >();
                                                for (int i = 0; i < jsonDataFriends.Value.Count; i++)
                                                {
                                                    friends.Add(TwitterModel.Instance(PrimaryUser.TwitterScreenName).GetLazyLoadedTweep(ulong.Parse(jsonDataFriends.Value[i].ToString()), Tweep.TweepType.Follower));
                                                }

                                                (processingStep as ITweepProcessingStep).ProcessTweeps(friends);
                                            }
                                            else
                                            {
                                                log.WriteLine("{0}: Unhandled Item in Stream (UserStream): {1}", DateTime.Now, strm.Content);
                                            }
                                        }
                                        else
                                        {
                                            log.WriteLine("{0}: Unhandled Item in Stream (UserStream): {1}", DateTime.Now, strm.Content);
                                        }
                                    }
                                }
                                else
                                {
                                    log.WriteLine("{0}: Twitter Keep Alive (UserStream)", DateTime.Now);
                                }
                            }
                            else
                            {
                                throw new ArgumentNullException("strm", "This value should never be null!");
                            }
                        }
                        catch (Exception ex)
                        {
                            log.WriteLine("{0}: Error (UserStream): {1}", DateTime.Now, ex.ToString());
                        }
                    });
                });
            }
            catch (Exception ex)
            {
                log.WriteLine("{0}: Error (UserStream): {1}", DateTime.Now, ex.ToString());
            }
        }
Esempio n. 28
0
        private void StartTwitterTrackerStream(TwitterContext context)
        {
            hadTrackerStreamFailure = false;
            List <string> trackList = null;

            context.Log = log;

            string track = ConfigurationManager.AppSettings["Track"] ?? (PrimaryUser.Track ?? "");

            string[] ignore = (ConfigurationManager.AppSettings["Ignore"] ?? "").ToLower().Split(',');

            int minFollowers = int.Parse(ConfigurationManager.AppSettings["MinFollowerCount"] ?? "0");

            try
            {
                if (string.IsNullOrEmpty(track) && !(processingStep is IKeywordSuggestionStep))
                {
                    log.WriteLine("{0}: To track keywords one of the following must be true: \n\t1) AppSetting Property 'Track' Cannot be Null or Empty.\n\t2) UserCollection Property 'Track' Cannot be Null or Empty.\n\t3) ProcessingStep must Implement IKeywordSuggestionStep.", DateTime.Now);
                    return;
                }
                else
                {
                    var processIgnoreWords = !string.IsNullOrEmpty(track) ? track.ToLower().Split(',').ToList() : new List <string>();
                    trackList = !string.IsNullOrEmpty(track) ? track.ToLower().Split(',').ToList() : new List <string>();

                    if (processingStep is IKeywordSuggestionStep)
                    {
                        var keywordSuggestionStep = processingStep as IKeywordSuggestionStep;
                        if (keywordSuggestionStep != null)
                        {
                            /* I have chosen to wrap these calls in seperate try catch statements incase one fails
                             * the other can still run. This way if the get fails we may still have hope of a reset.
                             */
                            try { keywordSuggestionStep.SetIgnoreKeywords(processIgnoreWords); }
                            catch { }
                            try { trackList.AddRange(keywordSuggestionStep.GetKeywordSuggestions().Select(x => x.ToLower()).ToList()); }
                            catch { }
                            try { keywordSuggestionStep.ResetHasNewKeywordSuggestions(); }
                            catch { }
                        }
                    }

                    if (trackList.Count == 0)
                    {
                        log.WriteLine("{0}: No Keywords to Track at this time.", DateTime.Now);
                        return;
                    }
                    else
                    {
                        if (trackList.Count > MAX_TRACK)
                        {
                            trackList = trackList.OrderByDescending(x => x.Length).Take(400).ToList();
                            log.WriteLine("{0}: Tracking List Exceeds Max {1} Reducing List", DateTime.Now, MAX_TRACK);
                        }
                        log.WriteLine("{0}: Attempting to Track: {1}", DateTime.Now, string.Join(",", trackList));
                        log.WriteLine("{0}: Ignoring : {1}", DateTime.Now, string.Join(",", ignore));
                    }

                    trackerStreamTask = context.Streaming
                                        .Where(s => s.Type == LinqToTwitter.StreamingType.Filter && s.Track == string.Join(",", trackList.Distinct()))
                                        .Select(strm => strm)
                                        .StartAsync(async strm =>
                    {
                        await Task.Run(() =>
                        {
                            try
                            {
                                lastCallBackTimeTrackerStream = DateTime.Now;
                                if (trackerStream == null)
                                {
                                    log.WriteLine("{0}: Twitter Connection Established (TrackerStream)", DateTime.Now);
                                }
                                trackerStream = strm;
                                if (strm != null)
                                {
                                    /* LinqToTwitter v3.0 no longer has *.Status
                                     * if (strm.Status == TwitterErrorStatus.RequestProcessingException)
                                     * {
                                     *  var wex = strm.Error as WebException;
                                     *  if (wex != null && wex.Status == WebExceptionStatus.ConnectFailure)
                                     *  {
                                     *      log.WriteLine("{0}: LinqToTwitter Stream Connection Failure (TrackerStream)", DateTime.Now);
                                     *      hadTrackerStreamFailure = true;
                                     *      //Will Be Restarted By Processing Queue
                                     *  }
                                     * }
                                     * else
                                     */
                                    if (!string.IsNullOrEmpty(strm.Content))
                                    {
                                        var status = new LinqToTwitter.Status(LitJson.JsonMapper.ToObject(strm.Content));
                                        if (status != null && status.StatusID > 0)
                                        {
                                            string statusText = status.Text.ToLower();
                                            if (
                                                trackList.Any(x => statusText.Contains(x)) &&         //Looking for exact matches
                                                status.User.FollowersCount >= minFollowers &&         //Meets the follower cutoff
                                                !ignore.Any(x => x != "" && statusText.Contains(x))   //Ignore these
                                                )
                                            {
                                                var tweet = new Tweet(status.RetweetedStatus.StatusID == 0 ? status : status.RetweetedStatus);
                                                lock (queue_lock)
                                                {
                                                    queue.Add(tweet);
                                                }
                                                log.WriteLine("{0}: Added Item to Queue (TrackerStream): @{1} said [{2}]", DateTime.Now, tweet.User.ScreenName, tweet.TweetText);
                                            }
                                        }
                                        else
                                        {
                                            log.WriteLine("{0}: Unhandled Item in Stream (TrackerStream): {1}", DateTime.Now, strm.Content);
                                        }
                                    }
                                    else
                                    {
                                        log.WriteLine("{0}: Twitter Keep Alive (TrackerStream)", DateTime.Now);
                                    }
                                }
                                else
                                {
                                    throw new ArgumentNullException("strm", "This value should never be null!");
                                }
                            }
                            catch (Exception ex)
                            {
                                log.WriteLine("{0}: Error (TrackerStream): {1}", DateTime.Now, ex.ToString());
                            }
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                log.WriteLine("{0}: Error (TrackerStream): {1}", DateTime.Now, ex.ToString());
            }
        }
Esempio n. 29
0
        void ParseJson(string json)
        {
            JsonData jsonObj = JsonMapper.ToObject(json);
            if (jsonObj == null || jsonObj.InstObject == null)
            {
                EntityType = StreamEntityType.Unknown;
                return;
            }
            var inst = jsonObj.InstObject;

            try
            {
                if (inst.ContainsKey("control"))
                {
                    EntityType = StreamEntityType.Control;
                    Entity = new Control(jsonObj);
                }
                else if (inst.ContainsKey("delete"))
                {
                    EntityType = StreamEntityType.Delete;
                    Entity = new Delete(jsonObj);
                }
                else if (inst.ContainsKey("direct_message"))
                {
                    EntityType = StreamEntityType.DirectMessage;
                    var dmObj = jsonObj.GetValue<JsonData>("direct_message");
                    Entity = new DirectMessage(dmObj);
                }
                else if (inst.ContainsKey("disconnect"))
                {
                    EntityType = StreamEntityType.Disconnect;
                    Entity = new Disconnect(jsonObj);
                }
                else if (inst.ContainsKey("event"))
                {
                    EntityType = StreamEntityType.Event;
                    Entity = new Event(jsonObj);
                }
                else if (inst.ContainsKey("for_user"))
                {
                    EntityType = StreamEntityType.ForUser;
                    Entity = new ForUser(jsonObj);
                }
                else if (inst.ContainsKey("friends") && inst.Count == 1)
                {
                    EntityType = StreamEntityType.FriendsList;
                    Entity = new FriendsList(jsonObj);
                }
                else if (inst.ContainsKey("geo_scrub"))
                {
                    EntityType = StreamEntityType.GeoScrub;
                    Entity = new GeoScrub(jsonObj);
                }
                else if (inst.ContainsKey("limit"))
                {
                    EntityType = StreamEntityType.Limit;
                    Entity = new Limit(jsonObj);
                }
                else if (inst.ContainsKey("warning") && inst.ContainsKey("percent_full"))
                {
                    EntityType = StreamEntityType.Stall;
                    Entity = new Stall(jsonObj);
                }
                else if (inst.ContainsKey("status_withheld"))
                {
                    EntityType = StreamEntityType.StatusWithheld;
                    Entity = new StatusWithheld(jsonObj);
                }
                else if (inst.ContainsKey("warning") && inst.ContainsKey("user_id"))
                {
                    EntityType = StreamEntityType.TooManyFollows;
                    Entity = new TooManyFollows(jsonObj);
                }
                else if (inst.ContainsKey("retweeted"))
                {
                    EntityType = StreamEntityType.Status;
                    Entity = new Status(jsonObj);
                }
                else if (inst.ContainsKey("user_withheld"))
                {
                    EntityType = StreamEntityType.UserWithheld;
                    Entity = new UserWithheld(jsonObj);
                }
                else
                {
                    EntityType = StreamEntityType.Unknown;
                }
            }
            catch (Exception ex)
            {
                string parseError = string.Format(
                    "Error parsing twitter message. Please create a new issue on the LINQ to Twitter site at https://linqtotwitter.codeplex.com/ " +
                    "with this info. \n\nMessage Type: {0}, Message Text:\n {1} \nException Details: {2} \n", EntityType, json, ex.ToString());
                
                EntityType = StreamEntityType.ParseError;
                Entity = parseError;

                if (TwitterExecute.Log != null)
                    TwitterExecute.Log.WriteLine(parseError);
            }
        }
Esempio n. 30
0
 private string CombineProfileAndTweet(Status status)
 {
     var combined = string.Format("<img class='twitter-headline' src='{0}' /> {1} {2}",
         _twitterTasks.ProfileImageUrl(status.ScreenName, TwitterImageSize.Mini), status.CreatedAt, status.Text);
     return combined;
 }
Esempio n. 31
0
        public void Status_Can_Serialize()
        {
            var tweet = new Status {Type = StatusType.Home};
            var stringBuilder = new StringBuilder();

            var writer = XmlWriter.Create(stringBuilder);
            var xmlSerializer = new XmlSerializer(typeof(Status));
            xmlSerializer.Serialize(writer, tweet);
        }
Esempio n. 32
0
 private void AddStatus(Status status)
 {
     this._statuses.Add(status);
     this.OnPropertyChanged("AllTweetsCount");
 }
Esempio n. 33
0
 public Tweet(LinqToTwitter.Status status)
     : this(new Status(status))
 {
 }
Esempio n. 34
0
 private static string CreateStatusText(Status source)
 {
     return string.Format(
         "ID:{0}\nUser:{1} / {2}\nText:{3}\n{4}CreatedAt:{5}\nSource:{6}",
         source.StatusID,
         source.User.Identifier.ScreenName,
         source.User.Name,
         source.Text,
         string.IsNullOrEmpty(source.InReplyToStatusID) ?
             "" : string.Format("InReplyToId:{0}\n", source.InReplyToStatusID),
         source.CreatedAt.ToLocalTime(),
         source.Source
     );
 }
Esempio n. 35
0
        /// <summary>
        /// Shreds an XML element into a Status object
        /// </summary>
        /// <param name="status">XML element with info</param>
        /// <returns>Newly populated status object</returns>
        public static Status CreateStatus(XElement status)
        {
            if (status == null)
            {
                return null;
            }

            var createdAtDate =
                status.Element("created_at") == null ||
                status.Element("created_at").Value == string.Empty
                    ? DateTime.MinValue
                    : DateTime.ParseExact(
                        status.Element("created_at").Value,
                        "ddd MMM dd HH:mm:ss %zzzz yyyy",
                        CultureInfo.InvariantCulture,
                        DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

            var favorite =
                    status.Element("favorited") == null ||
                    status.Element("favorited").Value == string.Empty ?
                         "false" :
                         status.Element("favorited").Value;

            var user = status.Element("user");
            var retweet = status.Element("retweeted_status");

            var retweetCount =
                status.Element("retweet_count") == null ||
                status.Element("retweet_count").Value == string.Empty ?
                    0 :
                    int.Parse(status.Element("retweet_count").Value.TrimEnd('+'));

            var retweeted =
                status.Element("retweeted") == null || status.Element("retweeted").Value == string.Empty ?
                    false :
                    bool.Parse(status.Element("retweeted").Value);

            var retweetDate = retweet == null
                              ? null
                              : retweet.Element("created_at").Value;

            var retweetedAtDate = String.IsNullOrEmpty(retweetDate)
                                ? DateTime.MinValue
                                : DateTime.ParseExact(
                                        retweetDate,
                                        "ddd MMM dd HH:mm:ss %zzzz yyyy",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

            List<Contributor> contributors = null;

            XElement contributorElement = status.Element("contributors");

            if (contributorElement != null)
            {
                if (contributorElement.Elements("user").Count() > 0)
                {
                    contributors =
                        (from contr in contributorElement.Elements("user")
                         select new Contributor
                         {
                             ID = contr.Element("id").Value,
                             ScreenName = contr.Element("screen_name").Value
                         })
                        .ToList();
                }
                else
                {
                    contributors =
                            (from id in contributorElement.Elements("user_id")
                             select new Contributor
                             {
                                 ID = id.Value,
                                 ScreenName = string.Empty
                             })
                            .ToList();
                }
            }

            XNamespace geoRss = "http://www.georss.org/georss";

            var geoStr =
               status.Element("geo") != null &&
               status.Element("geo").Element(geoRss + "point") != null ?
                   status.Element("geo").Element(geoRss + "point").Value :
                   string.Empty;

            Geo geo = new Geo();
            if (!string.IsNullOrEmpty(geoStr))
            {
                var coordArr = geoStr.Split(' ');

                double tempLatitude = 0;
                double tempLongitide = 0;

                if (double.TryParse(coordArr[Coordinate.LatitudePos], out tempLatitude) &&
                    double.TryParse(coordArr[Coordinate.LongitudePos], out tempLongitide))
                {
                    geo =
                        new Geo
                        {
                            Latitude = tempLatitude,
                            Longitude = tempLongitide
                        };
                }
            }

            var coordStr =
                status.Element("coordinates") != null &&
                status.Element("coordinates").Element(geoRss + "point") != null ?
                    status.Element("coordinates").Element(geoRss + "point").Value :
                    string.Empty;

            Coordinate coord = new Coordinate();
            if (!string.IsNullOrEmpty(coordStr))
            {
                var coordArr = coordStr.Split(' ');

                double tempLatitude = 0;
                double tempLongitide = 0;

                if (double.TryParse(coordArr[Coordinate.LatitudePos], out tempLatitude) &&
                    double.TryParse(coordArr[Coordinate.LongitudePos], out tempLongitide))
                {
                    coord =
                        new Coordinate
                        {
                            Latitude = tempLatitude,
                            Longitude = tempLongitide
                        };
                }
            }

            var place = Place.CreatePlace(status.Element("place"));
            var annotation = Annotation.CreateAnnotation(status.Element("annotation"));
            var entities = Entities.CreateEntities(status.Element("entities"));

            var newStatus = new Status
            {
                CreatedAt = createdAtDate,
                Favorited = bool.Parse(favorite),
                StatusID = status.GetString("id"),
                InReplyToStatusID = status.GetString("in_reply_to_status_id"),
                InReplyToUserID = status.GetString("in_reply_to_user_id"),
                Source = status.GetString("source"),
                Text = status.GetString("text"),
                Truncated = status.GetBool("truncated"),
                InReplyToScreenName = status.GetString("in_reply_to_screen_name"),
                Contributors = contributors,
                Geo = geo,
                Coordinates = coord,
                Place = place,
                Annotation = annotation,
                User = User.CreateUser(user),
                Entities = entities,
                Retweeted = retweeted,
                RetweetCount = retweetCount,
                Retweet =
                    retweet == null ?
                        null :
                        new Retweet
                        {
                            ID = retweet.GetString("id"),
                            CreatedAt = retweetedAtDate,
                            Favorited = retweet.GetBool("favorited"),
                            InReplyToScreenName = retweet.GetString("in_reply_to_screen_name"),
                            InReplyToStatusID = retweet.GetString("in_reply_to_status_id"),
                            InReplyToUserID = retweet.GetString("in_reply_to_user_id"),
                            Source = retweet.GetString("source"),
                            Text = retweet.GetString("text"),
                            Retweeted = retweet.GetBool("retweeted"),
                            RetweetCount =
                                //retweet.GetInt("retweet_count"),
                                retweet.Element("retweet_count") == null ||
                                retweet.Element("retweet_count").Value == string.Empty ?
                                    0 :
                                    int.Parse(retweet.Element("retweet_count").Value.TrimEnd('+')),
                            Truncated = retweet.GetBool("truncated", true),
                            RetweetingUser = User.CreateUser(retweet.Element("user"))
                        }
            };

            return newStatus;
        }
Esempio n. 36
0
        private void StartTwitterTrackerStream(TwitterContext context)
        {
            hadTrackerStreamFailure = false;
            List<string> trackList = null;

            context.Log = log;

            string track = ConfigurationManager.AppSettings["Track"] ?? (PrimaryUser.Track ?? "");
            string[] ignore = (ConfigurationManager.AppSettings["Ignore"] ?? "").ToLower().Split(',');

            int minFollowers = int.Parse(ConfigurationManager.AppSettings["MinFollowerCount"] ?? "0");

            try
            {
                if (string.IsNullOrEmpty(track) && !(processingStep is IKeywordSuggestionStep))
                {
                    log.WriteLine("{0}: To track keywords one of the following must be true: \n\t1) AppSetting Property 'Track' Cannot be Null or Empty.\n\t2) UserCollection Property 'Track' Cannot be Null or Empty.\n\t3) ProcessingStep must Implement IKeywordSuggestionStep.", DateTime.Now);
                    return;
                }
                else
                {
                    var processIgnoreWords = !string.IsNullOrEmpty(track) ? track.ToLower().Split(',').ToList() : new List<string>();
                    trackList = !string.IsNullOrEmpty(track) ? track.ToLower().Split(',').ToList() : new List<string>();

                    if (processingStep is IKeywordSuggestionStep)
                    {
                        var keywordSuggestionStep = processingStep as IKeywordSuggestionStep;
                        if (keywordSuggestionStep != null)
                        {
                            /* I have chosen to wrap these calls in seperate try catch statements incase one fails
                             * the other can still run. This way if the get fails we may still have hope of a reset.
                             */
                            try { keywordSuggestionStep.SetIgnoreKeywords(processIgnoreWords); }
                            catch { }
                            try { trackList.AddRange(keywordSuggestionStep.GetKeywordSuggestions().Select(x => x.ToLower()).ToList()); }
                            catch { }
                            try { keywordSuggestionStep.ResetHasNewKeywordSuggestions(); }
                            catch { }
                        }
                    }

                    if (trackList.Count == 0)
                    {
                        log.WriteLine("{0}: No Keywords to Track at this time.", DateTime.Now);
                        return;
                    }
                    else
                    {
                        if (trackList.Count > MAX_TRACK)
                        {
                            trackList = trackList.OrderByDescending(x => x.Length).Take(400).ToList();
                            log.WriteLine("{0}: Tracking List Exceeds Max {1} Reducing List", DateTime.Now, MAX_TRACK);
                        }
                        log.WriteLine("{0}: Attempting to Track: {1}", DateTime.Now, string.Join(",", trackList));
                        log.WriteLine("{0}: Ignoring : {1}", DateTime.Now, string.Join(",", ignore));
                    }

                    trackerStreamTask = context.Streaming
                        .Where(s => s.Type == LinqToTwitter.StreamingType.Filter && s.Track == string.Join(",", trackList.Distinct()))
                        .Select(strm => strm)
                        .StartAsync(async strm =>
                        {
                            await Task.Run(() =>
                                {
                                    try
                                    {
                                        lastCallBackTimeTrackerStream = DateTime.Now;
                                        if (trackerStream == null)
                                            log.WriteLine("{0}: Twitter Connection Established (TrackerStream)", DateTime.Now);
                                        trackerStream = strm;
                                        if (strm != null)
                                        {
                                            /* LinqToTwitter v3.0 no longer has *.Status
                                            if (strm.Status == TwitterErrorStatus.RequestProcessingException)
                                            {
                                                var wex = strm.Error as WebException;
                                                if (wex != null && wex.Status == WebExceptionStatus.ConnectFailure)
                                                {
                                                    log.WriteLine("{0}: LinqToTwitter Stream Connection Failure (TrackerStream)", DateTime.Now);
                                                    hadTrackerStreamFailure = true;
                                                    //Will Be Restarted By Processing Queue
                                                }
                                            }
                                            else
                                            */
                                            if (!string.IsNullOrEmpty(strm.Content))
                                            {
                                                var status = new LinqToTwitter.Status(LitJson.JsonMapper.ToObject(strm.Content));
                                                if (status != null && status.StatusID > 0)
                                                {
                                                    string statusText = status.Text.ToLower();
                                                    if (
                                                        trackList.Any(x => statusText.Contains(x)) && //Looking for exact matches
                                                        status.User.FollowersCount >= minFollowers && //Meets the follower cutoff
                                                        !ignore.Any(x => x != "" && statusText.Contains(x)) //Ignore these
                                                        )
                                                    {
                                                        var tweet = new Tweet(status.RetweetedStatus.StatusID == 0 ? status : status.RetweetedStatus);
                                                        lock (queue_lock)
                                                        {
                                                            queue.Add(tweet);
                                                        }
                                                        log.WriteLine("{0}: Added Item to Queue (TrackerStream): @{1} said [{2}]", DateTime.Now, tweet.User.ScreenName, tweet.TweetText);
                                                    }
                                                }
                                                else
                                                    log.WriteLine("{0}: Unhandled Item in Stream (TrackerStream): {1}", DateTime.Now, strm.Content);
                                            }
                                            else
                                                log.WriteLine("{0}: Twitter Keep Alive (TrackerStream)", DateTime.Now);
                                        }
                                        else
                                            throw new ArgumentNullException("strm", "This value should never be null!");
                                    }
                                    catch (Exception ex)
                                    {
                                        log.WriteLine("{0}: Error (TrackerStream): {1}", DateTime.Now, ex.ToString());
                                    }
                                });
                        });
                }
            }
            catch (Exception ex)
            {
                log.WriteLine("{0}: Error (TrackerStream): {1}", DateTime.Now, ex.ToString());
            }
        }