Exemplo n.º 1
0
            private async Task GetBaseComments()
            {
                var url = string.Format(GetCommentsUrl, post.Id);

                if (limit > 0)
                {
                    var query = "limit=" + limit;
                    url = string.Format("{0}?{1}", url, query);
                }
                var json = await agent.Get(url).ConfigureAwait(false);

                var postJson = json.Last()["data"]["children"];

                List <Comment> retrieved = new List <Things.Comment>();

                foreach (var item in postJson)
                {
                    Comment newComment = new Comment(agent, item, post);
                    if (newComment.Kind != "more")
                    {
                        retrieved.Add(newComment);
                    }
                    else
                    {
                        existingMores.Add(new More(agent, item));
                    }
                }
                currentBranch = retrieved;
            }
        /// <summary>
        /// Get a <see cref="JToken"/> from a url.
        /// </summary>
        /// <param name="agent">IWebAgent to use to make request</param>
        /// <param name="uri">uri to fetch</param>
        /// <param name="isLive">bool indicating if it's a live thread or not</param>
        /// <returns></returns>
        public static async Task <JToken> GetTokenAsync(IWebAgent agent, Uri uri, bool isLive = false)
        {
            //TODO clean this up
            if ((!String.IsNullOrEmpty(agent.AccessToken) || agent.GetType() == typeof(RefreshTokenWebAgent)) && uri.AbsoluteUri.StartsWith("https://www.reddit.com"))
            {
                uri = new Uri(uri.AbsoluteUri.Replace("https://www.reddit.com", "https://oauth.reddit.com"));
            }

            var url = uri.AbsoluteUri;

            if (url.EndsWith("/"))
            {
                url = url.Remove(url.Length - 1);
            }

            if (!url.ToLower().EndsWith(".json"))
            {
                url += ".json";
            }

            var json = await agent.Get(url);

            if (isLive)
            {
                return(json);
            }
            else
            {
                return(json[0]["data"]["children"].First);
            }
        }
        public static async Task <string[]> GetWarningKeys(IWebAgent webAgent, string subName)
        {
            var reqResponse = await webAgent.Get(string.Format(ToolBoxUserNotesWiki, subName)).ConfigureAwait(false);

            var response = JObject.Parse(reqResponse["data"]["content_md"].Value <string>());
            int version  = response["ver"].Value <int>();

            if (version < 6)
            {
                throw new ToolBoxUserNotesException("Unsupported ToolBox version");
            }

            string[] warnings = response["constants"]["warnings"].Values <string>().ToArray();

            return(warnings);
        }
Exemplo n.º 4
0
        public static async Task <IEnumerable <ModeratorUser> > GetModeratorsAsync(IWebAgent agent, string subreddit)
        {
            var json = await agent.Get(string.Format(ModeratorsUrl, subreddit)).ConfigureAwait(false);

            var type = json["kind"].ToString();

            if (type != "UserList")
            {
                throw new FormatException("Reddit responded with an object that is not a user listing.");
            }

            var data   = json["data"];
            var mods   = data["children"].ToArray();
            var result = new ModeratorUser[mods.Length];

            for (var i = 0; i < mods.Length; i++)
            {
                var mod = new ModeratorUser(mods[i]);
                result[i] = mod;
            }
            return(result);
        }
        protected static async internal Task <T> GetThingAsync <T>(IWebAgent agent, string url) where T : Things.Thing
        {
            var json = await agent.Get(url).ConfigureAwait(false);

            return(Things.Thing.Parse <T>(agent, json));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Returns a <see cref="RedditUser"/> by username
        /// </summary>
        /// <param name="agent">WebAgent to perform search</param>
        /// <param name="username">Username of user to return</param>
        /// <returns></returns>
        public static async Task <RedditUser> GetUserAsync(IWebAgent agent, string username)
        {
            var json = await agent.Get(string.Format(UserInfoUrl, username)).ConfigureAwait(false);

            return(new RedditUser(agent, json));
        }
        public static async Task <IEnumerable <TBUserNote> > GetUserNotesAsync(IWebAgent webAgent, string subName)
        {
            var reqResponse = await webAgent.Get(string.Format(ToolBoxUserNotesWiki, subName)).ConfigureAwait(false);

            var response = JObject.Parse(reqResponse["data"]["content_md"].Value <string>());
            int version  = response["ver"].Value <int>();

            if (version < 6)
            {
                throw new ToolBoxUserNotesException("Unsupported ToolBox version");
            }

            string[] mods = response["constants"]["users"].Values <string>().ToArray();

            string[] warnings = response["constants"]["warnings"].Values <string>().ToArray();

            try
            {
                var data = Convert.FromBase64String(response["blob"].Value <string>());

                string uncompressed;
                using (System.IO.MemoryStream compressedStream = new System.IO.MemoryStream(data))
                {
                    compressedStream.ReadByte();
                    compressedStream.ReadByte(); //skips first to bytes to fix zlib block size
                    using (DeflateStream blobStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
                    {
                        using (var decompressedReader = new System.IO.StreamReader(blobStream))
                        {
                            uncompressed = decompressedReader.ReadToEnd();
                        }
                    }
                }

                JObject users = JObject.Parse(uncompressed);

                List <TBUserNote> toReturn = new List <TBUserNote>();
                foreach (KeyValuePair <string, JToken> user in users)
                {
                    var x = user.Value;
                    foreach (JToken note in x["ns"].Children())
                    {
                        TBUserNote uNote = new TBUserNote()
                        {
                            AppliesToUsername = user.Key,
                            SubName           = subName,
                            SubmitterIndex    = note["m"].Value <int>(),
                            Submitter         = mods[note["m"].Value <int>()],
                            NoteTypeIndex     = note["w"].Value <int>(),
                            NoteType          = warnings[note["w"].Value <int>()],
                            Message           = note["n"].Value <string>(),
                            Timestamp         = UnixTimeStamp.UnixTimeStampToDateTime(note["t"].Value <long>()),
                            Url = UnsquashLink(subName, note["l"].ValueOrDefault <string>())
                        };
                        toReturn.Add(uNote);
                    }
                }
                return(toReturn);
            }
            catch (Exception e)
            {
                throw new ToolBoxUserNotesException("An error occured while processing Usernotes wiki. See inner exception for details", e);
            }
        }
        /// <summary>
        /// Get a <see cref="Thing"/> by full name.
        /// </summary>
        /// <param name="agent">IWebAgent to use to make request</param>
        /// <param name="fullname">fullname including kind + underscore. EG ("t1_######")</param>
        /// <returns></returns>
        public static async Task <Thing> GetThingByFullnameAsync(IWebAgent agent, string fullname)
        {
            var json = await agent.Get(string.Format(GetThingUrl, fullname)).ConfigureAwait(false);

            return(Thing.Parse(agent, json["data"]["children"][0]));
        }