Ejemplo n.º 1
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, YafRssFeeds feedType, int sf, [NotNull] string urlAlphaNum)
        {
            this.Copyright =
                new TextSyndicationContent(
                    "Copyright {0} {1}".FormatWith(DateTime.Now.Year, YafContext.Current.BoardSettings.Name));
            this.Description =
                new TextSyndicationContent(
                    "{0} - {1}".FormatWith(
                        YafContext.Current.BoardSettings.Name,
                        sf == YafSyndicationFormats.Atom.ToInt()
              ? YafContext.Current.Get <ILocalization>().GetText("ATOMFEED")
              : YafContext.Current.Get <ILocalization>().GetText("RSSFEED")));
            this.Title =
                new TextSyndicationContent(
                    "{0} - {1} - {2}".FormatWith(
                        sf == YafSyndicationFormats.Atom.ToInt()
              ? YafContext.Current.Get <ILocalization>().GetText("ATOMFEED")
              : YafContext.Current.Get <ILocalization>().GetText("RSSFEED"),
                        YafContext.Current.BoardSettings.Name,
                        subTitle));

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

            // Self Link
            var slink =
                new Uri(
                    YafBuildLink.GetLinkNotEscaped(ForumPages.rsstopic, true, "pg={0}&ft={1}".FormatWith(feedType.ToInt(), sf)));

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

            this.Generator       = "YetAnotherForum.NET";
            this.LastUpdatedTime = DateTime.UtcNow;
            this.Language        = YafContext.Current.Get <ILocalization>().LanguageCode;
            this.ImageUrl        =
                new Uri("{0}/YAFLogo.png".FormatWith(Path.Combine(YafForumInfo.ForumBaseUrl, YafBoardFolders.Current.Images)));

            this.Id =
                "urn:{0}:{1}:{2}:{3}:{4}".FormatWith(
                    urlAlphaNum,
                    sf == YafSyndicationFormats.Atom.ToInt()
            ? YafContext.Current.Get <ILocalization>().GetText("ATOMFEED")
            : YafContext.Current.Get <ILocalization>().GetText("RSSFEED"),
                    YafContext.Current.BoardSettings.Name,
                    subTitle,
                    YafContext.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(YafContext.Current.BoardSettings.ForumEmail, "Forum Admin", BaseUrlBuilder.BaseUrl));
            this.Categories.Add(new SyndicationCategory(FeedCategories));

            // writer.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + YafForumInfo.ForumClientFileRoot + "rss.xsl\" media=\"screen\"?>");
        }
Ejemplo n.º 2
0
        public override async Task Invoke(IOwinContext context)
        {
            PathString subPath;

            context.Request.Path.StartsWithSegments(options.Path, out subPath);
            if (!subPath.StartsWithSegments(new PathString("/rss")))
            {
                await Next.Invoke(context);

                return;
            }

            const int pageSize        = 15;
            var       errorLogEntries = await errorLog.GetErrorsAsync(0, pageSize);

            var syndicationFeed = new SyndicationFeed();

            var hostName = EnvironmentUtilities.GetMachineNameOrDefault("Unknown Host");

            syndicationFeed.Title       = new TextSyndicationContent($"Error log of {errorLog.ApplicationName} on {hostName}.");
            syndicationFeed.Description = new TextSyndicationContent("Log of recent errors");
            syndicationFeed.Language    = "en-us";

            var uriAsString = context.Request.Uri.ToString();
            var baseUri     = new Uri(uriAsString.Remove(uriAsString.LastIndexOf("/rss", StringComparison.InvariantCulture)));

            syndicationFeed.Links.Add(SyndicationLink.CreateAlternateLink(baseUri));

            var items = new List <SyndicationItem>();

            foreach (var errorLogEntry in errorLogEntries)
            {
                var item = new SyndicationItem
                {
                    Title   = SyndicationContent.CreatePlaintextContent(errorLogEntry.Error.Message),
                    Content =
                        SyndicationContent.CreatePlaintextContent(
                            $"An error of type {errorLogEntry.Error.TypeName} occurred. {errorLogEntry.Error.Message}"),
                    PublishDate = errorLogEntry.Error.Time
                };
                item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(baseUri, $"/detail?id={errorLogEntry.Id}")));

                items.Add(item);
            }

            syndicationFeed.Items = items;

            context.Response.ContentType = "application/rss+xml";
            context.Response.StatusCode  = 200;

            using (var writer = XmlWriter.Create(context.Response.Body, SettingsUtility.XmlWriterSettings))
            {
                var formatter = new Rss20FeedFormatter(syndicationFeed);
                formatter.WriteTo(writer);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Add the channel links
        /// </summary>
        /// <param name="feed"></param>
        /// <returns></returns>
        public new SyndicationFeed AddFeedLinksToFeed(SyndicationFeed feed, I_Base_Rss_Feed rssFeed)
        {
            string searchUrl = GetSearchUrl(WebUtil.GetHostName());

            feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(searchUrl)));
            feed.ElementExtensions.Add(new XElement(RssConstants.AtomNamespace + "link",
                                                    new XAttribute("href", new Uri(searchUrl)), new XAttribute("rel", "self"),
                                                    new XAttribute("type", "application/rss+xml")));

            return(feed);
        }
Ejemplo n.º 4
0
        private async Task UpdateSyndicationFeed()
        {
            //See if feed is already in the cache
            List <SyndicationItem> items = Cache["news"] as List <SyndicationItem>;

            if (items == null)
            {
                var container = client.GetContainerReference(companyName.ToLower());
                var blob      = container.GetBlockBlobReference("news/" + "news.rss");
                using (MemoryStream ms = new MemoryStream())
                {
                    await blob.DownloadToStreamAsync(ms);

                    StreamReader reader = new StreamReader(ms);
                    if (reader != null)
                    {
                        reader.BaseStream.Position = 0;
                    }
                    SyndicationFeed audiosList = SyndicationFeed.Load(XmlReader.Create(ms));
                    items = audiosList.Items.ToList <SyndicationItem>();

                    SyndicationItem item = new SyndicationItem();


                    //Create syndication Item
                    item.Title       = TextSyndicationContent.CreatePlaintextContent(name.Text);
                    item.PublishDate = DateTimeOffset.Now;
                    item.Links.Add(SyndicationLink.CreateAlternateLink(uri));
                    item.Summary = TextSyndicationContent.CreatePlaintextContent(description.Text);
                    items.Add(item);

                    //recreate Feed
                    audiosList.Items = items;
                    blob.Delete();

                    MemoryStream       ms1          = new MemoryStream();
                    XmlWriter          feedWriter   = XmlWriter.Create(ms1);
                    Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(audiosList);
                    rssFormatter.WriteTo(feedWriter);
                    feedWriter.Close();

                    await blob.UploadFromByteArrayAsync(ms1.ToArray(), 0, ms1.ToArray().Length);

                    ms1.Close();
                }
                Cache.Insert("news",
                             items,
                             null,
                             DateTime.Now.AddHours(1.0),
                             TimeSpan.Zero);
            }
        }
Ejemplo n.º 5
0
        public SyndicationFeed AddFeedLinksToFeed(SyndicationFeed feed, I_Base_Rss_Feed rssFeed)
        {
            if (!string.IsNullOrEmpty(rssFeed.Link))
            {
                feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(rssFeed.Link)));

                feed.ElementExtensions.Add(new XElement(RssConstants.AtomNamespace + "link",
                                                        new XAttribute("href", new Uri(rssFeed.Link)), new XAttribute("rel", "self"),
                                                        new XAttribute("type", "application/rss+xml")));
            }

            return(feed);
        }
