Inheritance: MonoBehaviour
Esempio n. 1
0
        protected override void SetUpSteps()
        {
            Given("the Refresh Cycle is {0} seconds", RefreshCycle =>
                App.Settings.DefaultRefreshCycle =
                    Int32.Parse(RefreshCycle) * 1000
            );

            And("Home is shown", () => {
                HomePresenter.Load();
                OriginalFirstTweet = TweetsShown[0];
            });

            When("Status is updated", () =>
                HomePresenter.TweetService.UpdateStatus(Tweet)
            );

            And("{0} seconds have passed", WaitTime =>
                Thread.Sleep(Convert.ToInt32(WaitTime)*1000)
            );

            Then("Home should contain the Tweet", () =>
                TweetsShown.ToList().ShouldContain(Tweet)
            );

            And("the Tweet should be shown above the older ones", () => {
                TweetsShown.ToList().ShouldContain(Tweet);
                TweetsShown.IndexOf(Tweet).ShouldBeLessThan(
                    TweetsShown.IndexOf(OriginalFirstTweet));}
            );
        }
        public ActionResult Create(TweetViewModel tweet)
        {
            if (this.ModelState.IsValid)
            {
                tweet.AuthorId = this.User.Identity.GetUserId();

                var newTweet = new Tweet {AuthorId = tweet.AuthorId, Text = tweet.Text};
                this.db.Tweets.Add(newTweet);
                this.db.SaveChanges();

                // Show Tweet to all followers
                var context = GlobalHost.ConnectionManager.GetHubContext<TweeterHub>();
                var usernames = this.UserProfile.Followers.Select(f => f.UserName).ToList();
                context.Clients.Users(usernames).showTweet(newTweet.Id);

                this.TempData["message"] = "Tweet added successfully.";
                this.TempData["isMessageSuccess"] = true;

                return this.RedirectToAction("Index", "Home");
            }

            this.TempData["message"] = "There are problem with tweet adding.";
            this.TempData["isMessageSuccess"] = false;

            this.ViewBag.AuthorId = new SelectList(this.db.Users, "Id", "FullName", tweet.AuthorId);
            return this.View("Tweet/_CreateTweetPartial", tweet);
        }
Esempio n. 3
0
 private void processTweet(Tweet tweet, bool force)
 {
     if (tweet != null)
     {
         Trace.WriteLine(tweet.text, "Information");
     }
 }
        public object Deserialize(JsonValue value, JsonMapper mapper)
        {
            Tweet tweet = new Tweet();

            tweet.ID = value.GetValue<long>("id");
            tweet.Text = value.GetValue<string>("text");
            JsonValue fromUserValue = value.GetValue("user");
            string dateFormat;
            if (fromUserValue != null)
            {
                tweet.FromUser = fromUserValue.GetValue<string>("screen_name");
                tweet.FromUserId = fromUserValue.GetValue<long>("id");
                tweet.ProfileImageUrl = fromUserValue.GetValue<string>("profile_image_url");
                dateFormat = TIMELINE_DATE_FORMAT;
            }
            else
            {
                tweet.FromUser = value.GetValue<string>("from_user");
                tweet.FromUserId = value.GetValue<long>("from_user_id");
                tweet.ProfileImageUrl = value.GetValue<string>("profile_image_url");
                dateFormat = SEARCH_DATE_FORMAT;
            }
            tweet.CreatedAt = JsonUtils.ToDateTime(value.GetValue<string>("created_at"), dateFormat);
            tweet.Source = value.GetValue<string>("source");
            JsonValue toUserIdValue = value.GetValue("in_reply_to_user_id");
            tweet.ToUserId = (toUserIdValue != null) ? toUserIdValue.GetValue<long?>() : null;
            JsonValue languageCodeValue = value.GetValue("iso_language_code");
            tweet.LanguageCode = (languageCodeValue != null) ? languageCodeValue.GetValue<string>() : null;
            JsonValue inReplyToStatusIdValue = value.GetValue("in_reply_to_status_id");
            tweet.InReplyToStatusId = ((inReplyToStatusIdValue != null) && !inReplyToStatusIdValue.IsNull) ? inReplyToStatusIdValue.GetValue<long?>() : null;

            return tweet;
        }
Esempio n. 5
0
        public void TweetToHtmlFormatUsernames()
        {
            var text = "RT @topascz: Test tweet";
            var tweet = new Tweet(new TwitterUser(null, null, null, null, null, 0, 0, 0), text, DateTime.MinValue, String.Empty);

            Assert.Equal("RT <a href=\"https://www.twitter.com/topascz\">@topascz</a>: Test tweet", tweet.TextToHtmlString().ToString());
        }
Esempio n. 6
0
 // Imitates a queue appending a status at the end of the list
 public void Add(Tweet status)
 {
     if (_tweets.Find(t => status.Id == t.Id) == null)
     {
         _tweets.Insert(_tweets.Count, status);
     }
 }
Esempio n. 7
0
        public void TweetToHtmlFormatNotLink()
        {
            var text = "Testing link www.twitter.com";
            var tweet = new Tweet(new TwitterUser(null, null, null, null, null, 0, 0, 0), text, DateTime.MinValue, String.Empty);

            Assert.Equal("Testing link www.twitter.com", tweet.TextToHtmlString().ToString());
        }
Esempio n. 8
0
        public void TweetToHtmlFormatNotUsernames()
        {
            var text = "Some email [email protected] @123";
            var tweet = new Tweet(new TwitterUser(null, null, null, null, null, 0, 0, 0), text, DateTime.MinValue, String.Empty);

            Assert.Equal("Some email [email protected] @123", tweet.TextToHtmlString().ToString());
        }
Esempio n. 9
0
        public void TweetToHtmlFormatNotHashtags()
        {
            var text = "Next test#test";
            var tweet = new Tweet(new TwitterUser(null, null, null, null, null, 0, 0, 0), text, DateTime.MinValue, String.Empty);

            Assert.Equal("Next test#test", tweet.TextToHtmlString().ToString());
        }
Esempio n. 10
0
        public void TweetToHtmlFormatHttpsLink()
        {
            var text = "Testing link https://www.twitter.com";
            var tweet = new Tweet(new TwitterUser(null, null, null, null, null, 0, 0, 0), text, DateTime.MinValue, String.Empty);

            Assert.Equal("Testing link <a href=\"https://www.twitter.com\">https://www.twitter.com</a>", tweet.TextToHtmlString().ToString());
        }
Esempio n. 11
0
        public void TweetToHtmlFormatHashtags()
        {
            var text = "Next #test #like";
            var tweet = new Tweet(new TwitterUser(null, null, null, null, null, 0, 0, 0), text, DateTime.MinValue, String.Empty);

            Assert.Equal("Next <a href=\"https://www.twitter.com/search/#test\">#test</a> <a href=\"https://www.twitter.com/search/#like\">#like</a>", tweet.TextToHtmlString().ToString());
        }
	    protected void AssertSingleTweet(Tweet tweet) 
        {
		    Assert.AreEqual(12345, tweet.ID);
		    Assert.AreEqual("Tweet 1", tweet.Text);
            Assert.IsNotNull(tweet.CreatedAt);
            Assert.AreEqual("13/07/2010 17:38:21", tweet.CreatedAt.Value.ToUniversalTime().ToString("dd/MM/yyyy HH:mm:ss"));
            Assert.AreEqual("habuma", tweet.User.ScreenName);
            Assert.AreEqual(112233, tweet.User.ID);
            Assert.AreEqual("http://a3.twimg.com/profile_images/1205746571/me2_300.jpg", tweet.User.ProfileImageUrl);
		    Assert.AreEqual("habuma", tweet.FromUser); // Deprecated
            Assert.AreEqual(112233, tweet.FromUserId); // Deprecated
            Assert.AreEqual("http://a3.twimg.com/profile_images/1205746571/me2_300.jpg", tweet.ProfileImageUrl); // Deprecated
            Assert.IsNotNull(tweet.InReplyToStatusId);
		    Assert.AreEqual(123123123123, tweet.InReplyToStatusId.Value);
            Assert.IsNotNull(tweet.InReplyToUserId);
            Assert.AreEqual(332211, tweet.InReplyToUserId.Value);
            Assert.IsNotNull(tweet.ToUserId); // Deprecated
            Assert.AreEqual(332211, tweet.ToUserId.Value); // Deprecated
            Assert.AreEqual("brbaia", tweet.InReplyToUserScreenName);
            Assert.AreEqual("Spring Social Showcase", tweet.Source);
            Assert.AreEqual(9, tweet.FavoriteCount);
            Assert.AreEqual(12, tweet.RetweetCount);
            Assert.IsTrue(tweet.IsRetweetedByUser);
            Assert.IsTrue(tweet.IsFavoritedByUser);
	    }
