public void Initialize(Settings settings, OfflineService offlineService, Reddit redditService, Dictionary<string, bool> initialFilter)
 {
     _settings = settings;
     _initialFilter = initialFilter;
     _offlineService = offlineService;
     _redditService = redditService;
 }
示例#2
0
 public Comment Init(Reddit reddit, JToken json, IWebAgent webAgent, Thing sender)
 {
     var data = CommonInit(reddit, json, webAgent, sender);
     ParseComments(reddit, json, webAgent, sender);
     JsonConvert.PopulateObject(data.ToString(), this, reddit.JsonSerializerSettings);
     return this;
 }
 public new AuthenticatedUser Init(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     CommonInit(reddit, json, webAgent);
     JsonConvert.PopulateObject(json["name"] == null ? json["data"].ToString() : json.ToString(), this,
         reddit.JsonSerializerSettings);
     return this;
 }
示例#4
0
 public async Task<Comment> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent, Thing sender)
 {
     var data = CommonInit(reddit, json, webAgent, sender);
     await ParseCommentsAsync(reddit, json, webAgent, sender);
     await Task.Factory.StartNew(() => JsonConvert.PopulateObject(data.ToString(), this, reddit.JsonSerializerSettings));
     return this;
 }
示例#5
0
 public async Task<RedditUser> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     CommonInit(reddit, json, webAgent);
     await JsonConvert.PopulateObjectAsync(json["name"] == null ? json["data"].ToString() : json.ToString(), this,
         reddit.JsonSerializerSettings);
     return this;
 }
 public async new Task<AuthenticatedUser> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     CommonInit(reddit, json, webAgent);
     await Task.Factory.StartNew(() => JsonConvert.PopulateObject(json["name"] == null ? json["data"].ToString() : json.ToString(), this,
         reddit.JsonSerializerSettings));
     return this;
 }
示例#7
0
 public SubredditImage(Reddit reddit, SubredditStyle subredditStyle,
     string cssLink, string name)
 {
     Reddit = reddit;
     SubredditStyle = subredditStyle;
     Name = name;
     CssLink = cssLink;
 }
 public SubredditImage(Reddit reddit, SubredditStyle subredditStyle,
     string cssLink, string name, IWebAgent webAgent)
 {
     Reddit = reddit;
     WebAgent = webAgent;
     SubredditStyle = subredditStyle;
     Name = name;
     CssLink = cssLink;
 }
示例#9
0
文件: Constants.cs 项目: gwely/Reddit
 public static Reddit GetReddit()
 {
     if (reddit == null)
     {
         reddit = new Reddit(UserAgent);
         reddit.Login("testjswrapper", "testjswrapper");
     }
     return reddit;
 }
 public SubredditImage(Reddit reddit, SubredditStyle subreddit,
     string cssLink, string name, string url, IWebAgent webAgent)
     : this(reddit, subreddit, cssLink, name, webAgent)
 {
     Url = url;
     // Handle legacy image urls
     // http://thumbs.reddit.com/FULLNAME_NUMBER.png
     int discarded;
     if (int.TryParse(url, out discarded))
         Url = string.Format("http://thumbs.reddit.com/{0}_{1}.png", subreddit.Subreddit.FullName, url);
 }
示例#11
0
 private async Task ParseCommentsAsync(Reddit reddit, JToken data, IWebAgent webAgent, Thing sender)
 {
     // Parse sub comments
     var replies = data["data"]["replies"];
     var subComments = new List<Comment>();
     if (replies != null && replies.Count() > 0)
     {
         foreach (var comment in replies["data"]["children"])
             subComments.Add(await new Comment().InitAsync(reddit, comment, webAgent, sender));
     }
     Comments = subComments.ToArray();            
 }
示例#12
0
 private async Task ParseCommentsAsync(Reddit reddit, JToken data, IWebAgent webAgent, Thing sender)
 {
     // Parse sub comments
     // TODO: Consider deserializing this properly
     var subComments = new List<Comment>();
     if (data["replies"] != null && data["replies"].Any())
     {
         foreach (var comment in data["replies"]["data"]["children"])
             subComments.Add(await new Comment().InitAsync(reddit, comment, webAgent, sender));
     }
     Comments = subComments.ToArray();            
 }