Ejemplo n.º 6
0
        public void CreateAlternateLink_Uri_String_ReturnsExpected(Uri uri, string mediaType)
        {
            SyndicationLink link = SyndicationLink.CreateAlternateLink(uri, mediaType);

            Assert.Empty(link.AttributeExtensions);
            Assert.Null(link.BaseUri);
            Assert.Empty(link.ElementExtensions);
            Assert.Equal(0, link.Length);
            Assert.Same(mediaType, link.MediaType);
            Assert.Equal("alternate", link.RelationshipType);
            Assert.Null(link.Title);
            Assert.Same(uri, link.Uri);
        }
        /// <summary>
        /// Gets the collection of <see cref="SyndicationItem"/>'s that represent the atom entries.
        /// </summary>
        /// <returns>A collection of <see cref="SyndicationItem"/>'s.</returns>
        private List <SyndicationItem> GetItems()
        {
            List <SyndicationItem> items = new List <SyndicationItem>();

            for (int i = 1; i < 4; ++i)
            {
                SyndicationItem item = new SyndicationItem()
                {
                    // id (Required) - Identifies the entry using a universally unique and permanent URI. Two entries in a feed can have the same value for id if they represent the same entry at different points in time.
                    Id = FeedId + i,
                    // title (Required) - Contains a human readable title for the entry. This value should not be blank.
                    Title = SyndicationContent.CreatePlaintextContent("Item " + i),
                    // description (Reccomended) - A summary of the entry.
                    Summary = SyndicationContent.CreatePlaintextContent("A summary of item " + i),
                    // updated (Optional) - Indicates the last time the entry was modified in a significant way. This value need not change after a typo is fixed, only after a substantial modification. Generally, different entries in a feed will have different updated timestamps.
                    LastUpdatedTime = DateTimeOffset.Now,
                    // published (Optional) - Contains the time of the initial creation or first availability of the entry.
                    PublishDate = DateTimeOffset.Now,
                    // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the entry.
                    Copyright = new TextSyndicationContent(string.Format("© {0} - {0}", DateTime.Now.Year, Application.Name)),
                };

                // link (Reccomended) - Identifies a related Web page. An entry must contain an alternate link if there is no content element.
                item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)), ContentType.Html));
                // AND/OR
                // Text content  (Optional) - Contains or links to the complete content of the entry. Content must be provided if there is no alternate link.
                // item.Content = SyndicationContent.CreatePlaintextContent("The actual plain text content of the entry");
                // HTML content (Optional) - Content can be plain text or HTML. Here is a HTML example.
                // item.Content = SyndicationContent.CreateHtmlContent("The actual HTML content of the entry");

                // author (Optional) - Names one author of the entry. An entry may have multiple authors. An entry must contain at least one author element unless there is an author element in the enclosing feed, or there is an author element in the enclosed source element.
                item.Authors.Add(this.GetPerson());

                // contributor (Optional) - Names one contributor to the entry. An entry may have multiple contributor elements.
                item.Contributors.Add(this.GetPerson());

                // category (Optional) - Specifies a category that the entry belongs to. A entry may have multiple category elements.
                item.Categories.Add(new SyndicationCategory("CategoryName"));

                // link - Add additional links to related images, audio or video like so.
                item.Links.Add(SyndicationLink.CreateMediaEnclosureLink(new Uri(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png")), ContentType.Png, 0));

                // media:thumbnail - Add a Yahoo Media thumbnail for the entry. See http://www.rssboard.org/media-rss for more information.
                item.SetThumbnail(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png"), 48, 48);

                items.Add(item);
            }

            return(items);
        }
        /// <summary>
        /// Gets the feed containing meta data about the feed and the feed entries.
        /// </summary>
        /// <returns>A <see cref="SyndicationFeed"/>.</returns>
        public SyndicationFeed GetFeed()
        {
            SyndicationFeed feed = new SyndicationFeed()
            {
                // id (Required) - The feed universally unique identifier.
                Id = FeedId,
                // title (Required) - Contains a human readable title for the feed. Often the same as the title of the associated website. This value should not be blank.
                Title = SyndicationContent.CreatePlaintextContent("ASP.NET MVC Boilerplate"),
                // items (Required) - The items to add to the feed.
                Items = this.GetItems(),
                // subtitle (Recommended) - Contains a human-readable description or subtitle for the feed.
                Description = SyndicationContent.CreatePlaintextContent("This is the ASP.NET MVC Boilerplate feed description."),
                // updated (Optional) - Indicates the last time the feed was modified in a significant way.
                LastUpdatedTime = DateTimeOffset.Now,
                // logo (Optional) - Identifies a larger image which provides visual identification for the feed. Images should be twice as wide as they are tall.
                ImageUrl = new Uri(this.urlHelper.AbsoluteContent("~/content/icons/atom-logo-96x48.png")),
                // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the feed.
                Copyright = new TextSyndicationContent(string.Format("© {0} - {0}", DateTime.Now.Year, Application.Name)),
                // lang (Optional) - The language of the feed.
                Language = "en-GB",
                // generator (Optional) - Identifies the software used to generate the feed, for debugging and other purposes. Do not put in anything that identifies the technology you are using.
                // Generator = "Sample Code",
                // base (Buggy) - Add the full base URL to the site so that all other links can be relative. This is great, except some feed readers are buggy with it, INCLUDING FIREFOX!!! (See https://bugzilla.mozilla.org/show_bug.cgi?id=480600).
                // BaseUri = new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex))
            };

            // self link (Required) - The URL for the syndication feed.
            feed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetFeed)), ContentType.Atom));

            // alternate link (Recommended) - The URL for the web page showing the same data as the syndication feed.
            feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)), ContentType.Html));

            // author (Recommended) - Names one author of the feed. A feed may have multiple author elements. A feed must contain at least one author element unless all of the entry elements contain at least one author element.
            feed.Authors.Add(this.GetPerson());

            // category (Optional) - Specifies a category that the feed belongs to. A feed may have multiple category elements.
            feed.Categories.Add(new SyndicationCategory("CategoryName"));

            // contributor (Optional) - Names one contributor to the feed. An feed may have multiple contributor elements.
            feed.Contributors.Add(this.GetPerson());

            // icon (Optional) - Identifies a small image which provides iconic visual identification for the feed. Icons should be square.
            feed.SetIcon(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png"));

            // Add the Yahoo Media namespace (xmlns:media="http://search.yahoo.com/mrss/") to the Atom feed.
            // This gives us extra abilities, like the ability to give thumbnail images to entries. See http://www.rssboard.org/media-rss for more information.
            feed.AddYahooMediaNamespace();

            return(feed);
        }