Esempio n. 13
0
        public TweetCollection GetSearchResults(string searchText, IWebProxy webProxy)
        {
            TweetCollection tweets = new TweetCollection();

            string tweetscanUrl = "http://tweetscan.com/trss.php?s=" + searchText;

            HttpWebRequest request = WebRequest.Create(tweetscanUrl) as HttpWebRequest;

            // Add configured web proxy
            request.Proxy = webProxy;

            //try
            //{
                // Get the Web Response
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    // Load the response data into a XmlDocument
                    XmlDocument doc = new XmlDocument();
                    doc.Load(reader);

                    // Get statuses with XPath
                    XmlNodeList nodes = doc.SelectNodes("/rss/channel/item");

                    foreach (XmlNode node in nodes)
                    {
                        Tweet tweet = new Tweet();
                        tweet.Id = double.Parse(node.SelectSingleNode("tweetid").InnerText);
                        tweet.Text = HttpUtility.HtmlDecode(node.SelectSingleNode("text").InnerText);

                        string dateString = node.SelectSingleNode("pubdate").InnerText;
                        if (!string.IsNullOrEmpty(dateString))
                        {
                            tweet.DateCreated = DateTime.Parse(dateString);
                        }

                        User user = new User();

                        user.Name = node.SelectSingleNode("username").InnerText;
                        user.ScreenName = node.SelectSingleNode("screenname").InnerText;
                        user.ImageUrl = node.SelectSingleNode("image").InnerText;

                        tweet.User = user;

                        tweets.Add(tweet);
                    }

                    tweets.SaveToDisk();
                }
            //}
            //catch {
            ////TODO: not sure what kind of errors are thrown by tweetcan
            //    // eat it.
            //}

            return tweets;
        }
Esempio n. 14
0
 public void Tweet_added_to_empty_collection_succeeds()
 {
     TweetCollection tweets = new TweetCollection();
     Tweet tweet = new Tweet() { DateCreated = DateTime.Now, Id = 1 };
     tweets.Add(tweet);
     Assert.That(tweets.Contains(tweet));
     Assert.That(tweets.Count == 1);
 }
Esempio n. 15
0
 private static void TweetThis(TwitterClient twitterClient, Tweet tweet, Sender<TweetStatus> sender) {
     var response = twitterClient.Tweet(tweet.Message, tweet.Token);
     var tweetStatus = new TweetStatus {
         CorrelationId = tweet.CorrelationId,
         Status = response
     };
     sender.Send(tweetStatus);
 }
 public void Create(Tweet tweet)
 {
     using (var context = new TwitterEntities())
     {
         context.Tweets.Add(tweet);
         context.SaveChanges();
     }
 }
Esempio n. 17
0
 private static InMemoryCredentials MapToCredentials(Token consumerToken, Tweet tweet) {
     return new InMemoryCredentials {
         ConsumerKey = consumerToken.Key,
         ConsumerSecret = consumerToken.Secret,
         AccessToken = tweet.AccessToken,
         OAuthToken = tweet.OAuthToken
     };
 }
Esempio n. 18
0
        public TweetLexer(Tweet tweet)
        {
            _Tweet = tweet;
            if(_Tweet.text == null)
                throw new NullReferenceException("The message text should NEVER be null. This is really BAD!");

            _CurrentIndex = 0;
            _EndIndex = tweet.text.Length - 1;
        }
Esempio n. 19
0
 public void Update(Tweet Tweet)
 {
     if (HasAssociatedTweet)
     {
         Tweet.ReplyTo = AssociatedTweetId;
         TweetService.SendReply(Tweet);
     }
     else
         TweetService.UpdateStatus(Tweet);
 }
Esempio n. 20
0
File: Search.cs Progetto: scy/twarph
 public override void Work()
 {
     HttpWebRequest req = HTTPXML.StartRequest("http://search.twitter.com/search.atom?" +
         "q=" + Uri.EscapeDataString(this.Query) +
         "&since_id=" + this.LastID.ToString()
         );
     WebResponse res = req.GetResponse();
     XmlDocument doc = new XmlDocument();
     Stream s = res.GetResponseStream();
     doc.Load(s);
     s.Close();
     int maxid = 0;
     foreach (XmlNode node in doc.GetElementsByTagName("entry", ATOMURI))
     {
         Tweet t = new Tweet();
         foreach (XmlNode entry in node.ChildNodes)
         {
             if (entry.NamespaceURI != ATOMURI)
                 continue;
             switch (entry.Name)
             {
                 case "id":
                     int id = ParseIDTag(entry.InnerText);
                     t.ID = id;
                     if (id > maxid)
                         maxid = id;
                     break;
                 case "title":
                     t.Text = entry.InnerText;
                     break;
                 case "author":
                     foreach (XmlNode authorentry in entry.ChildNodes)
                     {
                         if (entry.NamespaceURI != ATOMURI)
                             continue;
                         switch (authorentry.Name)
                         {
                             case "name":
                                 t.Nick = authorentry.InnerText.Split(' ')[0];
                                 break;
                         }
                     }
                     break;
             }
         }
         Tweets.Add(t);
     }
     lock (lastids)
     {
         if (maxid > lastids[this.Query])
             lastids[this.Query] = maxid;
     }
     HTTPXML.FinishRequest(req);
 }
        public object Deserialize(JsonValue value, JsonMapper mapper)
        {
            Tweet tweet = new Tweet();

            tweet.ID = value.GetValue<long>("id");
            tweet.Text = value.GetValue<string>("text");
            tweet.CreatedAt = JsonUtils.ToDateTime(value.GetValueOrDefault<string>("created_at"), TWEET_DATE_FORMAT);
            JsonValue userValue = value.GetValue("user");
            if (userValue != null && userValue.IsObject)
            {
                tweet.User = mapper.Deserialize<TwitterProfile>(userValue);
                tweet.FromUser = tweet.User.ScreenName;
                tweet.FromUserId = tweet.User.ID;
                tweet.ProfileImageUrl = tweet.User.ProfileImageUrl;
            }
            tweet.ToUserId = value.GetValueOrDefault<long?>("in_reply_to_user_id");
            tweet.InReplyToUserId = value.GetValueOrDefault<long?>("in_reply_to_user_id");
            tweet.InReplyToUserScreenName = value.GetValueOrDefault<string>("in_reply_to_screen_name");
            tweet.InReplyToStatusId = value.GetValueOrDefault<long?>("in_reply_to_status_id");
            tweet.Source = value.GetValueOrDefault<string>("source");
            JsonValue placeValue = value.GetValue("place");
            if (placeValue != null && placeValue.IsObject)
            {
                tweet.Place = mapper.Deserialize<Place>(placeValue);
            }
            tweet.LanguageCode = value.GetValueOrDefault<string>("iso_language_code");
            tweet.RetweetCount = value.GetValueOrDefault<int>("retweet_count");
            JsonValue retweetedStatusValue = value.GetValue("retweeted_status");
            if (retweetedStatusValue != null && retweetedStatusValue.IsObject)
            {
                tweet.RetweetedStatus = mapper.Deserialize<Tweet>(retweetedStatusValue);
            }
            tweet.IsRetweetedByUser = value.GetValueOrDefault<bool>("retweeted");
            tweet.IsFavoritedByUser = value.GetValueOrDefault<bool>("favorited");
            JsonValue retweetIdValue = value.GetValue("current_user_retweet");
            if (retweetIdValue != null && retweetIdValue.IsObject)
            {
                tweet.RetweetIdByUser = retweetIdValue.GetValue<long?>("id");
            }

            // Entities
            JsonValue entitiesValue = value.GetValue("entities");
            if (entitiesValue != null)
            {
                tweet.Entities = new TweetEntities();
                tweet.Entities.Hashtags = DeserializeHashtags(entitiesValue.GetValue("hashtags"));
                tweet.Entities.UserMentions = DeserializeUserMentions(entitiesValue.GetValue("user_mentions"));
                tweet.Entities.Urls = DeserializeUrls(entitiesValue.GetValue("urls"));
                tweet.Entities.Media = DeserializeMedia(entitiesValue.GetValue("media"));
            }

            return tweet;
        }