示例#13
0
        public SubredditImage(Reddit reddit, SubredditStyle subreddit,
                              string cssLink, string name, string url)
            : this(reddit, subreddit, cssLink, name)
        {
            Url = url;
            // Handle legacy image urls
            // http://thumbs.reddit.com/FULLNAME_NUMBER.png
            int discarded;

            if (int.TryParse(url, out discarded))
            {
                Url = string.Format("http://thumbs.reddit.com/{0}_{1}.png", subreddit.Subreddit.FullName, url);
            }
        }
示例#14
0
 private bool redditLogin()
 {
     try
     {
         reddit           = new Reddit(Properties.Settings.Default.RedditAccountName, Properties.Settings.Default.RedditAccountPassword);
         lRedditName.Text = "Logged in as " + reddit.User.Name;
         return(true);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error while trying to login. Is your user/pass correct?", "Error", MessageBoxButtons.OK);
         return(false);
     }
 }
示例#15
0
        /// <summary>
        /// Utility that will remove all db entries that are older than x days as repopulate the database with fresh data for any new entries across all subs that are configured
        /// </summary>
        private static void DatabaseManagement()
        {
            Reddit reddit = Get.Reddit();

            C.WriteLine("Database management mode entered.");
            DbSubredditPosts dbSubredditPosts = new DbSubredditPosts();

            C.WriteLine($"Deleteing all Posts older than {Config.reddit.Check_Back_X_Days} days...");
            C.WriteLine($"{dbSubredditPosts.DeleteAllPostsOlderThan(Config.reddit.Check_Back_X_Days)} Posts deleted!");
            List <Post> postsOnReddit = new List <Post>();

            reddit.LogIn(Config.reddit.username, Config.reddit.password);
            foreach (configurationSub sub in Config.subreddit_configurations)
            {
                C.WriteLine($"Collecting posts for /r/{sub.subreddit}!");
                Subreddit subby = reddit.GetSubreddit(sub.subreddit);
                postsOnReddit.AddRange(subby.New
                                       .Where(x => !x.IsSelfPost && x.Created >= DateTimeOffset.Now.AddDays(-Config.reddit.Check_Back_X_Days))
                                       .ToList());
            }

            List <ImgHash> postsInDb = dbSubredditPosts.GetAllIds();

            //Don't need to process posts that are already hashed in the database!
            postsOnReddit = postsOnReddit.Where(x => postsInDb.All(d => x.Id != d.PostId)).ToList();

            C.WriteLine($"Found {postsOnReddit.Count} Posts to be added to database.");

            string defaultTitle    = Title;
            int    progressCounter = 0;
            int    totalPosts      = postsOnReddit.Count;

            Title = $"{defaultTitle} [{progressCounter}/{totalPosts}]";
            foreach (var newPost in postsOnReddit)
            {
                progressCounter++;
                C.Write($"Working on {newPost.Id}...");
                Stopwatch timer = new Stopwatch();
                timer.Start();
                ImgHash thisPair = F.Hashing.FromPost(newPost);
                dbSubredditPosts.AddPostToDatabase(thisPair);
                timer.Stop();
                C.WriteLineNoTime($"Done in {timer.ElapsedMilliseconds}ms!");
                Title = progressCounter > totalPosts
                    ? $"{defaultTitle} [DONE!]"
                    : $"{defaultTitle} [{progressCounter}/{totalPosts}]";
            }
            C.WriteLine("Database updated!");
            Environment.Exit(0);
        }
示例#16
0
        public async Task DownloadImagesAsync(string sub)
        {
            Reddit reddit    = new Reddit();
            var    subreddit = reddit.GetSubreddit(sub);

            List <Task> tasks = new List <Task>((int)Amount);

            foreach (var post in subreddit.Hot.Take((int)Amount))
            {
                tasks.Add(DownloadImageAsync(post));
            }

            await Task.WhenAll(tasks);
        }
示例#17
0
        /// <summary>
        /// Gets the frontpage of the user
        /// </summary>
        /// <param name="reddit">Reddit you're logged into</param>
        /// <returns>the frontpage of reddit</returns>
        public static Subreddit GetFrontPage(Reddit reddit)
        {
            var frontPage = new Subreddit
            {
                DisplayName = "Front Page",
                Title       = "reddit: the front page of the internet",
                Url         = new Uri("/", UriKind.Relative),
                Name        = "/",
                Reddit      = reddit,
                WebAgent    = reddit.WebAgent
            };

            return(frontPage);
        }
