// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            // use the session
            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            // initialize the feeds list
            RssFeeds.Init();
        }
 /// <CheckFeedExists>
 /// Check the Feed is Exists.
 /// </summary>
 /// <param name="FeedsUrl">Url of feed.(String)</param>
 /// <param name="Message">Message of feedReader.(String)</param>
 /// <param name="PublishedDate">Date and time of publishing.(String)</param>
 /// <returns>True or False.(bool)</returns>
 public bool CheckFeedExists(string FeedsUrl, string Message, string PublishedDate)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 NHibernate.IQuery query = session.CreateQuery("from RssReader where FeedsUrl =:feedurl and Description =:desc and PublishedDate=:published");
                 query.SetParameter("feedurl", FeedsUrl);
                 query.SetParameter("desc", Message);
                 query.SetParameter("published", PublishedDate);
                 RssFeeds rss = query.UniqueResult <RssFeeds>();
                 if (rss == null)
                 {
                     return(false);
                 }
                 else
                 {
                     return(true);
                 }
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return(true);
             }
         } //End Transaction
     }     //End Session
 }
Beispiel #3
0
        public async Task <WrapperSimpleTypesDTO> InteractuarRssFeed(List <RssFeeds> rssFeedParaInteractuar)
        {
            using (SportsGoEntities context = new SportsGoEntities(false))
            {
                NoticiasRepository noticiaRepo = new NoticiasRepository(context);

                foreach (var feed in rssFeedParaInteractuar)
                {
                    if (feed.Consecutivo <= 0)
                    {
                        noticiaRepo.CrearRssFeed(feed);
                    }
                    else
                    {
                        RssFeeds feedExistente = await noticiaRepo.ModificarRssFeed(feed);
                    }
                }

                WrapperSimpleTypesDTO wrapperInteractuarRssFeed = new WrapperSimpleTypesDTO();

                wrapperInteractuarRssFeed.NumeroRegistrosAfectados = await context.SaveChangesAsync();

                if (wrapperInteractuarRssFeed.NumeroRegistrosAfectados > 0)
                {
                    wrapperInteractuarRssFeed.Exitoso = true;
                }

                return(wrapperInteractuarRssFeed);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Gets data path so tests look for data files in correct place
        /// </summary>
        /// <returns>string including post pend slash</returns>
        public static string GetDataPath()
        {
            string finalPath = string.Empty;

            RssFeeds feeds = new RssFeeds();

            string binPath = AppDomain.CurrentDomain.BaseDirectory;
            string[] splitString = null;
            string basePath = string.Empty;

            // everything before the bin directory
            if (binPath.Contains("bin"))
            {
                Regex matchPattern = new Regex("bin");
                splitString = matchPattern.Split(binPath);
                basePath = splitString[0];
                finalPath = Path.Combine(basePath, @"App_Data\");
            }
            else if (binPath.Contains("TestResults"))
            {
                Regex matchPattern = new Regex("TestResults");
                splitString = matchPattern.Split(binPath);
                basePath = splitString[0];
                finalPath = Path.Combine(basePath, "XmlTestProject", @"App_Data\");
            }
            else
            {
                // don't know where the path is at this point
            }

            return finalPath;
        }
Beispiel #5
0
        public async Task <Dictionary <string, string> > GetFeedXmlContent(RssFeeds listOfRssFeeds)
        {
            var responseXmlcontent = new Dictionary <string, string>();

            using (var client = new HttpClient())
            {
                // we create a response
                // we can just asynchronously iterate over the list and get the feed
                // content for each one
                foreach (var feed in listOfRssFeeds.ListOfRssFeeds)
                {
                    using (var response = await client.GetAsync(feed.FeedUrl))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            // feedcontent is store in an collection for later process
                            responseXmlcontent.Add(feed.FeedName, await response.Content.ReadAsStringAsync());
                        }
                        else
                        {
                            // in case of error we return a friendly message
                            Console.WriteLine($"Cannot connect to the Feed for {feed.FeedName}. Please try again later");
                        }
                    }
                }

                return(responseXmlcontent);
            }
        }
Beispiel #6
0
        public async Task Info()
        {
            var server = RssFeeds.FirstOrDefault(x => x.GuildId == Context.Guild.Id);

            if (server == null)
            {
                await Initialise();

                return;
            }

            await ReplyAsync("", false, new EmbedBuilder
            {
                Description = $"**RSS URL**\n" +
                              $"{server.RssUrl}\n" +
                              $"**RSS Channel**\n" +
                              $"{(await Context.Guild.GetChannelAsync(server.ChannelId))?.Name}\n" +
                              $"**RSS Formatting**\n" +
                              $"```\n" +
                              $"{server.Formatting}\n" +
                              $"```\n" +
                              $"**RSS Feed Status (running)**\n" +
                              $"{server.Running}",
                Color = Color.Blue
            });
        }
        /// <summary>
        /// Adds a new feed to the list of feeds.
        /// The feed is downloaded and the articles are added to the list of articles as well.
        /// </summary>
        /// <param name="url">The url of the feed to be added</param>
        public async void AddFeed(string url)
        {
            var favorites = FavoritesManager.Instance.GetFavorites();

            var result = await RssManager.Instance.GetFeeds(url);

            var feed = result.First();

            RssFeeds.Add(feed);

            List <EasyNewsFeedItem> easyFeedItems = new List <EasyNewsFeedItem>();

            foreach (var feedItem in feed.Items)
            {
                var isFav        = favorites.Contains(feedItem);
                var easyFeedItem = new EasyNewsFeedItem(feedItem, isFav);
                // Parse Image URL
                easyFeedItem.ImageLink = RssManager.Instance.GetImageUrl(feedItem);
                // Strip HTML tags
                easyFeedItem.Description = RssManager.Instance.StripHtml(feedItem.Description);
                // Add the item at the correct position;
                easyFeedItems.Add(easyFeedItem);
            }
            AddFeedItems(easyFeedItems);
        }
Beispiel #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="feedSubscription"></param>
        public void ProcessRssSubscription(EventRssSubscription feedSubscription)
        {
            try
            {
                _log.DebugFormat("{0}: Processing feed Id {1} ({2}).", _name, feedSubscription.Id, feedSubscription.RssUrl);
                RssFeeds.ProcessFeed(feedSubscription, _db);
                feedSubscription.ErrorCount = 0;
                _db.ORManager.SaveOrUpdate(feedSubscription);
            }
            catch (Exception ex)
            {
                if (feedSubscription != null)
                {
                    _db.ORManager.Refresh(feedSubscription);

                    feedSubscription.ErrorCount += 1;
                    _db.ORManager.SaveOrUpdate(feedSubscription);

                    _log.Error(string.Format("{0}: Error processing feed {1} ({2})", _name, feedSubscription.Id, feedSubscription.RssUrl), ex);

                    if (feedSubscription.ErrorCount >= ERROR_THRESHOLD)
                    {
                        TextMessagesInterface.SendMessage(_db, feedSubscription.Url.UserId, string.Format("RankTrend has tried unsuccessfully {1} or more times to read the RSS feed that you specified in your RSS Subscription \"{0}\".  This could be for a number of reasons such as the URL you specified does not point to an RSS feed or the RSS feed is not available.  Please verify the URL that you specified for this feed.  If you feel this is in error, please let us know.", feedSubscription.Name, ERROR_THRESHOLD));
                    }
                }
                else
                {
                    _log.Error(ex);
                }
            }
        }
Beispiel #9
0
        public async Task Dupe()
        {
            var server = RssFeeds.FirstOrDefault(x => x.GuildId == Context.Guild.Id);

            if (server == null)
            {
                await Initialise();

                return;
            }

            server.RemoveDuplicates = !server.RemoveDuplicates;

            if (RssFeeds != null)
            {
                var feeds = JsonConvert.SerializeObject(RssFeeds, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "setup/RSS.json"), feeds);
            }

            await ReplyAsync("", false, new EmbedBuilder
            {
                Description = $"Duplicates are removed: {server.RemoveDuplicates}",
                Color       = Color.Blue
            });
        }
Beispiel #10
0
        public async Task Bdel(string input)
        {
            var server = RssFeeds.FirstOrDefault(x => x.GuildId == Context.Guild.Id);

            if (server == null)
            {
                await Initialise();

                return;
            }

            server.BlacklistedWords.Remove(input);

            if (RssFeeds != null)
            {
                var feeds = JsonConvert.SerializeObject(RssFeeds, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "setup/RSS.json"), feeds);
            }

            await ReplyAsync("", false, new EmbedBuilder
            {
                Description = $"**Blacklisted Words/Phrases:** \n" +
                              $"{string.Join(", ", server.BlacklistedWords)}",
                Color = Color.Blue
            });
        }