Esempio n. 22
0
        private void ConversationIdsHelper(Tweet CurrentTweet, ICollection<long> Ids)
        {
            var Children = Tweets.Where(Tweet => Tweet.ReplyTo == CurrentTweet.Id);

            if (Children.Count() == 0) return;

            Children.ForEach(Tweet =>
            {
                Ids.Add(Tweet.Id);
                ConversationIdsHelper(Tweet, Ids);
            });
        }
Esempio n. 23
0
        protected Tweet RootTweet(Tweet Tweet)
        {
            var CurrentTweet = Tweet;

            while (CurrentTweet.ReplyTo > 0)
            {
                var TempTweet = CurrentTweet;
                CurrentTweet = Tweets.Where(X => X.Id == TempTweet.ReplyTo).First();
            }

            return CurrentTweet;
        }
 public CommentsWindow(IServiceApi api, Tweet t)
 {
     twitterApi = api;
     tweet = t;
     InitializeComponent();
     comments = new CommentCollection();
     //HeadImage.Source = new BitmapImage(new Uri(tweet.User.ImageUrl)); ;
     TitleBar.DataContext = tweet;
     TweetText.DataContext = tweet;
     CommentsListBox.DataContext = comments;
     UpdateComments();
 }
Esempio n. 25
0
        private static void getSites(TweetDataEntities db, params string[] query)
        {
            HashSet<string> seenUrls = new HashSet<string>();
            var twitter = new TwitterSearch();
            int count = 0;
            foreach (var tweet in twitter.Search(100, 10, query)) {
                Debug.Print("Tweet number: " + (++count).ToString());
                if (db.Tweets.Any(i => i.TweetID == tweet.TweetID)) {
                    continue;
                }
                Tweet t = new Tweet() { Text = tweet.Text, TweetID = tweet.TweetID };
                Debug.Print("Tweet: " + tweet.Text);
                Regex linkParser = new Regex(@"\b(?:http://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                foreach (Match m in linkParser.Matches(tweet.Text)) {
                    string fullUrl = "";
                    try {
                        fullUrl = m.Value.ExpandUrl();
                    } catch {
                        continue;
                    }
                    if (db.Websites.Any(i => i.Url == fullUrl)) {
                        continue;
                    }
                    Debug.Print("Website: " + fullUrl);
                    var page = new PageScraper(fullUrl);
                    var website = new Website() { Url = page.Url, Title = page.Title() };
                    db.Websites.AddObject(website);
                    foreach (var m2 in page.Media()) {
                        if (db.Media.Any(i => i.Url == m2.Link)) {
                            continue;
                        }
                        Medium media = new Medium() { Type = m2.Type, Url = m2.Link, SourceSite = website.Url };
                        if (m2.Type == "image") {
                            var request = WebRequest.Create(m2.Link);

                            using (var response = request.GetResponse())
                            using (var stream = response.GetResponseStream())
                            using (var b = Bitmap.FromStream(stream)) {
                                int area = b.Width * b.Height;
                                media.ImageArea = area;
                            }
                        }
                        db.Media.AddObject(media);
                        Debug.Print("Media element: " + m2.Link);
                    }
                    t.LinkSite = website.Url;

                }
                db.Tweets.AddObject(t);
                db.SaveChanges();
            }
        }
        public ActionResult Create(Tweet tweet)
        {
            tweet.LikesCount = 0;
            tweet.TimeStamp = DateTime.Now;
            tweet.UserId = HttpContext.User.Identity.GetUserId();
            if (ModelState.IsValid)
            {
                this.tweetsData.Add(tweet);
                return RedirectToAction("Details");
            }

            return View(tweet);
        }
Esempio n. 27
0
 public void TimeAgoShouldNotifyWhenValueChanges()
 {
     var tweet = new Tweet();
     var called = 0;
     tweet.PropertyChanged += (sender, args) => called += 1;
     tweet.TimeAgo = "20m";
     called.Should().Be(1);
     tweet.TimeAgo = "21m";
     called.Should().Be(2);
     tweet.TimeAgo = "21m";
     called.Should().Be(2);
     tweet.TimeAgo.Should().Be("21m");
 }
	    protected void AssertSingleTweet(Tweet tweet) 
        {
		    Assert.AreEqual(12345, tweet.ID);
		    Assert.AreEqual("Tweet 1", tweet.Text);
		    Assert.AreEqual("habuma", tweet.FromUser);
		    Assert.AreEqual(112233, tweet.FromUserId);
		    Assert.AreEqual("http://a3.twimg.com/profile_images/1205746571/me2_300.jpg", tweet.ProfileImageUrl);
		    Assert.AreEqual("Spring Social Showcase", tweet.Source);
            Assert.IsNotNull(tweet.CreatedAt);
            Assert.AreEqual("13/07/2010 17:38:21", tweet.CreatedAt.Value.ToUniversalTime().ToString("dd/MM/yyyy HH:mm:ss"));
            Assert.IsNotNull(tweet.InReplyToStatusId);
		    Assert.AreEqual(123123123123, tweet.InReplyToStatusId.Value);
	    }
Esempio n. 29
0
        public void Tweet_added_to_collection_unsorted()
        {
            TweetCollection tweets = new TweetCollection(SortOrder.None);
            Tweet tweet1 = new Tweet() { DateCreated = DateTime.Now, Id = 1 };
            Tweet tweet2 = new Tweet() { DateCreated = tweet1.DateCreated.Value.Subtract(TimeSpan.FromMinutes(5)), Id = 2 };
            Tweet tweet3 = new Tweet() { DateCreated = tweet1.DateCreated.Value.Subtract(TimeSpan.FromMinutes(2)), Id = 2 };

            tweets.Add(tweet1);
            tweets.Add(tweet2);
            tweets.Add(tweet3);
            Assert.That(tweets[0], Is.EqualTo(tweet1));
            Assert.That(tweets[1], Is.EqualTo(tweet2));
            Assert.That(tweets[2], Is.EqualTo(tweet3));
        }
Esempio n. 30
0
 public bool Delete(Tweet tweet)
 {
     bool result = false;
     using (context = new TwitterEntities())
     {
         tweet.User = userDao.GetById(tweet.User_Id);
         context.Tweets.Attach(tweet);
         context.Tweets.Remove(tweet);
         //context.Entry(tweet).State = EntityState.Deleted;
         result = context.SaveChanges() > 0;
         Logger.Log.Debug("user ID:" + tweet.User_Id + " " + userDao.GetById(tweet.User_Id).Email + " deleted a tweet ID:" + tweet.Id);
     }
     return result;
 }
Esempio n. 31
0
 public virtual async Task GetStreamMentions(Tweet tweet)
 {
     await CheckAndDeleteMaxRowAsync();
 }
        public ITweet SendTweet(string message)
        {
            _creds.Authenticate();

            return(Tweet.PublishTweet(message));
        }
Esempio n. 33
0
 public void EditTweet(Tweet t)
 {
     tweetDao.EditTweet(t);
 }
Esempio n. 34
0
 public void PublishTweet()
 {
     Tweet.PublishTweet("Check out #tweetinvi, the best c# library!");
 }
Esempio n. 35
0
 public void ClickImage(Tweet tweet)
 {
     ImageClick.Invoke(tweet);
 }
Esempio n. 36
0
 public void AddComment(Tweet mainTweet, Tweet commentTweet)
 {
     _allTweets.Add(commentTweet);
     mainTweet.AddComment(commentTweet.Id);
 }
        /// <summary>
        /// Gets the Retweets of a particular tweet
        /// </summary>
        /// <param name="tweet"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        /// <remarks> ref: https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid  </remarks>
        public async static Task <TwitterResponseCollection <Tweet> > GetRetweets(this ITwitterSession session, Tweet tweet, int count = 20)
        {
            var parameters = new TwitterParametersCollection
            {
                { "count", count.ToString() },
            };
            var path = TwitterApi.Resolve("/1.1/statuses/retweets/{0}.json", tweet.Id);

            return(await session.GetAsync(path, parameters)
                   .ContinueWith(c => c.MapToMany <Tweet>()));
        }