示例#18
0
        /// <summary>
        /// http://www.reddit.com/r/all
        /// </summary>
        /// <param name="reddit">reddit, to help personalization</param>
        /// <returns>http://www.reddit.com/r/all</returns>
        public static Subreddit GetRSlashAll(Reddit reddit)
        {
            var rSlashAll = new Subreddit
            {
                DisplayName = "/r/all",
                Title       = "/r/all",
                Url         = new Uri("/r/all", UriKind.Relative),
                Name        = "all",
                Reddit      = reddit,
                WebAgent    = reddit.WebAgent
            };

            return(rSlashAll);
        }
示例#19
0
        public void showTechFinanceArticles()
        {
            Reddit reddit    = new Reddit();
            var    subreddit = reddit.GetSubreddit("/r/stockmarket");

            foreach (var post in subreddit.Hot.Take(50))
            {
                if (post.Title.ToLower().Contains("tech"))
                {
                    Console.WriteLine("Article Title: " + post.Title);
                    Console.WriteLine("Reddit post Link: " + post.Shortlink + "\n");
                }
            }
        }
示例#20
0
        private async Task ParseCommentsAsync(Reddit reddit, JToken data, IWebAgent webAgent, Thing sender)
        {
            // Parse sub comments
            // TODO: Consider deserializing this properly
            var subComments = new List <Comment>();

            if (data["replies"] != null && data["replies"].Any())
            {
                foreach (var comment in data["replies"]["data"]["children"])
                {
                    subComments.Add(await new Comment().InitAsync(reddit, comment, webAgent, sender));
                }
            }
            Comments = subComments.ToArray();
        }
        private bool verifyUser(string username)
        {
            var reddit = new Reddit();

            try
            {
                var user = reddit.GetUser(username);
            }
            catch (Exception ex)
            {
                return(false);
            }
            clearError();
            return(true);
        }
示例#22
0
        public async Task Auth(string filePath)
        {
            Console.WriteLine("Authorizing Reddit...");

            WebAgent webAgent = GetWebAgentCredentialsFromFile(filePath);

            redditService = new Reddit(webAgent, true);

            foreach (string subRedditName in subredditNamesAndCommentAmounts.Keys)
            {
                subreddits.Add(await redditService.GetSubredditAsync(subRedditName));
            }

            Console.WriteLine("Reddit authed successfully");
        }