Beispiel #11
0
        public async Task Rss([Remainder] string url)
        {
            var server = RssFeeds.FirstOrDefault(x => x.GuildId == Context.Guild.Id);

            if (server == null)
            {
                await Initialise();

                return;
            }

            server.RssUrl = url;

            await ReplyAsync("", false, new EmbedBuilder
            {
                Description = $"RSS URL Will now be set to {url}",
                Color       = Color.Blue
            });

            if (RssFeeds != null)
            {
                var feeds = JsonConvert.SerializeObject(RssFeeds, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "setup/RSS.json"), feeds);
            }
        }
Beispiel #12
0
        /// <summary>
        /// The method creates SyndicationFeed for topic announcements.
        /// </summary>
        /// <param name="feedType">
        /// The FeedType.
        /// </param>
        /// <param name="atomFeedByVar">
        /// The Atom feed checker.
        /// </param>
        /// <returns>
        /// The <see cref="YafSyndicationFeed"/>.
        /// </returns>
        private YafSyndicationFeed GetLatestAnnouncementsFeed(RssFeeds feedType, bool atomFeedByVar)
        {
            var syndicationItems = new List <SyndicationItem>();

            var dt = this.GetRepository <Topic>().AnnouncementsAsDataTable(
                this.PageContext.PageBoardID,
                10,
                this.PageContext.PageUserID);
            var urlAlphaNum = FormatUrlForFeed(BaseUrlBuilder.BaseUrl);

            var feed = new YafSyndicationFeed(
                this.GetText("POSTMESSAGE", "ANNOUNCEMENT"),
                feedType,
                atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt(),
                urlAlphaNum);

            dt.Rows.Cast <DataRow>().Where(row => !row["TopicMovedID"].IsNullOrEmptyDBField()).ForEach(
                row =>
            {
                var lastPosted = Convert.ToDateTime(row["LastPosted"]) + this.Get <IDateTime>().TimeOffset;

                if (syndicationItems.Count <= 0)
                {
                    feed.Authors.Add(
                        SyndicationItemExtensions.NewSyndicationPerson(
                            string.Empty,
                            row["UserID"].ToType <int>(),
                            null,
                            null));
                    feed.LastUpdatedTime = DateTime.UtcNow + this.Get <IDateTime>().TimeOffset;
                }

                feed.Contributors.Add(
                    SyndicationItemExtensions.NewSyndicationPerson(
                        string.Empty,
                        row["LastUserID"].ToType <int>(),
                        null,
                        null));

                syndicationItems.AddSyndicationItem(
                    row["Topic"].ToString(),
                    row["Message"].ToString(),
                    null,
                    BuildLink.GetLink(
                        ForumPages.Posts,
                        true,
                        "t={0}&name={1}",
                        this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("t"),
                        row["Topic"].ToString()),
                    $"urn:{urlAlphaNum}:ft{feedType}:st{(atomFeedByVar ? SyndicationFormats.Atom.ToInt() : SyndicationFormats.Rss.ToInt())}:tid{this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("t")}:lmid{row["LastMessageID"]}:{this.PageContext.PageBoardID}"
                    .Unidecode(),
                    lastPosted,
                    feed);
            });

            feed.Items = syndicationItems;

            return(feed);
        }