Esempio n. 38
0
        protected override void ExecuteInContext(IUnitOfWorkContext context, PostNewTweetCommand command)
        {
            var newTweet = new Tweet(command.Message, Guid.Parse(command.Channel), command.Who);

            context.Accept();
        }
Esempio n. 39
0
 void ITweetService.Add(Tweet tweet)
 {
     this.tweets.Add(tweet);
 }
 private void SendNotification(Tweet tweet, string user)
 => _logger.Info($"Sent notification to user '{user}'. Tweet text: '{tweet.Text}'");
Esempio n. 41
0
 public void NewTweet(ServiceActionContent obj)
 {
     Authentification(obj);
     Tweet.PublishTweet(obj.Args.ToString());
 }
        /// <summary>
        /// Sends a Tweet in reply to another tweet
        /// </summary>
        /// <param name="tweet">Text to send</param>
        /// <param name="text">Text of tweet to send</param>
        /// <param name="fileName">Name of the file, including extension</param>
        /// <param name="imageDataStream">Stream containing the image</param>
        /// <param name="latitude">Latitude</param>
        /// <param name="longitude">Longitude</param>
        /// <param name="placeId">A place in the world identified by a Twitter place ID. Place IDs can be retrieved from geo/reverse_geocode.</param>
        /// <returns></returns>
        /// <remarks> ref: https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media </remarks>
        public async static Task <Tweet> ReplyToTweetWithImage(this IUserSession session, Tweet tweet, string text, string fileName, Stream imageDataStream, double latitude = 0.0, double longitude = 0.0, string placeId = "")
        {
            var parameters = new TwitterParametersCollection
            {
                { "status", text },
                { "in_reply_to_status_id", tweet.Id.ToString() }
            };

            parameters.Create(place_id: placeId);

            if (Math.Abs(latitude) > 0.0 && Math.Abs(longitude) > 0.0)
            {
                parameters.Add("lat", latitude.ToString());
                parameters.Add("long", longitude.ToString());
            }

            return(await session.PostFileAsync(TwitterApi.Upload("/1.1/statuses/update_with_media.json"), parameters, fileName, "media[]", srImage : imageDataStream)
                   .ContinueWith(c => c.MapToSingle <Tweet>()));
        }
Esempio n. 43
0
 public void TweetWithUTF32Character()
 {
     Assert.AreEqual(6, Tweet.Length("sa🚒osa"));
 }
        private void AddTweet()
        {
            var newTweet = new Tweet();

            EditTweet(new TweetViewModel(newTweet, _tweetRepository));
        }
Esempio n. 45
0
 public void AddTweet(Tweet tweet)
 {
     _allTweets.Add(tweet);
     _allRootTweets.Add(tweet);
 }
 void Like(Tweet tweet) => tweet.IsLikedByMe = !tweet.IsLikedByMe;
Esempio n. 47
0
    public static void Initialize(DB db, bool isDevEnvironment)
    {
        db.Database.EnsureDeleted(); // delete then, ...
        db.Database.EnsureCreated(); // create the tables!!
        // db.Database.Migrate(); // ensure migrations are registered

        if (db.Tweets.Any() || db.Users.Any() || db.Tags.Any() || db.Likes.Any())
        {
            return;
        }

        var Users = new List <User> {
            new User {
                Username  = "******",
                AvatarURL = "https://images.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.pbs.org%2Fnewshour%2Fwp-content%2Fuploads%2F2014%2F03%2Fdolphin.jpg&f=1"
            },
            new User {
                Username  = "******",
                AvatarURL = "https://www.theironyard.com/assets/iron-yard-logo-709fbbf7ff0d1d76e83b9a782b79e7c4edb840974a7b3d9dd4f33b8cf5b87571.svg"
            },
            new User {
                Username  = "******",
                AvatarURL = "https://images.duckduckgo.com/iu/?u=http%3A%2F%2F4.bp.blogspot.com%2F_lrKSQHqv38Q%2FTQ4kAGAgq4I%2FAAAAAAAAADk%2FkIHFYQ8qVi8%2Fs1600%2Fcool%2Bmustache%2Bgallery.jpg&f=1"
            }
        };

        var Tags = new List <Tag> {
            new Tag {
                Value = "tacos"
            },
            new Tag {
                Value = "bbq"
            }
        };

        var f = new Tweet {
            Content   = "Give me tacos. All. The. Tacos.",
            User      = Users[0],
            IsRetweet = false,
            Tags      = new List <Tag> {
                Tags[0]
            },
            Likes = 1
        };

        db.Tweets.Add(f);
        db.SaveChanges();

        var g = new Tweet {
            Content      = "This.",
            User         = Users[0],
            ReplyToTweet = f.Id,
            IsRetweet    = true,
            Tags         = new List <Tag> {
                Tags[0]
            },
            Likes = 2
        };

        var Tweets = new List <Tweet> {
            g,
            new Tweet {
                Content      = "YOU CAN'T HANDLE THE TACOS",
                User         = Users[2],
                ReplyToTweet = f.Id,
                IsRetweet    = false,
                Tags         = new List <Tag> {
                    Tags[1]
                },
                Likes = 0
            }
        };

        foreach (var t in Tweets)
        {
            db.Tweets.Add(t);
        }

        db.SaveChanges();
        Console.WriteLine("----------DB SEEDED-------------");
    }
Esempio n. 48
0
 static void Main(string[] args)
 {
     Auth.SetUserCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
     Tweet.PublishTweet("Hello World!");
 }
        private List <TweetEmoji> ProcessEmojis(IEnumerable <Codepoint> codePointItems, Tweet theTweet)
        {
            var tweetEmojis = new List <TweetEmoji>();

            codePointItems.ToList().ForEach(item =>
            {
                var emojiCodeArray = item.ToString().Trim().Split("+");
                var emojiCode      = string.Empty;
                if (emojiCodeArray.Length > 1)
                {
                    //for multi code emojis our datbase seperates them with -
                    emojiCode = emojiCodeArray[1].Trim().Replace(' ', '-');
                }
                else
                {
                    emojiCode = emojiCodeArray[0];
                }

                var ourEmoji = _repository.GetAll <Shared.Models.Emoji>().FirstOrDefault(x => x.EmojiUnified == emojiCode || x.EmojiNonQualified == emojiCode);


                if (ourEmoji != null && ourEmoji.EmojiId != Guid.Empty)
                {
                    tweetEmojis.Add(new TweetEmoji
                    {
                        ChirpId      = theTweet.ChirpId,
                        TweetEmojiId = Guid.NewGuid(),
                        EmojiId      = ourEmoji.EmojiId
                    });
                }
            });

            return(tweetEmojis);
        }
        private async Task ParseTweetMedtaData(Tweet theTweet, SampledStreamModel streamModel)
        {
            var hasEmoji   = false;
            var hasHashTag = false;
            var hasUrl     = false;
            var hasImage   = false;

            if (_repository == null)
            {
                throw new Exception("WTF!!");
            }

            dynamic twitterJsonResult = JObject.Parse(streamModel.data.source);
            var     emojiMatches      = EmojiData.Emoji.EmojiRegex.Matches(theTweet.TweetContent);

            hasEmoji = emojiMatches.Count() > 0;
            hasUrl   = streamModel.data?.entities?.urls != null?streamModel.data.entities.urls.Any() : false;

            if (hasEmoji)
            {
                var tweetMojis = ProcessEmojis(theTweet.TweetContent.Codepoints(), theTweet);
                if (tweetMojis != null && tweetMojis.Any())
                {
                    await _repository.Insert <TweetEmoji>(tweetMojis);

                    await _repository.Save();
                }
            }


            if (hasUrl)
            {
                var tweetUrls = new List <TweetUrl>();
                streamModel.data.entities.urls.ForEach(item =>
                {
                    hasImage = item.expanded_url.Contains("pic.twitter.com", StringComparison.InvariantCultureIgnoreCase) ||
                               item.expanded_url.Contains("Instagram", StringComparison.InvariantCultureIgnoreCase);

                    var tUrl = new TweetUrl
                    {
                        ChirpId    = theTweet.ChirpId,
                        TweetUrlId = Guid.NewGuid(),
                        Url        = item.expanded_url,
                        IsImage    = hasImage,
                        Domain     = new Uri(item.expanded_url).Host
                    };
                    tweetUrls.Add(tUrl);
                });
                await _repository.Insert <TweetUrl>(tweetUrls);

                await _repository.Save();
            }


            if (twitterJsonResult != null && twitterJsonResult.data.entities != null)
            {
                if (twitterJsonResult?.data?.entities?.hashtags != null)
                {
                    hasHashTag = true;

                    var hashEntries = twitterJsonResult.data.entities.hashtags.Count;
                    List <TweetHashTag> tweetHashTags = new List <TweetHashTag>();
                    for (var counter = 0; counter < hashEntries; counter++)
                    {
                        tweetHashTags.Add(new TweetHashTag
                        {
                            ChirpId        = theTweet.ChirpId,
                            TweetHashTagId = Guid.NewGuid(),
                            HashTag        = twitterJsonResult.data.entities.hashtags[counter].tag
                        });
                    }
                    await _repository.Insert <TweetHashTag>(tweetHashTags);

                    await _repository.Save();

                    ;
                }
            }

            var feathers = new List <TweetFeather> {
                new TweetFeather {
                    ChirpId    = theTweet.ChirpId,
                    FeatherId  = Guid.NewGuid(),
                    HasEmoji   = hasEmoji,
                    HasHashTag = hasHashTag,
                    HasImage   = hasImage,
                    HasUrl     = hasUrl,
                    TweetStamp = DateTime.Now
                }
            };

            await _repository.Insert <TweetFeather>(feathers);

            await _repository.Save();
        }