Ejemplo n.º 9
0
        private void AddLink(Sitecore.Data.Items.Item item, SyndicationItem syndicationItem)
        {
            Sitecore.Diagnostics.Assert.ArgumentNotNull(item, "item");

            if (item.TemplateID.ToString() == "{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}")
            {
                item = item.Parent;
            }

            Sitecore.Links.UrlOptions defaultOptions = Sitecore.Links.UrlOptions.DefaultOptions;
            defaultOptions.AlwaysIncludeServerUrl = true;
            string itemUrl = Sitecore.Links.LinkManager.GetItemUrl(item, defaultOptions);

            syndicationItem.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(itemUrl)));
        }
        public SyndicationFeed CreateFeed(IPortalContext portal, HttpContext context, string selfRouteName, int maximumItems)
        {
            if (portal == null)
            {
                throw new ArgumentNullException("portal");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var blog = _dataAdapter.Select();

            if (blog == null)
            {
                throw new InvalidOperationException("Blog not found.");
            }

            var posts = _dataAdapter.SelectPosts(0, maximumItems).ToArray();

            var feedLastUpdatedTime = posts.Any() ? new DateTimeOffset(posts.First().PublishDate) : DateTimeOffset.UtcNow;
            var blogHtmlUri         = new Uri(context.Request.Url, blog.ApplicationPath.AbsolutePath);

            var feed = new SyndicationFeed(posts.Select(p => GetFeedItem(p, context)))
            {
                Id              = "uuid:{0};{1}".FormatWith(blog.Id, feedLastUpdatedTime.Ticks),
                Title           = SyndicationContent.CreatePlaintextContent(blog.Title),
                Description     = SyndicationContent.CreateHtmlContent(blog.Summary.ToString()),
                LastUpdatedTime = feedLastUpdatedTime,
                BaseUri         = new Uri(context.Request.Url, "/")
            };

            var selfPath = RouteTable.Routes.GetVirtualPath(context.Request.RequestContext, selfRouteName, new RouteValueDictionary
            {
                { "__portalScopeId__", portal.Website.Id },
                { "id", blog.Id }
            });

            if (selfPath != null)
            {
                feed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(context.Request.Url, ApplicationPath.FromPartialPath(selfPath.VirtualPath).AbsolutePath), "application/atom+xml"));
            }

            feed.Links.Add(SyndicationLink.CreateAlternateLink(blogHtmlUri, "text/html"));

            return(feed);
        }
Ejemplo n.º 11
0
        //public ActionResult TestRssFeed()
        //{
        //	var items = new List<SyndicationItem>();
        //	for (int i = 0; i < 20; i++)
        //	{
        //		var item = new SyndicationItem()
        //		{
        //			Id = Guid.NewGuid().ToString(),
        //			Title = SyndicationContent.CreatePlaintextContent(String.Format("My Title {0}", Guid.NewGuid())),
        //			Content = SyndicationContent.CreateHtmlContent("Content The stuff."),
        //			PublishDate = DateTime.Now
        //		};
        //		item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri("http://www.google.com")));//Nothing alternate about it. It is the MAIN link for the item.
        //		items.Add(item);
        //	}


        //	return new RssFeed(title: "Test rss",
        //					   items: items,
        //					   contentType: "application/rss+xml",
        //					   description: String.Format("rss de test  {0}", Guid.NewGuid()));

        //}

        public ActionResult RssFeed()
        {
            var fundInvestments = InvestmentStream.GetNewFundInvestmentList();
            var news            = new List <SyndicationItem>();

            foreach (var fundInvestment in fundInvestments)
            {
                foreach (var investment in fundInvestment.Investments)
                {
                    SyndicationItem newInvestment = new SyndicationItem()
                    {
                        Title       = SyndicationContent.CreatePlaintextContent(string.Format("{0} {1} {2}", fundInvestment.Fund.Name, Constants.INVEST_IN, investment.Startup.Name)),
                        Content     = SyndicationContent.CreateHtmlContent(investment.Description),
                        PublishDate = DateTime.Parse(investment.DateActivityFeed),
                    };
                    newInvestment.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(investment.Startup.Url)));
                    news.Add(newInvestment);
                }
            }

            var fundIncubations = IncubationStream.GetNewFundIncubationList();

            foreach (var fundIncubation in fundIncubations)
            {
                foreach (var incubation in fundIncubation.Incubations)
                {
                    SyndicationItem newInvestment = new SyndicationItem()
                    {
                        Title       = SyndicationContent.CreatePlaintextContent(string.Format("{0} {1} {2}", fundIncubation.Fund.Name, Constants.INCUBATE, incubation.Startup.Name)),
                        PublishDate = DateTime.Parse(incubation.DateActivityFeed),
                    };
                    newInvestment.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(incubation.Startup.Url)));
                    news.Add(newInvestment);
                }
            }

            ExecutionUpdater.UpdateRss();

            Log.Info("RssFeed", "refresh new feeds");

            return(new RssFeed(title: "Angel list feed",
                               items: news,
                               contentType: "application/rss+xml",
                               description: String.Format("Thibaut Cantet Angel list  {0}", Guid.NewGuid())));
        }
Ejemplo n.º 12
0
    private static List <SyndicationItem> GetPosts(string pbaseUrl, SortedDictionary <string, dynamic> pPostMetaData)
    {
        var items = new List <SyndicationItem>();

        foreach (var post in pPostMetaData)
        {
            var item = new SyndicationItem();
            item.Title = TextSyndicationContent.CreatePlaintextContent(post.Value.title);
            item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(pbaseUrl + post.Value.link.url)));
            item.Summary = TextSyndicationContent.CreateHtmlContent(post.Value.summary);
            var date = DateTime.Parse(post.Value.publish_date);
            item.PublishDate = new DateTimeOffset(date);
            item.Authors.Add(new SyndicationPerson(post.Value.author.email, post.Value.author.name, post.Value.author.url));

            items.Add(item);
        }

        return(items);
    }
Ejemplo n.º 13
0
        public ActionResult Atom(string blogid)
        {
            var feed = new SyndicationFeed();
            var blog = MASTERdomain.blogs.Where(x => string.Equals(x.permalink, blogid, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();

            if (blog != null)
            {
                var creator = new SyndicationPerson();
                creator.Name = blog.MASTERsubdomain.organisation.name;
                feed.Authors.Add(creator);
                feed.Id              = Request.Url.ToString();
                feed.Title           = new TextSyndicationContent(string.Format("{0} - {1}", blog.MASTERsubdomain.organisation.name, blog.title));
                feed.LastUpdatedTime = blog.updated;
                var items = new List <SyndicationItem>();
                foreach (var article in blog.articles)
                {
                    if (!article.published.HasValue)
                    {
                        continue;
                    }
                    var item = new SyndicationItem
                    {
                        Title           = new TextSyndicationContent(article.title),
                        Id              = string.Format("articles-{0}", article.id),
                        PublishDate     = article.published.Value,
                        LastUpdatedTime = article.published.Value
                    };

                    var author = new SyndicationPerson();
                    author.Name = article.user.ToFullName();
                    item.Authors.Add(author);
                    item.Summary = new TextSyndicationContent(article.content, TextSyndicationContentKind.Html);
                    var link =
                        SyndicationLink.CreateAlternateLink(
                            new Uri(accountHostname.ToDomainUrl(article.ToLiquidUrl())), "text/html");
                    item.Links.Add(link);
                    items.Add(item);
                }
                feed.Items = items;
            }

            return(new AtomActionResult(feed));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Executes the syndication result on the given context.
        /// </summary>
        /// <param name="context">The current context.</param>
        public virtual void Write(IStreamResponse response)
        {
            var writer = new XmlTextWriter(response.OutputStream, Encoding.UTF8);
            var ui     = new Client.Helpers.UIHelper();

            // Write headers
            response.ContentType     = ContentType;
            response.ContentEncoding = Encoding.UTF8;

            var feed = new SyndicationFeed()
            {
                Title           = new TextSyndicationContent(Config.Site.Title),
                LastUpdatedTime = Posts.First().Published.Value,
                Description     = new TextSyndicationContent(Config.Site.Description),
            };

            feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(App.Env.AbsoluteUrl("~/"))));

            var items = new List <SyndicationItem>();

            foreach (var post in Posts)
            {
                var item = new SyndicationItem()
                {
                    Title       = SyndicationContent.CreatePlaintextContent(post.Title),
                    PublishDate = post.Published.Value,
                    Summary     = SyndicationContent.CreateHtmlContent(post.Body)
                };
                item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(App.Env.AbsoluteUrl("~/" + post.Type.Slug + "/" + post.Slug))));
                items.Add(item);
            }
            feed.Items = items;

            var formatter = GetFormatter(feed);

            formatter.WriteTo(writer);

            writer.Flush();
            writer.Close();
        }