示例#23
0
        public async Task <bool> CheckSubredditAsync(string name)
        {
            try
            {
                Reddit    reddit    = new Reddit();
                Subreddit subreddit = await reddit.GetSubredditAsync(name);

                var post = subreddit.New.Take(1);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
示例#24
0
文件: Get.cs 项目: Bitz/OwO_Bot
        public static Reddit Reddit()
        {
            BotWebAgent webAgent = new BotWebAgent(
                Config.reddit.username,
                Config.reddit.password,
                Config.reddit.client_id,
                Config.reddit.secret_id,
                Config.reddit.callback_url);
            var reddit = new Reddit(webAgent, true);

            //Login to reddit
            reddit.LogIn(Config.reddit.username, Config.reddit.password);

            return(reddit);
        }
示例#25
0
 static async ValueTask <ImageSource?> FetchImageAsync(Uri url)
 {
     try
     {
         var bitmap = new WriteableBitmap(
             BitmapFrame.Create(new MemoryStream(await Reddit.FetchImageAsync(url))));
         bitmap.Freeze();
         return(bitmap);
     }
     // Some images will cause decoding error by WPF's BitmapFrame, so ignoring it.
     catch (FileFormatException)
     {
         return(null);
     }
 }
示例#26
0
        private async Task ParseCommentsAsync(Reddit reddit, JToken data, IWebAgent webAgent, Thing sender)
        {
            // Parse sub comments
            var replies     = data["data"]["replies"];
            var subComments = new List <Comment>();

            if (replies != null && replies.Count() > 0)
            {
                foreach (var comment in replies["data"]["children"])
                {
                    subComments.Add(await new Comment().InitAsync(reddit, comment, webAgent, sender));
                }
            }
            Comments = subComments.ToArray();
        }
示例#27
0
        public async Task ScrapeReddit()
        {
            _subredditName = Program.ProjectConfiguration["subreddit"];
            _channelId     = UInt64.Parse(Program.ProjectConfiguration["channelId"]);
            _reddit        = new Reddit();
            var channel = Context.Client.GetChannel(_channelId) as Discord.WebSocket.SocketTextChannel;

            await Log("Got Channel");

            if (channel == null)
            {
                await Log("Could not find memeMachine");

                return;
            }
            var subreddit = _reddit.GetSubreddit("/r/youtubehaiku");

            await Log("Created subreddit var");

            switch (_subredditName)
            {
            case "":
                subreddit = _reddit.GetSubreddit("/r/youtubehaiku");
                break;

            default:
                subreddit = _reddit.GetSubreddit("/r/" + _subredditName);
                break;
            }
            await Log("Got subreddit");

            var urlList = new List <string>();

            foreach (var post in subreddit.Hot.GetListing(5))
            {
                if (notASelfPost(post.Url.ToString()))
                {
                    urlList.Add(post.Url.ToString());
                }
                else
                {
                    await Log(channel.Name);
                }
                await Log(post.Url.ToString());
            }
            string s = string.Join(" ", urlList.ToArray());
            await channel.SendMessageAsync("RETRIEVING MEMES FROM /r/" + _subredditName + "... DONE\n " + s);
        }
示例#28
0
        private static void Main(string[] args)
        {
            //Console.Clear();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Starting ChannelBot2");
            Console.CancelKeyPress += (sender, eArgs) => {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            Console.ForegroundColor = ConsoleColor.White;

            // Rainbows!!
            Console.ForegroundColor = ConsoleColor.Cyan;
            // Setup RedditToken for use in polling etc.
            var redditTokenManager = new RedditTokenManager();

            redditTokenManager.Start();
            Console.WriteLine("Initialized reddit token manager..");

            // Setup Reddit Client
            var redditAPI = new RedditAPI(accessToken: RedditTokenManager.CurrentToken);

            using (var reddit = new Reddit(redditAPI))
            {
                Program.reddit          = reddit;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Initialized reddit logic..");
                reddit.MonitorUnreadPMs();
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine("Monitoring reddit PMs every 30sec..");

                //Start polling
                var pollManager = new PollManager();
                pollManager.Start();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Initialized backup poller for sending out posts to subreddits");

                // Start pubsubhubbub, call dispose on it to remove listeners from event
                using (var hubbub = new PubSubHubBub())
                {
                    hubbub.Start();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("[SUPERDEBUG] Setup pubsubhubbub TCP listener..\r\n");
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    QuitEvent.WaitOne();
                }
            }
        }
示例#29
0
        /// <summary>
        /// Method used to establish a connection with Reddit and log in.
        /// </summary>
        /// <returns>A Reddit object</returns>
        static Reddit ConnectToReddit()
        {
            var webAgent = new BotWebAgent("USERNAME", "PASSWORD", "CLIENTID", "SECRET", "https://www.nowebsite.com/");
            //This will check if the access token is about to expire before each request and automatically request a new one for you
            //"false" means that it will NOT load the logged in user profile so reddit.User will be null
            var reddit = new Reddit(webAgent, true);

            //Make sure we are not exceeding Reddit API Limits.
            if (SubsToMonitorList.Count > 99)
            {
                throw new Exception("Bots can only monitor up to 100 subreddits at the same time.");
            }

            Log("Successfully connected to Reddit!");
            return(reddit);
        }
示例#30
0
        private static Task <HttpResponseMessage> CheckMail(Reddit r, ILogger log, HttpClient client)
        {
            Task <HttpResponseMessage> result = Task.FromResult <HttpResponseMessage>(null);

            if (r.User.HasMail)
            {
                log.LogInformation("has mail");

                if (!Debug)
                {
                    result = client.PostAsync($"/api/CheckBotMail/name/{r.User.Name}/", null);
                    log.LogInformation("posting:" + client.BaseAddress + $"/api/CheckBotMail/name/{r.User.Name}/ \n {result.Status}");
                }
            }
            return(result);
        }
示例#31
0
        public void Initialize(Reddit r)
        {
            if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["WikiPageName"]))
            {
                throw new Exception("Provide setting 'WikiPageName' in AppConfig to store bot settings.");
            }
            WikiPageName = System.Configuration.ConfigurationManager.AppSettings["WikiPageName"];
            LastModified = new DateTime(1900, 1, 1, 1, 1, 1);
            var state = new SettingsTimerState
            {
                RedditRef   = r,
                SettingsRef = this
            };

            state.TimerRef = new Timer(SettingsTimer, state, 0, FortyFiveMinutes);
        }
示例#32
0
        public RedditPoster(SettingsKeeper settingsKeeper)
        {
            _settingsKeeper = settingsKeeper;

            if (bool.Parse(_settingsKeeper.GetSetting("EnableReddit").Value))
            {
                var user         = settingsKeeper.GetSetting("RedditUser").Value;
                var password     = settingsKeeper.GetSetting("RedditPassword").Value;
                var clientId     = settingsKeeper.GetSetting("RedditClientId").Value;
                var clientSecret = settingsKeeper.GetSetting("RedditClientSecret").Value;
                var redirectUrl  = settingsKeeper.GetSetting("SiteUrl").Value;

                var botAgent = new BotWebAgent(user, password, clientId, clientSecret, redirectUrl);
                _reddit = new Reddit(botAgent);
            }
        }
示例#33
0
        public ActionResult Index()
        {
            var reddit = new Reddit();
            //var user = reddit.LogIn("EddieValiantsRabbit", "camaro");
            var all = reddit.GetSubreddit("/r/news");

            var listOfPosts = all.Hot.Take(25);

            ViewBag.Posts = new List <RedditSharp.Things.Post>();
            ViewBag.Posts = listOfPosts;

            ViewBag.Greeting = "Good " + SpareParts.DeterminePartOfDay();
            WebRequest weatherRequest = WebRequest.Create(@"http://api.openweathermap.org/data/2.5/weather?zip=94040,us&appid=8b3de9d1132f5c7199d2650d858cef68");

            weatherRequest.ContentType = "application/json; charset=utf-8";

            WeatherResponse jsonResponse = new WeatherResponse();

            using (HttpWebResponse weatherResponse = weatherRequest.GetResponse() as HttpWebResponse)
            {
                if (weatherResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception(String.Format(
                                            "Server error (HTTP {0}: {1}).",
                                            weatherResponse.StatusCode,
                                            weatherResponse.StatusDescription));
                }
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(WeatherResponse));
                object objResponse = jsonSerializer.ReadObject(weatherResponse.GetResponseStream());
                jsonResponse
                    = objResponse as WeatherResponse;
            }


            ViewBag.CurrentMonth       = SpareParts.GetCurrentMonth(DateTime.Now.Month);
            ViewBag.CurrentDayOfMonth  = DateTime.Now.Day;
            ViewBag.CurrentDayOfWeek   = DateTime.Now.DayOfWeek;
            ViewBag.CurrentHour        = DateTime.Now.Hour;
            ViewBag.CurrentMinute      = DateTime.Now.Minute;
            ViewBag.CurrentSecond      = DateTime.Now.Second;
            ViewBag.CurrentTemp        = (jsonResponse.main.Temp - 273.15) * 1.8 + 32;
            ViewBag.WeatherDescription = jsonResponse.weather[0].Description;



            return(View());
        }