Esempio n. 51
0
 public void CreateTweet(Tweet t, Gebruiker g)
 {
     tweetDao.CreateTweet(t, g);
 }
Esempio n. 52
0
        public static string ComposeTwitterMessage(string message, string profileid, long userid, string picurl, bool isScheduled, DatabaseRepository dbr, Domain.Socioboard.Models.TwitterAccount TwitterAccount, Domain.Socioboard.Models.ScheduledMessage schmessage, Domain.Socioboard.Models.User _user)
        {
            bool   rt  = false;
            string ret = "";
            string str = "Message posted";

            if (message.Length > 140)
            {
                message = message.Substring(0, 135);
            }
            Domain.Socioboard.Models.TwitterAccount objTwitterAccount = TwitterAccount;
            oAuthTwitter OAuthTwt = new oAuthTwitter(AppSettings.twitterConsumerKey, AppSettings.twitterConsumerScreatKey, AppSettings.twitterRedirectionUrl);

            OAuthTwt.AccessToken       = objTwitterAccount.oAuthToken;
            OAuthTwt.AccessTokenSecret = objTwitterAccount.oAuthSecret;
            OAuthTwt.TwitterScreenName = objTwitterAccount.twitterScreenName;
            OAuthTwt.TwitterUserId     = objTwitterAccount.twitterUserId;

            Tweet twt = new Tweet();

            if (!string.IsNullOrEmpty(picurl))
            {
                try
                {
                    PhotoUpload ph  = new PhotoUpload();
                    string      res = string.Empty;
                    rt = ph.NewTweet(picurl, message, OAuthTwt, ref res);
                }
                catch (Exception ex)
                {
                    apiHitsCount = MaxapiHitsCount;
                }
            }
            else
            {
                try
                {
                    JArray post = twt.Post_Statuses_Update(OAuthTwt, message);
                    ret = post[0]["id_str"].ToString();
                }
                catch (Exception ex)
                {
                    apiHitsCount = MaxapiHitsCount;
                }
            }

            if (!string.IsNullOrEmpty(ret) || rt == true)
            {
                schmessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated;
                schmessage.url    = ret;
                dbr.Update <ScheduledMessage>(schmessage);
                Domain.Socioboard.Models.Notifications notify = new Notifications();
                Notifications lstnotifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id);
                if (lstnotifications == null)
                {
                    notify.MsgId            = schmessage.id;
                    notify.MsgStatus        = "Scheduled";
                    notify.notificationtime = schmessage.localscheduletime;
                    notify.NotificationType = "Schedule Successfully";
                    notify.ReadOrUnread     = "Unread";
                    notify.UserId           = userid;
                    dbr.Add <Notifications>(notify);
                    if (_user.scheduleSuccessUpdates)
                    {
                        string sucResponse = SendMailbySendGrid(AppSettings.frommail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, true, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
                else
                {
                    if (_user.scheduleSuccessUpdates)
                    {
                        string sucResponse = SendMailbySendGrid(AppSettings.frommail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, true, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
            }
            else
            {
                str = "Message not posted";
                Domain.Socioboard.Models.Notifications notify = new Notifications();
                Notifications lstnotifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id);
                if (lstnotifications == null)
                {
                    notify.MsgId            = schmessage.id;
                    notify.MsgStatus        = "Failed";
                    notify.notificationtime = schmessage.localscheduletime.ToString();
                    notify.NotificationType = "Schedule Failed";
                    notify.ReadOrUnread     = "Unread";
                    notify.UserId           = userid;
                    dbr.Add <Notifications>(notify);
                    if (_user.scheduleFailureUpdates)
                    {
                        string falResponse = SendMailbySendGrid(AppSettings.frommail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, false, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
                else
                {
                    if (_user.scheduleFailureUpdates)
                    {
                        string falResponse = SendMailbySendGrid(AppSettings.frommail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, false, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
            }

            return(str);
        }
Esempio n. 53
0
        public async Task ProcessIncommingTweet(IHttpClientFactory httpClientFactory, string rawTweetData, string knownEmojis, int tweetCount, ILogger logger)
        {
            var tasks = new List <Task <string> >();

            try
            {
                if (rawTweetData != null)
                {
                    Tweet    tweet = JsonConvert.DeserializeObject <Tweet>(rawTweetData);
                    DateTime stamp;
                    DateTime.TryParse(tweet?.data?.created_at, out stamp);
                    string partitionKey = Constants.PartitionKeyFormat;

                    if (tweet != null && stamp != null && tweet?.data?.id != null)
                    {
                        var mentionsTask = Task.Run(() => _tweetScrapingService.CollectDataWithRegex(Constants.RegexMentions, tweet?.data?.text, tweetCount, logger));
                        var hashTagTask  = Task.Run(() => _tweetScrapingService.CollectDataWithRegex(Constants.RegexHashtags, tweet?.data?.text, tweetCount, logger));
                        var urlTask      = Task.Run(() => _tweetScrapingService.CollectDataWithRegex(Constants.RegexLinks, tweet?.data?.text, tweetCount, logger));
                        var emojiTask    = Task.Run(() => _tweetScrapingService.GetEmojisFromString(tweet?.data?.text, knownEmojis, tweetCount, logger));

                        Task.WaitAll(urlTask, emojiTask, hashTagTask, mentionsTask);

                        var urlLengthenTask = await Task.Run(() => _tweetScrapingService.LengthenUrls(httpClientFactory, urlTask.Result, tweetCount, logger));



                        Regex regexInstagram = new Regex(Constants.RegexInstagram);
                        Regex regexTwitter   = new Regex(Constants.RegexTwitter);

                        ProcessedTweet rawTweet = new ProcessedTweet()
                        {
                            TweetCount     = tweetCount,
                            Hour           = stamp.Hour,
                            Minute         = stamp.Minute,
                            Second         = stamp.Second,
                            Text           = tweet?.data?.text,
                            Hashtags       = JsonConvert.SerializeObject(hashTagTask.Result),
                            Urls           = JsonConvert.SerializeObject(urlLengthenTask),
                            Emojis         = emojiTask.Result,
                            Mentions       = JsonConvert.SerializeObject(mentionsTask.Result.ToList()),
                            TwitterPicture = JsonConvert.SerializeObject(urlLengthenTask.Where(o => regexTwitter.IsMatch(o)).ToList()),
                            InstagramLink  = JsonConvert.SerializeObject(urlLengthenTask.Where(o => regexInstagram.IsMatch(o)).ToList()),
                            PartitionKey   = partitionKey,
                            RowKey         = tweet?.data?.id,
                            TweetStamp     = stamp,
                            YearMonthDay   = stamp.Year.ToString() + stamp.Month.ToString() + stamp.Day.ToString()
                        };

                        await _processedIncommingQueue.SendMessageOntoQueue(JsonConvert.SerializeObject(rawTweet));

                        logger.LogInformation($"ProcessIncommingTweet saved tweet {tweetCount} ");
                    }
                }
            }
            catch (Exception exc)
            {
                logger.LogError($"Process Incomming Tweet process failed: {exc.Message} {exc.StackTrace}");
                //throw exc;
            }
            logger.LogInformation($"Process Incomming Tweet {tweetCount} ");
        }
        public async Task ReplaceCommonSpecialModifiers(UserViewModel user, IEnumerable <string> arguments = null)
        {
            foreach (string counter in ChannelSession.Counters.Keys)
            {
                this.ReplaceSpecialIdentifier(counter, ChannelSession.Counters[counter].ToString());
            }

            foreach (var kvp in SpecialIdentifierStringBuilder.CustomSpecialIdentifiers)
            {
                this.ReplaceSpecialIdentifier(kvp.Key, kvp.Value);
            }

            this.ReplaceSpecialIdentifier("timedigits", DateTimeOffset.Now.ToString("HHmm"));
            this.ReplaceSpecialIdentifier("datetime", DateTimeOffset.Now.ToString("g"));
            this.ReplaceSpecialIdentifier("date", DateTimeOffset.Now.ToString("d"));
            this.ReplaceSpecialIdentifier("time", DateTimeOffset.Now.ToString("t"));
            this.ReplaceSpecialIdentifier("linebreak", Environment.NewLine);

            if (this.ContainsSpecialIdentifier(SpecialIdentifierStringBuilder.TopSpecialIdentifierHeader))
            {
                Dictionary <uint, UserDataViewModel> allUsersDictionary = ChannelSession.Settings.UserData.ToDictionary();
                allUsersDictionary.Remove(ChannelSession.Channel.user.id);

                IEnumerable <UserDataViewModel> allUsers = allUsersDictionary.Select(kvp => kvp.Value);
                allUsers = allUsers.Where(u => !u.IsCurrencyRankExempt);

                foreach (UserCurrencyViewModel currency in ChannelSession.Settings.Currencies.Values)
                {
                    if (this.ContainsRegexSpecialIdentifier(currency.TopRegexSpecialIdentifier))
                    {
                        this.ReplaceNumberBasedRegexSpecialIdentifier(currency.TopRegexSpecialIdentifier, (total) =>
                        {
                            List <string> currencyUserList = new List <string>();
                            int userPosition = 1;
                            foreach (UserDataViewModel currencyUser in allUsers.OrderByDescending(u => u.GetCurrencyAmount(currency)).Take(total))
                            {
                                currencyUserList.Add($"#{userPosition}) {currencyUser.UserName} - {currencyUser.GetCurrencyAmount(currency)}");
                                userPosition++;
                            }

                            string result = "No users found.";
                            if (currencyUserList.Count > 0)
                            {
                                result = string.Join(", ", currencyUserList);
                            }
                            return(result);
                        });
                    }
                }

                if (this.ContainsRegexSpecialIdentifier(SpecialIdentifierStringBuilder.TopTimeRegexSpecialIdentifier))
                {
                    this.ReplaceNumberBasedRegexSpecialIdentifier(SpecialIdentifierStringBuilder.TopTimeRegexSpecialIdentifier, (total) =>
                    {
                        List <string> timeUserList = new List <string>();
                        int userPosition           = 1;
                        foreach (UserDataViewModel timeUser in allUsers.OrderByDescending(u => u.ViewingMinutes).Take(total))
                        {
                            timeUserList.Add($"#{userPosition}) {timeUser.UserName} - {timeUser.ViewingTimeShortString}");
                            userPosition++;
                        }

                        string result = "No users found.";
                        if (timeUserList.Count > 0)
                        {
                            result = string.Join(", ", timeUserList);
                        }
                        return(result);
                    });
                }

                if (this.ContainsRegexSpecialIdentifier(SpecialIdentifierStringBuilder.TopSparksUsedRegexSpecialIdentifierHeader))
                {
                    await this.HandleSparksUsed("weekly", async() => { return(await ChannelSession.Connection.GetWeeklyLeaderboard(ChannelSession.Channel)); });

                    await this.HandleSparksUsed("monthly", async() => { return(await ChannelSession.Connection.GetMonthlyLeaderboard(ChannelSession.Channel)); });

                    await this.HandleSparksUsed("yearly", async() => { return(await ChannelSession.Connection.GetYearlyLeaderboard(ChannelSession.Channel)); });

                    await this.HandleSparksUsed("alltime", async() => { return(await ChannelSession.Connection.GetAllTimeLeaderboard(ChannelSession.Channel)); });
                }
            }

            if (this.ContainsSpecialIdentifier(CurrentSongIdentifierHeader))
            {
                SongRequestItem song = null;

                if (ChannelSession.Services.SongRequestService != null && ChannelSession.Services.SongRequestService.IsEnabled)
                {
                    song = await ChannelSession.Services.SongRequestService.GetCurrentlyPlaying();
                }

                if (song != null)
                {
                    this.ReplaceSpecialIdentifier(CurrentSongIdentifierHeader + "title", song.Name);
                    this.ReplaceSpecialIdentifier(CurrentSongIdentifierHeader + "username", song.User.UserName);
                    this.ReplaceSpecialIdentifier(CurrentSongIdentifierHeader + "albumimage", song.AlbumImage ?? string.Empty);
                }
                else
                {
                    this.ReplaceSpecialIdentifier(CurrentSongIdentifierHeader + "title", "No Song");
                    this.ReplaceSpecialIdentifier(CurrentSongIdentifierHeader + "username", "Nobody");
                    this.ReplaceSpecialIdentifier(CurrentSongIdentifierHeader + "albumimage", string.Empty);
                }
            }

            if (this.ContainsSpecialIdentifier(NextSongIdentifierHeader))
            {
                SongRequestItem song = null;

                if (ChannelSession.Services.SongRequestService != null && ChannelSession.Services.SongRequestService.IsEnabled)
                {
                    song = await ChannelSession.Services.SongRequestService.GetNextTrack();
                }

                if (song != null)
                {
                    this.ReplaceSpecialIdentifier(NextSongIdentifierHeader + "title", song.Name);
                    this.ReplaceSpecialIdentifier(NextSongIdentifierHeader + "username", song.User.UserName);
                    this.ReplaceSpecialIdentifier(NextSongIdentifierHeader + "albumimage", song.AlbumImage ?? string.Empty);
                }
                else
                {
                    this.ReplaceSpecialIdentifier(NextSongIdentifierHeader + "title", "No Song");
                    this.ReplaceSpecialIdentifier(NextSongIdentifierHeader + "username", "Nobody");
                    this.ReplaceSpecialIdentifier(NextSongIdentifierHeader + "albumimage", string.Empty);
                }
            }

            if (this.ContainsSpecialIdentifier(UptimeSpecialIdentifierHeader) || this.ContainsSpecialIdentifier(StartSpecialIdentifierHeader))
            {
                DateTimeOffset startTime = await UptimeChatCommand.GetStartTime();

                if (startTime > DateTimeOffset.MinValue)
                {
                    TimeSpan duration = DateTimeOffset.Now.Subtract(startTime);

                    this.ReplaceSpecialIdentifier(StartSpecialIdentifierHeader + "datetime", startTime.ToString("g"));
                    this.ReplaceSpecialIdentifier(StartSpecialIdentifierHeader + "date", startTime.ToString("d"));
                    this.ReplaceSpecialIdentifier(StartSpecialIdentifierHeader + "time", startTime.ToString("t"));

                    this.ReplaceSpecialIdentifier(UptimeSpecialIdentifierHeader + "total", (int)duration.TotalHours + duration.ToString("\\:mm"));
                    this.ReplaceSpecialIdentifier(UptimeSpecialIdentifierHeader + "hours", ((int)duration.TotalHours).ToString());
                    this.ReplaceSpecialIdentifier(UptimeSpecialIdentifierHeader + "minutes", duration.ToString("mm"));
                    this.ReplaceSpecialIdentifier(UptimeSpecialIdentifierHeader + "seconds", duration.ToString("ss"));
                }
            }

            if (this.ContainsSpecialIdentifier(CostreamUsersSpecialIdentifier))
            {
                this.ReplaceSpecialIdentifier(CostreamUsersSpecialIdentifier, await CostreamChatCommand.GetCostreamUsers());
            }

            if (ChannelSession.Services.Twitter != null && this.ContainsSpecialIdentifier("tweet"))
            {
                IEnumerable <Tweet> tweets = await ChannelSession.Services.Twitter.GetLatestTweets();

                if (tweets != null && tweets.Count() > 0)
                {
                    Tweet          latestTweet          = tweets.FirstOrDefault();
                    DateTimeOffset latestTweetLocalTime = latestTweet.DateTime.ToLocalTime();

                    this.ReplaceSpecialIdentifier("tweetlatesturl", latestTweet.TweetLink);
                    this.ReplaceSpecialIdentifier("tweetlatesttext", latestTweet.Text);
                    this.ReplaceSpecialIdentifier("tweetlatestdatetime", latestTweetLocalTime.ToString("g"));
                    this.ReplaceSpecialIdentifier("tweetlatestdate", latestTweetLocalTime.ToString("d"));
                    this.ReplaceSpecialIdentifier("tweetlatesttime", latestTweetLocalTime.ToString("t"));

                    Tweet streamTweet = tweets.FirstOrDefault(t => t.IsStreamTweet);
                    if (streamTweet != null)
                    {
                        DateTimeOffset streamTweetLocalTime = streamTweet.DateTime.ToLocalTime();
                        this.ReplaceSpecialIdentifier("tweetstreamurl", streamTweet.TweetLink);
                        this.ReplaceSpecialIdentifier("tweetstreamtext", streamTweet.Text);
                        this.ReplaceSpecialIdentifier("tweetstreamdatetime", streamTweetLocalTime.ToString("g"));
                        this.ReplaceSpecialIdentifier("tweetstreamdate", streamTweetLocalTime.ToString("d"));
                        this.ReplaceSpecialIdentifier("tweetstreamtime", streamTweetLocalTime.ToString("t"));
                    }
                }
            }

            if (ChannelSession.Services.Spotify != null && this.ContainsSpecialIdentifier("spotify"))
            {
                SpotifyUserProfile profile = await ChannelSession.Services.Spotify.GetCurrentProfile();

                if (profile != null)
                {
                    this.ReplaceSpecialIdentifier("spotifyprofileurl", profile.Link);
                }

                SpotifyCurrentlyPlaying currentlyPlaying = await ChannelSession.Services.Spotify.GetCurrentlyPlaying();

                if (currentlyPlaying != null)
                {
                    this.ReplaceSpecialIdentifier("spotifycurrentlyplaying", currentlyPlaying.ToString());
                }
            }

            if (ChannelSession.Services.ExtraLife.IsConnected() && this.ContainsSpecialIdentifier(ExtraLifeSpecialIdentifierHeader))
            {
                ExtraLifeTeam team = await ChannelSession.Services.ExtraLife.GetTeam();

                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "teamdonationgoal", team.fundraisingGoal.ToString());
                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "teamdonationcount", team.numDonations.ToString());
                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "teamdonationamount", team.sumDonations.ToString());

                ExtraLifeTeamParticipant participant = await ChannelSession.Services.ExtraLife.GetParticipant();

                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "userdonationgoal", participant.fundraisingGoal.ToString());
                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "userdonationcount", participant.numDonations.ToString());
                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "userdonationamount", participant.sumDonations.ToString());
            }

            if (this.ContainsSpecialIdentifier(FeaturedChannelsSpecialIdentifer))
            {
                IEnumerable <ExpandedChannelModel> featuredChannels = await ChannelSession.Connection.GetFeaturedChannels();

                if (featuredChannels != null)
                {
                    this.ReplaceSpecialIdentifier(FeaturedChannelsSpecialIdentifer, string.Join(", ", featuredChannels.Select(c => "@" + c.user.username)));
                }
            }

            if (this.ContainsSpecialIdentifier(StreamSpecialIdentifierHeader))
            {
                ChannelDetailsModel details = await ChannelSession.Connection.GetChannelDetails(ChannelSession.Channel);

                if (details != null)
                {
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "title", details.name);
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "agerating", details.audience);
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "viewercount", details.viewersCurrent.ToString());
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "followcount", details.numFollowers.ToString());
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "subcount", details.numSubscribers.ToString());
                }

                if (this.ContainsSpecialIdentifier(StreamHostCountSpecialIdentifier))
                {
                    IEnumerable <ChannelAdvancedModel> hosters = await ChannelSession.Connection.GetHosters(ChannelSession.Channel);

                    if (hosters != null)
                    {
                        this.ReplaceSpecialIdentifier(StreamHostCountSpecialIdentifier, hosters.Count().ToString());
                    }
                }
            }

            if (this.ContainsSpecialIdentifier(MilestoneSpecialIdentifierHeader))
            {
                PatronageStatusModel patronageStatus = await ChannelSession.Connection.GetPatronageStatus(ChannelSession.Channel);

                if (patronageStatus != null)
                {
                    PatronagePeriodModel patronagePeriod = await ChannelSession.Connection.GetPatronagePeriod(patronageStatus);

                    if (patronagePeriod != null)
                    {
                        IEnumerable <PatronageMilestoneModel> patronageMilestones = patronagePeriod.milestoneGroups.SelectMany(mg => mg.milestones);

                        PatronageMilestoneModel patronageMilestone = patronageMilestones.FirstOrDefault(m => m.id == patronageStatus.currentMilestoneId);
                        if (patronageMilestone != null)
                        {
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "amount", patronageMilestone.target.ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "remainingamount", (patronageMilestone.target - patronageStatus.patronageEarned).ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "reward", patronageMilestone.DollarAmountText());
                        }

                        PatronageMilestoneModel patronageNextMilestone = patronageMilestones.FirstOrDefault(m => m.id == (patronageStatus.currentMilestoneId + 1));
                        if (patronageNextMilestone != null)
                        {
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "nextamount", patronageNextMilestone.target.ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "remainingnextamount", (patronageNextMilestone.target - patronageStatus.patronageEarned).ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "nextreward", patronageNextMilestone.DollarAmountText());
                        }

                        PatronageMilestoneModel patronageFinalMilestone = patronageMilestones.OrderByDescending(m => m.id).FirstOrDefault();
                        if (patronageNextMilestone != null)
                        {
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "finalamount", patronageFinalMilestone.target.ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "remainingfinalamount", (patronageFinalMilestone.target - patronageStatus.patronageEarned).ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "finalreward", patronageFinalMilestone.DollarAmountText());
                        }

                        IEnumerable <PatronageMilestoneModel> patronageMilestonesEarned = patronageMilestones.Where(m => m.target <= patronageStatus.patronageEarned);
                        if (patronageMilestonesEarned.Count() > 0)
                        {
                            PatronageMilestoneModel patronageMilestoneHighestEarned = patronageMilestonesEarned.OrderByDescending(m => m.reward).FirstOrDefault();
                            if (patronageMilestoneHighestEarned != null)
                            {
                                this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "earnedamount", patronageStatus.patronageEarned.ToString());
                                this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "earnedreward", patronageMilestoneHighestEarned.DollarAmountText());
                            }
                        }
                    }
                }
            }

            if (this.ContainsSpecialIdentifier(UserSpecialIdentifierHeader))
            {
                await this.HandleUserSpecialIdentifiers(user, string.Empty);
            }

            if (arguments != null)
            {
                for (int i = 0; i < arguments.Count(); i++)
                {
                    string currentArgumentSpecialIdentifierHeader = ArgSpecialIdentifierHeader + (i + 1);
                    if (this.ContainsSpecialIdentifier(currentArgumentSpecialIdentifierHeader))
                    {
                        UserViewModel argUser = await this.GetUserFromArgument(arguments.ElementAt(i));

                        if (argUser != null)
                        {
                            await this.HandleUserSpecialIdentifiers(argUser, currentArgumentSpecialIdentifierHeader);
                        }

                        this.ReplaceSpecialIdentifier(currentArgumentSpecialIdentifierHeader + "text", arguments.ElementAt(i));
                    }
                }

                this.ReplaceSpecialIdentifier("allargs", string.Join(" ", arguments));
            }

            if (this.ContainsSpecialIdentifier(TargetSpecialIdentifierHeader))
            {
                UserViewModel targetUser = null;
                if (arguments != null && arguments.Count() > 0)
                {
                    targetUser = await this.GetUserFromArgument(arguments.ElementAt(0));
                }

                if (targetUser == null)
                {
                    targetUser = user;
                }

                await this.HandleUserSpecialIdentifiers(targetUser, TargetSpecialIdentifierHeader);
            }

            if (this.ContainsSpecialIdentifier(StreamerSpecialIdentifierHeader))
            {
                await this.HandleUserSpecialIdentifiers(new UserViewModel(ChannelSession.Channel.user), StreamerSpecialIdentifierHeader);
            }

            if (this.ContainsSpecialIdentifier(StreamBossSpecialIdentifierHeader))
            {
                OverlayWidget streamBossWidget = ChannelSession.Settings.OverlayWidgets.FirstOrDefault(w => w.Item is OverlayStreamBoss);
                if (streamBossWidget != null)
                {
                    OverlayStreamBoss streamBossOverlay = (OverlayStreamBoss)streamBossWidget.Item;
                    if (streamBossOverlay != null && streamBossOverlay.CurrentBoss != null)
                    {
                        await this.HandleUserSpecialIdentifiers(streamBossOverlay.CurrentBoss, StreamBossSpecialIdentifierHeader);
                    }
                }
            }

            if (this.ContainsSpecialIdentifier(RandomSpecialIdentifierHeader))
            {
                if (this.randomUserSpecialIdentifierGroupID != Guid.Empty && RandomUserSpecialIdentifierGroups.ContainsKey(this.randomUserSpecialIdentifierGroupID))
                {
                    if (RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomUser != null && this.ContainsSpecialIdentifier(SpecialIdentifierStringBuilder.RandomSpecialIdentifierHeader + "user"))
                    {
                        await this.HandleUserSpecialIdentifiers(RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomUser, RandomSpecialIdentifierHeader);
                    }

                    if (RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomFollower != null && this.ContainsSpecialIdentifier(SpecialIdentifierStringBuilder.RandomFollowerSpecialIdentifierHeader + "user"))
                    {
                        await this.HandleUserSpecialIdentifiers(RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomFollower, RandomFollowerSpecialIdentifierHeader);
                    }

                    if (RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomSubscriber != null && this.ContainsSpecialIdentifier(SpecialIdentifierStringBuilder.RandomSubscriberSpecialIdentifierHeader + "user"))
                    {
                        await this.HandleUserSpecialIdentifiers(RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomSubscriber, RandomSubscriberSpecialIdentifierHeader);
                    }
                }

                if (this.ContainsRegexSpecialIdentifier(RandomNumberRegexSpecialIdentifier))
                {
                    this.ReplaceNumberBasedRegexSpecialIdentifier(RandomNumberRegexSpecialIdentifier, (maxNumber) =>
                    {
                        int number = RandomHelper.GenerateRandomNumber(maxNumber) + 1;
                        return(number.ToString());
                    });
                }
            }

            if (this.ContainsRegexSpecialIdentifier(UnicodeRegexSpecialIdentifier))
            {
                this.ReplaceNumberBasedRegexSpecialIdentifier(UnicodeRegexSpecialIdentifier, (number) =>
                {
                    char uChar = (char)number;
                    return(uChar.ToString());
                });
            }
        }