Ejemplo n.º 15
0
        public SyndicationFeed CreateSyndicationFeed(string nickname, string feedType, string scheme, string host)
        {
            IList <Post> posts = _postRepository.GetBlogPosts(nickname);
            Blog         blog  = _blogRepository.GetBlog(nickname);

            string url  = string.Format("{0}://{1}/{2}", scheme, host, nickname);
            var    feed = new SyndicationFeed(blog.Title, blog.Description, new Uri(url), url, blog.LastUpdated);

            feed.Authors.Add(new SyndicationPerson {
                Name = blog.User.Name
            });

            feed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(url + "/feed/" + feedType)));

            var items = new List <SyndicationItem>();

            foreach (Post post in posts)
            {
                var htmlurl = string.Format("{0}://{1}/{2}/{3}/{4}/{5}/{6}", scheme, host, nickname, post.Posted.Year,
                                            post.Posted.Month, post.Posted.Day, post.TitleLink);

                var item = new SyndicationItem();
                item.Title   = new TextSyndicationContent(post.Title, TextSyndicationContentKind.Html);
                item.Content = new TextSyndicationContent(post.BlogPost, TextSyndicationContentKind.Html);
                item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(htmlurl), "text/html"));

                var editurl = string.Format("{0}://{1}/{2}/pub/atom/{3}", scheme, host, nickname, post.Id);
                item.Links.Add(SyndicationLink.CreateSelfLink(new Uri(editurl)));
                item.Links.Add(new SyndicationLink {
                    RelationshipType = "edit", Uri = new Uri(editurl), MediaType = "application/atom+xml;type=entry"
                });

                item.PublishDate = post.Edited;
                item.Id          = editurl;
                items.Add(item);
            }
            feed.Items = items;
            return(feed);
        }