Beispiel #13
0
        public async Task <RssFeeds> ModificarRssFeed(RssFeeds rssFeedParaModificar)
        {
            RssFeeds rssFeedExistente = await _context.RssFeeds.Where(x => x.Consecutivo == rssFeedParaModificar.Consecutivo).FirstOrDefaultAsync();

            rssFeedExistente.UrlFeed = rssFeedParaModificar.UrlFeed;

            return(rssFeedExistente);
        }
        public void RemoveRssFeed(RssFeed rssFeed)
        {
            var rssFeeds = isolatedStorageSettings[RssFeedsKey] as Collection <RssFeed>;

            rssFeeds.Remove(rssFeed);
            RssFeeds.Remove(rssFeed);
            isolatedStorageSettings.Save();
            NotifyPropertyChanged("RssFeeds");
        }
Beispiel #15
0
        public async Task <RssFeeds> BuscarRssFeed(RssFeeds rssParaBuscar)
        {
            using (SportsGoEntities context = new SportsGoEntities(false))
            {
                NoticiasRepository noticiaRepo = new NoticiasRepository(context);
                RssFeeds           rssBuscado  = await noticiaRepo.BuscarRssFeed(rssParaBuscar);

                return(rssBuscado);
            }
        }
        /// <summary>
        /// The method creates YAF SyndicationFeed for forums in a category.
        /// </summary>
        /// <param name="feedType">
        /// The FeedType.
        /// </param>
        /// <param name="categoryId">
        /// The category id.
        /// </param>
        /// <returns>
        /// The <see cref="FeedItem"/>.
        /// </returns>
        public FeedItem GetForumFeed([NotNull] RssFeeds feedType, [CanBeNull] int?categoryId)
        {
            var syndicationItems = new List <SyndicationItem>();

            var forums = this.GetRepository <Forum>().ListRead(
                BoardContext.Current.PageBoardID,
                BoardContext.Current.PageUserID,
                categoryId,
                null,
                false);

            var urlAlphaNum = FormatUrlForFeed(BaseUrlBuilder.BaseUrl);

            var feed = new FeedItem(this.Get <ILocalization>().GetText("DEFAULT", "FORUM"), feedType, urlAlphaNum);

            forums.Where(x => x.LastPosted.HasValue && !x.TopicMovedID.HasValue).ForEach(
                forum =>
            {
                var lastPosted = forum.LastPosted.Value + this.Get <IDateTimeService>().TimeOffset;

                if (syndicationItems.Count <= 0)
                {
                    feed.Authors.Add(
                        SyndicationItemExtensions.NewSyndicationPerson(
                            string.Empty,
                            forum.LastUserID.Value,
                            null,
                            null));

                    feed.LastUpdatedTime = System.DateTime.UtcNow + this.Get <IDateTimeService>().TimeOffset;
                }

                feed.Contributors.Add(
                    SyndicationItemExtensions.NewSyndicationPerson(
                        string.Empty,
                        forum.LastUserID.Value,
                        null,
                        null));

                syndicationItems.AddSyndicationItem(
                    forum.Forum,
                    forum.Description,
                    null,
                    this.Get <LinkBuilder>().GetLink(ForumPages.Topics, true, "f={0}&name={1}", forum.ForumID, forum.Forum),
                    $@"urn:{urlAlphaNum}:ft{feedType}:
                              fid{forum.ForumID}:lmid{forum.LastMessageID}:{BoardContext.Current.PageBoardID}"
                    .Unidecode(),
                    lastPosted,
                    feed);
            });

            feed.Items = syndicationItems;

            return(feed);
        }
