Пример #1
0
        private CommentTree GetCommentTree(List <RedditComment> comments, RedditComment comment, bool parity)
        {
            List <RedditComment> children = comments.Where(child => child.parentID.ToString() == comment.id.ToString()).ToList();

            if (children.Count == 0)
            {
                comment.parity = parity;
                return(new CommentTree()
                {
                    children = null, comment = comment
                });
            }
            else
            {
                RedditComment whatcomment = comment;
                comment.parity = parity;
                CommentTree rt = new CommentTree()
                {
                    children = new List <CommentTree>(),
                    comment  = whatcomment
                };
                List <CommentTree> what = new List <CommentTree>();
                foreach (var item in children)
                {
                    what.Add(GetCommentTree(comments, item, !parity));
                }
                rt.children = what;

                return(rt);
            }
        }
Пример #2
0
        /// <summary>
        /// Gets the last 100 Reddit comments for a specified username
        /// </summary>
        /// <param name="user">Reddit Username to lookup</param>
        /// <returns>Array of Reddit Comments</returns>
        public RedditComment[] GetComments(string user)
        {
            //Create our GET request with the specified user, limiting to 100 comments (max allowed by Reddit API)
            HttpWebRequest request = WebRequest.CreateHttp($"https://www.reddit.com/user/{user}/comments/.json?limit=100");

            request.Method = "GET";

            //Get response Json object
            WebResponse response = request.GetResponse();

            //Stream Json to string then deserialize into a RedditListing of type RedditComment (Basically a listing of comments)
            Stream stream = response.GetResponseStream();

            RedditComment[] comments;
            using (StreamReader sr = new StreamReader(stream))
            {
                string json = sr.ReadToEnd();
                RedditListingChild <RedditComment>[] children = RedditListing <RedditComment> .FromJson(json).Data.Children;

                comments = new RedditComment[children.Length];
                for (int i = 0; i < children.Length; i++)
                {
                    comments[i] = children[i].Data;
                }
            }

            return(comments);
        }
        private CommentViewModel NestReplies(RedditComment c)
        {
            CommentViewModel ncvm = new CommentViewModel(c);

            ncvm.replies = new List <CommentViewModel>();
            foreach (var reply in c.replies)
            {
                ncvm.replies.Add(NestReplies(reply));
            }
            return(ncvm);
        }
Пример #4
0
        public void RedditCommentReaderCanRetrieveMostRecentComment()
        {
            RedditHttpsReader reader  = new RedditHttpsReader("chefknives");
            RedditComment     comment = reader.GetRecentComments(1).FirstOrDefault();

            Assert.IsNotNull(comment);
            Assert.IsNotNull(comment.Author);
            Assert.IsNotNull(comment.Body);
            Assert.IsNotNull(comment.Id);
            Assert.IsNotNull(comment.PostLinkId);
        }
Пример #5
0
        public async Task <IActionResult> CreateComment(RedditComment comment, string ReturnURL)
        {
            RedditPost post = await _context.Posts.FindAsync(comment.postID);

            post.num_comments += 1;

            Int64 unixTimestamp = (Int64)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            comment.unixTimestamp = unixTimestamp;
            await _context.AddAsync(comment);

            await _context.SaveChangesAsync();

            return(LocalRedirect("/reddit/comments/" + comment.postID));
        }
Пример #6
0
        public void ObjectEqualityOnDatabaseObjectsWorksAsExpected()
        {
            using (DatabaseCache <RedditComment> cache = new DatabaseCache <RedditComment>(5))
            {
                for (int i = 0; i < 5; ++i)
                {
                    RedditComment comment = new RedditComment()
                    {
                        Body = $"info: {i}"
                    };
                    Assert.IsFalse(cache.Contains(comment));
                    cache.Add(comment);
                    Assert.IsTrue(cache.Contains(comment));
                }

                Assert.IsTrue(cache.Contains(new RedditComment()
                {
                    Body = $"info: 0"
                }));
            }

            using (DatabaseCache <RedditPost> postCache = new DatabaseCache <RedditPost>(15))
            {
                for (int i = 0; i < 20; ++i)
                {
                    RedditPost post = new RedditPost()
                    {
                        Title = $"info: {i}"
                    };
                    Assert.IsFalse(postCache.Contains(post));
                    postCache.Add(post);
                    Assert.IsTrue(postCache.Contains(post));
                }

                Assert.IsTrue(postCache.Contains(new RedditPost()
                {
                    Title = $"info: 10"
                }));
                Assert.IsFalse(postCache.Contains(new RedditPost()
                {
                    Title = $"info: 0"
                }));
            }
        }
Пример #7
0
        public void DatabaseCacheWorksWithDatabaseObjects()
        {
            DatabaseCache <RedditComment> cache = new DatabaseCache <RedditComment>(5);

            for (int i = 0; i < 10; ++i)
            {
                RedditComment comment = new RedditComment()
                {
                    Body = $"info: {i}"
                };
                Assert.IsFalse(cache.Contains(comment));
                cache.Add(comment);
                Assert.IsTrue(cache.Contains(comment));
            }

            Assert.IsFalse(cache.Contains(new RedditComment()
            {
                Body = $"info: 0"
            }));
        }
