Example #1
0
        public void CreateRetweetUnofficial_WithFormatterTest()
        {
            // TweetFormatterでHTMLに整形 → CreateRetweetUnofficialで復元 までの動作が正しく行えているか

            var text     = "#てすと @TwitterAPI \n http://t.co/KYi7vMZzRt";
            var entities = new TwitterEntity[]
            {
                new TwitterEntityHashtag
                {
                    Indices = new[] { 0, 4 },
                    Text    = "てすと",
                },
                new TwitterEntityMention
                {
                    Indices    = new[] { 5, 16 },
                    Id         = 6253282L,
                    Name       = "Twitter API",
                    ScreenName = "twitterapi",
                },
                new TwitterEntityUrl
                {
                    Indices     = new[] { 19, 41 },
                    DisplayUrl  = "twitter.com",
                    ExpandedUrl = "http://twitter.com/",
                    Url         = "http://t.co/KYi7vMZzRt",
                },
            };

            var html = TweetFormatter.AutoLinkHtml(text, entities);

            var expected = "#てすと @TwitterAPI " + Environment.NewLine + " http://twitter.com/";

            Assert.Equal(expected, TweenMain.CreateRetweetUnofficial(html, true));
        }
 public TwitterDiscordAttachment(string url, int width, int height, TwitterEntity source)
 {
     this.url    = url;
     this.size   = width * height;
     this.width  = width;
     this.height = height;
     this.m      = source;
 }
Example #3
0
        public void AutoLinkHtml_EntityNullTest4()
        {
            var text = "てすとてすとー";
            IEnumerable <TwitterEntity> entities = new TwitterEntity[] { null };

            var expected = "てすとてすとー";

            Assert.Equal(expected, TweetFormatter.AutoLinkHtml(text, entities));
        }
Example #4
0
        public static bool UpdateTweetById(this IStore store, TwitterEntity tweet)
        {
            Debug.Assert(tweet != null);
            var list = new List <TwitterEntity> {
                tweet
            };
            var retList = store.UpdateTweetById(list);

            Debug.Assert(retList.Count == 1);
            return(retList[retList.Keys.FirstOrDefault()]);
        }
Example #5
0
 private static T Map <T>(long parentId, [NotNull] TwitterEntity entity)
     where T : DatabaseEntity, new()
 {
     if (entity == null)
     {
         throw new ArgumentNullException("entity");
     }
     return(new T
     {
         DisplayText = entity.DisplayText,
         EndIndex = entity.EndIndex,
         EntityType = entity.EntityType,
         MediaUrl = entity.MediaUrl,
         OriginalUrl = entity.OriginalUrl,
         UserId = entity.UserId,
         StartIndex = entity.StartIndex,
         ParentId = parentId,
     });
 }
Example #6
0
        public TwitterUser(JsonValue json)
        {
            Id                        = json["id_str"].AsString().ParseLong();
            ScreenName                = ParsingExtension.ResolveEntity(json["screen_name"].AsString());
            Name                      = ParsingExtension.ResolveEntity(json["name"].AsString());
            Description               = ParsingExtension.ResolveEntity(json["description"].AsString());
            Location                  = ParsingExtension.ResolveEntity(json["location"].AsString());
            Url                       = json["url"].AsString();
            IsDefaultProfileImage     = json["default_profile_image"].AsBooleanOrNull() ?? true;
            ProfileImageUri           = json["profile_image_url"].AsString().ParseUri();
            ProfileBackgroundImageUri = json["profile_background_image_url"].AsString().ParseUri();
            ProfileBannerUri          = json["profile_banner_url"].AsString().ParseUri();
            IsProtected               = json["protected"].AsBoolean();
            IsVerified                = json["verified"].AsBoolean();
            IsTranslator              = json["is_translator"].AsBoolean();
            IsContributorsEnabled     = json["contributors_enabled"].AsBoolean();
            IsGeoEnabled              = json["geo_enabled"].AsBoolean();
            StatusesCount             = json["statuses_count"].AsLong();
            FollowingsCount           = json["friends_count"].AsLong();
            FollowersCount            = json["followers_count"].AsLong();
            FavoritesCount            = json["favourites_count"].AsLong();
            ListedCount               = json["listed_count"].AsLong();
            Language                  = json["lang"].AsString();
            CreatedAt                 = json["created_at"].AsString().ParseDateTime(ParsingExtension.TwitterDateTimeFormat);
            var entities = json["entities"];
            var urls     = entities["url"];
            var descs    = entities["description"];

            UrlEntities = !urls.IsNull
                ? TwitterEntity.ParseEntities(urls).OfType <TwitterUrlEntity>().ToArray()
                : new TwitterUrlEntity[0];

            DescriptionEntities = !descs.IsNull
                ? TwitterEntity.ParseEntities(descs).ToArray()
                : new TwitterEntity[0];
        }
 public TextEntityDescription(string text, TwitterEntity entity = null)
 {
     _text   = text;
     _entity = entity;
 }