Ejemplo n.º 16
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, YafRssFeeds feedType, int sf, [NotNull] string urlAlphaNum)
        {
            this.Copyright =
                new TextSyndicationContent($"Copyright {DateTime.Now.Year} {YafContext.Current.BoardSettings.Name}");
            this.Description = new TextSyndicationContent(
                $"{YafContext.Current.BoardSettings.Name} - {(sf == YafSyndicationFormats.Atom.ToInt() ? YafContext.Current.Get<ILocalization>().GetText("ATOMFEED") : YafContext.Current.Get<ILocalization>().GetText("RSSFEED"))}");
            this.Title = new TextSyndicationContent(
                $"{(sf == YafSyndicationFormats.Atom.ToInt() ? YafContext.Current.Get<ILocalization>().GetText("ATOMFEED") : YafContext.Current.Get<ILocalization>().GetText("RSSFEED"))} - {YafContext.Current.BoardSettings.Name} - {subTitle}");

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

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

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

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

            this.Id =
                $"urn:{urlAlphaNum}:{(sf == YafSyndicationFormats.Atom.ToInt() ? YafContext.Current.Get<ILocalization>().GetText("ATOMFEED") : YafContext.Current.Get<ILocalization>().GetText("RSSFEED"))}:{YafContext.Current.BoardSettings.Name}:{subTitle}:{YafContext.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(
                    YafContext.Current.BoardSettings.ForumEmail,
                    "Forum Admin",
                    BaseUrlBuilder.BaseUrl));
            this.Categories.Add(new SyndicationCategory(FeedCategories));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FeedItem"/> class.
        /// </summary>
        /// <param name="subTitle">
        /// The sub title.
        /// </param>
        /// <param name="feedType">
        /// The feed source.
        /// </param>
        /// <param name="urlAlphaNum">
        /// The alphanumerically encoded base site Url.
        /// </param>
        public FeedItem([NotNull] string subTitle, RssFeeds feedType, string urlAlphaNum)
        {
            this.Copyright = new TextSyndicationContent(
                $"Copyright {DateTime.Now.Year} {BoardContext.Current.BoardSettings.Name}");
            this.Description = new TextSyndicationContent(
                $"{BoardContext.Current.BoardSettings.Name} - {BoardContext.Current.Get<ILocalization>().GetText("ATOMFEED")}");
            this.Title = new TextSyndicationContent(
                $"{BoardContext.Current.Get<ILocalization>().GetText("ATOMFEED")} - {BoardContext.Current.BoardSettings.Name} - {subTitle}");

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

            // Self Link
            var slink = new Uri(
                BoardContext.Current.Get <LinkBuilder>().GetLink(ForumPages.Feed, true, $"feed={feedType.ToInt()}"));

            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}{BoardContext.Current.Get<BoardFolders>().Logos}/{BoardContext.Current.BoardSettings.ForumLogo}");

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

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

            this.BaseUri = slink;
            this.Authors.Add(
                new SyndicationPerson(
                    BoardContext.Current.BoardSettings.ForumEmail,
                    "Forum Admin",
                    BaseUrlBuilder.BaseUrl));
            this.Categories.Add(new SyndicationCategory(FeedCategories));
        }
        private static SyndicationItem GetFeedItem(IBlogPost post, HttpContext context)
        {
            if (post == null)
            {
                throw new ArgumentNullException("post");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var item = new SyndicationItem
            {
                Id              = "uuid:{0};{1}".FormatWith(post.Id, post.LastUpdatedTime.Ticks),
                Title           = SyndicationContent.CreatePlaintextContent(post.Title),
                LastUpdatedTime = post.LastUpdatedTime,
                PublishDate     = post.PublishDate
            };

            var postHtmlUri = new Uri(context.Request.Url, post.ApplicationPath.AbsolutePath);

            item.Authors.Add(new SyndicationPerson {
                Name = post.Author.Name
            });
            item.Links.Add(SyndicationLink.CreateAlternateLink(postHtmlUri, "text/html"));

            if (post.HasExcerpt)
            {
                item.Summary = SyndicationContent.CreateHtmlContent(post.Summary.ToString());
            }
            else
            {
                item.Content = SyndicationContent.CreateHtmlContent(post.Content.ToString());
            }

            return(item);
        }
Ejemplo n.º 19
0
        private SyndicationItem CreateCommentItem(ListParameters p, GitHubComment comment)
        {
            GitHubCommentModel model = CreateCommentModel(p.Version, comment);
            string             title = p.Version == 1 ? "{0} commented on {1}/{2}".FormatWith(model.Commenter, p.User, p.Repo) :
                                       "{0}’s commit: {1}".FormatWith(model.Author, RenderCommitForSubject(model));

            return(new SyndicationItem
            {
                Authors = { new SyndicationPerson(null, comment.user.login, null) },
                Content = new TextSyndicationContent(CreateCommentHtml(p.Version, model), TextSyndicationContentKind.Html),
                Id = comment.url.AbsoluteUri,
                LastUpdatedTime = comment.updated_at,
                Links =
                {
                    SyndicationLink.CreateAlternateLink(comment.html_url),
                    new SyndicationLink(new Uri(model.CommitUrl))
                    {
                        RelationshipType = "related",                     Title= "CommitUrl"
                    }
                },
                PublishDate = comment.created_at,
                Title = new TextSyndicationContent(HttpUtility.HtmlEncode(title), TextSyndicationContentKind.Html),
            });
        }
Ejemplo n.º 20
0
        public static SyndicationItem AsSyndicationItem(this Notification notification, SyndicationFeed feed = null)
        {
            var item = new SyndicationItem
            {
                SourceFeed      = feed,
                Title           = SyndicationContent.CreatePlaintextContent(notification.Title),
                Summary         = SyndicationContent.CreatePlaintextContent(notification.Summary),
                PublishDate     = notification.NotificationDate,
                Content         = SyndicationContent.CreatePlaintextContent(notification.Description),
                LastUpdatedTime = notification.NotificationDate
            };

            item.Authors.Add(new SyndicationPerson
            {
                Name  = notification.Author.Name,
                Email = notification.Author.Email
            });

            var uri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri + "/" + notification.Id);

            item.Links.Add(SyndicationLink.CreateAlternateLink(uri, "application/atom+xml"));

            return(item);
        }
        /// <summary>
        /// Gets the feed containing meta data about the feed and the feed entries.
        /// </summary>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> signifying if the request is cancelled.</param>
        /// <returns>A <see cref="SyndicationFeed"/>.</returns>
        public async Task <SyndicationFeed> GetFeed(CancellationToken cancellationToken)
        {
            SyndicationFeed feed = new SyndicationFeed()
            {
                // id (Required) - The feed universally unique identifier.
                Id = FeedId,
                // title (Required) - Contains a human readable title for the feed. Often the same as the title of the
                //                    associated website. This value should not be blank.
                Title = SyndicationContent.CreatePlaintextContent("ASP.NET MVC Boilerplate"),
                // items (Required) - The items to add to the feed.
                Items = await this.GetItems(cancellationToken),
                // subtitle (Recommended) - Contains a human-readable description or subtitle for the feed.
                Description = SyndicationContent.CreatePlaintextContent(
                    "This is the ASP.NET MVC Boilerplate feed description."),
                // updated (Optional) - Indicates the last time the feed was modified in a significant way.
                LastUpdatedTime = DateTimeOffset.Now,
                // logo (Optional) - Identifies a larger image which provides visual identification for the feed.
                //                   Images should be twice as wide as they are tall.
                ImageUrl = new Uri(this.urlHelper.AbsoluteContent("~/content/icons/atom-logo-96x48.png")),
                // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the feed.
                Copyright = SyndicationContent.CreatePlaintextContent(
                    string.Format("© {0} - {1}", DateTime.Now.Year, Application.Name)),
                // lang (Optional) - The language of the feed.
                Language = "en-GB",
                // generator (Optional) - Identifies the software used to generate the feed, for debugging and other
                //                        purposes. Do not put in anything that identifies the technology you are using.
                // Generator = "Sample Code",
                // base (Buggy) - Add the full base URL to the site so that all other links can be relative. This is
                //                great, except some feed readers are buggy with it, INCLUDING FIREFOX!!!
                //                (See https://bugzilla.mozilla.org/show_bug.cgi?id=480600).
                // BaseUri = new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex))
            };

            // self link (Required) - The URL for the syndication feed.
            feed.Links.Add(SyndicationLink.CreateSelfLink(
                               new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetFeed)),
                               ContentType.Atom));

            // alternate link (Recommended) - The URL for the web page showing the same data as the syndication feed.
            feed.Links.Add(SyndicationLink.CreateAlternateLink(
                               new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)),
                               ContentType.Html));

            // hub link (Recommended) - The URL for the PubSubHubbub hub. Used to push new entries to subscribers
            //                          instead of making them poll the feed. See feed updated method below.
            feed.Links.Add(new SyndicationLink(new Uri(PubSubHubbubHubUrl), "hub", null, null, 0));

            // first, last, next previous (Optional) - Atom 1.0 supports paging of your feed. This is good if your feed
            //                                         becomes very large and needs splitting up into pages. To add
            //                                         paging, you must add links to the first, last, next and previous
            //                                         feed pages.
            // feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed"), "first", null, null, 0));
            // feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=10"), "last", null, null, 0));
            // if ([HAS_PREVIOUS_PAGE])
            //     feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=1")), "previous", null, null, 0));
            // if ([HAS_NEXT_PAGE])
            //     feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=3"), "next", null, null, 0));

            // author (Recommended) - Names one author of the feed. A feed may have multiple author elements. A feed
            //                        must contain at least one author element unless all of the entry elements contain
            //                        at least one author element.
            feed.Authors.Add(this.GetPerson());

            // category (Optional) - Specifies a category that the feed belongs to. A feed may have multiple category
            //                       elements.
            feed.Categories.Add(new SyndicationCategory("CategoryName"));

            // contributor (Optional) - Names one contributor to the feed. An feed may have multiple contributor
            //                          elements.
            feed.Contributors.Add(this.GetPerson());

            // icon (Optional) - Identifies a small image which provides iconic visual identification for the feed.
            //                   Icons should be square.
            feed.SetIcon(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png"));

            // Add the Yahoo Media namespace (xmlns:media="http://search.yahoo.com/mrss/") to the Atom feed.
            // This gives us extra abilities, like the ability to give thumbnail images to entries.
            // See http://www.rssboard.org/media-rss for more information.
            feed.AddYahooMediaNamespace();

            return(feed);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates the syndication items from issue list.
        /// </summary>
        /// <param name="issueList">The issue list.</param>
        /// <returns></returns>
        private IEnumerable <SyndicationItem> CreateSyndicationItemsFromIssueList(IEnumerable <Issue> issueList)
        {
            var feedItems = new List <SyndicationItem>();

            foreach (Issue issue in issueList.Take(maxItemsInFeed))
            {
                // Atom items MUST have an author, so if there are no authors for this content item then go to next item in loop
                //if (outputAtom && t.TitleAuthors.Count == 0)
                //    continue;
                var item = new SyndicationItem
                {
                    Title = SyndicationContent.CreatePlaintextContent(string.Format("{0} - {1}", issue.FullId, issue.Title))
                };

                item.Links.Add(
                    SyndicationLink.CreateAlternateLink(
                        new Uri(
                            GetFullyQualifiedUrl(string.Format("~/Issues/IssueDetail.aspx?id={0}", issue.Id)))));
                item.Summary = SyndicationContent.CreatePlaintextContent(issue.Description);
                item.Categories.Add(new SyndicationCategory(issue.CategoryName));
                item.PublishDate = issue.DateCreated;

                // Add a custom element.
                var doc         = new XmlDocument();
                var itemElement = doc.CreateElement("milestone");
                itemElement.InnerText = issue.MilestoneName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("project");
                itemElement.InnerText = issue.ProjectName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("issueType");
                itemElement.InnerText = issue.IssueTypeName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("priority");
                itemElement.InnerText = issue.PriorityName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("status");
                itemElement.InnerText = issue.StatusName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("resolution");
                itemElement.InnerText = issue.ResolutionName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("assignedTo");
                itemElement.InnerText = issue.AssignedDisplayName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("owner");
                itemElement.InnerText = issue.OwnerDisplayName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("dueDate");
                itemElement.InnerText = issue.DueDate.ToShortDateString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("progress");
                itemElement.InnerText = issue.Progress.ToString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("estimation");
                itemElement.InnerText = issue.Estimation.ToString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("lastUpdated");
                itemElement.InnerText = issue.LastUpdate.ToShortDateString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("lastUpdateBy");
                itemElement.InnerText = issue.LastUpdateDisplayName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("created");
                itemElement.InnerText = issue.DateCreated.ToShortDateString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("createdBy");
                itemElement.InnerText = issue.CreatorDisplayName;
                item.ElementExtensions.Add(itemElement);

                //foreach (TitleAuthor ta in t.TitleAuthors)
                //{
                //    SyndicationPerson authInfo = new SyndicationPerson();
                //    authInfo.Email = ta.Author.au_lname + "@example.com";
                //    authInfo.Name = ta.Author.au_fullname;
                //    item.Authors.Add(authInfo);

                //    // RSS feeds can only have one author, so quit loop after first author has been added
                //    if (outputRss)
                //        break;
                //}
                var profile  = new WebProfile().GetProfile(issue.CreatorUserName);
                var authInfo = new SyndicationPerson {
                    Name = profile.DisplayName
                };
                //authInfo.Email = Membership.GetUser(IssueCreatorUserId).Email;
                item.Authors.Add(authInfo);

                // Add the item to the feed
                feedItems.Add(item);
            }

            return(feedItems);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            var channelId = 0;

            // Determine the maximum number of items to show in the feed

            if (Request.QueryString["pid"] != null)
            {
                _projectId = Convert.ToInt32(Request.Params["pid"]);
            }

            //get feed id
            if (Request.QueryString["channel"] != null)
            {
                channelId = Convert.ToInt32(Request.Params["channel"]);
            }

            if (!User.Identity.IsAuthenticated && _projectId == 0)
            {
                throw new HttpException(403, "Access Denied");
            }

            if (_projectId != 0)
            {
                //Security Checks
                if (!User.Identity.IsAuthenticated &&
                    ProjectManager.GetById(_projectId).AccessType == ProjectAccessType.Private)
                {
                    throw new HttpException(403, "Access Denied");
                }

                if (User.Identity.IsAuthenticated &&
                    ProjectManager.GetById(_projectId).AccessType == ProjectAccessType.Private &&
                    !ProjectManager.IsUserProjectMember(User.Identity.Name, _projectId))
                {
                    throw new HttpException(403, "Access Denied");
                }
            }


            // Determine whether we're outputting an Atom or RSS feed
            var outputRss  = (Request.QueryString["Type"] == "RSS");
            var outputAtom = !outputRss;

            // Output the appropriate ContentType
            Response.ContentType = outputRss ? "application/rss+xml" : "application/atom+xml";

            // Create the feed and specify the feed's attributes
            var myFeed = new SyndicationFeed();

            myFeed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(GetFullyQualifiedUrl("~/Default.aspx"))));
            myFeed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(GetFullyQualifiedUrl(Request.RawUrl))));
            myFeed.Language = "en-us";

            switch (channelId)
            {
            case 1:
                MilestoneFeed(ref myFeed);
                break;

            case 2:
                CategoryFeed(ref myFeed);
                break;

            case 3:
                StatusFeed(ref myFeed);
                break;

            case 4:
                PriorityFeed(ref myFeed);
                break;

            case 5:
                TypeFeed(ref myFeed);
                break;

            case 6:
                AssigneeFeed(ref myFeed);
                break;

            case 7:
                FilteredIssuesFeed(ref myFeed);
                break;

            case 8:
                RelevantFeed(ref myFeed);
                break;

            case 9:
                AssignedFeed(ref myFeed);
                break;

            case 10:
                OwnedFeed(ref myFeed);
                break;

            case 11:
                CreatedFeed(ref myFeed);
                break;

            case 12:
                AllIssuesFeed(ref myFeed);
                break;

            case 13:
                QueryFeed(ref myFeed);
                break;

            case 14:
                OpenIssueFeed(ref myFeed);
                break;

            case 15:
                MonitoredFeed(ref myFeed);
                break;

            case 16:
                ClosedFeed(ref myFeed);
                break;
            }

            // Return the feed's XML content as the response
            var outputSettings = new XmlWriterSettings {
                Indent = true
            };
            //(Uncomment for readability during testing)
            var feedWriter = XmlWriter.Create(Response.OutputStream, outputSettings);

            if (outputAtom)
            {
                // Use Atom 1.0
                var atomFormatter = new Atom10FeedFormatter(myFeed);
                atomFormatter.WriteTo(feedWriter);
            }
            else
            {
                // Emit RSS 2.0
                var rssFormatter = new Rss20FeedFormatter(myFeed);
                rssFormatter.WriteTo(feedWriter);
            }

            feedWriter.Close();
        }
