Ejemplo n.º 1
0
        public List <Post> GetPosts(PostContainer postContainer, Dispatch dispatch, out List <LinkPost> linkPosts, out List <SelfPost> selfPosts)
        {
            linkPosts = new List <LinkPost>();
            selfPosts = new List <SelfPost>();

            if (postContainer == null || postContainer.Data == null || postContainer.Data.Children == null)
            {
                return(null);
            }

            List <Post> posts = new List <Post>();

            foreach (PostChild postChild in postContainer.Data.Children)
            {
                if (postChild.Data != null)
                {
                    if (postChild.Data.IsSelf)
                    {
                        SelfPost selfPost = new SelfPost(dispatch, postChild.Data);
                        posts.Add(selfPost);
                        selfPosts.Add(selfPost);
                    }
                    else
                    {
                        LinkPost linkPost = new LinkPost(dispatch, postChild.Data);
                        posts.Add(linkPost);
                        linkPosts.Add(linkPost);
                    }
                }
            }

            return(posts);
        }
Ejemplo n.º 2
0
        public void SpeedLimit()
        {
            Subreddit.Posts.GetNew();
            Subreddit.Posts.MonitorNew();
            Subreddit.Posts.NewUpdated += C_NewPostsUpdated;

            // 60 requests are allowed per minute.  --Kris
            for (int i = 1; i <= 100; i++)
            {
                // Despite what VS says, we don't want to use await here.  --Kris
                LinkPost.SubmitAsync(resubmit: true);
            }

            // Note - The best way to verify the speed limit is working is to debug this test and observe the events relative to the timing.  --Kris

            // Make sure the remaining posts eventually trickle in.  --Kris
            DateTime start = DateTime.Now;

            while (NewPosts.Count < 100 &&
                   start.AddMinutes(5) > DateTime.Now)
            {
            }

            Subreddit.Posts.NewUpdated -= C_NewPostsUpdated;
            Subreddit.Posts.MonitorNew();

            Assert.IsTrue(NewPosts.Count >= 100);
        }
Ejemplo n.º 3
0
        public void SetLinkFlairWithTemplate()
        {
            LinkPost linkPost = Subreddit.LinkPost("Test Link Flair Post", "https://www.nuget.org/packages/Reddit").Submit(resubmit: true);

            // Get the available templates and use the first one that isn't empty.  --Kris
            Reddit.Things.FlairSelectorResultContainer flairSelectorResultContainer = Subreddit.Flairs.FlairSelector(link: linkPost.Fullname);
            Validate(flairSelectorResultContainer);

            string flairTemplateId = null;

            foreach (Reddit.Things.FlairSelectorResult flairSelectorResult in flairSelectorResultContainer.Choices)
            {
                if (!string.IsNullOrWhiteSpace(flairSelectorResult.FlairTemplateId))
                {
                    flairTemplateId = flairSelectorResult.FlairTemplateId;
                    break;
                }
            }

            if (string.IsNullOrWhiteSpace(flairTemplateId))
            {
                Assert.Inconclusive("Unable to find a flair template ID for this subreddit.  Please create one then retry.");
            }

            linkPost.SetFlair("NuGet Package", flairTemplateId);
        }
Ejemplo n.º 4
0
        public void MonitorPostAndCommentHistory()
        {
            // Monitor new posts for 2 minutes.  --Kris
            reddit.Account.Me.GetPostHistory(sort: "newForced");
            reddit.Account.Me.MonitorPostHistory(monitoringExpiration: DateTime.Now.AddMinutes(2));
            reddit.Account.Me.PostHistoryUpdated += C_NewPostsUpdated;

            // Monitor new comments for 2 minutes.  --Kris
            reddit.Account.Me.GetCommentHistory();
            reddit.Account.Me.MonitorCommentHistory(monitoringExpiration: DateTime.Now.AddMinutes(2));
            reddit.Account.Me.CommentHistoryUpdated += C_NewCommentsUpdated;

            LinkPost post = Subreddit.LinkPost("Test Link Post", "https://www.nuget.org/packages/Reddit").Submit(resubmit: true);

            Validate(post);

            Comment comment = post.Reply("Test comment.");

            Validate(comment);

            DateTime start = DateTime.Now;

            while (NewPosts.Count == 0 &&
                   NewComments.Count == 0 &&
                   start.AddMinutes(2) > DateTime.Now)
            {
                Thread.Sleep(1000);
            }
        }
Ejemplo n.º 5
0
        // HELPER FUNCTIONS
        private LinkPostDto CreateLinkDto(LinkPost linkpost)
        {
            var dto = _mapper.Map <LinkPostDto>(linkpost);

            dto.Link = Url.Link(
                nameof(GetLinkPostId),
                new { linkPostId = linkpost.PostId });
            return(dto);
        }