Beispiel #17
0
        static async Task Main(string[] args)
        {
            // we gave two RSS Feed for the sake of the demo

            // we generate two object with the feed property
            var theBibleInAYear = new RSSFeed
            {
                FeedId   = 1,
                FeedName = "The Bible in a Year",
                FeedUrl  = new Uri("https://feeds.fireside.fm/bibleinayear/rss"),
            };


            //feed two
            var theApologyLine = new RSSFeed
            {
                FeedId   = 2,
                FeedName = "The Apology Line",
                FeedUrl  = new Uri("https://rss.art19.com/apology-line"),
            };

            // we store all the feed in the listOfRssFeed
            var listOfRssFeeds = new RssFeeds()
            {
                ListOfRssFeeds = new List <RSSFeed>
                {
                    theApologyLine,
                    theBibleInAYear
                }
            };

            // we instanciate the rssService
            ILastPublishedDateServices lastPublishedDateServices = new LastPublishedDateServices();


            //we instanciate the rss call service to get the xml from api call
            IRssCallServices rssCallServices = new RssCallServices();

            // we call the service
            var result = await lastPublishedDateServices.NumberOfInactivityDays(listOfRssFeeds, rssCallServices);

            foreach (var item in result)
            {
                var msg = $"Feed {item.FeedName}, a total of {(int)item.InactivityPeriod} days has past since the last publication";

                if ((int)item.InactivityPeriod == 0)
                {
                    msg = $"Feed {item.FeedName}, a total of 0 day has past since the last publication. The RSS is current";
                }


                Console.WriteLine(msg);
            }
        }
Beispiel #18
0
 /// <AddRssFeed>
 /// Add new Rss feeds
 /// </summary>
 /// <param name="rss">Set Values in a RssFeeds Class Property and Pass the Object of RssFeeds Class.(Domein.RssFeeds)</param>
 public void AddRssFeed(RssFeeds rss)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             //Proceed action, to save new Rss feed.
             session.Save(rss);
             transaction.Commit();
         } //End Transaction
     }     //End Session
 }
 public void UpdateRssFeeds()
 {
     if (isolatedStorageSettings.Contains(RssFeedKey))
     {
         var rssFeed = isolatedStorageSettings[RssFeedKey] as RssFeed;
         if (!RssFeeds.Contains(rssFeed))
         {
             RssFeeds.Add(rssFeed);
             var rssFeeds = isolatedStorageSettings[RssFeedsKey] as Collection <RssFeed>;
             rssFeeds.Add(rssFeed);
         }
         isolatedStorageSettings.Remove(RssFeedKey);
     }
     RssFeeds = new ObservableCollection <RssFeed>(_rssFeeds);
 }