示例#34
0
        // if we can't determine the type of thing by "kind", try by type
        public static Thing Parse <T>(Reddit reddit, JToken json, IWebAgent webAgent) where T : Thing
        {
            Thing result = Parse(reddit, json, webAgent);

            if (result == null)
            {
                if (typeof(T) == typeof(WikiPageRevision))
                {
                    return(new WikiPageRevision().Init(reddit, json, webAgent));
                }
                else if (typeof(T) == typeof(ModAction))
                {
                    return(new ModAction().Init(reddit, json, webAgent));
                }
            }
            return(result);
        }
示例#35
0
        // if we can't determine the type of thing by "kind", try by type
        public static async Task <Thing> ParseAsync <T>(Reddit reddit, JToken json, IWebAgent webAgent) where T : Thing
        {
            Thing result = await ParseAsync(reddit, json, webAgent);

            if (result == null)
            {
                if (typeof(T) == typeof(WikiPageRevision))
                {
                    return(await new WikiPageRevision().InitAsync(reddit, json, webAgent));
                }
                else if (typeof(T) == typeof(ModAction))
                {
                    return(await new ModAction().InitAsync(reddit, json, webAgent));
                }
            }
            return(result);
        }
示例#36
0
        public void Delete()
        {
            var request = Reddit.CreatePost(DeleteImageUrl);
            var stream  = request.GetRequestStream();

            Reddit.WritePostBody(stream, new
            {
                img_name = Name,
                uh       = Reddit.User.Modhash,
                r        = SubredditStyle.Subreddit.Name
            });
            stream.Close();
            var response = request.GetResponse();
            var data     = Reddit.GetResponseString(response.GetResponseStream());

            SubredditStyle.Images.Remove(this);
        }