Ejemplo n.º 6
0
        private void ImportFromLinkPost(LinkPost linkPost)
        {
            ImportFromPost(linkPost);

            Preview         = linkPost.Preview;
            URL             = linkPost.URL;
            Thumbnail       = linkPost.Thumbnail;
            ThumbnailHeight = linkPost.ThumbnailHeight;
            ThumbnailWidth  = linkPost.ThumbnailWidth;
        }
Ejemplo n.º 7
0
        public void PoliceState()
        {
            // Monitor all kinds of shit.  --Kris
            Subreddit.Posts.GetNew();
            Subreddit.Posts.MonitorNew();
            Subreddit.Posts.NewUpdated += C_NewPostsUpdated;

            // Create 60 posts, each with 10 comments.  --Kris
            List <LinkPost> posts = new List <LinkPost>();

            for (int i = 1; i <= 60; i++)
            {
                posts.Add(LinkPost.Submit(resubmit: true));  // Add .About() after the Submit call if you want more than just the fullname/id of the new post.  --Kris

                posts[i - 1].Comments.GetNew();
                posts[i - 1].Comments.MonitorNew();
                posts[i - 1].Comments.NewUpdated += C_NewCommentsUpdated;

                for (int ii = 1; ii <= 10; ii++)
                {
                    // Despite what VS says, we don't want to use await here.  --Kris
                    posts[i - 1].ReplyAsync("Stress test comment #" + i.ToString() + "-" + ii.ToString());
                }
            }

            // We're deliberately flooding it with requests here (660 total, plus monitoring), so it may take awhile for the test to complete.  --Kris
            DateTime start = DateTime.Now;

            while ((NewPosts.Count < 60 ||
                    NewComments.Count < 600) &&
                   start.AddHours(1) > DateTime.Now)
            {
            }

            Assert.IsTrue(NewPosts.Count >= 60);

            /*
             * Occasionally, the Reddit API will correctly report the number of comments in a thread but omit one or more of those comments in the actual results,
             * even though those comments have not been deleted/etc.  This phenomenon also seems to occur in the web UI (confirmed in both old and redesign), which
             * means the problem must be on Reddit's end.  My guess is it's related to the heavy query load that this particular stress test generates.
             *
             * On one such thread (https://www.reddit.com/r/RedditDotNETBot/comments/a7wlfp/stress_test_link_post), only 1 comment was missing, even though
             * Reddit reported 10 comments (as you can see, there are only 9 comments showing; the first one is missing).  All 9 of those comments appeared in the
             * thread within a couple minutes of one another.  That was about an hour ago and it's still only showing 9 of the 10 comments.  Same result on other sorts.
             * Waiting/refreshing the results had no effect.
             *
             * If I'm right, there's nothing we can do on this end other than adjust the assertion to allow for a certain number of lost comments.  In every test I ran,
             * over 95% of the comments were able to be retrieved, so we'll allow for up to 10% loss.
             *
             * --Kris
             */
            Assert.IsTrue(NewComments.Count >= 540);
        }