Ejemplo n.º 24
0
        static async Task Main(string[] args)
        {
            var outputDirectory = FullPath.FromPath(args[0]);
            var githubToken     = args.Length > 1 ? args[1] : null;
            var client          = githubToken != null ? new GitHubClient(new ProductHeaderValue("issue-to-rss"), new InMemoryCredentialStore(new Credentials(githubToken)))
                                             : new GitHubClient(new ProductHeaderValue("issue-to-rss"));

            var feeds = new List <FeedData>();
            await Configuration.Repositories.ParallelForEachAsync(degreeOfParallelism : 16, async repository =>
            {
                Console.WriteLine("Generating feed for " + repository);

                // Get issues
                var issuesItems     = new List <SyndicationItem>(200);
                var prItems         = new List <SyndicationItem>(200);
                var parts           = repository.Split('/');
                var repositoryOwner = parts[0];
                var repositoryName  = parts[1];

                foreach (var issue in await GetIssuesForRepository(client, repositoryOwner, repositoryName))
                {
                    if (Configuration.ExcludedUsers.Contains(issue.User.Login))
                    {
                        continue;
                    }

                    if (issue.Labels.Any(label => Configuration.ExcludedLabels.Contains(label.Name)))
                    {
                        continue;
                    }

                    var isPullRequest = issue.PullRequest != null;
                    var title         = (isPullRequest ? "PR: " : "Issue: ") + issue.Title + " - @" + issue.User.Login;

                    var item = new SyndicationItem
                    {
                        Id      = issue.HtmlUrl,
                        Title   = new TextSyndicationContent(SanitizeString(title)),
                        Content = new TextSyndicationContent(SanitizeString(Markdig.Markdown.ToHtml(issue.Body ?? ""))),
                        Links   =
                        {
                            SyndicationLink.CreateAlternateLink(new Uri(issue.HtmlUrl)),
                        },
                        PublishDate     = issue.CreatedAt,
                        LastUpdatedTime = issue.CreatedAt,
                        Authors         =
                        {
                            new SyndicationPerson(issue.User.Email, issue.User.Login, issue.User.HtmlUrl),
                        }
                    };

                    if (isPullRequest)
                    {
                        prItems.Add(item);
                    }
                    else
                    {
                        issuesItems.Add(item);
                    }
                }

                // Generate feeds
                {
                    var issuesFeed = new SyndicationFeed
                    {
                        Title       = new TextSyndicationContent(repository + " Issues"),
                        Description = new TextSyndicationContent($"Issues from https://github.com/{repository}, generated by {Configuration.GitHubRepositoryUrl}"),
                        Items       = issuesItems,
                        TimeToLive  = TimeSpan.FromHours(1),
                        Authors     = { new SyndicationPerson("*****@*****.**", "Gérald Barré", "https://www.meziantou.net/") },
                    };

                    lock (feeds)
                    {
                        feeds.Add(new FeedData {
                            Feed = issuesFeed, OutputRelativePath = $"{repository}.issues.rss"
                        });
                    }
                }

                {
                    var prFeed = new SyndicationFeed
                    {
                        Title       = new TextSyndicationContent(repository + " Pull Requests"),
                        Description = new TextSyndicationContent($"Pull Requests from https://github.com/{repository}, generated by {Configuration.GitHubRepositoryUrl}", TextSyndicationContentKind.Html),
                        Items       = prItems,
                        TimeToLive  = TimeSpan.FromHours(1),
                        Authors     = { new SyndicationPerson("*****@*****.**", "Gérald Barré", "https://www.meziantou.net/") },
                    };

                    lock (feeds)
                    {
                        feeds.Add(new FeedData {
                            Feed = prFeed, OutputRelativePath = $"{repository}.pr.rss"
                        });
                    }
                }
            });

            feeds.Sort((a, b) => a.OutputRelativePath.CompareTo(b.OutputRelativePath));

            // Write feeds
            foreach (var feedData in feeds)
            {
                Console.WriteLine($"Writing feed '{feedData.OutputRelativePath}'");
                var feedPath = FullPath.Combine(outputDirectory, feedData.OutputRelativePath);
                Directory.CreateDirectory(feedPath.Parent);
                using var stream    = File.OpenWrite(feedPath);
                using var xmlWriter = XmlWriter.Create(stream, new XmlWriterSettings()
                {
                    Indent = true
                });
                var rssFormatter = new Rss20FeedFormatter(feedData.Feed, serializeExtensionsAsAtom: false);
                rssFormatter.WriteTo(xmlWriter);
            }

            // index.opml
            {
                Console.WriteLine("Generating opml");
                var indexPath = FullPath.Combine(outputDirectory, "feeds.opml");
                Directory.CreateDirectory(indexPath.Parent);
                var document = new XDocument(
                    new XElement("opml", new XAttribute("version", "1.0"),
                                 new XElement("head",
                                              new XElement("title", "GitHub issues feeds")),
                                 new XElement("body", feeds.Select(GetOutline).ToArray())));

                using var stream    = File.OpenWrite(indexPath);
                using var xmlWriter = XmlWriter.Create(stream, new XmlWriterSettings()
                {
                    Indent = true
                });
                document.WriteTo(xmlWriter);
Ejemplo n.º 25
0
 public static void Snippet5()
 {
     // <Snippet5>
     SyndicationLink link = SyndicationLink.CreateAlternateLink(new Uri("http://server/link"), "text/html");
     // </Snippet5>
 }
Ejemplo n.º 26
0
 public static void Snippet4()
 {
     // <Snippet4>
     SyndicationLink link = SyndicationLink.CreateAlternateLink(new Uri("http://server/link"));
     // </Snippet4>
 }
Ejemplo n.º 27
0
        private void UpdateSyndicationFeed()
        {
            //See if feed is already in the cache
            List <SyndicationItem> items = Cache["AudiosFeed"] as List <SyndicationItem>;

            if (items == null)
            {
                var container = client.GetContainerReference(companyName.ToLower());
                var blob      = container.GetBlockBlobReference("audios/" + "audio.rss");
                using (MemoryStream ms = new MemoryStream())
                {
                    blob.DownloadToStream(ms);
                    StreamReader reader = new StreamReader(ms);
                    if (reader != null)
                    {
                        reader.BaseStream.Position = 0;
                    }
                    SyndicationFeed audiosList = SyndicationFeed.Load(XmlReader.Create(ms));
                    items = audiosList.Items.ToList <SyndicationItem>();
                    //Custom Tags
                    string           prefix   = "itunes";
                    XmlQualifiedName nam      = new XmlQualifiedName(prefix, "http://www.w3.org/2000/xmlns/");
                    XNamespace       itunesNs = "http://www.itunes.com/dtds/podcast-1.0.dtd";
                    audiosList.AttributeExtensions.Add(nam, itunesNs.NamespaceName);
                    SyndicationItem item = new SyndicationItem();


                    //Create syndication Item
                    item.Title       = TextSyndicationContent.CreatePlaintextContent(name.Text);
                    item.PublishDate = DateTimeOffset.Now;
                    item.Links.Add(SyndicationLink.CreateAlternateLink(uri));
                    item.ElementExtensions.Add(new SyndicationElementExtension("author", itunesNs.NamespaceName, name.Text));
                    item.ElementExtensions.Add(new SyndicationElementExtension("explicit", itunesNs.NamespaceName, "no"));
                    item.ElementExtensions.Add(new SyndicationElementExtension("summary", itunesNs.NamespaceName, description.Text));
                    item.ElementExtensions.Add(new SyndicationElementExtension("subtitle", itunesNs.NamespaceName, subtitle.Text));
                    item.ElementExtensions.Add(
                        new XElement(itunesNs + "image", new XAttribute("href", uri2.ToString())));
                    item.ElementExtensions.Add(new SyndicationElementExtension("Size", null, upload_file.PostedFile.ContentLength / 1000000));

                    item.Summary = TextSyndicationContent.CreatePlaintextContent(description.Text);
                    item.Categories.Add(new SyndicationCategory(category.Text));
                    SyndicationLink enclosure = SyndicationLink.CreateMediaEnclosureLink(uri, "audio/mpeg", upload_file.PostedFile.ContentLength);
                    item.ElementExtensions.Add(new SyndicationElementExtension("subtitle", itunesNs.NamespaceName, subtitle.Text));
                    item.Links.Add(enclosure);

                    //create author Info
                    SyndicationPerson authInfo = new SyndicationPerson();
                    authInfo.Name = authorName.Text;
                    item.Authors.Add(authInfo);
                    items.Add(item);

                    //recreate Feed
                    audiosList.Items = items;
                    blob.Delete();

                    MemoryStream       ms1          = new MemoryStream();
                    XmlWriter          feedWriter   = XmlWriter.Create(ms1);
                    Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(audiosList);
                    rssFormatter.WriteTo(feedWriter);
                    feedWriter.Close();

                    blob.UploadFromByteArray(ms1.ToArray(), 0, ms1.ToArray().Length);
                    ms1.Close();
                }
                Cache.Insert("AudiosFeed",
                             items,
                             null,
                             DateTime.Now.AddHours(1.0),
                             TimeSpan.Zero);
            }
        }
Ejemplo n.º 28
0
        public ActionResult GetMainRss()
        {
            var lstNoticias = Service.Models.Noticia.GetLastestNews(5, true);

            var lastDate = lstNoticias.First().DataPublicacao;

            if (lastDate == null)
            {
                return(null);
            }

            var feed = new SyndicationFeed
            {
                Title           = new TextSyndicationContent("Massa News - Todas as Noticias"),
                Language        = "pt-BR",
                LastUpdatedTime = new DateTimeOffset(lastDate.Value),
                Copyright       = new TextSyndicationContent("© Todos os direitos reservados.")
            };

            feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri($"{Constants.UrlWeb}/{"noticias"}")));

            feed.ImageUrl = new Uri($"{Constants.UrlCdn}/static/images/avatar/avatar-massanews-144x144.jpg");

            var feedItems = new List <SyndicationItem>();

            foreach (var noticia in lstNoticias)
            {
                var permalink = new Uri($"{Constants.UrlWeb}/{noticia.EditorialUrl}/{noticia.CategoriaUrl}/{noticia.Url}.html");

                var feedItem = new SyndicationItem
                {
                    Title       = new TextSyndicationContent(noticia.Titulo),
                    Content     = new TextSyndicationContent(StripHtml(noticia.Conteudo) + "... Leia mais no <a href='" + permalink + "'>Massa News</a>!"),
                    PublishDate = noticia.DataPublicacao ?? DateTime.Now,
                };

                //Adiciona Imagem ao item
                if (!string.IsNullOrEmpty(noticia.ImgLg))
                {
                    feedItem.ElementExtensions.Add(new XElement("image",
                                                                $"{Constants.UrlDominioEstaticoUploads}/noticias/{noticia.ImgLg}"));
                }

                feedItem.Links.Add(SyndicationLink.CreateAlternateLink(permalink));

                feedItems.Add(feedItem);
            }

            feed.Items = feedItems;

            SyndicationFeedFormatter rssFormatter = new Rss20FeedFormatter(feed);

            MemoryStream output = new MemoryStream();

            XmlWriterSettings ws = new XmlWriterSettings
            {
                Indent   = true,
                Encoding = new UTF8Encoding(false)
            };

            XmlWriter w = XmlWriter.Create(output, ws);

            rssFormatter.WriteTo(w);
            w.Flush();

            return(Content(Encoding.UTF8.GetString(output.ToArray()), "text/xml"));
        }