Example #8
0
        private List <TwitterEntity> GetLatestTweets(string handle)
        {
            List <TwitterEntity> tweets = new List <TwitterEntity>();

            #region Twitter Library Setup
            OAuthTokens oaccesstkn     = new OAuthTokens();
            string      consumerKey    = ConfigurationManager.AppSettings["TwitterConsumerKey"];
            string      consumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];

            oaccesstkn.AccessToken       = ConfigurationManager.AppSettings["TwitterAccessToken"];
            oaccesstkn.AccessTokenSecret = ConfigurationManager.AppSettings["TwitterAccessSecret"];;
            oaccesstkn.ConsumerKey       = consumerKey;
            oaccesstkn.ConsumerSecret    = consumerSecret;
            #endregion

            try
            {
                #region Get Tweets From Twitter
                WebRequestBuilder webRequest = new WebRequestBuilder(new Uri(string.Format(ConfigurationManager.AppSettings["TwitterUrl"], handle, 500)), HTTPVerb.GET, oaccesstkn);

                string responseText;
                using (var response = webRequest.ExecuteRequest())
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseText = reader.ReadToEnd();
                    }
                }

                var brr = Encoding.UTF8.GetBytes(responseText);

                var streamReader = new StreamReader(new MemoryStream(brr));

                var serializer = new DataContractJsonSerializer(typeof(SearchResults));

                var tweetsResponse = (SearchResults)serializer.ReadObject(streamReader.BaseStream);

                streamReader.Close();
                #endregion

                foreach (var mmTweetData in tweetsResponse.Results)
                {
                    var tweetId = mmTweetData.Id.ToString();
                    try
                    {
                        var myTweet = new TwitterEntity
                        {
                            RowKey                = Guid.NewGuid().ToString(),
                            TwitterId             = tweetId,
                            TwitterIdString       = mmTweetData.Id_Str,
                            TextMessage           = mmTweetData.Text,
                            Source                = mmTweetData.Source,
                            FromUser              = mmTweetData.Source,
                            FromUserId            = mmTweetData.ToUserName,
                            ProfileImageUrl       = mmTweetData.User.ProfileImageUrl,
                            ProfileSecureImageUrl = mmTweetData.User.ProfileImageUrlHttps,
                            ReplyUserId           = mmTweetData.User.FromUserId.ToString(),
                            ReplyScreenName       = mmTweetData.User.FromUser,
                            ResultType            = mmTweetData.SearchMetaData.ResultType,
                            LanguageCode          = mmTweetData.SearchMetaData.IsoLanguageCode,
                            Created_At            = ParseTwitterDateTime(mmTweetData.CreatedAt),
                            Status                = "-1"
                        };

                        tweets.Add(myTweet);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (Exception)
            {
            }

            return(tweets);
        }
Example #9
0
        public void CreateRetweetUnofficial_WithFormatterTest()
        {
            // TweetFormatterでHTMLに整形 → CreateRetweetUnofficialで復元 までの動作が正しく行えているか

            var text = "#てすと @TwitterAPI \n http://t.co/KYi7vMZzRt";
            var entities = new TwitterEntity[]
            {
                new TwitterEntityHashtag
                {
                    Indices = new[] { 0, 4 },
                    Text = "てすと",
                },
                new TwitterEntityMention
                {
                    Indices = new[] { 5, 16 },
                    Id = 6253282L,
                    Name = "Twitter API",
                    ScreenName = "twitterapi",
                },
                new TwitterEntityUrl
                {
                    Indices = new[] { 19, 41 },
                    DisplayUrl = "twitter.com",
                    ExpandedUrl = "http://twitter.com/",
                    Url = "http://t.co/KYi7vMZzRt",
                },
            };

            var html = TweetFormatter.AutoLinkHtml(text, entities);

            var expected = "#てすと @TwitterAPI " + Environment.NewLine + " http://twitter.com/";
            Assert.Equal(expected, TweenMain.CreateRetweetUnofficial(html, true));
        }
Example #10
0
        public void AutoLinkHtml_EntityNullTest4()
        {
            var text = "てすとてすとー";
            IEnumerable<TwitterEntity> entities = new TwitterEntity[] { null };

            var expected = "てすとてすとー";
            Assert.Equal(expected, TweetFormatter.AutoLinkHtml(text, entities));
        }
Example #11
0
        public TwitterStatus(JsonValue json)
        {
            GenerateFromJson = true;

            // read numeric id and timestamp
            Id        = json["id_str"].AsString().ParseLong();
            CreatedAt = json["created_at"].AsString().ParseDateTime(ParsingExtension.TwitterDateTimeFormat);

            // check extended_tweet is existed
            var exjson = json.ContainsKey("extended_tweet") ? json["extended_tweet"] : json;

            // read full_text ?? text
            var text = exjson.ContainsKey("full_text") ? exjson["full_text"] : exjson["text"];

            Text = ParsingExtension.ResolveEntity(text.AsString());

            var array = exjson["display_text_range"].AsArrayOrNull()?.AsLongArray();

            if (array != null && array.Length >= 2)
            {
                DisplayTextRange = new Tuple <int, int>((int)array[0], (int)array[1]);
            }

            if (exjson.ContainsKey("extended_entities"))
            {
                // get correctly typed entities array
                var orgEntities = TwitterEntity.ParseEntities(exjson["entities"]).ToArray();
                var extEntities = TwitterEntity.ParseEntities(exjson["extended_entities"]).ToArray();

                // merge entities
                Entities = orgEntities.Where(e => !(e is TwitterMediaEntity))
                           .Concat(extEntities)            // extended entities contains media entities only.
                           .ToArray();
            }
            else if (exjson.ContainsKey("entities"))
            {
                Entities = TwitterEntity.ParseEntities(exjson["entities"]).ToArray();
            }
            else
            {
                Entities = new TwitterEntity[0];
            }
            if (json.ContainsKey("recipient"))
            {
                // THIS IS DIRECT MESSAGE!
                StatusType = StatusType.DirectMessage;
                User       = new TwitterUser(json["sender"]);
                Recipient  = new TwitterUser(json["recipient"]);
            }
            else
            {
                StatusType          = StatusType.Tweet;
                User                = new TwitterUser(json["user"]);
                Source              = json["source"].AsString();
                InReplyToStatusId   = json["in_reply_to_status_id_str"].AsString().ParseNullableId();
                InReplyToUserId     = json["in_reply_to_user_id_str"].AsString().ParseNullableId();
                FavoriteCount       = json["favorite_count"].AsLongOrNull();
                RetweetCount        = json["retweet_count"].AsLongOrNull();
                InReplyToScreenName = json["in_reply_to_screen_name"].AsString();

                if (json.ContainsKey("retweeted_status"))
                {
                    var retweeted = new TwitterStatus(json["retweeted_status"]);
                    RetweetedStatus = retweeted;
                    // merge text and entities
                    Text     = retweeted.Text;
                    Entities = retweeted.Entities;
                }
                if (json.ContainsKey("quoted_status"))
                {
                    var quoted = new TwitterStatus(json["quoted_status"]);
                    QuotedStatus = quoted;
                }
                var coordinates = json["coordinates"]["coordinates"].AsArrayOrNull()?.AsDoubleArray();
                if (coordinates != null && coordinates.Length >= 2)
                {
                    Coordinates = Tuple.Create(coordinates[0], coordinates[1]);
                }
            }
        }
Example #12
0
        private static T Map <T>(long parentId, [CanBeNull] TwitterEntity entity)
            where T : DatabaseEntity, new()
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            EntityType et;
            string     murl = null;
            string     ourl = null;
            long?      uid  = null;
            var        mt   = (Casket.DatabaseModels.MediaType?)null;

            if (entity is TwitterUrlEntity ue)
            {
                et   = EntityType.Urls;
                murl = ue.ExpandedUrl;
                ourl = ue.ExpandedUrl;
            }
            else if (entity is TwitterMediaEntity me)
            {
                et   = EntityType.Media;
                murl = me.MediaUrlHttps;
                ourl = me.ExpandedUrl;
                uid  = me.Id;
                switch (me.MediaType)
                {
                case MediaType.Photo:
                    mt = Casket.DatabaseModels.MediaType.Photo;
                    break;

                case MediaType.Video:
                    mt = Casket.DatabaseModels.MediaType.Video;
                    break;

                case MediaType.AnimatedGif:
                    mt = Casket.DatabaseModels.MediaType.AnimatedGif;
                    break;
                }
            }
            else if (entity is TwitterHashtagEntity)
            {
                et = EntityType.Hashtags;
            }
            else if (entity is TwitterSymbolEntity)
            {
                et = EntityType.Symbols;
            }
            else if (entity is TwitterUserMentionEntity re)
            {
                et  = EntityType.UserMentions;
                uid = re.Id;
            }
            else
            {
                throw new ArgumentException($"mapper did not support type {entity.GetType().FullName} yet.");
            }

            return(new T
            {
                DisplayText = entity.DisplayText,
                StartIndex = entity.Indices.Item1,
                EndIndex = entity.Indices.Item2,
                EntityType = et,
                MediaUrl = murl,
                OriginalUrl = ourl,
                UserId = uid,
                ParentId = parentId,
                MediaType = mt
            });
        }