Ejemplo n.º 8
0
 private void HandleLinkPostAdded(LinkPost lp, bool isCatchUpLog)
 {
     InvokeContentPosted(new UserContentPostedEventArgs {
         Id                  = lp.Id,
         FullName            = lp.Fullname,
         Author              = lp.Author,
         Title               = lp.Title,
         Content             = null,
         AuthorFlairText     = lp.Listing.AuthorFlairText,
         AuthorFlairCssClass = lp.Listing.AuthorFlairCSSClass,
         IsCatchUpLog        = isCatchUpLog,
         IsPost              = true,
         Post                = lp,
         Comment             = null,
     }, isCatchUpLog);
 }
        public object Deserialize(JsonValue json, JsonMapper mapper)
        {
            LinkPost post = null;

            if (json != null && !json.IsNull)
            {
                post             = new LinkPost();
                post.ID          = json.ContainsName("id") ? json.GetValue <string>("id") : String.Empty;
                post.ObjectId    = json.ContainsName("object_id") ? json.GetValue <string>("object_id") : String.Empty;
                post.CreatedTime = json.ContainsName("created_time") ? JsonUtils.ToDateTime(json.GetValue <string>("created_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue;
                post.UpdatedTime = json.ContainsName("updated_time") ? JsonUtils.ToDateTime(json.GetValue <string>("updated_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue;

                post.From = mapper.Deserialize <Reference>(json.GetValue("from"));
            }
            return(post);
        }
Ejemplo n.º 10
0
        private LinkPost ParseLinkPost(JObject jObject, HashSet <string> checkedProperties)
        {
            LinkPost newPost = new LinkPost();
            JToken   current;

            if (CheckProperty(jObject, "title", checkedProperties, out current))
            {
                newPost.Title = (string)current;
            }
            if (CheckProperty(jObject, "url", checkedProperties, out current))
            {
                newPost.Url = (string)current;
            }
            if (CheckProperty(jObject, "description", checkedProperties, out current))
            {
                newPost.Description = (string)current;
            }
            return(newPost);
        }
Ejemplo n.º 11
0
        public void SetBrowserContent()
        {
            if (SelectedPost != null)
            {
                Browser.Navigate((Uri)null);

                if (SelectedPost.GetType() == typeof(SelfPost))
                {
                    SelfPost self = (SelfPost)SelectedPost;
                    Browser.NavigateToString("<html><body>" + self.SelfTextHTML + "</body></html>");
                }
                else if (SelectedPost.GetType() == typeof(LinkPost))
                {
                    LinkPost link  = (LinkPost)SelectedPost;
                    string   thumb = link.Thumbnail;
                    Browser.NavigateToString($"<html><body> <img src='{thumb}' width='100%'   </body></html>");
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="post"></param>
        /// <param name="jPost"></param>
        public static void GenerateLinkPost(ref TumblrPost post, dynamic jPost)
        {
            if (post == null)
            {
                throw new ArgumentNullException(nameof(post));
            }
            if (jPost == null)
            {
                throw new ArgumentNullException(nameof(jPost));
            }

            post = new LinkPost
            {
                LinkAuthor  = !string.IsNullOrEmpty((string)jPost.link_author) ? jPost.link_author : null,
                LinkImage   = !string.IsNullOrEmpty((string)jPost.link_image) ? jPost.link_image : null,
                LinkUrl     = !string.IsNullOrEmpty((string)jPost.url) ? jPost.url : null,
                Title       = !string.IsNullOrEmpty((string)jPost.title) ? jPost.title : null,
                Description = !string.IsNullOrEmpty((string)jPost.description) ? jPost.description : null,
                Excerpt     = !string.IsNullOrEmpty((string)jPost.excerpt) ? jPost.excerpt : null,
                Publisher   = !string.IsNullOrEmpty((string)jPost.publisher) ? jPost.publisher : null
            };
            IncludeCommonPostFields(ref post, jPost);
        }
Ejemplo n.º 13
0
        static void SaveBlogposts(XElement[] children)
        {
            var io        = new IO(UserSettings.PathToJekyllSite);
            var blogPosts = children.Where(i => i.Name == "item" && i.Element(Namespaces.wpNS + "post_type").Value == "post").ToArray();

            Parallel.ForEach(blogPosts, xmlBlogPost => {
                BlogPost blogPost;
                if (xmlBlogPost.Element(Namespaces.wpNS + "postmeta")?.Element(Namespaces.wpNS + "meta_key")?.Value == "passthrough_url")
                {
                    blogPost = new LinkPost(xmlBlogPost, io)
                    {
                        ExternalLink = xmlBlogPost.Element(Namespaces.wpNS + "postmeta").Element(Namespaces.wpNS + "meta_value").Value
                    };
                }
                else
                {
                    blogPost = new BlogPost(xmlBlogPost, io);
                }

                blogPost.Title = xmlBlogPost.Element("title").Value;
                blogPost.Link  = xmlBlogPost.Element("link").Value;

                foreach (var tag in xmlBlogPost.Elements("category").Where(e => e.Attribute("domain")?.Value == "post_tag").Select(e => e.Value))
                {
                    blogPost.AddTag(tag);
                }

                // Single post filter
                //if (blogPost.Title != "No content in Solution Explorer using Visual Studio 2013") {
                //    return;
                //}

                blogPost.Content = xmlBlogPost.Element(Namespaces.contentNS + "encoded").Value;

                blogPost.Save();
            });
        }
Ejemplo n.º 14
0
        public void MoreReplies()
        {
            LinkPost post = reddit.Subreddit("news").LinkPost("t3_2lt3d0").About();

            Assert.IsNotNull(post);

            Assert.IsNotNull(post.Comments.Confidence);
            Assert.IsFalse(post.Comments.Confidence.Count.Equals(0));
            Assert.AreEqual(post.Comments.Confidence[0].Body, "I have no idea whats going on");
            Assert.AreEqual(post.Comments.Confidence[0].Id, "cly40cf");
            Assert.IsNotNull(post.Comments.Confidence[0].Replies);
            Assert.IsFalse(post.Comments.Confidence[0].Replies.Count.Equals(0));
            Assert.AreEqual(post.Comments.Confidence[0].Replies[0].Id, "cly6q06");
            Assert.IsNotNull(post.Comments.Confidence[0].Replies[0].Replies);
            Assert.IsFalse(post.Comments.Confidence[0].Replies[0].Replies.Count.Equals(0));
            Assert.AreEqual(post.Comments.Confidence[0].Replies[0].Replies[0].Id, "clyaevo");

            Assert.IsNotNull(post.Comments.Confidence[0].Replies[0].Replies[0].More);
            Assert.IsFalse(post.Comments.Confidence[0].Replies[0].Replies[0].More.Count.Equals(0));
            Assert.IsNotNull(post.Comments.Confidence[0].Replies[0].Replies[0].More[0].Children);
            Assert.IsFalse(post.Comments.Confidence[0].Replies[0].Replies[0].More[0].Children.Count.Equals(0));
            Assert.IsNotNull(post.Comments.Confidence[0].Replies[0].Replies[0].Replies);
            Assert.IsFalse(post.Comments.Confidence[0].Replies[0].Replies[0].Replies.Count.Equals(0));

            // Now make sure the more entries correspond to actual replies.  --Kris
            HashSet <string> ids = new HashSet <string>();

            foreach (Comment comment in post.Comments.Confidence[0].Replies[0].Replies[0].Replies)
            {
                ids.Add(comment.Id);
            }

            foreach (string childId in post.Comments.Confidence[0].Replies[0].Replies[0].More[0].Children)
            {
                Assert.IsTrue(ids.Contains(childId));
            }
        }
Ejemplo n.º 15
0
 public Post(LinkPost linkPost)
 {
     ImportFromLinkPost(linkPost);
 }
Ejemplo n.º 16
0
 private LinkPost GetPost()
 {
     Post = reddit.LinkPost(PostFullname).About();
     return(Post);
 }
Ejemplo n.º 17
0
 private LinkPost TestLinkPost()
 {
     Post = reddit.Subreddit(testData["Subreddit"]).LinkPost("Test Link Post", "http://www.go-f**k-yourself.com").Submit(resubmit: true);
     return(post);
 }
Ejemplo n.º 18
0
        public void SetLinkFlair()
        {
            LinkPost linkPost = Subreddit.LinkPost("Test Link Flair Post", "https://www.nuget.org/packages/Reddit").Submit(resubmit: true);

            linkPost.SetFlair("NuGet Package");
        }
Ejemplo n.º 19
0
        private async void NewRedditPost(object sender, PostsUpdateEventArgs e)
        {
            foreach (var post in e.Added)
            {
                // Old post... somehow
                if (post.Created.AddHours(1) < DateTime.Now)
                {
                    continue;
                }
                foreach (var guildData in SaveDataManager.saveData.guildDataList)
                {
                    try
                    {
                        if (ConfigManager.config.guildWhitelist.Contains(guildData.guildId.ToString()))
                        {
                            LinkPost linkPost = post as LinkPost;

                            EmbedBuilder builder = new EmbedBuilder()
                            {
                                Title = $"[r/{post.Subreddit}] {post.Title}",
                                Url   = $"https://www.reddit.com{post.Permalink}"
                            };
                            if (linkPost != null)
                            {
                                if (linkPost.URL.Contains("i.redd.it"))
                                {
                                    builder.ImageUrl = linkPost.URL;
                                }
                                else if (linkPost.URL.Contains("v.redd.it"))
                                {
                                    builder.ImageUrl = linkPost.URL;
                                    builder.Title   += "[Video]";
                                }
                                else
                                {
                                    builder.ImageUrl    = linkPost.Thumbnail;
                                    builder.Url         = linkPost.URL;
                                    builder.Description = $"[Permalink to post]({$"https://www.reddit.com{linkPost.Permalink}"}){Environment.NewLine}";
                                }
                            }
                            else
                            {
                                if (post.Listing.SelfText.Length >= 301)
                                {
                                    builder.Description = WebUtility.HtmlDecode(post.Listing.SelfText.Substring(0, 300)) + "...";
                                }
                                else
                                {
                                    builder.Description = WebUtility.HtmlDecode(post.Listing.SelfText);
                                }
                            }
                            builder.Footer = new EmbedFooterBuilder()
                            {
                                Text = $"by u/{post.Author}"
                            };
                            string mention = guildData.useMention ? $"<@&{guildData.mentionRoleId}>" : "";
                            await socketClient.GetGuild(guildData.guildId).GetTextChannel(guildData.channelId).SendMessageAsync(text: mention, embed: builder.Build());
                        }
                        else
                        {
                            await socketClient.GetGuild(guildData.guildId).LeaveAsync();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("[!!.] Had an error while trying to handle new post." + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
                    }
                }
            }
        }