Ejemplo n.º 29
0
            internal SyndicationFeed CreateUpdateFeed(UpdateFeedModel feedModel, Uri currentUri, UrlHelper urlHelper)
            {
                var updateFeed = new SyndicationFeed
                {
                    Id              = string.Format("tag:{0},{1:yyyy-MM-dd}:feed/utc-time/{1:HH:mm:ss}", currentUri.Host, feedModel.LastUpdateUtcDateTimeOffset),
                    Language        = "en",
                    Title           = SyndicationContent.CreatePlaintextContent("IT Training Manager"),
                    Description     = SyndicationContent.CreatePlaintextContent("New Courses"),
                    LastUpdatedTime = feedModel.LastUpdateUtcDateTimeOffset,
                    Links           =
                    {
                        SyndicationLink.CreateSelfLink(currentUri, "application/atom+xml"),
                        SyndicationLink.CreateAlternateLink(new UriBuilder {
                            Scheme = currentUri.Scheme,            Host = currentUri.Host, Port= currentUri.Port
                        }.Uri,
                                                            "text/html")
                    },
                    Items = feedModel.Courses.Select(item =>
                    {
                        var syndicationItem = new SyndicationItem
                        {
                            Id      = item.GetCourseUri(urlHelper, currentUri.Scheme).ToString(),
                            Title   = SyndicationContent.CreatePlaintextContent(item.CourseTitle),
                            Content = SyndicationContent.CreateHtmlContent(item.CourseDescription),
                            Links   =
                            {
                                SyndicationLink.CreateAlternateLink(item.GetCourseUri(urlHelper, currentUri.Scheme), "text/html")
                            },
                            PublishDate     = item.PublishedUtcDateOffset,
                            LastUpdatedTime = feedModel.LastUpdateUtcDateTimeOffset,
                            Categories      =
                            {
                                new SyndicationCategory
                                {
                                    Label  = "/" + item.CategoryTitle,
                                    Name   = item.CategoryTitle,
                                    Scheme = item.GetCategoryUriString(urlHelper, currentUri.Scheme)
                                }
                            }
                        };

                        foreach (var person in item.Authors)
                        {
                            syndicationItem.Authors.Add(new SyndicationPerson
                            {
                                Name = person.Title,
                                Uri  = item.GetPersonUriString(person.UrlName, urlHelper, currentUri.Scheme)
                            });
                        }

                        foreach (var person in item.CoAuthors)
                        {
                            syndicationItem.Contributors.Add(new SyndicationPerson
                            {
                                Name = person.Title,
                                Uri  = item.GetPersonUriString(person.UrlName, urlHelper, currentUri.Scheme)
                            });
                        }

                        return(syndicationItem);
                    })
                };

                return(updateFeed);
            }