示例#37
0
        public async Task About(CommandContext ctx, [Description("What sub?")] string sub)
        {
            await ctx.TriggerTypingAsync();

            var interactivity = ctx.Client.GetInteractivity();

            var about = Reddit.Subreddit(sub).About();

            var embed = GetBaseEmbed();

            foreach (var post in about.Posts.GetHot().Where(post => embed.Fields.Count < 11))
            {
                embed.AddField($"{post.Title}", $"{Formatter.MaskedUrl("Read more...", new Uri($"https://reddit.com{post.Permalink}"))}");
            }

            await ctx.RespondAsync(embed : embed);
        }
示例#38
0
        public async Task DownloadImageFromReddit()
        {
            Reddit reddit    = new Reddit();
            var    subreddit = reddit.GetSubreddit("me_irl");

            int i = 2;

restart:
            foreach (var post in subreddit.Hot.Skip(i).Take(1))
            {
                var lines = File.ReadAllLines(@"C:\dev\me_irl_bot_two\credit\done.txt");

                if (!lines.Contains(post.Shortlink))
                {
                    if (post.IsStickied || post.IsSelfPost || Convert.ToString(post.Url).Contains("reddituploads"))
                    {
                        continue;
                    }
                    string postURL = Convert.ToString(post.Url);

                    if (postURL.Contains(".png") || postURL.Contains(".jpg") || postURL.Contains(".jpeg"))
                    {
                        File.AppendAllText(@"C:\dev\me_irl_bot_two\credit\done.txt", post.Shortlink + Environment.NewLine);

                        DownloadImage(postURL, imageFolder);

                        File.WriteAllText(@"C:\dev\me_irl_bot_two\credit\author.txt", post.Author.FullName);
                        File.WriteAllText(@"C:\dev\me_irl_bot_two\credit\title.txt", post.Title);
                        File.WriteAllText(@"C:\dev\me_irl_bot_two\credit\link.txt", post.Shortlink);

                        await ConvertImage();
                    }
                    else
                    {
                        Process("Media was not an image.");
                        i++;
                        goto restart;
                    }
                }
                else
                {
                    i++;
                    goto restart;
                }
            }
        }
示例#39
0
        static void Main(string[] args)
        {
            String user         = System.Configuration.ConfigurationSettings.AppSettings["username"];
            String pass         = System.Configuration.ConfigurationSettings.AppSettings["password"];
            String sub          = System.Configuration.ConfigurationSettings.AppSettings["subreddit"];
            String secret       = System.Configuration.ConfigurationSettings.AppSettings["secret"];
            String client       = System.Configuration.ConfigurationSettings.AppSettings["client"];
            String redirect     = System.Configuration.ConfigurationSettings.AppSettings["redirect"];
            String storeDir     = System.Configuration.ConfigurationSettings.AppSettings["storageDir"];
            int    maxBlockSize = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["maxBlockSize"]);


            var webAgent  = new BotWebAgent(user, pass, client, secret, redirect);
            var reddit    = new Reddit(webAgent, true);
            var subreddit = reddit.GetSubreddit(sub);

            RedditFsStore    store    = new RedditFsStore(subreddit, maxBlockSize);
            RedditFsRetrieve retrieve = new RedditFsRetrieve(reddit, subreddit, storeDir);
            Shell            shell    = new Shell(reddit, subreddit);

            if (args.Length == 2)
            {
                if (args[0] == "store")
                {
                    Console.WriteLine("Attempting to store file at root: " + args[1]);
                    store.storeFile(args[1]);
                }
                else if (args[0] == "retrieve")
                {
                    Console.WriteLine("Attempting to retrive file into current dir: " + args[1]);
                    retrieve.retrieveFile(args[1]);
                }
            }
            else if (args.Length == 1)
            {
                if (args[0] == "shell")
                {
                    Console.WriteLine("h e l l o  r e d d i t");
                    shell.startShell();
                }
            }
            else
            {
                Console.WriteLine("Unsupported op.");
            }
        }