Esempio n. 55
0
        public async void uploadFile()
        {
            if (_client == null ||
                _session?.AccessToken == null)
            {
                var dialog = new MessageDialog("Please authenticate first!", "Sorry!");
                await dialog.ShowAsync();

                return;
            }

            var picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };

            picker.FileTypeFilter.Add("*");
            var file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                //ShowBusy(true);

                Exception error = null;

                try
                {
                    using (var stream = await file.OpenStreamForReadAsync())
                    {
                        var item =
                            await
                            _client.Drive.Special.AppRoot.ItemWithPath(file.Name)
                            .Content.Request()
                            .PutAsync <Item>(stream);


                        _savedId = item.Id;
                        var successDialog =
                            new MessageDialog(
                                $"Uploaded file has ID {item.Id}. You can now use the Get Link button to retrieve a direct link to the file",
                                "Success");
                        await successDialog.ShowAsync();
                    }

                    //  ShowBusy(false);
                }
                catch (Exception ex)
                {
                    error = ex;
                }

                if (error != null)
                {
                    var dialog = new MessageDialog(error.Message, "Error!");
                    await dialog.ShowAsync();

                    // ShowBusy(false);
                }

                if (error == null)
                {
                    /*IRandomAccessStream random = await RandomAccessStreamReference.CreateFromUri(new Uri(_savedId.Trim())).OpenReadAsync();
                     * Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(random);
                     * Windows.Graphics.Imaging.PixelDataProvider pixelData = await decoder.GetPixelDataAsync();
                     * byte[] bytes = pixelData.DetachPixelData(); */


                    var Stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                    var image = new BitmapImage();
                    image.SetSource(Stream);
                    img.Source = image;

                    using (var inputStream = await file.OpenSequentialReadAsync())
                    {
                        var readStream = inputStream.AsStreamForRead();
                        var byteArray  = new byte[readStream.Length];
                        await readStream.ReadAsync(byteArray, 0, byteArray.Length);

                        Tweet.PublishTweetWithImage(file.Name.ToString(), byteArray);
                    }
                }
            }
        }