Beispiel #20
0
        public async Task <IHttpActionResult> BuscarRssFeed(RssFeeds rssFeedParaBuscar)
        {
            if (rssFeedParaBuscar == null || rssFeedParaBuscar.Consecutivo <= 0)
            {
                return(BadRequest("rssFeedParaBuscar vacio y/o invalido!."));
            }

            try
            {
                RssFeeds rssFeedBuscado = await _noticiasBusiness.BuscarRssFeed(rssFeedParaBuscar);

                return(Ok(rssFeedBuscado));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Beispiel #21
0
        public async Task <IHttpActionResult> EliminarRssFeed(RssFeeds rssFeedParaEliminar)
        {
            if (rssFeedParaEliminar == null || rssFeedParaEliminar.Consecutivo <= 0)
            {
                return(BadRequest("rssFeedParaEliminar vacio y/o invalido!."));
            }

            try
            {
                WrapperSimpleTypesDTO wrapperEliminarRssFeed = await _noticiasBusiness.EliminarRssFeed(rssFeedParaEliminar);

                return(Ok(wrapperEliminarRssFeed));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Beispiel #22
0
        public async Task <WrapperSimpleTypesDTO> EliminarRssFeed(RssFeeds rssFeedParaEliminar)
        {
            using (SportsGoEntities context = new SportsGoEntities(false))
            {
                NoticiasRepository noticiaRepo = new NoticiasRepository(context);

                noticiaRepo.EliminarRssFeed(rssFeedParaEliminar);

                WrapperSimpleTypesDTO wrapperEliminarRssFeed = new WrapperSimpleTypesDTO();

                wrapperEliminarRssFeed.NumeroRegistrosAfectados = await context.SaveChangesAsync();

                if (wrapperEliminarRssFeed.NumeroRegistrosAfectados > 0)
                {
                    wrapperEliminarRssFeed.Exitoso = true;
                }

                return(wrapperEliminarRssFeed);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Removes a feed from the list of feeds.
        /// After that the articles from that feed are also removed from the list of articles.
        /// </summary>
        /// <param name="url">URL of the feed to be removed</param>
        public void RemoveFeed(string url)
        {
            Feed feedToBeRemoved = null;

            for (var i = 0; i < RssFeeds.Count; i++)
            {
                if (RssFeeds[i].Link == url)
                {
                    feedToBeRemoved = RssFeeds[i];
                    RssFeeds.Remove(feedToBeRemoved);
                }
            }

            if (feedToBeRemoved == null)
            {
                return;
            }

            RemoveFeedItems(feedToBeRemoved);
        }
Beispiel #24
0
        public async void ListPublishedDateServiceShouldContainFeedNameAndInactivtyDate()
        {
            //Arrage
            // fake api response xml
            string FakeXmlReponse = "<Channel><pubDate>Tue, 16 Feb 2021 08:05:00 -0000</pubDate></Channel>";

            // dictionnary reponse from the rsscalls service
            var dictionaryResponseApi = new Dictionary <string, string>();

            dictionaryResponseApi.Add("Test Feed", FakeXmlReponse);
            var listOfFakeFeeds = new RssFeeds
            {
                ListOfRssFeeds = new List <RSSFeed>
                {
                    new RssFeed.Models.RSSFeed
                    {
                        FeedId   = 1,
                        FeedName = "Test Feed",
                        FeedUrl  = new Uri("https://fakelink"),
                    }
                }
            };

            //Act
            // real call the rsscall service to process the fake xml
            var apiReponse = rssCallServices.GetFeedXmlContent(listOfFakeFeeds)
                             .Returns(dictionaryResponseApi);
            // we get the result as a collection and extract only one
            var result = await lastPublishedDateServices.NumberOfInactivityDays(listOfFakeFeeds, rssCallServices);

            var oneFeedRssResult = result.FirstOrDefault();


            // Assert
            // we check in the reponse is greater than 1 (there are more than one rssfeed name and inactivty day)
            result.Count.Should().BeGreaterThan(0);
            // we check if the name is the same
            oneFeedRssResult.FeedName.Should().Contain("Test Feed");
            // we check if the inactivity period is more than 1 since the fake date in the xml is 16 it should be greater
            oneFeedRssResult.InactivityPeriod.Should().BeGreaterThan(0);
        }
Beispiel #25
0
        public async Task Initialise()
        {
            if (RssFeeds.Any(x => x.GuildId == Context.Guild.Id))
            {
                await ReplyAsync("", false, new EmbedBuilder
                {
                    Description = $"Server Already Initialised",
                    Color       = Color.Red
                });

                return;
            }
            var server = new RssObject
            {
                GuildId    = Context.Guild.Id,
                ChannelId  = Context.Channel.Id,
                Embed      = true,
                Formatting = "New Post in $postroot\n" +
                             "[$posttitle]($postlink)\n\n" +
                             "$postcontent"
            };

            if (RssFeeds.Any(x => x.GuildId == Context.Guild.Id))
            {
                RssFeeds.Remove(RssFeeds.First(x => x.GuildId == Context.Guild.Id));
            }
            RssFeeds.Add(server);

            await ReplyAsync("", false, new EmbedBuilder
            {
                Description = $"Server Initialised",
                Color       = Color.Blue
            });

            if (RssFeeds != null)
            {
                var feeds = JsonConvert.SerializeObject(RssFeeds, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "setup/RSS.json"), feeds);
            }
        }
Beispiel #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="YafSyndicationFeed" /> class.
        /// </summary>
        /// <param name="subTitle">The sub title.</param>
        /// <param name="feedType">The feed source.</param>
        /// <param name="sf">The feed type Atom/RSS.</param>
        /// <param name="urlAlphaNum">The alphanumerically encoded base site Url.</param>
        public YafSyndicationFeed([NotNull] string subTitle, RssFeeds feedType, int sf, [NotNull] string urlAlphaNum)
        {
            this.Copyright =
                new TextSyndicationContent($"Copyright {DateTime.Now.Year} {BoardContext.Current.BoardSettings.Name}");
            this.Description = new TextSyndicationContent(
                $"{BoardContext.Current.BoardSettings.Name} - {(sf == SyndicationFormats.Atom.ToInt() ? BoardContext.Current.Get<ILocalization>().GetText("ATOMFEED") : BoardContext.Current.Get<ILocalization>().GetText("RSSFEED"))}");
            this.Title = new TextSyndicationContent(
                $"{(sf == SyndicationFormats.Atom.ToInt() ? BoardContext.Current.Get<ILocalization>().GetText("ATOMFEED") : BoardContext.Current.Get<ILocalization>().GetText("RSSFEED"))} - {BoardContext.Current.BoardSettings.Name} - {subTitle}");

            // Alternate link
            this.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(BaseUrlBuilder.BaseUrl)));

            // Self Link
            var slink = new Uri(
                BuildLink.GetLink(ForumPages.RssTopic, true, $"pg={feedType.ToInt()}&ft={sf}"));

            this.Links.Add(SyndicationLink.CreateSelfLink(slink));

            this.Generator       = "YetAnotherForum.NET";
            this.LastUpdatedTime = DateTime.UtcNow;
            this.Language        = BoardContext.Current.Get <ILocalization>().LanguageCode;
            this.ImageUrl        = new Uri(
                $"{BaseUrlBuilder.BaseUrl}{BoardInfo.ForumClientFileRoot}{BoardFolders.Current.Logos}/{BoardContext.Current.BoardSettings.ForumLogo}");

            this.Id =
                $"urn:{urlAlphaNum}:{(sf == SyndicationFormats.Atom.ToInt() ? BoardContext.Current.Get<ILocalization>().GetText("ATOMFEED") : BoardContext.Current.Get<ILocalization>().GetText("RSSFEED"))}:{BoardContext.Current.BoardSettings.Name}:{subTitle}:{BoardContext.Current.PageBoardID}"
                .Unidecode();

            this.Id = this.Id.Replace(" ", string.Empty);

            // this.Id = "urn:uuid:{0}".FormatWith(Guid.NewGuid().ToString("D"));
            this.BaseUri = slink;
            this.Authors.Add(
                new SyndicationPerson(
                    BoardContext.Current.BoardSettings.ForumEmail,
                    "Forum Admin",
                    BaseUrlBuilder.BaseUrl));
            this.Categories.Add(new SyndicationCategory(FeedCategories));
        }
Beispiel #27
0
        public async Task RssChannel()
        {
            var server = RssFeeds.FirstOrDefault(x => x.GuildId == Context.Guild.Id);

            if (server == null)
            {
                await Initialise();

                return;
            }
            server.ChannelId = Context.Channel.Id;

            await ReplyAsync("", false, new EmbedBuilder
            {
                Description = $"RSS Updates will now be posted in {Context.Channel.Name}",
                Color       = Color.Blue
            });

            if (RssFeeds != null)
            {
                var feeds = JsonConvert.SerializeObject(RssFeeds, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "setup/RSS.json"), feeds);
            }
        }
Beispiel #28
0
 public override void Stop()
 {
     base.Stop();
     RssFeeds.ClearCache();
 }
Beispiel #29
0
        /// <summary>
        /// Get RssFeeds from uri specified in config file
        /// </summary>
        /// <returns>RssFeeds from parsed html from uri</returns>
        public RssFeeds Get()
        {
            // get raw html
            this.uricontent = this.GetHtml();

            string uriPrefix = this.configuration.AzureFeedUriPrefix;

            // parse content into object
            HtmlParser htmlParser = new HtmlParser(uriPrefix);
            this.rssFeeds = htmlParser.ParseHtmlForFeeds(this.uricontent);

            return this.rssFeeds;
        }
Beispiel #30
0
 public void UpdateRss(RssFeeds rss)
 {
     throw new NotImplementedException();
 }
Beispiel #31
0
        /// <summary>
        /// Returns importable file as string for Google Reader
        /// based on feeds passed in.
        /// </summary>
        /// <param name="rssFeeds">RssFeeds to convert to opml</param>
        /// <returns>Returns OPML formatted string of RSS Feeds</returns>
        public string OPML(RssFeeds rssFeeds)
        {
            if (rssFeeds == null)
            {
                throw new ArgumentNullException("FileDatasource::OPML - " + "RssFeeds rssFeeds");
            }

            return rssFeeds.OPML();
        }
        /// <summary>
        /// The method creates SyndicationFeed for topics in a forum.
        /// </summary>
        /// <param name="feedType">
        /// The FeedType.
        /// </param>
        /// <param name="lastPostName">
        /// The last post name.
        /// </param>
        /// <param name="forumId">
        /// The forum id.
        /// </param>
        /// <returns>
        /// The <see cref="FeedItem"/>.
        /// </returns>
        public FeedItem GetTopicsFeed([NotNull] RssFeeds feedType, [NotNull] string lastPostName, [NotNull] int forumId)
        {
            var syndicationItems = new List <SyndicationItem>();

            var topics = this.GetRepository <Topic>().RssList(
                forumId,
                BoardContext.Current.PageUserID,
                BoardContext.Current.BoardSettings.TopicsFeedItemsCount);

            var urlAlphaNum = FormatUrlForFeed(BaseUrlBuilder.BaseUrl);

            var feed = new FeedItem(
                $"{this.Get<ILocalization>().GetText("DEFAULT", "FORUM")}:{BoardContext.Current.PageForumName}",
                feedType,
                urlAlphaNum);

            topics.ForEach(
                topic =>
            {
                var lastPosted = (System.DateTime)topic.LastPosted + this.Get <IDateTimeService>().TimeOffset;

                if (syndicationItems.Count <= 0)
                {
                    feed.Authors.Add(
                        SyndicationItemExtensions.NewSyndicationPerson(
                            string.Empty,
                            (int)topic.LastUserID,
                            null,
                            null));
                    feed.LastUpdatedTime = System.DateTime.UtcNow + this.Get <IDateTimeService>().TimeOffset;
                }

                feed.Contributors.Add(
                    SyndicationItemExtensions.NewSyndicationPerson(
                        string.Empty,
                        (int)topic.LastUserID,
                        null,
                        null));

                var postLink = this.Get <LinkBuilder>().GetLink(
                    ForumPages.Posts,
                    true,
                    "m={0}&name={1}#post{0}",
                    (int)topic.LastMessageID,
                    (string)topic.Topic);

                var content = this.GetPostLatestContent(
                    postLink,
                    lastPostName,
                    (string)topic.LastMessage,
                    (int)topic.LastMessageFlags,
                    false);

                syndicationItems.AddSyndicationItem(
                    (string)topic.Topic,
                    content,
                    null,
                    postLink,
                    $"urn:{urlAlphaNum}:ft{feedType}:tid{topic.TopicID}:lmid{topic.LastMessageID}:{BoardContext.Current.PageBoardID}"
                    .Unidecode(),
                    lastPosted,
                    feed);
            });

            feed.Items = syndicationItems;

            return(feed);
        }
        /// <summary>
        /// The method creates the SyndicationFeed for posts.
        /// </summary>
        /// <param name="feedType">
        /// The FeedType.
        /// </param>
        /// <param name="topicId">
        /// The TopicID
        /// </param>
        /// <returns>
        /// The <see cref="FeedItem"/>.
        /// </returns>
        public FeedItem GetPostsFeed([NotNull] RssFeeds feedType, [NotNull] int topicId)
        {
            var syndicationItems = new List <SyndicationItem>();

            var showDeleted = false;
            var userId      = 0;

            if (BoardContext.Current.BoardSettings.ShowDeletedMessagesToAll)
            {
                showDeleted = true;
            }

            if (!showDeleted &&
                (BoardContext.Current.BoardSettings.ShowDeletedMessages &&
                 !BoardContext.Current.BoardSettings.ShowDeletedMessagesToAll || BoardContext.Current.IsAdmin ||
                 BoardContext.Current.IsForumModerator))
            {
                userId = BoardContext.Current.PageUserID;
            }

            var posts = this.GetRepository <Message>().PostListPaged(
                topicId,
                BoardContext.Current.PageUserID,
                userId,
                false,
                showDeleted,
                DateTimeHelper.SqlDbMinTime(),
                System.DateTime.UtcNow,
                0,
                BoardContext.Current.BoardSettings.PostsPerPage,
                -1);

            var altItem = false;

            var urlAlphaNum = FormatUrlForFeed(BaseUrlBuilder.BaseUrl);

            var feed = new FeedItem(
                $"{this.Get<ILocalization>().GetText("PROFILE", "TOPIC")}{BoardContext.Current.PageTopicName} - {BoardContext.Current.BoardSettings.PostsPerPage}",
                feedType,
                urlAlphaNum);

            posts.ForEach(
                row =>
            {
                var posted = row.Edited + this.Get <IDateTimeService>().TimeOffset;

                if (syndicationItems.Count <= 0)
                {
                    feed.Authors.Add(
                        SyndicationItemExtensions.NewSyndicationPerson(string.Empty, row.UserID, null, null));
                    feed.LastUpdatedTime = System.DateTime.UtcNow + this.Get <IDateTimeService>().TimeOffset;
                }

                List <SyndicationLink> attachmentLinks = null;

                // if the user doesn't have download access we simply don't show enclosure links.
                if (BoardContext.Current.ForumDownloadAccess)
                {
                    attachmentLinks = this.GetMediaLinks(row.MessageID);
                }

                feed.Contributors.Add(
                    SyndicationItemExtensions.NewSyndicationPerson(string.Empty, row.UserID, null, null));

                syndicationItems.AddSyndicationItem(
                    row.Topic,
                    this.Get <IFormatMessage>().FormatSyndicationMessage(
                        row.Message,
                        new MessageFlags(row.Flags),
                        altItem,
                        4000),
                    null,
                    this.Get <LinkBuilder>().GetLink(
                        ForumPages.Posts,
                        true,
                        "m={0}&name={1}&find=lastpost",
                        row.MessageID,
                        row.Topic),
                    $"urn:{urlAlphaNum}:ft{feedType}:meid{row.MessageID}:{BoardContext.Current.PageBoardID}"
                    .Unidecode(),
                    posted,
                    feed,
                    attachmentLinks);

                // used to format feeds
                altItem = !altItem;
            });

            feed.Items = syndicationItems;

            return(feed);
        }
 public ActionResult Index()
 {
     ViewBag.Message = "Welcome to ASP.NET MVC!";
     _MainFeedData = _MicroOperations.GetMainFeeds();
     return View(_MainFeedData);
 }
Beispiel #35
0
        /// <summary>
        /// Serialize the feeds to a filename. Neither can be 
        /// null.
        /// </summary>
        /// <param name="feeds">list of feeds</param>
        /// <param name="filename">filename and path</param>
        public void Set(RssFeeds feeds, string filename)
        {
            if (feeds == null)
            {
                throw new ArgumentNullException("FileDatasource::Set - " + "RssFeeds feeds");
            }

            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException("FileDatasource::Set - " + "string filename");
            }

            Serializer.Serialize(filename, feeds);
        }
 public void UpdateRss(RssFeeds rss)
 {
     throw new NotImplementedException();
 }
Beispiel #37
0
        /// <summary>
        /// Deserialize RssFeeds from serializedFile
        /// </summary>
        /// <param name="serializedFile">path and filename</param>
        /// <returns>RssFeeds from file</returns>
        public RssFeeds GetFeeds(string serializedFile)
        {
            if (string.IsNullOrEmpty(serializedFile))
            {
                throw new ArgumentNullException("FileDatasource::GetFeeds - " + "string serializedFile");
            }

            if (File.Exists(serializedFile))
            {
                this.feeds = Serializer.Deserialize<RssFeeds>(serializedFile);
                return this.feeds;
            }
            else
            {
                throw new ArgumentNullException("FileDatasource::GetFeeds - " + "serializedFile doesn't exist");
            }
        }