示例#40
0
        // Get the top 50 of the Reddit entries by all the time.
        public static IEnumerable <Post> GetTop()
        {
            try
            {
                var reddit    = new Reddit();
                var subreddit = reddit.FrontPage;

                IEnumerable <Post> topPosts = subreddit.GetTop(FromTime.All).Take(50);

                return(topPosts);
            }
            catch (Exception e)
            {
                Console.Write("Error: " + e);
                return(null);
            }
        }
示例#41
0
        private JToken CommonInit(Reddit reddit, JToken json, IWebAgent webAgent, Thing sender)
        {
            base.Init(reddit, webAgent, json);
            var data = json["data"];
            Reddit = reddit;
            WebAgent = webAgent;
            this.Parent = sender;

            // Handle Reddit's API being horrible
            if (data["context"] != null)
            {
                var context = data["context"].Value<string>();
                LinkId = context.Split('/')[4];
            }
         
            return data;
        }
        public async Task <IActionResult> GetRedditFlair(string flair)
        {
            if (!User.Identity.IsAuthenticated || !User.HasClaim(x => x.Issuer == "Reddit"))
            {
                return(Unauthorized());
            }

            var       username = HttpContext.Session.GetString(SessionClaims.RedditUsername);
            var       reddit   = new Reddit(_redditWebAgent);
            Subreddit subreddit;
            string    flairCss;

            // validate the parameter from spoofing
            if (HttpContext.Session.GetString(SessionClaims.LoginType) == SessionClaims.RedhatScheme)
            {
                if (_roleService.Config.RedditFlairs["Redhat"] != flair)
                {
                    return(Unauthorized("Nice try"));
                }

                subreddit = await reddit.GetSubredditAsync(_roleService.Config.RedhatSubreddit);

                flairCss = _roleService.Config.RedhatFlairCss;
            }
            else
            {
                string[] groups = HttpContext.Session.GetString(SessionClaims.Groups).Trim().Split();

                if (!_roleService.Config.RedditFlairs.Any(x => groups.Contains(x.Key) && x.Value == flair))
                {
                    return(Unauthorized("Nice try"));
                }

                subreddit = await reddit.GetSubredditAsync(_roleService.Config.Subreddit);

                flairCss = _roleService.Config.FedoraFlairCss;
            }

            if (subreddit != null)
            {
                await subreddit.SetUserFlairAsync(username, flairCss, flair);
            }

            // Check for error TODO (look into the lib source for possible error states)
            return(View("Success"));
        }
示例#43
0
        static async void DownloadPageAsync()
        {
            string page = "http://www.reddit.com/.json";

            using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(page))
                    using (HttpContent content = response.Content)
                    {
                        string result = await content.ReadAsStringAsync();

                        Reddit json = JsonConvert.DeserializeObject <Reddit>(result);
                        Console.WriteLine(json.kind);
                        Console.WriteLine(json.data);
                        Console.WriteLine(json.id);
                        Console.WriteLine(json.name);
                    }
        }
        protected void FinishInit()
        {
            Current = this;
            _listingFilter = new NSFWListingFilter();
            if (IsInDesignMode)
            {
                _initializationBlob = new InitializationBlob { Settings = new Dictionary<string, string>(), NSFWFilter = new Dictionary<string, bool>() };
            }
            else
            {
                OfflineService = new OfflineService();
                _initializationBlob = OfflineService.LoadInitializationBlob("");
            }
            Settings = new Model.Settings(_initializationBlob.Settings);
            SettingsHub = new SettingsViewModel(Settings);

            RedditUserState = _initializationBlob.DefaultUser ?? new UserState();

            SnooStreamViewModel.ActivityManager.OAuth = SnooStreamViewModel.RedditUserState != null && SnooStreamViewModel.RedditUserState.OAuth != null ?
                    JsonConvert.SerializeObject(SnooStreamViewModel.RedditUserState) : "";

            SnooStreamViewModel.ActivityManager.CanStore = SnooStreamViewModel.RedditUserState != null && SnooStreamViewModel.RedditUserState.IsDefault;

            NotificationService = new Common.NotificationService();
            CaptchaProvider = new CaptchaService();
            RedditService = new Reddit(_listingFilter, RedditUserState, OfflineService, CaptchaProvider, "3m9rQtBinOg_rA", null, "http://www.google.com");
            Login = new LoginViewModel();

            _listingFilter.Initialize(Settings, OfflineService, RedditService, _initializationBlob.NSFWFilter);
            CommandDispatcher = new CommandDispatcher();
            SubredditRiver = new SubredditRiverViewModel(_initializationBlob.Subreddits);
            SelfStream = new SelfStreamViewModel();
            ModStream = new ModStreamViewModel();
            NavMenu = new NavMenu(Enumerable.Empty<LinkRiverViewModel>(), this);
            MessengerInstance.Register<UserLoggedInMessage>(this, OnUserLoggedIn);

            if (RedditUserState.Username != null)
            {
                SelfUser = new AboutUserViewModel(RedditUserState.Username);
            }
        }