Ejemplo n.º 30
0
        public override async Task Invoke(IOwinContext context)
        {
            PathString subPath;

            context.Request.Path.StartsWithSegments(options.Path, out subPath);
            if (!subPath.StartsWithSegments(new PathString("/digestrss")))
            {
                await Next.Invoke(context);

                return;
            }

            var syndicationFeed = new SyndicationFeed();

            var hostName = EnvironmentUtilities.GetMachineNameOrDefault("Unknown Host");

            syndicationFeed.Title       = new TextSyndicationContent($"Daily digest of errors in {errorLog.ApplicationName} on {hostName}.");
            syndicationFeed.Description = new TextSyndicationContent("Daily digest of application errors");
            syndicationFeed.Language    = "en-us";

            var uriAsString = context.Request.Uri.ToString();
            var baseUri     = new Uri(uriAsString.Remove(uriAsString.LastIndexOf("/digestrss", StringComparison.InvariantCulture)));

            syndicationFeed.Links.Add(SyndicationLink.CreateAlternateLink(baseUri));

            var logEntries = await GetAllEntriesAsync();

            var groupBy = logEntries.GroupBy(
                entry => new DateTime(entry.Error.Time.Year, entry.Error.Time.Month, entry.Error.Time.Day));


            var itemList = new List <SyndicationItem>();

            foreach (var grouping in groupBy)
            {
                var syndicationItem = new SyndicationItem
                {
                    Title =
                        new TextSyndicationContent(
                            $"Digest for {grouping.Key.ToString("yyyy-MM-dd")} ({grouping.Key.ToLongDateString()})"),
                    PublishDate = grouping.Key,
                    Id          = grouping.Key.ToString("yyyy-MM-dd")
                };

                var builder = new StringBuilder();

                builder.AppendLine("<ul>");
                foreach (var errorLogEntry in grouping)
                {
                    builder.AppendLine("<li>");
                    builder.AppendLine($"{errorLogEntry.Error.TypeName}: <a href=\"{baseUri}/detail?id={errorLogEntry.Id}\">{errorLogEntry.Error.Message}</a>");
                    builder.AppendLine("</li>");
                }
                builder.AppendLine("</ul>");

                syndicationItem.Content = SyndicationContent.CreateHtmlContent(builder.ToString());

                itemList.Add(syndicationItem);
            }

            syndicationFeed.Items = itemList;

            context.Response.ContentType = "application/rss+xml";
            context.Response.StatusCode  = 200;

            using (var writer = XmlWriter.Create(context.Response.Body, SettingsUtility.XmlWriterSettings))
            {
                var formatter = new Rss20FeedFormatter(syndicationFeed);
                formatter.WriteTo(writer);
            }
        }