Esempio n. 56
0
 public void sendtweet(string tweet)
 {
     Auth.SetUserCredentials(_consumerKey, _consumerSecret, _accessToken, _accessTokenSecret);
     Tweet.PublishTweet(tweet);
 }
Esempio n. 57
0
        public async Task <Tweet> Update(Tweet tweet)
        {
            tweet = await _repository.Update(tweet);

            return(tweet);
        }
Esempio n. 58
0
        // GetTopTweet
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (UserName.Text == "UserName")
            {
                Console.WriteLine("UserNameを入れてくれないとどうしようもない");
            }
            else
            {
                long?maxTweetIdParse = null;
                if (long.TryParse(MaxTweetId.Text, out long maxTweetIdValue))
                {
                    maxTweetIdParse = maxTweetIdValue;
                }
                Console.WriteLine($"ID:{maxTweetIdValue}から過去を取得");

                int?getCountParse = null;
                if (int.TryParse(Count.Text, out int getCountValue))
                {
                    getCountParse = Math.Min(200, getCountValue);
                }
                else
                {
                    getCountParse = 10;
                }
                Console.WriteLine($"{getCountParse}件取得");
                try
                {
                    var tl     = Tokens.Statuses.UserTimelineAsync(UserName.Text, getCountParse, null, maxTweetIdParse);
                    var tlList = tl.Result.ToList();
                    if ((bool)RetweetOnly.IsChecked)
                    {
                        // RTのみにする
                        tlList = tlList.Where(item => item.Text.StartsWith("RT @")).ToList();
                    }
                    Console.WriteLine($"取得件数:{tlList.Count}");
                    TweetList.Clear();
                    int count = 0;
                    foreach (var item in tlList)
                    {
                        string text = item.Text;
                        if (IsUnicode(item.Text))
                        {
                            text = GetTranslateUnicode(text);
                        }
                        var tweet = new Tweet
                        {
                            Id   = item.Id,
                            Text = text
                        };
                        TweetList.Add(tweet);

                        count++;
                        Console.WriteLine($"{count}--------------------{item.Id}--------------------");
                        Console.WriteLine($"投稿時間:{item.CreatedAt}");                          // 投稿時間
                        Console.WriteLine($"{item.FavoriteCount}いいね\t{item.RetweetCount}RT"); // いいね,RT数
                        Console.WriteLine($"{item.User.Name}({item.User.ScreenName})");
                        Console.WriteLine(item.Text);

                        maxTweetIdParse = item.Id;
                    }
                    MaxTweetId.Text = maxTweetIdParse.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"TLの取得に失敗した\nUserNameが合ってるか確かめて欲しい");
                    Console.WriteLine($"{ex.ToString()}");
                }
            }
        }
Esempio n. 59
0
 public void AddTweet(Tweet newTweet)
 {
     _context.Tweets.Add(newTweet);
     _context.SaveChanges();
 }
Esempio n. 60
0
 private void IncrementPartyCount(Party party, Tweet tweet)
 {
     party.count++;
     partyRelatedTweets.Add(new PartyTweetData(tweet, party));
 }