示例#45
0
 public async Task<ModAction> InitAsync(Reddit reddit, JToken post, IWebAgent webAgent)
 {
     CommonInit(reddit, post, webAgent);
     await Task.Factory.StartNew(() => JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings));
     return this;
 }
示例#46
0
 private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     base.Init(json);
     Author = new RedditUser().Init(reddit, json["author"], webAgent);
 }
示例#47
0
 private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     base.Init(json);
     Reddit = reddit;
     WebAgent = webAgent;
     var data = json["data"];
     if (data["replies"] != null && data["replies"].Any())
     {
         if (data["replies"]["data"] != null)
         {
             if (data["replies"]["data"]["children"] != null)
             {
                 var replies = new List<PrivateMessage>();
                 foreach (var reply in data["replies"]["data"]["children"])
                     replies.Add(new PrivateMessage().Init(reddit, reply, webAgent));
                 Replies = replies.ToArray();
             }
         }
     }
 }
示例#48
0
 private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     base.Init(reddit, json, webAgent);
 }
示例#49
0
 public MainPage()
 {
     InitializeComponent();
     var reddit = new Reddit();
 }
示例#50
0
 public async Task<Post> InitAsync(Reddit reddit, JToken post, IWebAgent webAgent)
 {
     CommonInit(reddit, post, webAgent);
     await JsonConvert.PopulateObjectAsync(post["data"].ToString(), this, reddit.JsonSerializerSettings);
     return this;
 }
示例#51
0
 public Post Init(Reddit reddit, JToken post, IWebAgent webAgent)
 {
     CommonInit(reddit, post, webAgent);
     JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings);
     return this;
 }
示例#52
0
 public RedditTests()
 {
     _reddit = Constants.GetReddit();
 }
示例#53
0
 private void CommonInit(Reddit reddit, JToken post, IWebAgent webAgent)
 {
     base.Init(reddit, webAgent, post);
     Reddit = reddit;
     WebAgent = webAgent;
 }
示例#54
0
 protected CreatedThing Init(Reddit reddit, JToken json)
 {
     CommonInit(reddit, json);
     JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings);
     return this;
 }
示例#55
0
 public ModAction Init(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     CommonInit(reddit, json, webAgent);
     JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings);
     return this;
 }
 protected async Task<VotableThing> InitAsync(Reddit reddit, IWebAgent webAgent, JToken json)
 {
     CommonInit(reddit, webAgent, json);
     await Task.Factory.StartNew(() => JsonConvert.PopulateObject(json["data"].ToString(), this, Reddit.JsonSerializerSettings));
     return this;
 }
 protected VotableThing Init(Reddit reddit, IWebAgent webAgent, JToken json)
 {
     CommonInit(reddit, webAgent, json);
     JsonConvert.PopulateObject(json["data"].ToString(), this, Reddit.JsonSerializerSettings);
     return this;
 }
示例#58
0
 private void CommonInit(Reddit reddit, JToken json)
 {
     base.Init(json);
     Reddit = reddit;
 }
示例#59
0
 private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     base.Init(json);
     Reddit = reddit;
     WebAgent = webAgent;
 }
示例#60
0
 public async Task<PrivateMessage> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     CommonInit(reddit, json, webAgent);
     await Task.Factory.StartNew(() => JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings));
     return this;
 }