Пример #8
0
        public static void GetCommentsAsync(RedditPost post)
        {
            int        index = Api.Posts.IndexOf(post);
            RedditPost Post  = Api.Posts[index];

            foreach (var child in Api.CommentData[1]["data"]["children"])
            {
                var  data      = child["data"];
                bool IsComment = (string)child["kind"] != "more";

                if (IsComment)
                {
                    try
                    {
                        bool IsNotDeleted       = (string)data["author"] != "[deleted]";
                        bool IsNotControversial = (int)data["score"] > 0;
                        if (IsNotDeleted && IsNotControversial)
                        {
                            var comment = new RedditComment
                            {
                                Author  = (string)data["author"],
                                Score   = (int)data["score"],
                                Utc     = (string)data["created_utc"],
                                Body    = (string)data["body"],
                                Link    = (string)$"{Api.DOMAIN}{data["permalink"]}",
                                Replies = data["replies"]
                            };
                            Api.Posts[index].Comments.Add(comment);
                            Console.WriteLine($"Title: {comment.Title}");
                            Console.WriteLine($"Is image? {comment.HasImage}");
                        }
                    }
                    catch (System.ArgumentNullException)
                    {
                        // If Comment Cannot be parsed, catch error
                        return;
                    }
                }
            }
        }
Пример #9
0
    private void PickComment()
    {
        int targetDirection = Random.value < 0.3f ? 1 : -1;

        currentComment = reddit.CurrentPostComments.Find(c => (int)Mathf.Sign(c.score) == targetDirection);
        var str = "Trying to get post with " + targetDirection + " karma...";

        if (currentComment == null)
        {
            str           += " Not found, getting random one";
            currentComment = reddit.CurrentPostComments[Random.Range(0, 3)];
        }
        else
        {
            str += "Success!";
        }

        reddit.CurrentPostComments.Remove(currentComment);

        Invoke("AlienComment", Random.Range(5f, 20f));

        //Debug.Log(str);
    }
Пример #10
0
        private RedditComment BuildComment(JsonObject entry)
        {
            Dictionary <String, object> stuff = new Dictionary <string, object>();
            List <String> keys = new List <String> {
            };
            string _author_flair_css_class, _subreddit_id, _link_id, _author, _parent_id, _body, _id, _name, _body_html, _subreddit, _author_flair_text;
            bool   _saved, _archived, _score_hidden, _stickied;
            double _score, _gilded, _controversiality, _downs, _created, _created_utc, _ups, _count;

            getJsonValue(entry, "author_flair_css_class", out _author_flair_css_class);
            getJsonValue(entry, "subreddit_id", out _subreddit_id);
            getJsonValue(entry, "link_id", out _link_id);
            getJsonValue(entry, "author", out _author);
            getJsonValue(entry, "parent_id", out _parent_id);
            getJsonValue(entry, "body", out _body);
            getJsonValue(entry, "id", out _id);
            getJsonValue(entry, "name", out _name);
            getJsonValue(entry, "body_html", out _body_html);
            getJsonValue(entry, "subreddit", out _subreddit);
            getJsonValue(entry, "author_flair_text", out _author_flair_text);
            getJsonValue(entry, "saved", out _saved);
            getJsonValue(entry, "out_archived", out _archived);
            getJsonValue(entry, "score_hidden", out _score_hidden);
            getJsonValue(entry, "stickied", out _stickied);
            getJsonValue(entry, "score", out _score);
            getJsonValue(entry, "gilded", out _gilded);
            getJsonValue(entry, "controversiality", out _controversiality);
            getJsonValue(entry, "downs", out _downs);
            getJsonValue(entry, "created", out _created);
            getJsonValue(entry, "created_utc", out _created_utc);
            getJsonValue(entry, "ups", out _ups);
            getJsonValue(entry, "count", out _count);

            bool       success;
            IJsonValue _dump;

            success = entry.TryGetValue("replies", out _dump);
            JsonArray jsonReplies = null;

            //handling the inconsistent returns of reddit's api
            if (success && _dump.ValueType.Equals(JsonValueType.Object))
            {
                JsonObject _repliesObject = entry.GetNamedObject("replies");

                success = _repliesObject.TryGetValue("data", out _dump);
                if (success && _dump.ValueType.Equals(JsonValueType.Object))
                {
                    JsonObject _dataObject = _repliesObject.GetNamedObject("data");

                    success = _dataObject.TryGetValue("children", out _dump);
                    if (success && _dump.ValueType.Equals(JsonValueType.Array))
                    {
                        jsonReplies = _dataObject.GetNamedArray("children");
                    }
                }
            }


            List <RedditComment> _replies = new List <RedditComment>();

            if (jsonReplies != null)
            {
                for (uint j = 0; j < jsonReplies.Count; j++)
                {
                    string kind = jsonReplies.GetObjectAt(j).GetNamedString("kind");
                    if (!kind.Equals("more"))
                    {
                        JsonObject    reply   = jsonReplies.GetObjectAt(j).GetNamedObject("data");
                        RedditComment comment = BuildComment(reply);
                        _replies.Add(comment);
                    }
                }
            }


            return(new RedditComment
            {
                subreddit_id = _subreddit_id,
                link_id = _link_id,
                author = _author,
                parent_id = _parent_id,
                body = _body,
                id = _id,
                name = _name,
                author_flair_css_class = _author_flair_css_class,
                body_html = _body_html,
                subreddit = _subreddit,
                author_flair_text = _author_flair_text,
                saved = _saved,
                archived = _archived,
                score_hidden = _score_hidden,
                stickied = _stickied,
                score = _score,
                gilded = _gilded,
                controversiality = _controversiality,
                downs = _downs,
                created = _created,
                created_utc = _created_utc,
                ups = _ups,
                count = _count,
                replies = _replies
            });
        }
Пример #11
0
 protected override void UpsertIntoCollection(RedditComment comment)
 {
     throw new Exception("UpsertIntoCollection was hit");
 }